From 22f52ca1955069d940e47bc93962f6965f9515cd Mon Sep 17 00:00:00 2001 From: denise Date: Thu, 21 Feb 2013 17:57:56 -0500 Subject: [PATCH 01/73] CC-4961: Show linking -initial schedule service experimentation --- .../controllers/ScheduleController.php | 20 +- .../controllers/_old_ScheduleController.php | 1002 +++++++++++++ airtime_mvc/application/models/Schedule.php | 36 +- .../application/models/_old_Schedule.php | 1329 +++++++++++++++++ .../application/services/ScheduleService.php | 90 ++ 5 files changed, 2458 insertions(+), 19 deletions(-) create mode 100644 airtime_mvc/application/controllers/_old_ScheduleController.php create mode 100644 airtime_mvc/application/models/_old_Schedule.php create mode 100644 airtime_mvc/application/services/ScheduleService.php diff --git a/airtime_mvc/application/controllers/ScheduleController.php b/airtime_mvc/application/controllers/ScheduleController.php index 08fde37dc..9ca879918 100644 --- a/airtime_mvc/application/controllers/ScheduleController.php +++ b/airtime_mvc/application/controllers/ScheduleController.php @@ -5,6 +5,8 @@ class ScheduleController extends Zend_Controller_Action protected $sched_sess = null; + private $service_schedule; + public function init() { $ajaxContext = $this->_helper->getHelper('AjaxContext'); @@ -38,6 +40,8 @@ class ScheduleController extends Zend_Controller_Action ->initContext(); $this->sched_sess = new Zend_Session_Namespace("schedule"); + + $this->service_schedule = new Application_Service_ScheduleService(); } public function indexAction() @@ -90,13 +94,27 @@ class ScheduleController extends Zend_Controller_Action $this->view->headLink()->appendStylesheet($baseUrl.'css/showbuilder.css?'.$CC_CONFIG['airtime_version']); //End Show builder JS/CSS requirements + $forms = $this->service_schedule->createShowForms(); + // populate forms with default values + $this->service_schedule->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_record"]; + $this->view->rebroadcast = $forms["rebroadcast"]; + $this->view->who = $forms["who"]; + $this->view->style = $forms["style"]; - 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". diff --git a/airtime_mvc/application/controllers/_old_ScheduleController.php b/airtime_mvc/application/controllers/_old_ScheduleController.php new file mode 100644 index 000000000..08fde37dc --- /dev/null +++ b/airtime_mvc/application/controllers/_old_ScheduleController.php @@ -0,0 +1,1002 @@ +_helper->getHelper('AjaxContext'); + $ajaxContext->addActionContext('event-feed', 'json') + ->addActionContext('event-feed-preload', 'json') + ->addActionContext('make-context-menu', 'json') + ->addActionContext('add-show-dialog', 'json') + ->addActionContext('add-show', 'json') + ->addActionContext('edit-show', 'json') + ->addActionContext('move-show', 'json') + ->addActionContext('resize-show', 'json') + ->addActionContext('delete-show', '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('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('dj-edit-show', 'json') + ->addActionContext('calculate-duration', 'json') + ->addActionContext('get-current-show', 'json') + ->addActionContext('update-future-is-scheduled', 'json') + ->initContext(); + + $this->sched_sess = new Zend_Session_Namespace("schedule"); + } + + public function indexAction() + { + $CC_CONFIG = Config::getConfig(); + + $baseUrl = Application_Common_OsPath::getBaseDir(); + + $this->view->headScript()->appendFile($baseUrl.'js/contextmenu/jquery.contextMenu.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + + //full-calendar-functions.js requires this variable, so that datePicker widget can be offset to server time instead of client time + $this->view->headScript()->appendScript("var timezoneOffset = ".date("Z")."; //in seconds"); + $this->view->headScript()->appendFile($baseUrl.'js/airtime/schedule/full-calendar-functions.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + + $this->view->headScript()->appendFile($baseUrl.'js/fullcalendar/fullcalendar.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + $this->view->headScript()->appendFile($baseUrl.'js/timepicker/jquery.ui.timepicker.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + $this->view->headScript()->appendFile($baseUrl.'js/colorpicker/js/colorpicker.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + + $this->view->headScript()->appendFile($baseUrl.'js/airtime/schedule/add-show.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + $this->view->headScript()->appendFile($baseUrl.'js/airtime/schedule/schedule.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + $this->view->headScript()->appendFile($baseUrl.'js/blockui/jquery.blockUI.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + + $this->view->headLink()->appendStylesheet($baseUrl.'css/jquery.ui.timepicker.css?'.$CC_CONFIG['airtime_version']); + $this->view->headLink()->appendStylesheet($baseUrl.'css/fullcalendar.css?'.$CC_CONFIG['airtime_version']); + $this->view->headLink()->appendStylesheet($baseUrl.'css/colorpicker/css/colorpicker.css?'.$CC_CONFIG['airtime_version']); + $this->view->headLink()->appendStylesheet($baseUrl.'css/add-show.css?'.$CC_CONFIG['airtime_version']); + $this->view->headLink()->appendStylesheet($baseUrl.'css/jquery.contextMenu.css?'.$CC_CONFIG['airtime_version']); + + //Start Show builder JS/CSS requirements + $this->view->headScript()->appendFile($baseUrl.'js/contextmenu/jquery.contextMenu.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + $this->view->headScript()->appendFile($baseUrl.'js/datatables/js/jquery.dataTables.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + $this->view->headScript()->appendFile($baseUrl.'js/datatables/plugin/dataTables.pluginAPI.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + $this->view->headScript()->appendFile($baseUrl.'js/datatables/plugin/dataTables.fnSetFilteringDelay.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + $this->view->headScript()->appendFile($baseUrl.'js/datatables/plugin/dataTables.ColVis.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + $this->view->headScript()->appendFile($baseUrl.'js/datatables/plugin/dataTables.ColReorder.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + $this->view->headScript()->appendFile($baseUrl.'js/datatables/plugin/dataTables.FixedColumns.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + $this->view->headScript()->appendFile($baseUrl.'js/datatables/plugin/dataTables.TableTools.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + $this->view->headScript()->appendFile($baseUrl.'js/datatables/plugin/dataTables.columnFilter.js?'.$CC_CONFIG['airtime_version'], 'text/javascript'); + + $this->view->headScript()->appendFile($baseUrl.'js/airtime/buttons/buttons.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + $this->view->headScript()->appendFile($baseUrl.'js/airtime/library/events/library_showbuilder.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + $this->view->headScript()->appendFile($baseUrl.'js/airtime/library/library.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + $this->view->headScript()->appendFile($baseUrl.'js/airtime/showbuilder/builder.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + + $this->view->headLink()->appendStylesheet($baseUrl.'css/media_library.css?'.$CC_CONFIG['airtime_version']); + $this->view->headLink()->appendStylesheet($baseUrl.'css/jquery.contextMenu.css?'.$CC_CONFIG['airtime_version']); + $this->view->headLink()->appendStylesheet($baseUrl.'css/datatables/css/ColVis.css?'.$CC_CONFIG['airtime_version']); + $this->view->headLink()->appendStylesheet($baseUrl.'css/datatables/css/ColReorder.css?'.$CC_CONFIG['airtime_version']); + $this->view->headLink()->appendStylesheet($baseUrl.'css/TableTools.css?'.$CC_CONFIG['airtime_version']); + $this->view->headLink()->appendStylesheet($baseUrl.'css/showbuilder.css?'.$CC_CONFIG['airtime_version']); + //End Show builder JS/CSS requirements + + + 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->headScript()->appendScript( + "var calendarPref = {};\n". + "calendarPref.weekStart = ".Application_Model_Preference::GetWeekStartDay().";\n". + "calendarPref.timestamp = ".time().";\n". + "calendarPref.timezoneOffset = ".date("Z").";\n". + "calendarPref.timeScale = '".Application_Model_Preference::GetCalendarTimeScale()."';\n". + "calendarPref.timeInterval = ".Application_Model_Preference::GetCalendarTimeInterval().";\n". + "calendarPref.weekStartDay = ".Application_Model_Preference::GetWeekStartDay().";\n". + "var calendarEvents = null;" + ); + } + + public function eventFeedAction() + { + $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, $editable); + $this->view->events = $events; + } + + public function eventFeedPreloadAction() + { + $userInfo = Zend_Auth::getInstance()->getStorage()->read(); + $user = new Application_Model_User($userInfo->id); + $editable = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER)); + + $calendar_interval = Application_Model_Preference::GetCalendarTimeScale(); + Logging::info($calendar_interval); + if ($calendar_interval == "agendaDay") { + list($start, $end) = Application_Model_Show::getStartEndCurrentDayView(); + } else if ($calendar_interval == "agendaWeek") { + list($start, $end) = Application_Model_Show::getStartEndCurrentWeekView(); + } else if ($calendar_interval == "month") { + list($start, $end) = Application_Model_Show::getStartEndCurrentMonthView(); + } else { + Logging::error("Invalid Calendar Interval '$calendar_interval'"); + } + + $events = &Application_Model_Show::getFullCalendarEvents($start, $end, $editable); + $this->view->events = $events; + } + + public function getCurrentShowAction() + { + $currentShow = Application_Model_Show::getCurrentShow(); + if (!empty($currentShow)) { + $this->view->si_id = $currentShow[0]["instance_id"]; + $this->view->current_show = true; + } else { + $this->view->current_show = false; + } + } + + public function moveShowAction() + { + $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); + } + + if (isset($error)) { + $this->view->error = $error; + } + } + + public function resizeShowAction() + { + $deltaDay = $this->_getParam('day'); + $deltaMin = $this->_getParam('min'); + $showId = $this->_getParam('showId'); + + $userInfo = Zend_Auth::getInstance()->getStorage()->read(); + $user = new Application_Model_User($userInfo->id); + + if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) { + try { + $show = new Application_Model_Show($showId); + } catch (Exception $e) { + $this->view->show_error = true; + + return false; + } + $error = $show->resizeShow($deltaDay, $deltaMin); + } + + if (isset($error)) { + $this->view->error = $error; + } + } + + public function deleteShowAction() + { + $showInstanceId = $this->_getParam('id'); + + $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) { + Logging::info($e->getMessage()); + $this->view->show_error = true; + + return false; + } + + $showInstance->delete(); + + $this->view->show_id = $showInstance->getShowId(); + } + } + + public function uploadToSoundCloudAction() + { + $show_instance = $this->_getParam('id'); + try { + $show_inst = new Application_Model_ShowInstance($show_instance); + } catch (Exception $e) { + $this->view->show_error = true; + + return false; + } + + $file = $show_inst->getRecordedFile(); + $id = $file->getId(); + Application_Model_Soundcloud::uploadSoundcloud($id); + // we should die with ui info + $this->_helper->json->sendJson(null); + } + + public function makeContextMenuAction() + { + $id = $this->_getParam('id'); + $menu = array(); + $epochNow = time(); + $baseUrl = Application_Common_OsPath::getBaseDir(); + + $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; + + 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; + } + + public function clearShowAction() + { + $showInstanceId = $this->_getParam('id'); + $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->clearShow(); + } + + public function getCurrentPlaylistAction() + { + $range = Application_Model_Schedule::GetPlayOrderRange(); + $show = Application_Model_Show::getCurrentShow(); + + /* Convert all UTC times to localtime before sending back to user. */ + if (isset($range["previous"])) { + $range["previous"]["starts"] = Application_Common_DateHelper::ConvertToLocalDateTimeString($range["previous"]["starts"]); + $range["previous"]["ends"] = Application_Common_DateHelper::ConvertToLocalDateTimeString($range["previous"]["ends"]); + } + if (isset($range["current"])) { + $range["current"]["starts"] = Application_Common_DateHelper::ConvertToLocalDateTimeString($range["current"]["starts"]); + $range["current"]["ends"] = Application_Common_DateHelper::ConvertToLocalDateTimeString($range["current"]["ends"]); + } + if (isset($range["next"])) { + $range["next"]["starts"] = Application_Common_DateHelper::ConvertToLocalDateTimeString($range["next"]["starts"]); + $range["next"]["ends"] = Application_Common_DateHelper::ConvertToLocalDateTimeString($range["next"]["ends"]); + } + + Application_Model_Show::convertToLocalTimeZone($range["currentShow"], array("starts", "ends", "start_timestamp", "end_timestamp")); + Application_Model_Show::convertToLocalTimeZone($range["nextShow"], array("starts", "ends", "start_timestamp", "end_timestamp")); + + $source_status = array(); + $switch_status = array(); + $live_dj = Application_Model_Preference::GetSourceStatus("live_dj"); + $master_dj = Application_Model_Preference::GetSourceStatus("master_dj"); + + $scheduled_play_switch = Application_Model_Preference::GetSourceSwitchStatus("scheduled_play"); + $live_dj_switch = Application_Model_Preference::GetSourceSwitchStatus("live_dj"); + $master_dj_switch = Application_Model_Preference::GetSourceSwitchStatus("master_dj"); + + //might not be the correct place to implement this but for now let's just do it here + $source_status['live_dj_source'] = $live_dj; + $source_status['master_dj_source'] = $master_dj; + $this->view->source_status = $source_status; + + $switch_status['live_dj_source'] = $live_dj_switch; + $switch_status['master_dj_source'] = $master_dj_switch; + $switch_status['scheduled_play'] = $scheduled_play_switch; + $this->view->switch_status = $switch_status; + + $this->view->entries = $range; + $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'); + try { + $show = new Application_Model_ShowInstance($showInstanceId); + } catch (Exception $e) { + $this->view->show_error = true; + + return false; + } + + $originalShowId = $show->isRebroadcast(); + if (!is_null($originalShowId)) { + try { + $originalShow = new Application_Model_ShowInstance($originalShowId); + } catch (Exception $e) { + $this->view->show_error = true; + + return false; + } + $originalShowName = $originalShow->getName(); + $originalShowStart = $originalShow->getShowInstanceStart(); + + //convert from UTC to user's timezone for display. + $originalDateTime = new DateTime($originalShowStart, new DateTimeZone("UTC")); + $originalDateTime->setTimezone(new DateTimeZone(date_default_timezone_get())); + //$timestamp = Application_Common_DateHelper::ConvertToLocalDateTimeString($originalDateTime->format("Y-m-d H:i:s")); + $this->view->additionalShowInfo = + sprintf(_("Rebroadcast of show %s from %s at %s"), + $originalShowName, + $originalDateTime->format("l, F jS"), + $originalDateTime->format("G:i")); + } + $this->view->showLength = $show->getShowLength(); + $this->view->timeFilled = $show->getTimeScheduled(); + $this->view->percentFilled = $show->getPercentScheduled(); + $this->view->showContent = $show->getShowListContent(); + $this->view->dialog = $this->view->render('schedule/show-content-dialog.phtml'); + $this->view->showTitle = htmlspecialchars($show->getName()); + 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(); + + $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; + + $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->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); + + $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; + } + + // 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) { + $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(); + + $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(); + } + + if (!$isAdminOrPM) { + $formWhat->disable(); + $formWho->disable(); + $formWhen->disable(); + $formRepeats->disable(); + $formStyle->disable(); + } + + $this->view->newForm = $this->view->render('schedule/add-show-form.phtml'); + $this->view->entries = 5; + } + + public function getFormAction() + { + $user = Application_Model_User::getCurrentUser(); + + if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) { + Application_Model_Schedule::createNewFormSections($this->view); + $this->view->form = $this->view->render('schedule/add-show-form.phtml'); + } + } + + public function djEditShowAction() + { + $js = $this->_getParam('data'); + $data = array(); + + //need to convert from serialized jQuery array. + foreach ($js as $j) { + $data[$j["name"]] = $j["value"]; + } + + //update cc_show + $show = new Application_Model_Show($data["add_show_id"]); + $show->setAirtimeAuthFlag($data["cb_airtime_auth"]); + $show->setCustomAuthFlag($data["cb_custom_auth"]); + $show->setCustomUsername($data["custom_username"]); + $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 + $js = $this->_getParam('data'); + $data = array(); + + //need to convert from serialized jQuery array. + foreach ($js as $j) { + $data[$j["name"]] = $j["value"]; + } + + $data['add_show_hosts'] = $this->_getParam('hosts'); + $data['add_show_day_check'] = $this->_getParam('days'); + + if ($data['add_show_day_check'] == "") { + $data['add_show_day_check'] = null; + } + + $show = new Application_Model_Show($data['add_show_id']); + + $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"); + + 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 ($show->isRepeating()) { + $nextFutureRepeatShow = $show->getNextFutureRepeatShowTime(); + $originalShowStartDateTime = $nextFutureRepeatShow["starts"]; + } else { + $originalShowStartDateTime = Application_Common_DateHelper::ConvertToLocalDateTime( + $show->getStartDateAndTime()); + } + + $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 { + 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 addShowAction() + { + $js = $this->_getParam('data'); + $data = array(); + + //need to convert from serialized jQuery array. + foreach ($js as $j) { + $data[$j["name"]] = $j["value"]; + } + + $data['add_show_hosts'] = $this->_getParam('hosts'); + $data['add_show_day_check'] = $this->_getParam('days'); + + if ($data['add_show_day_check'] == "") { + $data['add_show_day_check'] = null; + } + + $validateStartDate = true; + $success = Application_Model_Schedule::addUpdateShow($data, $this, + $validateStartDate); + + 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'); + Logging::debug("Show creation failed"); + } + } + + public function cancelShowAction() + { + $user = Application_Model_User::getCurrentUser(); + + if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) { + $showInstanceId = $this->_getParam('id'); + + 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(); + } + } + + public function cancelCurrentShowAction() + { + $user = Application_Model_User::getCurrentUser(); + + if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) { + $id = $this->_getParam('id'); + + try { + $scheduler = new Application_Model_Scheduler(); + $scheduler->cancelShow($id); + Application_Model_StoredFile::updatePastFilesIsScheduled(); + // send kick out source stream signal to pypo + $data = array("sourcename"=>"live_dj"); + Application_Model_RabbitMq::SendMessageToPypo("disconnect_source", $data); + } catch (Exception $e) { + $this->view->error = $e->getMessage(); + Logging::info($e->getMessage()); + } + } + } + + public function contentContextMenuAction() + { + $id = $this->_getParam('id'); + + $params = '/format/json/id/#id#/'; + + $paramsPop = str_replace('#id#', $id, $params); + + // added for downlaod + $id = $this->_getParam('id'); + + $file_id = $this->_getParam('id', null); + $file = Application_Model_StoredFile::Recall($file_id); + + $baseUrl = $this->getRequest()->getBaseUrl(); + $url = $file->getRelativeFileUrl($baseUrl).'download/true'; + $menu[] = array('action' => array('type' => 'gourl', 'url' => $url), + 'title' => _('Download')); + + //returns format jjmenu is looking for. + $this->_helper->json->sendJson($menu); + } + + /** + * Sets the user specific preference for which time scale to use in Calendar. + * This is only being used by schedule.js at the moment. + */ + public function setTimeScaleAction() + { + Application_Model_Preference::SetCalendarTimeScale($this->_getParam('timeScale')); + } + +/** + * Sets the user specific preference for which time interval to use in Calendar. + * This is only being used by schedule.js at the moment. + */ + public function setTimeIntervalAction() + { + Application_Model_Preference::SetCalendarTimeInterval($this->_getParam('timeInterval')); + } + + 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"; + } + + echo Zend_Json::encode($result); + exit(); + } + + public function updateFutureIsScheduledAction() + { + $schedId = $this->_getParam('schedId'); + $redrawLibTable = Application_Model_StoredFile::setIsScheduled($schedId, false); + $this->_helper->json->sendJson(array("redrawLibTable" => $redrawLibTable)); + } +} diff --git a/airtime_mvc/application/models/Schedule.php b/airtime_mvc/application/models/Schedule.php index 1aac2566e..2778074d2 100644 --- a/airtime_mvc/application/models/Schedule.php +++ b/airtime_mvc/application/models/Schedule.php @@ -960,7 +960,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(); @@ -1005,7 +1005,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). @@ -1140,13 +1140,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); @@ -1156,18 +1156,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(); diff --git a/airtime_mvc/application/models/_old_Schedule.php b/airtime_mvc/application/models/_old_Schedule.php new file mode 100644 index 000000000..1aac2566e --- /dev/null +++ b/airtime_mvc/application/models/_old_Schedule.php @@ -0,0 +1,1329 @@ + NOW() AT TIME ZONE 'UTC' +SQL; + $count = Application_Common_Database::prepareAndExecute( $sql, array( + ':file_id'=>$p_fileId), 'column'); + return (is_numeric($count) && ($count != '0')); + } + + public static function getAllFutureScheduledFiles() + { + $con = Propel::getConnection(); + $sql = << now() AT TIME ZONE 'UTC' +AND file_id is not null +SQL; + $files = $con->query($sql)->fetchAll(); + $real_files = array(); + foreach ($files as $f) { + $real_files[] = $f['file_id']; + } + + return $real_files; + } + + public static function getAllFutureScheduledWebstreams() + { + $con = Propel::getConnection(); + $sql = << now() AT TIME ZONE 'UTC' +AND stream_id is not null +SQL; + $streams = $con->query($sql)->fetchAll(); + $real_streams = array(); + foreach ($streams as $s) { + $real_streams[] = $s['stream_id']; + } + + return $real_streams; + } + /** + * Returns data related to the scheduled items. + * + * @param int $p_prev + * @param int $p_next + * @return date + */ + public static function GetPlayOrderRange($p_prev = 1, $p_next = 1) + { + if (!is_int($p_prev) || !is_int($p_next)) { + //must enter integers to specify ranges + Logging::info("Invalid range parameters: $p_prev or $p_next"); + + return array(); + } + + $date = new Application_Common_DateHelper; + $timeNow = $date->getTimestamp(); + $utcTimeNow = $date->getUtcTimestamp(); + + $shows = Application_Model_Show::getPrevCurrentNext($utcTimeNow); + $previousShowID = count($shows['previousShow'])>0?$shows['previousShow'][0]['instance_id']:null; + $currentShowID = count($shows['currentShow'])>0?$shows['currentShow'][0]['instance_id']:null; + $nextShowID = count($shows['nextShow'])>0?$shows['nextShow'][0]['instance_id']:null; + $results = self::GetPrevCurrentNext($previousShowID, $currentShowID, $nextShowID, $utcTimeNow); + + $range = array("env"=>APPLICATION_ENV, + "schedulerTime"=>$timeNow, + "previous"=>$results['previous'] !=null?$results['previous']:(count($shows['previousShow'])>0?$shows['previousShow'][0]:null), + "current"=>$results['current'] !=null?$results['current']:((count($shows['currentShow'])>0 && $shows['currentShow'][0]['record'] == 1)?$shows['currentShow'][0]:null), + "next"=> $results['next'] !=null?$results['next']:(count($shows['nextShow'])>0?$shows['nextShow'][0]:null), + "currentShow"=>$shows['currentShow'], + "nextShow"=>$shows['nextShow'], + "timezone"=> date("T"), + "timezoneOffset"=> date("Z") + ); + + return $range; + } + + /** + * Queries the database for the set of schedules one hour before + * and after the given time. If a show starts and ends within that + * time that is considered the current show. Then the scheduled item + * before it is the previous show, and the scheduled item after it + * is the next show. This way the dashboard getCurrentPlaylist is + * very fast. But if any one of the three show types are not found + * through this mechanism a call is made to the old way of querying + * the database to find the track info. + **/ + public static function GetPrevCurrentNext($p_previousShowID, $p_currentShowID, $p_nextShowID, $p_timeNow) + { + if ($p_previousShowID == null && $p_currentShowID == null && $p_nextShowID == null) { + return; + } + + $sql = "SELECT %%columns%% st.starts as starts, st.ends as ends, + st.media_item_played as media_item_played, si.ends as show_ends + %%tables%% WHERE "; + + $fileColumns = "ft.artist_name, ft.track_title, "; + $fileJoin = "FROM cc_schedule st JOIN cc_files ft ON st.file_id = ft.id + LEFT JOIN cc_show_instances si ON st.instance_id = si.id"; + + $streamColumns = "ws.name AS artist_name, wm.liquidsoap_data AS track_title, "; + $streamJoin = << $rows[$i]["show_ends"]) { + $rows[$i]['ends'] = $rows[$i]["show_ends"]; + } + + if ((strtotime($rows[$i]['starts']) <= $timeNowAsMillis) && (strtotime($rows[$i]['ends']) >= $timeNowAsMillis)) { + if ($i - 1 >= 0) { + $results['previous'] = array("name"=>$rows[$i-1]["artist_name"]." - ".$rows[$i-1]["track_title"], + "starts"=>$rows[$i-1]["starts"], + "ends"=>$rows[$i-1]["ends"], + "type"=>'track'); + } + $results['current'] = array("name"=>$rows[$i]["artist_name"]." - ".$rows[$i]["track_title"], + "starts"=>$rows[$i]["starts"], + "ends"=> (($rows[$i]["ends"] > $rows[$i]["show_ends"]) ? $rows[$i]["show_ends"]: $rows[$i]["ends"]), + "media_item_played"=>$rows[$i]["media_item_played"], + "record"=>0, + "type"=>'track'); + if (isset($rows[$i+1])) { + $results['next'] = array("name"=>$rows[$i+1]["artist_name"]." - ".$rows[$i+1]["track_title"], + "starts"=>$rows[$i+1]["starts"], + "ends"=>$rows[$i+1]["ends"], + "type"=>'track'); + } + break; + } + if (strtotime($rows[$i]['ends']) < $timeNowAsMillis ) { + $previousIndex = $i; + } + if (strtotime($rows[$i]['starts']) > $timeNowAsMillis) { + $results['next'] = array("name"=>$rows[$i]["artist_name"]." - ".$rows[$i]["track_title"], + "starts"=>$rows[$i]["starts"], + "ends"=>$rows[$i]["ends"], + "type"=>'track'); + break; + } + } + //If we didn't find a a current show because the time didn't fit we may still have + //found a previous show so use it. + if ($results['previous'] === null && isset($previousIndex)) { + $results['previous'] = array("name"=>$rows[$previousIndex]["artist_name"]." - ".$rows[$previousIndex]["track_title"], + "starts"=>$rows[$previousIndex]["starts"], + "ends"=>$rows[$previousIndex]["ends"]);; + } + + return $results; + } + + public static function GetLastScheduleItem($p_timeNow) + { + $sql = <<= sit.starts + AND st.starts < sit.ends +ORDER BY st.ends DESC LIMIT 1; +SQL; + $row = Application_Common_Database::prepareAndExecute($sql, array(':timeNow'=>$p_timeNow)); + + return $row; + } + + public static function GetCurrentScheduleItem($p_timeNow, $p_instanceId) + { + /* Note that usually there will be one result returned. In some + * rare cases two songs are returned. This happens when a track + * that was overbooked from a previous show appears as if it + * hasnt ended yet (track end time hasn't been reached yet). For + * this reason, we need to get the track that starts later, as + * this is the *real* track that is currently playing. So this + * is why we are ordering by track start time. */ + $sql = "SELECT *" + ." FROM cc_schedule st" + ." LEFT JOIN cc_files ft" + ." ON st.file_id = ft.id" + ." WHERE st.starts <= TIMESTAMP :timeNow1" + ." AND st.instance_id = :instanceId" + ." AND st.ends > TIMESTAMP :timeNow2" + ." ORDER BY st.starts DESC" + ." LIMIT 1"; + + $row = Application_Common_Database::prepareAndExecute($sql, array(':timeNow1'=>$p_timeNow, ':instanceId'=>$p_instanceId, ':timeNow2'=>$p_timeNow,)); + + return $row; + } + + public static function GetNextScheduleItem($p_timeNow) + { + $sql = "SELECT" + ." ft.artist_name, ft.track_title," + ." st.starts as starts, st.ends as ends" + ." FROM cc_schedule st" + ." LEFT JOIN cc_files ft" + ." ON st.file_id = ft.id" + ." LEFT JOIN cc_show_instances sit" + ." ON st.instance_id = sit.id" + ." WHERE st.starts > TIMESTAMP :timeNow" + ." AND st.starts >= sit.starts" //this and the next line are necessary since we can overbook shows. + ." AND st.starts < sit.ends" + ." ORDER BY st.starts" + ." LIMIT 1"; + + $row = Application_Common_Database::prepareAndExecute($sql, array(':timeNow'=>$p_timeNow)); + + return $row; + } + + /* + * + * @param DateTime $p_startDateTime + * + * @param DateTime $p_endDateTime + * + * @return array $scheduledItems + * + */ + public static function GetScheduleDetailItems($p_start, $p_end, $p_shows) + { + $con = Propel::getConnection(); + + $p_start_str = $p_start->format("Y-m-d H:i:s"); + $p_end_str = $p_end->format("Y-m-d H:i:s"); + + + //We need to search 24 hours before and after the show times so that that we + //capture all of the show's contents. + $p_track_start= $p_start->sub(new DateInterval("PT24H"))->format("Y-m-d H:i:s"); + $p_track_end = $p_end->add(new DateInterval("PT24H"))->format("Y-m-d H:i:s"); + + $templateSql = <<= '{$p_track_start}' + AND sched.starts < '{$p_track_end}') + OR (sched.ends > '{$p_track_start}' + AND sched.ends <= '{$p_track_end}') + OR (sched.starts <= '{$p_track_start}' + AND sched.ends >= '{$p_track_end}')) + ) +SQL; + + + $filesSql = str_replace("%%columns%%", + $filesColumns, + $templateSql); + $filesSql= str_replace("%%join%%", + $filesJoin, + $filesSql); + + $streamColumns = <<= '{$p_track_start}' + AND sched.starts < '{$p_track_end}') + OR (sched.ends > '{$p_track_start}' + AND sched.ends <= '{$p_track_end}') + OR (sched.starts <= '{$p_track_start}' + AND sched.ends >= '{$p_track_end}')) + ) + LEFT JOIN cc_subjs AS sub ON (ws.creator_id = sub.id) +SQL; + + $streamSql = str_replace("%%columns%%", + $streamColumns, + $templateSql); + $streamSql = str_replace("%%join%%", + $streamJoin, + $streamSql); + + + $showPredicate = ""; + if (count($p_shows) > 0) { + $showPredicate = " AND show_id IN (".implode(",", $p_shows).")"; + } + + $sql = <<= '{$p_start_str}' + AND si.starts < '{$p_end_str}') + OR (si.ends > '{$p_start_str}' + AND si.ends <= '{$p_end_str}') + OR (si.starts <= '{$p_start_str}' + AND si.ends >= '{$p_end_str}')) +ORDER BY si_starts, + sched_starts; +SQL; + + $rows = $con->query($sql)->fetchAll(PDO::FETCH_ASSOC); + + return $rows; + } + + public static function UpdateMediaPlayedStatus($p_id) + { + $con = Propel::getConnection(); + $sql = "UPDATE cc_schedule" + ." SET media_item_played=TRUE"; + // we need to update 'broadcasted' column as well + // check the current switch status + $live_dj = Application_Model_Preference::GetSourceSwitchStatus('live_dj') == 'on'; + $master_dj = Application_Model_Preference::GetSourceSwitchStatus('master_dj') == 'on'; + $scheduled_play = Application_Model_Preference::GetSourceSwitchStatus('scheduled_play') == 'on'; + + if (!$live_dj && !$master_dj && $scheduled_play) { + $sql .= ", broadcasted=1"; + } + + $sql .= " WHERE id=$p_id"; + + $retVal = $con->exec($sql); + + return $retVal; + } + + public static function UpdateBrodcastedStatus($dateTime, $value) + { + $now = $dateTime->format("Y-m-d H:i:s"); + + $sql = <<= :ends::TIMESTAMP +SQL; + + $retVal = Application_Common_Database::prepareAndExecute($sql, array( + ':broadcastedValue' => $value, + ':starts' => $now, + ':ends' => $now), 'execute'); + return $retVal; + } + + public static function getSchduledPlaylistCount() + { + $con = Propel::getConnection(); + $sql = "SELECT count(*) as cnt FROM cc_schedule"; + + return $con->query($sql)->fetchColumn(0); + } + + /** + * Convert a time string in the format "YYYY-MM-DD HH:mm:SS" + * to "YYYY-MM-DD-HH-mm-SS". + * + * @param string $p_time + * @return string + */ + private static function AirtimeTimeToPypoTime($p_time) + { + $p_time = substr($p_time, 0, 19); + $p_time = str_replace(" ", "-", $p_time); + $p_time = str_replace(":", "-", $p_time); + + return $p_time; + } + + /** + * Convert a time string in the format "YYYY-MM-DD-HH-mm-SS" to + * "YYYY-MM-DD HH:mm:SS". + * + * @param string $p_time + * @return string + */ + private static function PypoTimeToAirtimeTime($p_time) + { + $t = explode("-", $p_time); + + return $t[0]."-".$t[1]."-".$t[2]." ".$t[3].":".$t[4].":00"; + } + + /** + * Return true if the input string is in the format YYYY-MM-DD-HH-mm + * + * @param string $p_time + * @return boolean + */ + public static function ValidPypoTimeFormat($p_time) + { + $t = explode("-", $p_time); + if (count($t) != 5) { + return false; + } + foreach ($t as $part) { + if (!is_numeric($part)) { + return false; + } + } + + return true; + } + + /** + * Converts a time value as a string (with format HH:MM:SS.mmmmmm) to + * millisecs. + * + * @param string $p_time + * @return int + */ + public static function WallTimeToMillisecs($p_time) + { + $t = explode(":", $p_time); + $millisecs = 0; + if (strpos($t[2], ".")) { + $secParts = explode(".", $t[2]); + $millisecs = $secParts[1]; + $millisecs = str_pad(substr($millisecs, 0, 3),3, '0'); + $millisecs = intval($millisecs); + $seconds = intval($secParts[0]); + } else { + $seconds = intval($t[2]); + } + $ret = $millisecs + ($seconds * 1000) + ($t[1] * 60 * 1000) + ($t[0] * 60 * 60 * 1000); + + return $ret; + } + + /** + * Compute the difference between two times in the format . + * "HH:MM:SS.mmmmmm" Note: currently only supports calculating . + * millisec differences . + * + * @param string $p_time1 + * @param string $p_time2 + * @return double + */ + private static function TimeDiff($p_time1, $p_time2) + { + $parts1 = explode(".", $p_time1); + $parts2 = explode(".", $p_time2); + $diff = 0; + if ( (count($parts1) > 1) && (count($parts2) > 1) ) { + $millisec1 = substr($parts1[1], 0, 3); + $millisec1 = str_pad($millisec1, 3, "0"); + $millisec1 = intval($millisec1); + $millisec2 = substr($parts2[1], 0, 3); + $millisec2 = str_pad($millisec2, 3, "0"); + $millisec2 = intval($millisec2); + $diff = abs($millisec1 - $millisec2)/1000; + } + + return $diff; + } + + /** + * Returns an array of schedule items from cc_schedule table. Tries + * to return at least 3 items (if they are available). The parameters + * $p_startTime and $p_endTime specify the range. Schedule items returned + * do not have to be entirely within this range. It is enough that the end + * or beginning of the scheduled item is in the range. + * + * + * @param string $p_startTime + * In the format YYYY-MM-DD HH:MM:SS.nnnnnn + * @param string $p_endTime + * In the format YYYY-MM-DD HH:MM:SS.nnnnnn + * @return array + * Returns null if nothing found, else an array of associative + * arrays representing each row. + */ + public static function getItems($p_startTime, $p_endTime) + { + $baseQuery = << :startTime1 + AND st.starts < :endTime + AND st.playout_status > 0 + AND si.ends > :startTime2 + AND si.modified_instance = 'f' +ORDER BY st.starts +SQL; + + $sql = $baseQuery." ".$predicates; + + $rows = Application_Common_Database::prepareAndExecute($sql, array( + ':startTime1' => $p_startTime, + ':endTime' => $p_endTime, + ':startTime2' => $p_startTime)); + + if (count($rows) < 3) { + $dt = new DateTime("@".time()); + $dt->add(new DateInterval("PT24H")); + $range_end = $dt->format("Y-m-d H:i:s"); + + $predicates = << :startTime1 + AND st.starts < :rangeEnd + AND st.playout_status > 0 + AND si.ends > :startTime2 + AND si.modified_instance = 'f' +ORDER BY st.starts LIMIT 3 +SQL; + + $sql = $baseQuery." ".$predicates." "; + $rows = Application_Common_Database::prepareAndExecute($sql, + array( + ':startTime1' => $p_startTime, + ':rangeEnd' => $range_end, + ':startTime2' => $p_startTime)); + } + + return $rows; + } + + /** + * This function will ensure that an existing index in the + * associative array is never overwritten, instead appending + * _0, _1, _2, ... to the end of the key to make sure it is unique + */ + private static function appendScheduleItem(&$data, $time, $item) + { + $key = $time; + $i = 0; + + while (array_key_exists($key, $data["media"])) { + $key = "{$time}_{$i}"; + $i++; + } + + $data["media"][$key] = $item; + } + + private static function createInputHarborKickTimes(&$data, $range_start, $range_end) + { + $utcTimeZone = new DateTimeZone("UTC"); + $kick_times = Application_Model_ShowInstance::GetEndTimeOfNextShowWithLiveDJ($range_start, $range_end); + foreach ($kick_times as $kick_time_info) { + $kick_time = $kick_time_info['ends']; + $temp = explode('.', Application_Model_Preference::GetDefaultTransitionFade()); + // we round down transition time since PHP cannot handle millisecond. We need to + // handle this better in the future + $transition_time = intval($temp[0]); + $switchOffDataTime = new DateTime($kick_time, $utcTimeZone); + $switch_off_time = $switchOffDataTime->sub(new DateInterval('PT'.$transition_time.'S')); + $switch_off_time = $switch_off_time->format("Y-m-d H:i:s"); + + $kick_start = self::AirtimeTimeToPypoTime($kick_time); + $data["media"][$kick_start]['start'] = $kick_start; + $data["media"][$kick_start]['end'] = $kick_start; + $data["media"][$kick_start]['event_type'] = "kick_out"; + $data["media"][$kick_start]['type'] = "event"; + $data["media"][$kick_start]['independent_event'] = true; + + if ($kick_time !== $switch_off_time) { + $switch_start = self::AirtimeTimeToPypoTime($switch_off_time); + $data["media"][$switch_start]['start'] = $switch_start; + $data["media"][$switch_start]['end'] = $switch_start; + $data["media"][$switch_start]['event_type'] = "switch_off"; + $data["media"][$switch_start]['type'] = "event"; + $data["media"][$switch_start]['independent_event'] = true; + } + } + } + + private static function createFileScheduleEvent(&$data, $item, $media_id, $uri) + { + $start = self::AirtimeTimeToPypoTime($item["start"]); + $end = self::AirtimeTimeToPypoTime($item["end"]); + + list(,,,$start_hour,,) = explode("-", $start); + list(,,,$end_hour,,) = explode("-", $end); + + $same_hour = $start_hour == $end_hour; + $independent_event = !$same_hour; + + $replay_gain = is_null($item["replay_gain"]) ? "0": $item["replay_gain"]; + $replay_gain += Application_Model_Preference::getReplayGainModifier(); + + if ( !Application_Model_Preference::GetEnableReplayGain() ) { + $replay_gain = 0; + } + + $schedule_item = array( + 'id' => $media_id, + 'type' => 'file', + 'row_id' => $item["id"], + 'uri' => $uri, + 'fade_in' => Application_Model_Schedule::WallTimeToMillisecs($item["fade_in"]), + 'fade_out' => Application_Model_Schedule::WallTimeToMillisecs($item["fade_out"]), + 'cue_in' => Application_Common_DateHelper::CalculateLengthInSeconds($item["cue_in"]), + 'cue_out' => Application_Common_DateHelper::CalculateLengthInSeconds($item["cue_out"]), + 'start' => $start, + 'end' => $end, + 'show_name' => $item["show_name"], + 'replay_gain' => $replay_gain, + 'independent_event' => $independent_event, + ); + + if ($schedule_item['cue_in'] > $schedule_item['cue_out']) { + $schedule_item['cue_in'] = $schedule_item['cue_out']; + } + self::appendScheduleItem($data, $start, $schedule_item); + } + + private static function createStreamScheduleEvent(&$data, $item, $media_id, $uri) + { + $start = self::AirtimeTimeToPypoTime($item["start"]); + $end = self::AirtimeTimeToPypoTime($item["end"]); + + //create an event to start stream buffering 5 seconds ahead of the streams actual time. + $buffer_start = new DateTime($item["start"], new DateTimeZone('UTC')); + $buffer_start->sub(new DateInterval("PT5S")); + + $stream_buffer_start = self::AirtimeTimeToPypoTime($buffer_start->format("Y-m-d H:i:s")); + + $schedule_item = array( + 'start' => $stream_buffer_start, + 'end' => $stream_buffer_start, + 'uri' => $uri, + 'row_id' => $item["id"], + 'type' => 'stream_buffer_start', + 'independent_event' => true + ); + + self::appendScheduleItem($data, $start, $schedule_item); + + $schedule_item = array( + 'id' => $media_id, + 'type' => 'stream_output_start', + 'row_id' => $item["id"], + 'uri' => $uri, + 'start' => $start, + 'end' => $end, + 'show_name' => $item["show_name"], + 'row_id' => $item["id"], + 'independent_event' => true + ); + self::appendScheduleItem($data, $start, $schedule_item); + + //since a stream never ends we have to insert an additional "kick stream" event. The "start" + //time of this event is the "end" time of the stream minus 1 second. + $dt = new DateTime($item["end"], new DateTimeZone('UTC')); + $dt->sub(new DateInterval("PT1S")); + + $stream_end = self::AirtimeTimeToPypoTime($dt->format("Y-m-d H:i:s")); + + $schedule_item = array( + 'start' => $stream_end, + 'end' => $stream_end, + 'uri' => $uri, + 'type' => 'stream_buffer_end', + 'row_id' => $item["id"], + 'independent_event' => true + ); + self::appendScheduleItem($data, $stream_end, $schedule_item); + + $schedule_item = array( + 'start' => $stream_end, + 'end' => $stream_end, + 'uri' => $uri, + 'type' => 'stream_output_end', + 'independent_event' => true + ); + self::appendScheduleItem($data, $stream_end, $schedule_item); + } + + private static function getRangeStartAndEnd($p_fromDateTime, $p_toDateTime) + { + $CC_CONFIG = Config::getConfig(); + + /* if $p_fromDateTime and $p_toDateTime function parameters are null, + then set range * from "now" to "now + 24 hours". */ + if (is_null($p_fromDateTime)) { + $t1 = new DateTime("@".time()); + $range_start = $t1->format("Y-m-d H:i:s"); + } else { + $range_start = Application_Model_Schedule::PypoTimeToAirtimeTime($p_fromDateTime); + } + if (is_null($p_fromDateTime)) { + $t2 = new DateTime("@".time()); + + $cache_ahead_hours = $CC_CONFIG["cache_ahead_hours"]; + + if (is_numeric($cache_ahead_hours)) { + //make sure we are not dealing with a float + $cache_ahead_hours = intval($cache_ahead_hours); + } else { + $cache_ahead_hours = 1; + } + + $t2->add(new DateInterval("PT".$cache_ahead_hours."H")); + $range_end = $t2->format("Y-m-d H:i:s"); + } else { + $range_end = Application_Model_Schedule::PypoTimeToAirtimeTime($p_toDateTime); + } + + return array($range_start, $range_end); + } + + + private static function createScheduledEvents(&$data, $range_start, $range_end) + { + $utcTimeZone = new DateTimeZone("UTC"); + $items = self::getItems($range_start, $range_end); + foreach ($items as $item) { + $showEndDateTime = new DateTime($item["show_end"], $utcTimeZone); + + $trackStartDateTime = new DateTime($item["start"], $utcTimeZone); + $trackEndDateTime = new DateTime($item["end"], $utcTimeZone); + + if ($trackStartDateTime->getTimestamp() > $showEndDateTime->getTimestamp()) { + //do not send any tracks that start past their show's end time + continue; + } + + if ($trackEndDateTime->getTimestamp() > $showEndDateTime->getTimestamp()) { + $di = $trackStartDateTime->diff($showEndDateTime); + + $item["cue_out"] = $di->format("%H:%i:%s").".000"; + $item["end"] = $showEndDateTime->format("Y-m-d H:i:s"); + } + + if (!is_null($item['file_id'])) { + //row is from "file" + $media_id = $item['file_id']; + $storedFile = Application_Model_StoredFile::Recall($media_id); + $uri = $storedFile->getFilePath(); + self::createFileScheduleEvent($data, $item, $media_id, $uri); + } elseif (!is_null($item['stream_id'])) { + //row is type "webstream" + $media_id = $item['stream_id']; + $uri = $item['url']; + self::createStreamScheduleEvent($data, $item, $media_id, $uri); + } else { + throw new Exception("Unknown schedule type: ".print_r($item, true)); + } + + } + } + + /* Check if two events are less than or equal to 1 second apart + */ + public static function areEventsLinked($event1, $event2) { + $dt1 = DateTime::createFromFormat("Y-m-d-H-i-s", $event1['start']); + $dt2 = DateTime::createFromFormat("Y-m-d-H-i-s", $event2['start']); + + $seconds = $dt2->getTimestamp() - $dt1->getTimestamp(); + return $seconds <= 1; + } + + /** + * Streams are a 4 stage process. + * 1) start buffering stream 5 seconds ahead of its start time + * 2) at the start time tell liquidsoap to switch to this source + * 3) at the end time, tell liquidsoap to stop reading this stream + * 4) at the end time, tell liquidsoap to switch away from input.http source. + * + * When we have two streams back-to-back, some of these steps are unnecessary + * for the second stream. Instead of sending commands 1,2,3,4,1,2,3,4 we should + * send 1,2,1,2,3,4 - We don't need to tell liquidsoap to stop reading (#3), because #1 + * of the next stream implies this when we pass in a new url. We also don't need #4. + * + * There's a special case here is well. When the back-to-back streams are the same, we + * can collapse the instructions 1,2,(3,4,1,2),3,4 to 1,2,3,4. We basically cut out the + * middle part. This function handles this. + */ + private static function foldData(&$data) + { + $previous_key = null; + $previous_val = null; + $previous_previous_key = null; + $previous_previous_val = null; + $previous_previous_previous_key = null; + $previous_previous_previous_val = null; + foreach ($data as $k => $v) { + + if ($v["type"] == "stream_output_start" + && !is_null($previous_previous_val) + && $previous_previous_val["type"] == "stream_output_end" + && self::areEventsLinked($previous_previous_val, $v)) { + + unset($data[$previous_previous_previous_key]); + unset($data[$previous_previous_key]); + unset($data[$previous_key]); + if ($previous_previous_val['uri'] == $v['uri']) { + unset($data[$k]); + } + } + + $previous_previous_previous_key = $previous_previous_key; + $previous_previous_previous_val = $previous_previous_val; + $previous_previous_key = $previous_key; + $previous_previous_val = $previous_val; + $previous_key = $k; + $previous_val = $v; + } + } + + public static function getSchedule($p_fromDateTime = null, $p_toDateTime = null) + { + list($range_start, $range_end) = self::getRangeStartAndEnd($p_fromDateTime, $p_toDateTime); + + $data = array(); + $data["media"] = array(); + + //Harbor kick times *MUST* be ahead of schedule events, so that pypo + //executes them first. + self::createInputHarborKickTimes($data, $range_start, $range_end); + self::createScheduledEvents($data, $range_start, $range_end); + + self::foldData($data["media"]); + return $data; + } + + public static function deleteAll() + { + $con = Propel::getConnection(); + $con->exec("TRUNCATE TABLE cc_schedule"); + } + + public static function deleteWithFileId($fileId) + { + $sql = "DELETE FROM cc_schedule WHERE file_id=:file_id"; + Application_Common_Database::prepareAndExecute($sql, array(':file_id'=>$fileId), 'execute'); + } + + public static function createNewFormSections($p_view) + { + $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(); + + $formWhat->removeDecorator('DtDdWrapper'); + $formWho->removeDecorator('DtDdWrapper'); + $formWhen->removeDecorator('DtDdWrapper'); + $formRepeats->removeDecorator('DtDdWrapper'); + $formStyle->removeDecorator('DtDdWrapper'); + $formLive->removeDecorator('DtDdWrapper'); + + $p_view->what = $formWhat; + $p_view->when = $formWhen; + $p_view->repeats = $formRepeats; + $p_view->who = $formWho; + $p_view->style = $formStyle; + $p_view->live = $formLive; + + $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"))); + + $formRecord = new Application_Form_AddShowRR(); + $formAbsoluteRebroadcast = new Application_Form_AddShowAbsoluteRebroadcastDates(); + $formRebroadcast = new Application_Form_AddShowRebroadcastDates(); + + $formRecord->removeDecorator('DtDdWrapper'); + $formAbsoluteRebroadcast->removeDecorator('DtDdWrapper'); + $formRebroadcast->removeDecorator('DtDdWrapper'); + + $p_view->rr = $formRecord; + $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). + * There is still lots of clean-up to do. For example we shouldn't be passing $controller into + * this method to manipulate the view (this should be done inside the controller function). With + * 2.1 deadline looming, this is OK for now. -Martin */ + public static function updateShowInstance($data, $controller) + { + $formWhat = new Application_Form_AddShowWhat(); + $formWhen = new Application_Form_AddShowWhen(); + $formRepeats = new Application_Form_AddShowRepeats(); + $formWho = new Application_Form_AddShowWho(); + $formStyle = new Application_Form_AddShowStyle(); + $formLive = new Application_Form_AddShowLiveStream(); + + $formWhat->removeDecorator('DtDdWrapper'); + $formWhen->removeDecorator('DtDdWrapper'); + $formRepeats->removeDecorator('DtDdWrapper'); + $formWho->removeDecorator('DtDdWrapper'); + $formStyle->removeDecorator('DtDdWrapper'); + $formLive->removeDecorator('DtDdWrapper'); + + $formRecord = new Application_Form_AddShowRR(); + $formAbsoluteRebroadcast = new Application_Form_AddShowAbsoluteRebroadcastDates(); + $formRebroadcast = new Application_Form_AddShowRebroadcastDates(); + + $formRecord->removeDecorator('DtDdWrapper'); + $formAbsoluteRebroadcast->removeDecorator('DtDdWrapper'); + $formRebroadcast->removeDecorator('DtDdWrapper'); + $when = $formWhen->isValid($data); + + if ($when && $formWhen->checkReliantFields($data, true, null, true)) { + $start_dt = new DateTime($data['add_show_start_date']." ".$data['add_show_start_time'], + new DateTimeZone(date_default_timezone_get())); + $start_dt->setTimezone(new DateTimeZone('UTC')); + + $end_dt = new DateTime($data['add_show_end_date_no_repeat']." ".$data['add_show_end_time'], + new DateTimeZone(date_default_timezone_get())); + $end_dt->setTimezone(new DateTimeZone('UTC')); + + $ccShowInstance = CcShowInstancesQuery::create()->findPK($data["add_show_instance_id"]); + $ccShowInstance->setDbStarts($start_dt); + $ccShowInstance->setDbEnds($end_dt); + $ccShowInstance->save(); + + Application_Model_Schedule::createNewFormSections($controller->view); + + return true; + } else { + $formWhat->disable(); + $formWhen->disableRepeatCheckbox(); + $formRepeats->disable(); + $formWho->disable(); + $formStyle->disable(); + //$formLive->disable(); + + $controller->view->what = $formWhat; + $controller->view->when = $formWhen; + $controller->view->repeats = $formRepeats; + $controller->view->who = $formWho; + $controller->view->style = $formStyle; + $controller->view->live = $formLive; + $controller->view->rr = $formRecord; + $controller->view->absoluteRebroadcast = $formAbsoluteRebroadcast; + $controller->view->rebroadcast = $formRebroadcast; + + //$formRecord->disable(); + //$formAbsoluteRebroadcast->disable(); + //$formRebroadcast->disable(); + + return false; + } + } + + /* This function is responsible for handling the case where the entire show (not a single show instance) + * was edited (via the context menu in the Calendar). + * There is still lots of clean-up to do. For example we shouldn't be passing $controller into + * this method to manipulate the view (this should be done inside the controller function). With + * 2.1 deadline looming, this is OK for now. + * Another clean-up is to move all the form manipulation to the proper form class..... + * -Martin + */ + public static function addUpdateShow($data, $controller, $validateStartDate, + $originalStartDate=null, $update=false, $instanceId=null) + { + $userInfo = Zend_Auth::getInstance()->getStorage()->read(); + $user = new Application_Model_User($userInfo->id); + $isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER)); + + $record = false; + + $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(); + + $formWhat->removeDecorator('DtDdWrapper'); + $formWho->removeDecorator('DtDdWrapper'); + $formWhen->removeDecorator('DtDdWrapper'); + $formRepeats->removeDecorator('DtDdWrapper'); + $formStyle->removeDecorator('DtDdWrapper'); + $formLive->removeDecorator('DtDdWrapper'); + + $what = $formWhat->isValid($data); + $when = $formWhen->isValid($data); + $live = $formLive->isValid($data); + if ($when) { + $when = $formWhen->checkReliantFields($data, $validateStartDate, $originalStartDate, $update, $instanceId); + } + + //The way the following code works is that is parses the hour and + //minute from a string with the format "1h 20m" or "2h" or "36m". + //So we are detecting whether an hour or minute value exists via strpos + //and then parse appropriately. A better way to do this in the future is + //actually pass the format from javascript in the format hh:mm so we don't + //have to do this extra String parsing. + $hPos = strpos($data["add_show_duration"], 'h'); + $mPos = strpos($data["add_show_duration"], 'm'); + + $hValue = 0; + $mValue = 0; + + if ($hPos !== false) { + $hValue = trim(substr($data["add_show_duration"], 0, $hPos)); + } + if ($mPos !== false) { + $hPos = $hPos === false ? 0 : $hPos+1; + $mValue = trim(substr($data["add_show_duration"], $hPos, -1 )); + } + + $data["add_show_duration"] = $hValue.":".$mValue; + + $formRecord = new Application_Form_AddShowRR(); + $formAbsoluteRebroadcast = new Application_Form_AddShowAbsoluteRebroadcastDates(); + $formRebroadcast = new Application_Form_AddShowRebroadcastDates(); + + $formRecord->removeDecorator('DtDdWrapper'); + $formAbsoluteRebroadcast->removeDecorator('DtDdWrapper'); + $formRebroadcast->removeDecorator('DtDdWrapper'); + + + $record = $formRecord->isValid($data); + + if ($data["add_show_repeats"]) { + $repeats = $formRepeats->isValid($data); + if ($repeats) { + $repeats = $formRepeats->checkReliantFields($data); + } + $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; + } + } else { + $repeats = 1; + $formRebroadcast->reset(); + //make it valid, results don't matter anyways. + $rebroad = 1; + + if ($data["add_show_rebroadcast"]) { + $rebroadAb = $formAbsoluteRebroadcast->isValid($data); + if ($rebroadAb) { + $rebroadAb = $formAbsoluteRebroadcast->checkReliantFields($data); + } + } else { + $rebroadAb = 1; + } + } + + $who = $formWho->isValid($data); + $style = $formStyle->isValid($data); + if ($what && $when && $repeats && $who && $style && $live) { + if ($record && $rebroadAb && $rebroad) { + if ($isAdminOrPM) { + Application_Model_Show::create($data); + } + + //send back a new form for the user. + Application_Model_Schedule::createNewFormSections($controller->view); + + //$controller->view->newForm = $controller->view->render('schedule/add-show-form.phtml'); + return true; + } else { + $controller->view->what = $formWhat; + $controller->view->when = $formWhen; + $controller->view->repeats = $formRepeats; + $controller->view->who = $formWho; + $controller->view->style = $formStyle; + $controller->view->rr = $formRecord; + $controller->view->absoluteRebroadcast = $formAbsoluteRebroadcast; + $controller->view->rebroadcast = $formRebroadcast; + $controller->view->live = $formLive; + //$controller->view->addNewShow = !$editShow; + + //$controller->view->form = $controller->view->render('schedule/add-show-form.phtml'); + return false; + + } + } else { + $controller->view->what = $formWhat; + $controller->view->when = $formWhen; + $controller->view->repeats = $formRepeats; + $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->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) + { + $overlapping = false; + + $params = array( + ':show_end1' => $show_end->format('Y-m-d H:i:s'), + ':show_end2' => $show_end->format('Y-m-d H:i:s'), + ':show_end3' => $show_end->format('Y-m-d H:i:s') + ); + + + /* If a show is being edited, exclude it from the query + * In both cases (new and edit) we only grab shows that + * are scheduled 2 days prior + */ + if ($update) { + $sql = <<= (date(:show_end3) - INTERVAL '2 days') + AND modified_instance = FALSE +SQL; + if (is_null($showId)) { + $sql .= <<= (date(:show_end3) - INTERVAL '2 days') + AND modified_instance = FALSE +ORDER BY ends +SQL; + + $rows = Application_Common_Database::prepareAndExecute($sql, array( + ':show_end1' => $show_end->format('Y-m-d H:i:s'), + ':show_end2' => $show_end->format('Y-m-d H:i:s'), + ':show_end3' => $show_end->format('Y-m-d H:i:s')), 'all'); + } + + foreach ($rows as $row) { + $start = new DateTime($row["starts"], new DateTimeZone('UTC')); + $end = new DateTime($row["ends"], new DateTimeZone('UTC')); + + if ($show_start->getTimestamp() < $end->getTimestamp() && + $show_end->getTimestamp() > $start->getTimestamp()) { + $overlapping = true; + break; + } + } + + return $overlapping; + } + + public static function GetType($p_scheduleId){ + $scheduledItem = CcScheduleQuery::create()->findPK($p_scheduleId); + if ($scheduledItem->getDbFileId() == null) { + return 'webstream'; + } else { + return 'file'; + } + } + + public static function GetFileId($p_scheduleId) + { + $scheduledItem = CcScheduleQuery::create()->findPK($p_scheduleId); + + return $scheduledItem->getDbFileId(); + } + + public static function GetStreamId($p_scheduleId) + { + $scheduledItem = CcScheduleQuery::create()->findPK($p_scheduleId); + + return $scheduledItem->getDbStreamId(); + } +} diff --git a/airtime_mvc/application/services/ScheduleService.php b/airtime_mvc/application/services/ScheduleService.php new file mode 100644 index 000000000..983d1bd6f --- /dev/null +++ b/airtime_mvc/application/services/ScheduleService.php @@ -0,0 +1,90 @@ +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_record"] = $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 array of booleans + */ + public function validateShowForms($forms) + { + + } + + /** + * + * Creates a new show if form data is valid + */ + public function createShow() + { + + } +} \ No newline at end of file From 3e4942122187ed87bf74cf7140096bbc269730ca Mon Sep 17 00:00:00 2001 From: drigato Date: Mon, 25 Feb 2013 09:15:03 -0500 Subject: [PATCH 02/73] Added comments to Schedule Service --- .../application/controllers/ScheduleController.php | 1 + airtime_mvc/application/models/Schedule.php | 7 +++---- airtime_mvc/application/services/ScheduleService.php | 11 ++++++++++- 3 files changed, 14 insertions(+), 5 deletions(-) diff --git a/airtime_mvc/application/controllers/ScheduleController.php b/airtime_mvc/application/controllers/ScheduleController.php index 9ca879918..ae91308e4 100644 --- a/airtime_mvc/application/controllers/ScheduleController.php +++ b/airtime_mvc/application/controllers/ScheduleController.php @@ -871,6 +871,7 @@ class ScheduleController extends Zend_Controller_Action $data[$j["name"]] = $j["value"]; } + // TODO: move this to js $data['add_show_hosts'] = $this->_getParam('hosts'); $data['add_show_day_check'] = $this->_getParam('days'); diff --git a/airtime_mvc/application/models/Schedule.php b/airtime_mvc/application/models/Schedule.php index 2778074d2..36aedf96c 100644 --- a/airtime_mvc/application/models/Schedule.php +++ b/airtime_mvc/application/models/Schedule.php @@ -1220,10 +1220,9 @@ 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; diff --git a/airtime_mvc/application/services/ScheduleService.php b/airtime_mvc/application/services/ScheduleService.php index 983d1bd6f..f5f397561 100644 --- a/airtime_mvc/application/services/ScheduleService.php +++ b/airtime_mvc/application/services/ScheduleService.php @@ -2,6 +2,13 @@ class Application_Service_ScheduleService { +/* + * 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 @@ -78,7 +85,9 @@ class Application_Service_ScheduleService { } - +/* + * Form stuff ends + */ /** * * Creates a new show if form data is valid From 9f0baba4f8c6f7fbbdf5627eeb60d2e5c0961b95 Mon Sep 17 00:00:00 2001 From: denise Date: Mon, 25 Feb 2013 17:31:43 -0500 Subject: [PATCH 03/73] - Moved all form validation to it's own function in schedule service - Moved show creation to it's own function in schedule service --- .../controllers/ScheduleController.php | 29 +++-- .../forms/AddShowAbsoluteRebroadcastDates.php | 8 ++ .../forms/AddShowRebroadcastDates.php | 8 ++ .../application/forms/AddShowRepeats.php | 8 ++ airtime_mvc/application/forms/AddShowWhen.php | 8 ++ airtime_mvc/application/models/Schedule.php | 4 +- airtime_mvc/application/models/Show.php | 32 +++--- .../application/services/ScheduleService.php | 104 +++++++++++++++++- 8 files changed, 167 insertions(+), 34 deletions(-) diff --git a/airtime_mvc/application/controllers/ScheduleController.php b/airtime_mvc/application/controllers/ScheduleController.php index ae91308e4..ea95d4bc7 100644 --- a/airtime_mvc/application/controllers/ScheduleController.php +++ b/airtime_mvc/application/controllers/ScheduleController.php @@ -104,7 +104,7 @@ class ScheduleController extends Zend_Controller_Action $this->view->repeats = $forms["repeats"]; $this->view->live = $forms["live"]; $this->view->rr = $forms["record"]; - $this->view->absoluteRebroadcast = $forms["abs_record"]; + $this->view->absoluteRebroadcast = $forms["abs_rebroadcast"]; $this->view->rebroadcast = $forms["rebroadcast"]; $this->view->who = $forms["who"]; $this->view->style = $forms["style"]; @@ -879,19 +879,26 @@ class ScheduleController extends Zend_Controller_Action $data['add_show_day_check'] = null; } - $validateStartDate = true; - $success = Application_Model_Schedule::addUpdateShow($data, $this, - $validateStartDate); + $forms = $this->service_schedule->createShowForms(); - if ($success) { - $this->view->addNewShow = true; - $this->view->newForm = $this->view->render( - 'schedule/add-show-form.phtml'); + $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"]; + + $this->view->addNewShow = true; + + if ($this->service_schedule->validateShowForms($forms, $data)) { + $this->view->newForm = $this->view->render('schedule/add-show-form.phtml'); + $this->service_schedule->createShow($data); 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"); } } 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..375942894 100644 --- a/airtime_mvc/application/forms/AddShowRepeats.php +++ b/airtime_mvc/application/forms/AddShowRepeats.php @@ -66,6 +66,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..9f73affbd 100644 --- a/airtime_mvc/application/forms/AddShowWhen.php +++ b/airtime_mvc/application/forms/AddShowWhen.php @@ -87,6 +87,14 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm } + public function isWhenFormValid($formData, $validateStartDate) { + if (parent::isValid($formData)) { + return self::checkReliantFields($formData, $validateStartDate); + } else { + return false; + } + } + public function checkReliantFields($formData, $validateStartDate, $originalStartDate=null, $update=false, $instanceId=null) { $valid = true; diff --git a/airtime_mvc/application/models/Schedule.php b/airtime_mvc/application/models/Schedule.php index 36aedf96c..6b19c5e3d 100644 --- a/airtime_mvc/application/models/Schedule.php +++ b/airtime_mvc/application/models/Schedule.php @@ -1088,7 +1088,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(); @@ -1227,7 +1227,7 @@ SQL; //$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) diff --git a/airtime_mvc/application/models/Show.php b/airtime_mvc/application/models/Show.php index f485e41bc..493f3ca37 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,28 @@ 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) { - $ccShow = new CcShow(); + /*$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,11 +1162,11 @@ 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) { $show = new Application_Model_Show($showId); @@ -1178,7 +1180,7 @@ SQL; } //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,7 +1217,7 @@ 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. diff --git a/airtime_mvc/application/services/ScheduleService.php b/airtime_mvc/application/services/ScheduleService.php index f5f397561..1204f689c 100644 --- a/airtime_mvc/application/services/ScheduleService.php +++ b/airtime_mvc/application/services/ScheduleService.php @@ -43,7 +43,7 @@ class Application_Service_ScheduleService $forms["style"] = $formStyle; $forms["live"] = $formLive; $forms["record"] = $formRecord; - $forms["abs_record"] = $formAbsoluteRebroadcast; + $forms["abs_rebroadcast"] = $formAbsoluteRebroadcast; $forms["rebroadcast"] = $formRebroadcast; return $forms; @@ -79,21 +79,113 @@ class Application_Service_ScheduleService * * Validates show forms * - * @return array of booleans + * @return boolean */ - public function validateShowForms($forms) + public function validateShowForms($forms, $formData, $validateStartDate = true) { - + $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); + + $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; + } + /** * * Creates a new show if form data is valid */ - public function createShow() + public function createShow($showData) { - + $userInfo = Zend_Auth::getInstance()->getStorage()->read(); + $user = new Application_Model_User($userInfo->id); + $isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER)); + + $repeatType = ($showData['add_show_repeats']) ? $showData['add_show_repeat_type'] : -1; + $isRecorded = (isset($showData['add_show_record']) && $showData['add_show_record']) ? 1 : 0; + + $showData["add_show_duration"] = $this->formatShowDuration( + $showData["add_show_duration"]); + + if ($isAdminOrPM) { + $service_show = new Application_Service_ShowService(); + + //create ccShow + $ccShow = new CcShow(); + $ccShow = $service_show->setShow($ccShow, $showData); + + //create ccShowDay + $service_show->createShowDays( + $showData, $ccShow->getDbId(), $user->getId(), $repeatType, $isRecorded); + + //create ccShowHosts + + //create ccShowRebroadcast + + //populate ccShowInstances + } } + } \ No newline at end of file From 2717c0845b47d1c4c9541cfec5e8a5219acc59dc Mon Sep 17 00:00:00 2001 From: denise Date: Tue, 26 Feb 2013 10:20:02 -0500 Subject: [PATCH 04/73] Created show service --- airtime_mvc/application/models/Show.php | 8 +- airtime_mvc/application/models/_old_Show.php | 2241 +++++++++++++++++ .../application/services/ScheduleService.php | 11 +- .../application/services/ShowService.php | 145 ++ 4 files changed, 2397 insertions(+), 8 deletions(-) create mode 100644 airtime_mvc/application/models/_old_Show.php create mode 100644 airtime_mvc/application/services/ShowService.php diff --git a/airtime_mvc/application/models/Show.php b/airtime_mvc/application/models/Show.php index 493f3ca37..d6f9db98b 100644 --- a/airtime_mvc/application/models/Show.php +++ b/airtime_mvc/application/models/Show.php @@ -1229,7 +1229,7 @@ SQL; //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(); @@ -1266,14 +1266,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) { 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(); @@ -1281,7 +1281,7 @@ SQL; $showHost->setDbHost($host); $showHost->save(); } - } + }*/ if ($data['add_show_id'] != -1) { $con = Propel::getConnection(CcSchedulePeer::DATABASE_NAME); diff --git a/airtime_mvc/application/models/_old_Show.php b/airtime_mvc/application/models/_old_Show.php new file mode 100644 index 000000000..f485e41bc --- /dev/null +++ b/airtime_mvc/application/models/_old_Show.php @@ -0,0 +1,2241 @@ +_showId = $showId; + } + + public function getName() + { + $show = CcShowQuery::create()->findPK($this->_showId); + + return $show->getDbName(); + } + + public function setName($name) + { + $show = CcShowQuery::create()->findPK($this->_showId); + $show->setDbName($name); + Application_Model_RabbitMq::PushSchedule(); + } + + public function setAirtimeAuthFlag($flag) + { + $show = CcShowQuery::create()->findPK($this->_showId); + $show->setDbLiveStreamUsingAirtimeAuth($flag); + $show->save(); + } + + public function setCustomAuthFlag($flag) + { + $show = CcShowQuery::create()->findPK($this->_showId); + $show->setDbLiveStreamUsingCustomAuth($flag); + $show->save(); + } + + public function setCustomUsername($username) + { + $show = CcShowQuery::create()->findPK($this->_showId); + $show->setDbLiveStreamUser($username); + $show->save(); + } + + public function setCustomPassword($password) + { + $show = CcShowQuery::create()->findPK($this->_showId); + $show->setDbLiveStreamPass($password); + $show->save(); + } + + public function getDescription() + { + $show = CcShowQuery::create()->findPK($this->_showId); + + return $show->getDbDescription(); + } + + public function setDescription($description) + { + $show = CcShowQuery::create()->findPK($this->_showId); + $show->setDbDescription($description); + } + + public function getColor() + { + $show = CcShowQuery::create()->findPK($this->_showId); + + return $show->getDbColor(); + } + + public function setColor($color) + { + $show = CcShowQuery::create()->findPK($this->_showId); + $show->setDbColor($color); + } + + public function getUrl() + { + $show = CcShowQuery::create()->findPK($this->_showId); + + return $show->getDbUrl(); + } + + /*TODO : This method is not actually used anywhere as far as I can tell. We + can safely remove it and probably many other superfluous methods. + --RG*/ + + public function setUrl($p_url) + { + $show = CcShowQuery::create()->findPK($this->_showId); + $show->setDbUrl($p_url); + } + + public function getGenre() + { + $show = CcShowQuery::create()->findPK($this->_showId); + + return $show->getDbGenre(); + } + + public function setGenre($p_genre) + { + $show = CcShowQuery::create()->findPK($this->_showId); + $show->setDbGenre($p_genre); + } + + public function getBackgroundColor() + { + $show = CcShowQuery::create()->findPK($this->_showId); + + return $show->getDbBackgroundColor(); + } + + public function setBackgroundColor($backgroundColor) + { + $show = CcShowQuery::create()->findPK($this->_showId); + $show->setDbBackgroundColor($backgroundColor); + } + + public function getId() + { + return $this->_showId; + } + + public function getHosts() + { + $sql = << $this->getId() ), 'all'); + + $res = array(); + foreach ($hosts as $host) { + $res[] = $host['first_name']." ".$host['last_name']; + } + return $res; + } + + public function getHostsIds() + { + $sql = << $this->getId() ), 'all'); + + return $hosts; + } + + /** + * remove everything about this show. + */ + public function delete() + { + //usually we hide the show-instance, but in this case we are deleting the show template + //so delete all show-instances as well. + CcShowInstancesQuery::create()->filterByDbOriginalShow($this->_showId)->delete(); + + $show = CcShowQuery::create()->findPK($this->_showId); + $show->delete(); + } + + public function resizeShow($deltaDay, $deltaMin) + { + $con = Propel::getConnection(); + + if ($deltaDay > 0) { + return _("Shows can have a max length of 24 hours."); + } + + $utc = new DateTimeZone("UTC"); + + $nowDateTime = new DateTime("now", $utc); + + $showInstances = CcShowInstancesQuery::create() + ->filterByDbShowId($this->_showId) + ->find($con); + + /* Check two things: + 1. If the show being resized and any of its repeats end in the past + 2. If the show being resized and any of its repeats overlap + with other scheduled shows */ + + foreach ($showInstances as $si) { + $startsDateTime = new DateTime($si->getDbStarts(), new DateTimeZone("UTC")); + $endsDateTime = new DateTime($si->getDbEnds(), new DateTimeZone("UTC")); + + /* 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 local * timestamp and + then converted back to UTC to avoid show time changes */ + $startsDateTime->setTimezone(new DateTimeZone(date_default_timezone_get())); + $endsDateTime->setTimezone(new DateTimeZone(date_default_timezone_get())); + + $newStartsDateTime = Application_Model_ShowInstance::addDeltas($startsDateTime, $deltaDay, $deltaMin); + $newEndsDateTime = Application_Model_ShowInstance::addDeltas($endsDateTime, $deltaDay, $deltaMin); + + if ($newEndsDateTime->getTimestamp() < $nowDateTime->getTimestamp()) { + return _("End date/time cannot be in the past"); + } + + //convert our new starts/ends to UTC. + $newStartsDateTime->setTimezone($utc); + $newEndsDateTime->setTimezone($utc); + + $overlapping = Application_Model_Schedule::checkOverlappingShows( + $newStartsDateTime, $newEndsDateTime, true, $si->getDbId()); + + if ($overlapping) { + return _("Cannot schedule overlapping shows.\nNote: Resizing a repeating show ". + "affects all of its repeats."); + } + } + + $hours = $deltaMin/60; + $hours = ($hours > 0) ? floor($hours) : ceil($hours); + $mins = abs($deltaMin % 60); + + //current timesamp in UTC. + $current_timestamp = gmdate("Y-m-d H:i:s"); + + $sql_gen = << :current_timestamp1) + AND ((ends + :deltaDay2::INTERVAL + :interval2::INTERVAL - starts) <= interval '24:00') +SQL; + + Application_Common_Database::prepareAndExecute($sql_gen, + array( + ':deltaDay1' => "$deltaDay days", + ':interval1' => "$hours:$mins", + ':show_id1' => $this->_showId, + ':current_timestamp1' => $current_timestamp, + ':deltaDay2' => "$deltaDay days", + ':interval2' => "$hours:$mins" + ), "execute"); + + $sql_gen = << "$deltaDay days", + ':interval3' => "$hours:$mins", + ':show_id2' => $this->_showId, + ':deltaDay4' => "$deltaDay days", + ':interval4' => "$hours:$mins" + ), "execute"); + + $con = Propel::getConnection(CcSchedulePeer::DATABASE_NAME); + $con->beginTransaction(); + + try { + //update the status flag in cc_schedule. + + /* Since we didn't use a propel object when updating + * cc_show_instances table we need to clear the instances + * so the correct information is retrieved from the db + */ + CcShowInstancesPeer::clearInstancePool(); + + $instances = CcShowInstancesQuery::create() + ->filterByDbEnds($current_timestamp, Criteria::GREATER_THAN) + ->filterByDbShowId($this->_showId) + ->find($con); + + foreach ($instances as $instance) { + $instance->updateScheduleStatus($con); + } + + $con->commit(); + } catch (Exception $e) { + $con->rollback(); + Logging::info("Couldn't update schedule status."); + Logging::info($e->getMessage()); + } + + Application_Model_RabbitMq::PushSchedule(); + } + + public function cancelShow($day_timestamp) + { + $timeinfo = explode(" ", $day_timestamp); + + CcShowDaysQuery::create() + ->filterByDbShowId($this->_showId) + ->update(array('DbLastShow' => $timeinfo[0])); + + $sql = <<= :dayTimestamp::TIMESTAMP + AND show_id = :showId +SQL; + + $rows = Application_Common_Database::prepareAndExecute( $sql, array( + ':dayTimestamp' => $day_timestamp, + ':showId' => $this->getId()), 'all'); + + foreach ($rows as $row) { + try { + $showInstance = new Application_Model_ShowInstance($row["id"]); + $showInstance->delete($rabbitmqPush = false); + } catch (Exception $e) { + Logging::info($e->getMessage()); + } + } + + Application_Model_RabbitMq::PushSchedule(); + } + + /** + * This function is called when a repeating show is edited and the + * days that is repeats on have changed. More specifically, a day + * that the show originally repeated on has been "unchecked". + * + * Removes Show Instances that occur on days of the week specified + * by input array. For example, if array contains one value of "0", + * (0 = Sunday, 1=Monday) then all show instances that occur on + * Sunday are removed. + * + * @param array p_uncheckedDays + * An array specifying which days should be removed. (in the local timezone) + */ + public function removeUncheckedDaysInstances($p_uncheckedDays) + { + //need to convert local doftw to UTC doftw (change made for 2.0 since shows are stored in UTC) + $daysRemovedUTC = array(); + + $showDays = CcShowDaysQuery::create() + ->filterByDbShowId($this->getId()) + ->find(); + + Logging::info("Unchecked days:"); + foreach ($p_uncheckedDays as $day) { + Logging::info($day); + } + + foreach ($showDays as $showDay) { + //Logging::info("Local show day is: {$showDay->getDbDay()}"); + //Logging::info("First show day is: {$showDay->getDbFirstShow()}"); + //Logging::info("Id show days is: {$showDay->getDbId()}"); + + if (in_array($showDay->getDbDay(), $p_uncheckedDays)) { + $showDay->reload(); + //Logging::info("Local show day is: {$showDay->getDbDay()}"); + //Logging::info("First show day is: {$showDay->getDbFirstShow()}"); + //Logging::info("Id show days is: {$showDay->getDbId()}"); + $startDay = new DateTime("{$showDay->getDbFirstShow()} {$showDay->getDbStartTime()}", new DateTimeZone($showDay->getDbTimezone())); + //Logging::info("Show start day: {$startDay->format('Y-m-d H:i:s')}"); + $startDay->setTimezone(new DateTimeZone("UTC")); + //Logging::info("Show start day UTC: {$startDay->format('Y-m-d H:i:s')}"); + $daysRemovedUTC[] = $startDay->format('w'); + //Logging::info("UTC show day is: {$startDay->format('w')}"); + } + } + + $uncheckedDaysImploded = implode(",", $daysRemovedUTC); + $showId = $this->getId(); + + $esc_uncheckedDays = pg_escape_string($uncheckedDaysImploded); + $timestamp = gmdate("Y-m-d H:i:s"); + + $sql = << :timestamp::TIMESTAMP + AND show_id = :showId +SQL; + + Application_Common_Database::prepareAndExecute( $sql, + array( + ":timestamp" => $timestamp, + ":showId" => $showId, + ), "execute"); + } + + /** + * Check whether the current show originated + * from a recording. + * + * @return boolean + * true if originated from recording, otherwise false. + */ + public function isRecorded() + { + $showInstancesRow = CcShowInstancesQuery::create() + ->filterByDbShowId($this->getId()) + ->filterByDbRecord(1) + ->filterByDbModifiedInstance(false) + ->findOne(); + + return !is_null($showInstancesRow); + } + + /** + * Check whether the current show has rebroadcasts of a recorded + * show. Should be used in conjunction with isRecorded(). + * + * @return boolean + * true if show has rebroadcasts, otherwise false. + */ + public function isRebroadcast() + { + $showInstancesRow = CcShowInstancesQuery::create() + ->filterByDbShowId($this->_showId) + ->filterByDbRebroadcast(1) + ->filterByDbModifiedInstance(false) + ->findOne(); + + return !is_null($showInstancesRow); + } + + /** + * Get start time and absolute start date for a recorded + * shows rebroadcasts. For example start date format would be + * YYYY-MM-DD and time would HH:MM + * + * @return array + * array of associate arrays containing "start_date" and "start_time" + */ + public function getRebroadcastsAbsolute() + { + $sql = << $this->getId() ), 'all' ); + + $rebroadcastsLocal = array(); + //get each rebroadcast show in cc_show_instances, convert to current timezone to get start date/time. + /*TODO: refactor the following code to get rid of the $i temporary + variable. -- RG*/ + $i = 0; + + $utc = new DateTimeZone("UTC"); + $dtz = new DateTimeZone( date_default_timezone_get() ); + + foreach ($rebroadcasts as $show) { + $startDateTime = new DateTime($show["starts"], $utc); + $startDateTime->setTimezone($dtz); + + $rebroadcastsLocal[$i]["start_date"] = + $startDateTime->format("Y-m-d"); + $rebroadcastsLocal[$i]["start_time"] = + $startDateTime->format("H:i"); + + $i = $i + 1; + } + + return $rebroadcastsLocal; + } + + /** + * Get start time and relative start date for a recorded + * shows rebroadcasts. For example start date format would be + * "x days" and time would HH:MM:SS + * + * @return array + * array of associate arrays containing "day_offset" and "start_time" + */ + public function getRebroadcastsRelative() + { + $sql = << $this->getId() ), 'all' ); + } + + /** + * Check whether the current show is set to repeat + * repeating shows. + * + * @return boolean + * true if repeating shows, otherwise false. + */ + public function isRepeating() + { + $showDaysRow = CcShowDaysQuery::create() + ->filterByDbShowId($this->_showId) + ->findOne(); + + if (!is_null($showDaysRow)) { + return ($showDaysRow->getDbRepeatType() != -1); + } else { + return false; + } + } + + /** + * Get the repeat type of the show. Show can have repeat + * type of "weekly", "bi-weekly" and "monthly". These values + * are represented by 0, 1, and 2 respectively. + * + * @return int + * Return the integer corresponding to the repeat type. + */ + public function getRepeatType() + { + $showDaysRow = CcShowDaysQuery::create() + ->filterByDbShowId($this->_showId) + ->findOne(); + + if (!is_null($showDaysRow)) + return $showDaysRow->getDbRepeatType(); + else + return -1; + } + + /** + * Get the end date for a repeating show in the format yyyy-mm-dd + * + * @return string + * Return the end date for the repeating show or the empty + * string if there is no end. + */ + public function getRepeatingEndDate() + { + $sql = << $this->getId() ), 'column' ); + + /* TODO: Why return empty string instead of false? very confusing --RG + */ + return ($query !== false) ? $query : ""; + } + + /** + * Deletes all future instances of the current show object + * from the show_instances table. This function is used when + * a show is being edited - in some cases, when a show is edited + * we just destroy all future show instances, and let another function + * regenerate them later on. Note that this isn't always the most + * desirable thing to do. Deleting a show instance and regenerating + * it cause any scheduled playlists within those show instances to + * be gone for good. + */ + public function deleteAllInstances() + { + $sql = << :timestamp::TIMESTAMP + AND show_id = :showId +SQL; + Application_Common_Database::prepareAndExecute( $sql, + array( ':timestamp' => gmdate("Y-m-d H:i:s"), + ':showId' => $this->getId()), 'execute'); + } + + /** + * Deletes all future rebroadcast instances of the current + * show object from the show_instances table. + */ + public function deleteAllRebroadcasts() + { + $sql = << :timestamp::TIMESTAMP + AND show_id :showId + AND rebroadcast 1 +SQL; + Application_Common_Database::prepareAndExecute( $sql, + array( ':showId' => $this->getId(), + ':timestamp' => gmdate("Y-m-d H:i:s")), 'execute'); + + $con->exec($sql); + } + + /** + * Deletes all show instances of current show after a + * certain date. Note that although not enforced, $p_date + * should never be in the past, as we never want to allow + * deletion of shows that have already occured. + * + * @param string $p_date + * The date which to delete after, if null deletes from the current timestamp. + */ + public function removeAllInstancesFromDate($p_date=null) + { + $con = Propel::getConnection(); + + $timestamp = gmdate("Y-m-d H:i:s"); + + if (is_null($p_date)) { + $date = new Application_Common_DateHelper; + $p_date = $date->getDate(); + } + + $showId = $this->getId(); + $sql = "DELETE FROM cc_show_instances " + ." WHERE date(starts) >= DATE '$p_date'" + ." AND starts > TIMESTAMP '$timestamp'" + ." AND show_id = $showId"; + + $con->exec($sql); + + } + + /** + * Deletes all show instances of current show before a + * certain date. + * + * This function is used in the case where a repeating show is being + * edited and the start date of the first show has been changed more + * into the future. In this case, delete any show instances that + * exist before the new start date. + * + * @param string $p_date + * The date which to delete before + */ + public function removeAllInstancesBeforeDate($p_date) + { + $con = Propel::getConnection(); + + $timestamp = gmdate("Y-m-d H:i:s"); + + $showId = $this->getId(); + $sql = "DELETE FROM cc_show_instances " + ." WHERE date(starts) < DATE '$p_date'" + ." AND starts > TIMESTAMP '$timestamp'" + ." AND show_id = $showId"; + + $con->exec($sql); + } + + public 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->getId() ), 'all' ); + + foreach ($result as $r) { + $show["starts"] = new DateTime($r["starts"], new DateTimeZone('UTC')); + $show["ends"] = new DateTime($r["ends"], new DateTimeZone('UTC')); + } + $currentUser = Application_Model_User::getCurrentUser(); + $currentUserId = $currentUser->getId(); + $userTimezone = Application_Model_Preference::GetUserTimezone($currentUserId); + $show["starts"]->setTimezone(new DateTimeZone($userTimezone)); + $show["ends"]->setTimezone(new DateTimeZone($userTimezone)); + return $show; + } + + /** + * Get the start date of the current show in UTC timezone. + * + * @return string + * The start date in the format YYYY-MM-DD or empty string in case + * start date could not be found + */ + public function getStartDateAndTime() + { + $con = Propel::getConnection(); + + $showId = $this->getId(); + $stmt = $con->prepare( + "SELECT first_show, start_time, timezone FROM cc_show_days" + ." WHERE show_id = :showId" + ." ORDER BY first_show" + ." LIMIT 1"); + + $stmt->bindParam(':showId', $showId); + $stmt->execute(); + + if (!$stmt) { + return ""; + } + + $rows = $stmt->fetchAll(); + $row = $rows[0]; + + $dt = new DateTime($row["first_show"]." ".$row["start_time"], new DateTimeZone($row["timezone"])); + $dt->setTimezone(new DateTimeZone("UTC")); + + return $dt->format("Y-m-d H:i"); + } + + /** + * Get the start date of the current show in UTC timezone. + * + * @return string + * The start date in the format YYYY-MM-DD + */ + public function getStartDate() + { + list($date,) = explode(" ", $this->getStartDateAndTime()); + + return $date; + } + + /** + * Get the start time of the current show in UTC timezone. + * + * @return string + * The start time in the format HH:MM + */ + + public function getStartTime() + { + list(,$time) = explode(" ", $this->getStartDateAndTime()); + + return $time; + } + + /** + * Get the end date of the current show. + * Note that this is not the end date of repeated show + * + * @return string + * The end date in the format YYYY-MM-DD + */ + public function getEndDate() + { + $startDate = $this->getStartDate(); + $startTime = $this->getStartTime(); + $duration = $this->getDuration(); + + $startDateTime = new DateTime($startDate.' '.$startTime); + $duration = explode(":", $duration); + + $endDate = $startDateTime->add(new DateInterval('PT'.$duration[0].'H'.$duration[1].'M')); + + return $endDate->format('Y-m-d'); + } + + /** + * Get the end time of the current show. + * + * @return string + * The start time in the format HH:MM:SS + */ + public function getEndTime() + { + $startDate = $this->getStartDate(); + $startTime = $this->getStartTime(); + $duration = $this->getDuration(); + + $startDateTime = new DateTime($startDate.' '.$startTime); + $duration = explode(":", $duration); + + $endDate = $startDateTime->add(new DateInterval('PT'.$duration[0].'H'.$duration[1].'M')); + + return $endDate->format('H:i:s'); + } + + /** + * Indicate whether the starting point of the show is in the + * past. + * + * @return boolean + * true if the StartDate is in the past, false otherwise + */ + public function isStartDateTimeInPast() + { + $date = new Application_Common_DateHelper; + $current_timestamp = $date->getUtcTimestamp(); + + return ($current_timestamp > ($this->getStartDate()." ".$this->getStartTime())); + } + + /** + * Get the ID's of future instance of the current show. + * + * @return array + * A simple array containing all ID's of show instance + * scheduled in the future. + */ + public function getAllFutureInstanceIds() + { + $sql = << :timestamp::TIMESTAMP + AND modified_instance != TRUE +SQL; + $rows = Application_Common_Database::prepareAndExecute($sql, + array( ':showId' => $this->getId(), + ':timestamp' => gmdate("Y-m-d H:i:s")), "all"); + + $res = array(); + foreach ($rows as $r) { + $res[] = $r['id']; + } + return $res; + } + + /* Called when a show's duration is changed (edited). + * + * @param array $p_data + * array containing the POST data about the show from the + * browser. + * + */ + private function updateDurationTime($p_data) + { + //need to update cc_show_instances, cc_show_days + $con = Propel::getConnection(); + + $date = new Application_Common_DateHelper; + $timestamp = $date->getUtcTimestamp(); + + $stmt = $con->prepare("UPDATE cc_show_days " + ."SET duration = :add_show_duration " + ."WHERE show_id = :add_show_id" ); + $stmt->execute( array( + ':add_show_duration' => $p_data['add_show_duration'], + ':add_show_id' => $p_data['add_show_id'] + )); + + + $sql = << :timestamp::TIMESTAMP +SQL; + + Application_Common_Database::prepareAndExecute( $sql, array( + ':add_show_duration' => $p_data['add_show_duration'], + ':show_id' => $p_data['add_show_id'], + ':timestamp' => $timestamp), "execute"); + } + + private function updateStartDateTime($p_data, $p_endDate) + { + //need to update cc_schedule, cc_show_instances, cc_show_days + $con = Propel::getConnection(); + + $date = new Application_Common_DateHelper; + $timestamp = $date->getTimestamp(); + + //TODO fix this from overwriting info. + $sql = "UPDATE cc_show_days " + ."SET start_time = TIME '$p_data[add_show_start_time]', " + ."first_show = DATE '$p_data[add_show_start_date]', "; + if (strlen ($p_endDate) == 0) { + $sql .= "last_show = NULL "; + } else { + $sql .= "last_show = DATE '$p_endDate' "; + } + $sql .= "WHERE show_id = $p_data[add_show_id]"; + $con->exec($sql); + + $dtOld = new DateTime($this->getStartDate()." ".$this->getStartTime(), new DateTimeZone("UTC")); + $dtNew = new DateTime($p_data['add_show_start_date']." ".$p_data['add_show_start_time'], new DateTimeZone(date_default_timezone_get())); + $diff = $dtOld->getTimestamp() - $dtNew->getTimestamp(); + + $sql = "UPDATE cc_show_instances " + ."SET starts = starts + INTERVAL '$diff sec', " + ."ends = ends + INTERVAL '$diff sec' " + ."WHERE show_id = $p_data[add_show_id] " + ."AND starts > TIMESTAMP '$timestamp'"; + $con->exec($sql); + + $showInstanceIds = $this->getAllFutureInstanceIds(); + if (count($showInstanceIds) > 0 && $diff != 0) { + $showIdsImploded = implode(",", $showInstanceIds); + $sql = "UPDATE cc_schedule " + ."SET starts = starts + INTERVAL '$diff sec', " + ."ends = ends + INTERVAL '$diff sec' " + ."WHERE instance_id IN ($showIdsImploded)"; + $con->exec($sql); + } + } + + public function getDuration($format=false) + { + $showDay = CcShowDaysQuery::create()->filterByDbShowId($this->getId())->findOne(); + if (!$format) { + return $showDay->getDbDuration(); + } else { + $info = explode(':',$showDay->getDbDuration()); + + return str_pad(intval($info[0]),2,'0',STR_PAD_LEFT).'h '.str_pad(intval($info[1]),2,'0',STR_PAD_LEFT).'m'; + } + } + + public function getShowDays() + { + $showDays = CcShowDaysQuery::create()->filterByDbShowId( + $this->getId())->find(); + $res = array(); + foreach ($showDays as $showDay) { + $res[] = $showDay->getDbDay(); + } + return $res; + } + + /* Only used for shows that aren't repeating. + * + * @return Boolean: true if show has an instance, otherwise false. */ + public function hasInstance() + { + return (!is_null($this->getInstance())); + } + + /* Only used for shows that aren't repeating. + * + * @return CcShowInstancesQuery: An propel object representing a + * row in the cc_show_instances table. */ + public function getInstance() + { + $showInstance = CcShowInstancesQuery::create() + ->filterByDbShowId($this->getId()) + ->findOne(); + + return $showInstance; + } + + /** + * returns info about live stream override info + */ + public function getLiveStreamInfo() + { + $info = array(); + if ($this->getId() == null) { + return $info; + } else { + $ccShow = CcShowQuery::create()->findPK($this->_showId); + $info['custom_username'] = $ccShow->getDbLiveStreamUser(); + $info['cb_airtime_auth'] = $ccShow->getDbLiveStreamUsingAirtimeAuth(); + $info['cb_custom_auth'] = $ccShow->getDbLiveStreamUsingCustomAuth(); + $info['custom_username'] = $ccShow->getDbLiveStreamUser(); + $info['custom_password'] = $ccShow->getDbLiveStreamPass(); + return $info; + } + } + + /* Only used for shows that are repeating. Note that this will return + * true even for dates that only have a "modified" show instance (does not + * check if the "modified_instance" column is set to true). This is intended + * behaviour. + * + * @param $p_dateTime: Date for which we are checking if instance + * exists. + * + * @return Boolean: true if show has an instance on $p_dateTime, + * otherwise false. */ + public function hasInstanceOnDate($p_dateTime) + { + return (!is_null($this->getInstanceOnDate($p_dateTime))); + } + + /* Only used for shows that are repeating. Note that this will return + * shows that have been "modified" (does not check if the "modified_instance" + * column is set to true). This is intended behaviour. + * + * @param $p_dateTime: Date for which we are getting an instance. + * + * @return CcShowInstancesQuery: An propel object representing a + * row in the cc_show_instances table. */ + public function getInstanceOnDate($p_dateTime) + { + $timestamp = $p_dateTime->format("Y-m-d H:i:s"); + $sql = << $this->getId(), + ':timestamp' => $timestamp ), 'column'); + return CcShowInstancesQuery::create() + ->findPk($row); + } catch (Exception $e) { + return null; + } + + } + + public function deletePossiblyInvalidInstances($p_data, $p_endDate, $isRecorded, $repeatType) + { + if ($p_data['add_show_repeats'] != $this->isRepeating()) { + //repeat option was toggled + $this->deleteAllInstances(); + } + + if ($p_data['add_show_duration'] != $this->getDuration()) { + //duration has changed + $this->updateDurationTime($p_data); + } + + if ($p_data['add_show_repeats']) { + if (($repeatType == 1 || $repeatType == 2) && + $p_data['add_show_start_date'] != $this->getStartDate()){ + + //start date has changed when repeat type is bi-weekly or monthly. + //This screws up the repeating positions of show instances, so lets + //just delete them for now. (CC-2351) + + $this->deleteAllInstances(); + } + + if ($repeatType != $this->getRepeatType()) { + //repeat type changed. + $this->deleteAllInstances(); + } else { + //repeat type is the same, check if the days of the week are the same + $repeatingDaysChanged = false; + $showDaysArray = $this->getShowDays(); + if (count($p_data['add_show_day_check']) == count($showDaysArray)) { + //same number of days checked, lets see if they are the same numbers + $intersect = array_intersect($p_data['add_show_day_check'], $showDaysArray); + if (count($intersect) != count($p_data['add_show_day_check'])) { + $repeatingDaysChanged = true; + } + } else { + $repeatingDaysChanged = true; + } + + if ($repeatingDaysChanged) { + $daysRemoved = array_diff($showDaysArray, $p_data['add_show_day_check']); + + if (count($daysRemoved) > 0) { + + $this->removeUncheckedDaysInstances($daysRemoved); + } + } + + if ($p_data['add_show_start_date'] != $this->getStartDate() + || $p_data['add_show_start_time'] != $this->getStartTime()){ + //start date/time has changed + + $newDate = strtotime($p_data['add_show_start_date']); + $oldDate = strtotime($this->getStartDate()); + if ($newDate > $oldDate) { + $this->removeAllInstancesBeforeDate($p_data['add_show_start_date']); + } + + $this->updateStartDateTime($p_data, $p_endDate); + } + } + + //Check if end date for the repeat option has changed. If so, need to take care + //of deleting possible invalid Show Instances. + if ((strlen($this->getRepeatingEndDate()) == 0) == $p_data['add_show_no_end']) { + //show "Never Ends" option was toggled. + if ($p_data['add_show_no_end']) { + } else { + $this->removeAllInstancesFromDate($p_endDate); + } + } + if ($this->getRepeatingEndDate() != $p_data['add_show_end_date']) { + //end date was changed. + + $newDate = strtotime($p_data['add_show_end_date']); + $oldDate = strtotime($this->getRepeatingEndDate()); + if ($newDate < $oldDate) { + $this->removeAllInstancesFromDate($p_endDate); + } + } + } + } + + /** + * Create a show. + * + * Note: end dates are non inclusive. + * + * @param array $data + * @return int + * Show ID + */ + 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')); + + if ($data['add_show_no_end']) { + $endDate = NULL; + } elseif ($data['add_show_repeats']) { + $endDateTime = new DateTime($data['add_show_end_date']); + //$endDateTime->setTimezone(new DateTimeZone('UTC')); + $endDateTime->add(new DateInterval("P1D")); + $endDate = $endDateTime->format("Y-m-d"); + } else { + $endDateTime = new DateTime($data['add_show_start_date']); + //$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()); + 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; + + 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->setDbDescription($data['add_show_description']); + $ccShow->setDbUrl($data['add_show_url']); + $ccShow->setDbGenre($data['add_show_genre']); + $ccShow->setDbColor($data['add_show_color']); + $ccShow->setDbBackgroundColor($data['add_show_background_color']); + $ccShow->setDbLiveStreamUsingAirtimeAuth($data['cb_airtime_auth'] == 1); + $ccShow->setDbLiveStreamUsingCustomAuth($data['cb_custom_auth'] == 1); + $ccShow->setDbLiveStreamUser($data['custom_username']); + $ccShow->setDbLiveStreamPass($data['custom_password']); + $ccShow->save(); + + $showId = $ccShow->getDbId(); + + $isRecorded = (isset($data['add_show_record']) && $data['add_show_record']) ? 1 : 0; + + if ($data['add_show_id'] != -1) { + $show = new Application_Model_Show($showId); + $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) { + 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) { + $showDay = new CcShowDays(); + $showDay->setDbFirstShow($startDateTime->format("Y-m-d")); + $showDay->setDbLastShow($endDate); + $showDay->setDbStartTime($startDateTime->format("H:i:s")); + $showDay->setDbTimezone(date_default_timezone_get()); + $showDay->setDbDuration($data['add_show_duration']); + $showDay->setDbRepeatType($repeatType); + $showDay->setDbShowId($showId); + $showDay->setDbRecord($isRecorded); + $showDay->save(); + } else { + foreach ($data['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(date_default_timezone_get()); + $showDay->setDbDuration($data['add_show_duration']); + $showDay->setDbDay($day); + $showDay->setDbRepeatType($repeatType); + $showDay->setDbShowId($showId); + $showDay->setDbRecord($isRecorded); + $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']) { + 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)) { + for ($i=1; $i<=10; $i++) { + if ($data['add_show_rebroadcast_date_'.$i]) { + $showRebroad = new CcShowRebroadcast(); + $showRebroad->setDbDayOffset($data['add_show_rebroadcast_date_'.$i]); + $showRebroad->setDbStartTime($data['add_show_rebroadcast_time_'.$i]); + $showRebroad->setDbShowId($showId); + $showRebroad->save(); + } + } + } elseif ($isRecorded && $data['add_show_rebroadcast'] && ($repeatType == -1)) { + for ($i=1; $i<=10; $i++) { + if ($data['add_show_rebroadcast_date_absolute_'.$i]) { + //$con = Propel::getConnection(CcShowPeer::DATABASE_NAME); + //$sql = "SELECT date '{$data['add_show_rebroadcast_date_absolute_'.$i]}' - date '{$data['add_show_start_date']}' "; + $sql = << + $data["add_show_rebroadcast_date_absolute_$i"], + 'start' => + $data['add_show_start_date']), "column" ); + + //$r = $con->query($sql); + //$offset_days = $r->fetchColumn(0); + + $showRebroad = new CcShowRebroadcast(); + $showRebroad->setDbDayOffset($offset_days." days"); + $showRebroad->setDbStartTime($data['add_show_rebroadcast_time_absolute_'.$i]); + $showRebroad->setDbShowId($showId); + $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) { + CcShowHostsQuery::create()->filterByDbShow($data['add_show_id'])->delete(); + } + 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(); + $showHost->setDbShow($showId); + $showHost->setDbHost($host); + $showHost->save(); + } + } + + if ($data['add_show_id'] != -1) { + $con = Propel::getConnection(CcSchedulePeer::DATABASE_NAME); + $con->beginTransaction(); + + + //current timesamp in UTC. + $current_timestamp = gmdate("Y-m-d H:i:s"); + + try { + //update the status flag in cc_schedule. + $instances = CcShowInstancesQuery::create() + ->filterByDbEnds($current_timestamp, Criteria::GREATER_THAN) + ->filterByDbShowId($data['add_show_id']) + ->find($con); + + foreach ($instances as $instance) { + $instance->updateScheduleStatus($con); + } + + $con->commit(); + } catch (Exception $e) { + $con->rollback(); + Logging::info("Couldn't update schedule status."); + Logging::info($e->getMessage()); + } + } + + Application_Model_Show::populateShowUntil($showId); + Application_Model_RabbitMq::PushSchedule(); + + return $showId; + } + + /** + * Generate repeating show instances for a single show up to the given date. + * It will always try to use enddate from DB but if that's empty, it will use + * time now. + * + * @param int $p_showId + */ + public static function populateShowUntil($p_showId) + { + $con = Propel::getConnection(); + $date = Application_Model_Preference::GetShowsPopulatedUntil(); + + if (is_null($date)) { + $p_populateUntilDateTime = new DateTime("now", new DateTimeZone('UTC')); + Application_Model_Preference::SetShowsPopulatedUntil($p_populateUntilDateTime); + } else { + $p_populateUntilDateTime = $date; + } + + $stmt = $con->prepare("SELECT * FROM cc_show_days WHERE show_id = :show_id"); + $stmt->bindParam(':show_id', $p_showId); + $stmt->execute(); + + $res = $stmt->fetchAll(); + + 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 + * is basically a dispatcher that looks at the show template, and sends it to the correct function + * so that Show Instance generation can begin. After the all show instances have been created, pushes + * the schedule to Pypo. + * + * @param array $p_showRow + * A row from cc_show_days table + * @param DateTime $p_populateUntilDateTime + * DateTime object in UTC time. + */ + 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 + if ($p_showDaysRow["repeat_type"] == -1) { + Application_Model_Show::populateNonRepeatingShow($p_showDaysRow, $p_populateUntilDateTime); + } elseif ($p_showDaysRow["repeat_type"] == 0) { + Application_Model_Show::populateRepeatingShow($p_showDaysRow, $p_populateUntilDateTime, 'P7D'); + } elseif ($p_showDaysRow["repeat_type"] == 1) { + Application_Model_Show::populateRepeatingShow($p_showDaysRow, $p_populateUntilDateTime, 'P14D'); + } elseif ($p_showDaysRow["repeat_type"] == 2) { + 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 + * rebroadcast dates, and so this function will create those as well. + * + * @param array $p_showRow + * A row from cc_show_days table + * @param DateTime $p_populateUntilDateTime + * DateTime object in UTC time. + */ + private static function populateNonRepeatingShow($p_showRow, $p_populateUntilDateTime) + { + $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"]; + $record = $p_showRow["record"]; + $timezone = $p_showRow["timezone"]; + $start = $first_show." ".$start_time; + + //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"); + + $show = new Application_Model_Show($show_id); + if ($show->hasInstance()) { + $ccShowInstance = $show->getInstance(); + $newInstance = false; + } else { + $ccShowInstance = new CcShowInstances(); + $newInstance = true; + } + + 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); + + if (!$newInstance) { + $showInstance->correctScheduleStartTimes(); + } + + $sql = "SELECT * FROM cc_show_rebroadcast WHERE show_id=:show_id"; + $rebroadcasts = Application_Common_Database::prepareAndExecute($sql, + array( ':show_id' => $show_id ), 'all'); + + if ($showInstance->isRecorded()) { + $showInstance->deleteRebroadcasts(); + self::createRebroadcastInstances($rebroadcasts, $currentUtcTimestamp, $show_id, $show_instance_id, $start, $duration, $timezone); + } + } + } + + /** + * Creates a 1 or more than 1 show instances (user has stated this show repeats). If the show + * is recorded, it may have multiple rebroadcast dates, and so this function will create + * those as well. + * + * @param array $p_showRow + * A row from cc_show_days table + * @param DateTime $p_populateUntilDateTime + * DateTime object in UTC time. "shows_populated_until" date YY-mm-dd in cc_pref + * @param string $p_interval + * Period of time between repeating shows (in php DateInterval notation 'P7D') + */ + private static function populateRepeatingShow($p_showDaysRow, $p_populateUntilDateTime, $p_interval) + { + $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 + $start_time = $p_showDaysRow["start_time"]; //non-UTC + $duration = $p_showDaysRow["duration"]; + $day = $p_showDaysRow["day"]; + $record = $p_showDaysRow["record"]; + $timezone = $p_showDaysRow["timezone"]; + + $currentUtcTimestamp = gmdate("Y-m-d H:i:s"); + + if (isset($next_pop_date)) { + $start = $next_pop_date." ".$start_time; + } else { + $start = $first_show." ".$start_time; + } + + $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; + + $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); + + while ($utcStartDateTime->getTimestamp() <= $p_populateUntilDateTime->getTimestamp() + && (is_null($utcLastShowDateTime) || $utcStartDateTime->getTimestamp() < $utcLastShowDateTime->getTimestamp())){ + + list($utcStartDateTime, $utcEndDateTime) = self::createUTCStartEndDateTime($start, $duration, $timezone); + + if ($show->hasInstanceOnDate($utcStartDateTime)) { + $ccShowInstance = $show->getInstanceOnDate($utcStartDateTime); + + if ($ccShowInstance->getDbModifiedInstance()) { + //show instance on this date has been deleted. + list($start, $utcStartDateTime) = self::advanceRepeatingDate($p_interval, $start, $timezone); + continue; + } + + $newInstance = false; + } 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) { + $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); + + /* If we are updating a show then make sure that the scheduled content within + * the show is updated to the correct time. */ + if (!$newInstance) { + $showInstance->correctScheduleStartTimes(); + } + + $showInstance->deleteRebroadcasts(); + self::createRebroadcastInstances($rebroadcasts, $currentUtcTimestamp, $show_id, $show_instance_id, $start, $duration, $timezone); + list($start, $utcStartDateTime) = self::advanceRepeatingDate($p_interval, $start, $timezone); + + } + + Application_Model_Show::setNextPop($start, $show_id, $day); + } + + private static function advanceRepeatingDate($p_interval, $start, $timezone) + { + $startDt = new DateTime($start, new DateTimeZone($timezone)); + if ($p_interval == 'P1M') { + /* When adding months, there is a problem if we are on January 31st and add one month with PHP. + * What ends up happening is that since February 31st doesn't exist, the date returned is + * March 3rd. For now let's ignore the day and assume we are always working with the + * first of each month, and use PHP to add 1 month to this (this will take care of rolling + * over the years 2011->2012, etc.). Then let's append the actual day, and use the php + * checkdate() function, to see if it is valid. If not, then we'll just skip this month. */ + + /* pass in only the year and month (not the day) */ + $dt = new DateTime($startDt->format("Y-m"), new DateTimeZone($timezone)); + + + /* Keep adding 1 month, until we find the next month that contains the day + * we are looking for (31st day for example) */ + do { + $dt->add(new DateInterval($p_interval)); + } while (!checkdate($dt->format("m"), $startDt->format("d"), $dt->format("Y"))); + + $dt->setDate($dt->format("Y"), $dt->format("m"), $startDt->format("d")); + + } else { + $dt = new DateTime($start, new DateTimeZone($timezone)); + $dt->add(new DateInterval($p_interval)); + } + + $start = $dt->format("Y-m-d H:i:s"); + + $dt->setTimezone(new DateTimeZone('UTC')); + $utcStartDateTime = $dt; + + return array($start, $utcStartDateTime); + } + + /* + * @param $p_start + * timestring format "Y-m-d H:i:s" (not UTC) + * @param $p_duration + * string time interval (h)h:(m)m(:ss) + * @param $p_timezone + * string "Europe/Prague" + * @param $p_offset + * array (days, hours, mins) used for rebroadcast shows. + * + * @return + * array of 2 DateTime objects, start/end time of the show in UTC. + */ + private static function createUTCStartEndDateTime($p_start, $p_duration, $p_timezone=null, $p_offset=null) + { + $timezone = $p_timezone ? $p_timezone : date_default_timezone_get(); + + $startDateTime = new DateTime($p_start, new DateTimeZone($timezone)); + if (isset($p_offset)) { + $startDateTime->add(new DateInterval("P{$p_offset["days"]}DT{$p_offset["hours"]}H{$p_offset["mins"]}M")); + } + //convert time to UTC + $startDateTime->setTimezone(new DateTimeZone('UTC')); + + $endDateTime = clone $startDateTime; + $duration = explode(":", $p_duration); + list($hours, $mins) = array_slice($duration, 0, 2); + $endDateTime->add(new DateInterval("PT{$hours}H{$mins}M")); + + return array($startDateTime, $endDateTime); + } + + /* Create rebroadcast instances for a created show marked for recording + * + * @param $p_rebroadcasts + * rows gotten from the db table cc_show_rebroadcasts, tells airtime when to schedule the rebroadcasts. + * @param $p_currentUtcTimestamp + * a timestring in format "Y-m-d H:i:s", current UTC time. + * @param $p_showId + * int of the show it belongs to (from cc_show) + * @param $p_showInstanceId + * the instance id of the created recorded show instance + * (from cc_show_instances), used to associate rebroadcasts to this show. + * @param $p_startTime + * a timestring in format "Y-m-d H:i:s" in the timezone, not UTC of the rebroadcasts' parent recorded show. + * @param $p_duration + * string time interval (h)h:(m)m:(ss) length of the show. + * @param $p_timezone + * string of user's timezone "Europe/Prague" + * + */ + private static function createRebroadcastInstances($p_rebroadcasts, $p_currentUtcTimestamp, $p_showId, $p_showInstanceId, $p_startTime, $p_duration, $p_timezone=null) + { + //Y-m-d + //use only the date part of the show start time stamp for the offsets to work properly. + $date = explode(" ", $p_startTime); + $start_date = $date[0]; + + foreach ($p_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) = Application_Model_Show::createUTCStartEndDateTime($start_date, $p_duration, $p_timezone, $offset); + + if ($utcStartDateTime->format("Y-m-d H:i:s") > $p_currentUtcTimestamp) { + + $newRebroadcastInstance = new CcShowInstances(); + $newRebroadcastInstance->setDbShowId($p_showId); + $newRebroadcastInstance->setDbStarts($utcStartDateTime); + $newRebroadcastInstance->setDbEnds($utcEndDateTime); + $newRebroadcastInstance->setDbRecord(0); + $newRebroadcastInstance->setDbRebroadcast(1); + $newRebroadcastInstance->setDbOriginalShow($p_showInstanceId); + $newRebroadcastInstance->save(); + } + } + } + + /** + * Get all the show instances in the given time range (inclusive). + * + * @param DateTime $start_timestamp + * In UTC time. + * @param DateTime $end_timestamp + * In UTC time. + * @param unknown_type $excludeInstance + * @param boolean $onlyRecord + * @return array + */ + public static function getShows($start_timestamp, $end_timestamp, $onlyRecord=FALSE) + { + //UTC DateTime object + $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); + Application_Model_Preference::SetShowsPopulatedUntil($end_timestamp); + } + + $sql = <<format("Y-m-d H:i:s"); + $end_string = $end_timestamp->format("Y-m-d H:i:s"); + if ($onlyRecord) { + $sql .= " AND (si1.starts >= :start::TIMESTAMP AND si1.starts < :end::TIMESTAMP)"; + $sql .= " AND (si1.record = 1)"; + + return Application_Common_Database::prepareAndExecute( $sql, + array( ':start' => $start_string, + ':end' => $end_string ), 'all'); + + } else { + $sql .= " ". <<= :start1::TIMESTAMP AND si1.starts < :end1::TIMESTAMP) + OR (si1.ends > :start2::TIMESTAMP AND si1.ends <= :end2::TIMESTAMP) + OR (si1.starts <= :start3::TIMESTAMP AND si1.ends >= :end3::TIMESTAMP)) +SQL; + return Application_Common_Database::prepareAndExecute( $sql, + array( + 'start1' => $start_string, + 'start2' => $start_string, + 'start3' => $start_string, + 'end1' => $end_string, + 'end2' => $end_string, + 'end3' => $end_string + ), 'all'); + } + } + + private static function setNextPop($next_date, $show_id, $day) + { + $nextInfo = explode(" ", $next_date); + + $repeatInfo = CcShowDaysQuery::create() + ->filterByDbShowId($show_id) + ->filterByDbDay($day) + ->findOne(); + + $repeatInfo->setDbNextPopDate($nextInfo[0]) + ->save(); + } + + /** + * Generate all the repeating shows in the given range. + * + * @param DateTime $p_startTimestamp + * In UTC format. + * @param DateTime $p_endTimestamp + * In UTC format. + */ + public static function populateAllShowsInRange($p_startTimestamp, $p_endTimestamp) + { + $con = Propel::getConnection(); + + $endTimeString = $p_endTimestamp->format("Y-m-d H:i:s"); + if (!is_null($p_startTimestamp)) { + $startTimeString = $p_startTimestamp->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"); + } + + $stmt = $con->prepare(" + SELECT * FROM cc_show_days + WHERE last_show IS NULL + OR first_show < :endTimeString AND last_show > :startTimeString"); + + $stmt->bindParam(':endTimeString', $endTimeString); + $stmt->bindParam(':startTimeString', $startTimeString); + $stmt->execute(); + + $res = $stmt->fetchAll(); + foreach ($res as $row) { + Application_Model_Show::populateShow($row, $p_endTimestamp); + } + } + + /** + * + * @param DateTime $start + * -in UTC time + * @param DateTime $end + * -in UTC time + * @param boolean $editable + */ + public static function &getFullCalendarEvents($p_start, $p_end, $p_editable=false) + { + $events = array(); + $interval = $p_start->diff($p_end); + $days = $interval->format('%a'); + $shows = Application_Model_Show::getShows($p_start, $p_end); + $content_count = Application_Model_ShowInstance::getContentCount( + $p_start, $p_end); + $isFull = Application_Model_ShowInstance::getIsFull($p_start, $p_end); + $timezone = date_default_timezone_get(); + $current_timezone = new DateTimeZone($timezone); + $utc = new DateTimeZone("UTC"); + $now = new DateTime("now", $utc); + + foreach ($shows as &$show) { + $options = array(); + + //only bother calculating percent for week or day view. + if (intval($days) <= 7) { + $options["percent"] = Application_Model_Show::getPercentScheduled($show["starts"], $show["ends"], $show["time_filled"]); + } + + if (isset($show["parent_starts"])) { + $parentStartsDT = new DateTime($show["parent_starts"], $utc); + } + + $startsDT = DateTime::createFromFormat("Y-m-d G:i:s", + $show["starts"],$utc); + $endsDT = DateTime::createFromFormat("Y-m-d G:i:s", + $show["ends"], $utc); + + if( $p_editable ) { + if ($show["record"] && $now > $startsDT) { + $options["editable"] = false; + } elseif ($show["rebroadcast"] && + $now > $parentStartsDT) { + $options["editable"] = false; + } elseif ($now < $endsDT) { + $options["editable"] = true; + } + } + + $startsDT->setTimezone($current_timezone); + $endsDT->setTimezone($current_timezone); + + $options["show_empty"] = (array_key_exists($show['instance_id'], + $content_count)) ? 0 : 1; + + $options["show_partial_filled"] = !$isFull[$show['instance_id']]; + + $event = array(); + + $event["id"] = intval($show["instance_id"]); + $event["title"] = $show["name"]; + $event["start"] = $startsDT->format("Y-m-d H:i:s"); + $event["end"] = $endsDT->format("Y-m-d H:i:s"); + $event["allDay"] = false; + $event["showId"] = intval($show["show_id"]); + $event["record"] = intval($show["record"]); + $event["rebroadcast"] = intval($show["rebroadcast"]); + $event["soundcloud_id"] = is_null($show["soundcloud_id"]) + ? -1 : $show["soundcloud_id"]; + + //event colouring + if ($show["color"] != "") { + $event["textColor"] = "#".$show["color"]; + } + + if ($show["background_color"] != "") { + $event["color"] = "#".$show["background_color"]; + } + + foreach ($options as $key => $value) { + $event[$key] = $value; + } + + $events[] = $event; + } + return $events; + } + + /** + * Calculates the percentage of a show scheduled given the start and end times in date/time format + * and the time_filled as the total time the schow is scheduled for in time format. + **/ + private static function getPercentScheduled($p_starts, $p_ends, $p_time_filled) + { + $durationSeconds = (strtotime($p_ends) - strtotime($p_starts)); + $time_filled = Application_Model_Schedule::WallTimeToMillisecs($p_time_filled) / 1000; + $percent = ceil(( $time_filled / $durationSeconds) * 100); + + return $percent; + } + +/* private static function &makeFullCalendarEvent(&$show, $options=array(), $startDateTime, $endDateTime, $startsEpoch, $endsEpoch) + { + $event = array(); + + $event["id"] = intval($show["instance_id"]); + $event["title"] = $show["name"]; + $event["start"] = $startDateTime->format("Y-m-d H:i:s"); + $event["startUnix"] = $startsEpoch; + $event["end"] = $endDateTime->format("Y-m-d H:i:s"); + $event["endUnix"] = $endsEpoch; + $event["allDay"] = false; + $event["showId"] = intval($show["show_id"]); + $event["record"] = intval($show["record"]); + $event["rebroadcast"] = intval($show["rebroadcast"]); + $event["soundcloud_id"] = is_null($show["soundcloud_id"]) + ? -1 : $show["soundcloud_id"]; + + //event colouring + if ($show["color"] != "") { + $event["textColor"] = "#".$show["color"]; + } + + if ($show["background_color"] != "") { + $event["color"] = "#".$show["background_color"]; + } + + foreach ($options as $key => $value) { + $event[$key] = $value; + } + + return $event; + }*/ + + /* Takes in a UTC DateTime object. + * Converts this to local time, since cc_show days + * requires local time. */ + public function setShowFirstShow($p_dt) + { + //clone object since we are modifying it and it was passed by reference. + $dt = clone $p_dt; + + $dt->setTimezone(new DateTimeZone(date_default_timezone_get())); + + $showDay = CcShowDaysQuery::create() + ->filterByDbShowId($this->_showId) + ->findOne(); + + $showDay->setDbFirstShow($dt)->setDbStartTime($dt) + ->save(); + + //Logging::info("setting show's first show."); + } + + /* Takes in a UTC DateTime object + * Converts this to local time, since cc_show days + * requires local time. */ + public function setShowLastShow($p_dt) + { + //clone object since we are modifying it and it was passed by reference. + $dt = clone $p_dt; + + $dt->setTimezone(new DateTimeZone(date_default_timezone_get())); + + //add one day since the Last Show date in CcShowDays is non-inclusive. + $dt->add(new DateInterval("P1D")); + + $showDay = CcShowDaysQuery::create() + ->filterByDbShowId($this->_showId) + ->findOne(); + + $showDay->setDbLastShow($dt) + ->save(); + } + + /** + * Given time $timeNow, returns the show being played right now. + * Times are all in UTC time. + * + * @param String $timeNow - current time (in UTC) + * @return array - show being played right now + */ + public static function getCurrentShow($timeNow=null) + { + $CC_CONFIG = Config::getConfig(); + $con = Propel::getConnection(); + if ($timeNow == null) { + $date = new Application_Common_DateHelper; + $timeNow = $date->getUtcTimestamp(); + } + //TODO, returning starts + ends twice (once with an alias). Unify this after the 2.0 release. --Martin + $sql = << :timeNow2::timestamp + AND modified_instance != TRUE +SQL; + + $stmt = $con->prepare($sql); + $stmt->bindParam(':timeNow1', $timeNow); + $stmt->bindParam(':timeNow2', $timeNow); + + if ($stmt->execute()) { + $rows = $stmt->fetchAll(); + } else { + $msg = implode(',', $stmt->errorInfo()); + throw new Exception("Error: $msg"); + } + + return $rows; + } + + /** + * Gets the current show, previous and next with an 2day window from + * the given timeNow, so timeNow-2days and timeNow+2days. + */ + public static function getPrevCurrentNext($p_timeNow) + { + $CC_CONFIG = Config::getConfig(); + $con = Propel::getConnection(); + // + //TODO, returning starts + ends twice (once with an alias). Unify this after the 2.0 release. --Martin + $sql = << :timeNow1::timestamp - INTERVAL '2 days' + AND si.ends < :timeNow2::timestamp + INTERVAL '2 days' + AND modified_instance != TRUE +ORDER BY si.starts +SQL; + + $stmt = $con->prepare($sql); + + $stmt->bindValue(':timeNow1', $p_timeNow); + $stmt->bindValue(':timeNow2', $p_timeNow); + + if ($stmt->execute()) { + $rows = $stmt->fetchAll(); + } else { + $msg = implode(',', $stmt->errorInfo()); + throw new Exception("Error: $msg"); + } + + $numberOfRows = count($rows); + + $results['previousShow'] = array(); + $results['currentShow'] = array(); + $results['nextShow'] = array(); + + $timeNowAsMillis = strtotime($p_timeNow); + + for ($i = 0; $i < $numberOfRows; ++$i) { + //Find the show that is within the current time. + if ((strtotime($rows[$i]['starts']) <= $timeNowAsMillis) + && (strtotime($rows[$i]['ends']) > $timeNowAsMillis)) { + if ($i-1 >= 0) { + $results['previousShow'][0] = array( + "id" => $rows[$i-1]['id'], + "instance_id" => $rows[$i-1]['instance_id'], + "name" => $rows[$i-1]['name'], + "url" => $rows[$i-1]['url'], + "start_timestamp" => $rows[$i-1]['start_timestamp'], + "end_timestamp" => $rows[$i-1]['end_timestamp'], + "starts" => $rows[$i-1]['starts'], + "ends" => $rows[$i-1]['ends'], + "record" => $rows[$i-1]['record'], + "type" => "show"); + } + + $results['currentShow'][0] = $rows[$i]; + + if (isset($rows[$i+1])) { + $results['nextShow'][0] = array( + "id" => $rows[$i+1]['id'], + "instance_id" => $rows[$i+1]['instance_id'], + "name" => $rows[$i+1]['name'], + "url" => $rows[$i+1]['url'], + "start_timestamp" => $rows[$i+1]['start_timestamp'], + "end_timestamp" => $rows[$i+1]['end_timestamp'], + "starts" => $rows[$i+1]['starts'], + "ends" => $rows[$i+1]['ends'], + "record" => $rows[$i+1]['record'], + "type" => "show"); + } + break; + } + //Previous is any row that ends after time now capture it in case we need it later. + if (strtotime($rows[$i]['ends']) < $timeNowAsMillis ) { + $previousShowIndex = $i; + } + //if we hit this we know we've gone to far and can stop looping. + if (strtotime($rows[$i]['starts']) > $timeNowAsMillis) { + $results['nextShow'][0] = array( + "id" => $rows[$i]['id'], + "instance_id" => $rows[$i]['instance_id'], + "name" => $rows[$i]['name'], + "url" => $rows[$i]['url'], + "start_timestamp" => $rows[$i]['start_timestamp'], + "end_timestamp" => $rows[$i]['end_timestamp'], + "starts" => $rows[$i]['starts'], + "ends" => $rows[$i]['ends'], + "record" => $rows[$i]['record'], + "type" => "show"); + break; + } + } + //If we didn't find a a current show because the time didn't fit we may still have + //found a previous show so use it. + if (count($results['previousShow']) == 0 && isset($previousShowIndex)) { + $results['previousShow'][0] = array( + "id" => $rows[$previousShowIndex]['id'], + "instance_id" => $rows[$previousShowIndex]['instance_id'], + "name" => $rows[$previousShowIndex]['name'], + "start_timestamp" => $rows[$previousShowIndex]['start_timestamp'], + "end_timestamp" => $rows[$previousShowIndex]['end_timestamp'], + "starts" => $rows[$previousShowIndex]['starts'], + "ends" => $rows[$previousShowIndex]['ends'], + "record" => $rows[$previousShowIndex]['record'], + "type" => "show"); + } + + return $results; + } + + /** + * Given a start time $timeStart and end time $timeEnd, returns the next $limit + * number of shows within the time interval + * If $timeEnd not given, shows within next 48 hours from $timeStart are returned + * If $limit not given, all shows within the intervals are returned + * Times are all in UTC time. + * + * @param String $timeStart - interval start time (in UTC) + * @param int $limit - number of shows to return + * @param String $timeEnd - interval end time (in UTC) + * @return array - the next $limit number of shows within the time interval + */ + public static function getNextShows($timeStart, $limit = "ALL", $timeEnd = "") + { + // defaults to retrieving shows from next 2 days if no end time has + // been specified + if ($timeEnd == "") { + $timeEnd = "'$timeStart' + INTERVAL '2 days'"; + } + + //TODO, returning starts + ends twice (once with an alias). Unify this after the 2.0 release. --Martin + $sql = <<= :timeStart::timestamp + AND si.starts < :timeEnd::timestamp + AND modified_instance != TRUE +ORDER BY si.starts +SQL; + + //PDO won't accept "ALL" as a limit value (complains it is not an + //integer, and so we must completely remove the limit clause if we + //want to show all results - MK + if ($limit != "ALL") { + $sql .= PHP_EOL."LIMIT :lim"; + $params = array( + ':timeStart' => $timeStart, + ':timeEnd' => $timeEnd, + ':lim' => $limit); + } else { + $params = array( + ':timeStart' => $timeStart, + ':timeEnd' => $timeEnd); + } + + return Application_Common_Database::prepareAndExecute( $sql, $params, 'all'); + } + + /** + * Convert the columns given in the array $columnsToConvert in the + * database result $rows to local timezone. + * + * @param type $rows arrays of arrays containing database query result + * @param type $columnsToConvert array of column names to convert + */ + public static function convertToLocalTimeZone(&$rows, $columnsToConvert) + { + if (!is_array($rows)) { + return; + } + foreach ($rows as &$row) { + foreach ($columnsToConvert as $column) { + $row[$column] = Application_Common_DateHelper::ConvertToLocalDateTimeString($row[$column]); + } + } + } + + public static function getMaxLengths() + { + $con = Propel::getConnection(); + $sql = << 0 +SQL; + $result = $con->query($sql)->fetchAll(); + $assocArray = array(); + foreach ($result as $row) { + $assocArray[$row['column_name']] = $row['character_maximum_length']; + } + return $assocArray; + } + + public static function getStartEndCurrentMonthView() { + $first_day_of_calendar_month_view = mktime(0, 0, 0, date("n"), 1); + $weekStart = Application_Model_Preference::GetWeekStartDay(); + while (date('w', $first_day_of_calendar_month_view) != $weekStart) { + $first_day_of_calendar_month_view -= 60*60*24; + } + $last_day_of_calendar_view = $first_day_of_calendar_month_view + 3600*24*42; + + $start = new DateTime("@".$first_day_of_calendar_month_view); + $end = new DateTime("@".$last_day_of_calendar_view); + + return array($start, $end); + } + + public static function getStartEndCurrentWeekView() { + $first_day_of_calendar_week_view = mktime(0, 0, 0, date("n"), date("j")); + $weekStart = Application_Model_Preference::GetWeekStartDay(); + while (date('w', $first_day_of_calendar_week_view) != $weekStart) { + $first_day_of_calendar_week_view -= 60*60*24; + } + $last_day_of_calendar_view = $first_day_of_calendar_week_view + 3600*24*7; + + $start = new DateTime("@".$first_day_of_calendar_week_view); + $end = new DateTime("@".$last_day_of_calendar_view); + + return array($start, $end); + } + + public static function getStartEndCurrentDayView() { + $today = mktime(0, 0, 0, date("n"), date("j")); + $tomorrow = $today + 3600*24; + + $start = new DateTime("@".$today); + $end = new DateTime("@".$tomorrow); + + return array($start, $end); + } +} diff --git a/airtime_mvc/application/services/ScheduleService.php b/airtime_mvc/application/services/ScheduleService.php index 1204f689c..e8322882b 100644 --- a/airtime_mvc/application/services/ScheduleService.php +++ b/airtime_mvc/application/services/ScheduleService.php @@ -175,15 +175,18 @@ class Application_Service_ScheduleService //create ccShow $ccShow = new CcShow(); $ccShow = $service_show->setShow($ccShow, $showData); + $showId = $ccShow->getDbId(); //create ccShowDay $service_show->createShowDays( - $showData, $ccShow->getDbId(), $user->getId(), $repeatType, $isRecorded); + $showData, $showId, $user->getId(), $repeatType, $isRecorded); + + //create ccShowRebroadcast + $service_show->createShowRebroadcast($showData, $showId, $repeatType, $isRecorded); //create ccShowHosts - - //create ccShowRebroadcast - + $service_show->createShowHosts($showData, $showId); + //populate ccShowInstances } } diff --git a/airtime_mvc/application/services/ShowService.php b/airtime_mvc/application/services/ShowService.php new file mode 100644 index 000000000..458cc4bd8 --- /dev/null +++ b/airtime_mvc/application/services/ShowService.php @@ -0,0 +1,145 @@ +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']); + + $ccShow->save(); + return $ccShow; + } + + /** + * Creates new cc_show_days entries + */ + public function createShowDays($showData, $showId, $userId, $repeatType, $isRecorded) + { + $startDateTime = new DateTime($showData['add_show_start_date']." ".$showData['add_show_start_time']); + + if ($showData['add_show_no_end']) { + $endDate = NULL; + } elseif ($showData['add_show_repeats']) { + $endDateTime = new DateTime($showData['add_show_end_date']); + $endDateTime->add(new DateInterval("P1D")); + $endDate = $endDateTime->format("Y-m-d"); + } else { + $endDateTime = new DateTime($showData['add_show_start_date']); + $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()); + 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::GetUserTimezone($userId)); + $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::GetUserTimezone($userId)); + $showDay->setDbDuration($showData['add_show_duration']); + $showDay->setDbDay($day); + $showDay->setDbRepeatType($repeatType); + $showDay->setDbShowId($showId); + $showDay->setDbRecord($isRecorded); + $showDay->save(); + } + } + } + } + + /** + * Creates new cc_show_rebroadcast entries + */ + public function createShowRebroadcast($showData, $showId, $repeatType, $isRecorded) + { + define("MAX_REBROADCAST_DATES", 10); + + if (($isRecorded && $showData['add_show_rebroadcast']) && ($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 ($isRecorded && $showData['add_show_rebroadcast'] && ($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(); + } + } + } + } + + /** + * Creates cc_show_hosts entries + */ + public function createShowHosts($showData, $showId) + { + if (is_array($showData['add_show_hosts'])) { + foreach ($showData['add_show_hosts'] as $host) { + $showHost = new CcShowHosts(); + $showHost->setDbShow($showId); + $showHost->setDbHost($host); + $showHost->save(); + } + } + } +} \ No newline at end of file From 8c8a7d11e1276a59df5b4e309395ae02c73dada2 Mon Sep 17 00:00:00 2001 From: denise Date: Tue, 26 Feb 2013 13:21:39 -0500 Subject: [PATCH 05/73] Created empty showInstance service. Split populateShowUntil into 2 new functions: getPopulateDateUntil, and getShowDays --- .../application/services/ScheduleService.php | 5 ++- .../services/ShowInstanceService.php | 8 +++++ .../application/services/ShowService.php | 32 +++++++++++++++++++ 3 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 airtime_mvc/application/services/ShowInstanceService.php diff --git a/airtime_mvc/application/services/ScheduleService.php b/airtime_mvc/application/services/ScheduleService.php index e8322882b..c0bc1a844 100644 --- a/airtime_mvc/application/services/ScheduleService.php +++ b/airtime_mvc/application/services/ScheduleService.php @@ -171,6 +171,7 @@ class Application_Service_ScheduleService if ($isAdminOrPM) { $service_show = new Application_Service_ShowService(); + $service_showInstances = new Application_Service_ShowInstanceService(); //create ccShow $ccShow = new CcShow(); @@ -187,7 +188,9 @@ class Application_Service_ScheduleService //create ccShowHosts $service_show->createShowHosts($showData, $showId); - //populate ccShowInstances + $populateShowsUntil = $service_show->getPopulateShowUntilDateTIme(); + //create ccShowInstances + $service_showInstances->createShowInstances($showId, $populateShowsUntil); } } diff --git a/airtime_mvc/application/services/ShowInstanceService.php b/airtime_mvc/application/services/ShowInstanceService.php new file mode 100644 index 000000000..1f7a2eedc --- /dev/null +++ b/airtime_mvc/application/services/ShowInstanceService.php @@ -0,0 +1,8 @@ + $showId), 'all'); + } } \ No newline at end of file From c7203aa40dd6a4b92b198671e83b2d43e7b6c774 Mon Sep 17 00:00:00 2001 From: denise Date: Tue, 26 Feb 2013 17:41:35 -0500 Subject: [PATCH 06/73] CC-4961: Show linking Refactored some more show instance creation functions --- airtime_mvc/application/models/Show.php | 10 +-- .../application/services/ScheduleService.php | 26 +++--- .../services/ShowInstanceService.php | 81 ++++++++++++++++++- .../application/services/ShowService.php | 70 +++++++++++++--- 4 files changed, 160 insertions(+), 27 deletions(-) diff --git a/airtime_mvc/application/models/Show.php b/airtime_mvc/application/models/Show.php index d6f9db98b..23cc4d02e 100644 --- a/airtime_mvc/application/models/Show.php +++ b/airtime_mvc/application/models/Show.php @@ -1310,7 +1310,7 @@ SQL; } } - Application_Model_Show::populateShowUntil($showId); + /*Application_Model_Show::populateShowUntil($showId);*/ Application_Model_RabbitMq::PushSchedule(); return $showId; @@ -1323,7 +1323,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(); @@ -1344,7 +1344,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 @@ -1357,7 +1357,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 @@ -1371,7 +1371,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 diff --git a/airtime_mvc/application/services/ScheduleService.php b/airtime_mvc/application/services/ScheduleService.php index c0bc1a844..0e6bbf2ff 100644 --- a/airtime_mvc/application/services/ScheduleService.php +++ b/airtime_mvc/application/services/ScheduleService.php @@ -2,6 +2,14 @@ class Application_Service_ScheduleService { + private $service_show; + private $service_showInstances; + + public function __construct() + { + $this->service_show = new Application_Service_ShowService(); + $this->service_showInstances = new Application_Service_ShowInstanceService(); + } /* * Form stuff begins here * Typically I would keep form creation and validation @@ -170,27 +178,23 @@ class Application_Service_ScheduleService $showData["add_show_duration"]); if ($isAdminOrPM) { - $service_show = new Application_Service_ShowService(); - $service_showInstances = new Application_Service_ShowInstanceService(); - //create ccShow $ccShow = new CcShow(); - $ccShow = $service_show->setShow($ccShow, $showData); + $ccShow = $this->service_show->setShow($ccShow, $showData); $showId = $ccShow->getDbId(); - //create ccShowDay - $service_show->createShowDays( + //create ccShowDays + $this->service_show->createShowDays( $showData, $showId, $user->getId(), $repeatType, $isRecorded); - //create ccShowRebroadcast - $service_show->createShowRebroadcast($showData, $showId, $repeatType, $isRecorded); + //create ccShowRebroadcasts + $this->service_show->createShowRebroadcasts($showData, $showId, $repeatType, $isRecorded); //create ccShowHosts - $service_show->createShowHosts($showData, $showId); + $this->service_show->createShowHosts($showData, $showId); - $populateShowsUntil = $service_show->getPopulateShowUntilDateTIme(); //create ccShowInstances - $service_showInstances->createShowInstances($showId, $populateShowsUntil); + $this->service_showInstances->createShowInstances($showId); } } diff --git a/airtime_mvc/application/services/ShowInstanceService.php b/airtime_mvc/application/services/ShowInstanceService.php index 1f7a2eedc..2b4d9a5f8 100644 --- a/airtime_mvc/application/services/ShowInstanceService.php +++ b/airtime_mvc/application/services/ShowInstanceService.php @@ -1,8 +1,85 @@ service_show = new Application_Service_ShowService(); + } + + /** + * + * Receives a cc_show id and determines whether to create a + * single show_instance or repeating show instances + */ + public function createShowInstances($showId) + { + $populateUntil = $this->service_show->getPopulateShowUntilDateTIme(); + + $showDays = $this->service_show->getShowDays($showId); + foreach ($showDays as $day) { + switch ($day["repeat_type"]) { + case self::NO_REPEAT: + $this->createNonRepeatingShowInstance($day, $populateUntil); + break; + case self::REPEAT_WEEKLY: + $this->createRepeatingShowInstances($day, $populateUntil, "P7D"); + break; + case self::REPEAT_BI_WEEKLY: + $this->createRepeatingShowInstances($day, $populateUntil, "P14D"); + break; + case self::REPEAT_MONTHLY_MONTHLY: + $this->createRepeatingShowInstances($day, $populateUntil, "P1M"); + break; + case self::REPEAT_MONTHLY_WEEKLY: + // do something here + break; + } + } + } + + /** + * + * Enter description here ... + * @param $showDay + * @param $populateUntil + */ + private function createNonRepeatingShowInstance($showDay, $populateUntil) + { + $start = $showDay["first_show"]." ".$showDay["start_time"]; + + list($utcStartDateTime, $utcEndDateTime) = $this->service_show->createUTCStartEndDateTime( + $start, $showDay["duration"], $showDay["timezone"]); + + if ($utcStartDateTime->getTimestamp() < $populateUntil->getTimestamp()) { + $currentUtcTimestamp = gmdate("Y-m-d H:i:s"); + + $ccShowInstance = new CcShowInstances(); + if ($ccShowInstance->getTimestamp() > $currentUtcTimestamp) { + $ccShowInstance->setDbShowId($showDay["show_id"]); + $ccShowInstance->setDbStarts($utcStartDateTime); + $ccShowInstance->setDbEnds($utcEndDateTime); + $ccShowInstance->setDbRecord($showDay["record"]); + $ccShowInstance->save(); + } + } + } + + /** + * + * Enter description here ... + * @param $showDay + * @param $populateUntil + * @param $repeatInterval + */ + private function createRepeatingShowInstances($showDay, $populateUntil, $repeatInterval) + { + Logging::info("repeating"); } } \ No newline at end of file diff --git a/airtime_mvc/application/services/ShowService.php b/airtime_mvc/application/services/ShowService.php index 82153300a..f69d42e42 100644 --- a/airtime_mvc/application/services/ShowService.php +++ b/airtime_mvc/application/services/ShowService.php @@ -2,8 +2,13 @@ class Application_Service_ShowService { + const MAX_REBROADCAST_DATES = 10; + /** - * Sets a cc_show entry + * + * Enter description here ... + * @param $ccShow + * @param $showData */ public function setShow($ccShow, $showData) { @@ -23,7 +28,13 @@ class Application_Service_ShowService } /** - * Creates new cc_show_days entries + * + * Enter description here ... + * @param $showData + * @param $showId + * @param $userId + * @param $repeatType + * @param $isRecorded */ public function createShowDays($showData, $showId, $userId, $repeatType, $isRecorded) { @@ -95,14 +106,17 @@ class Application_Service_ShowService } /** - * Creates new cc_show_rebroadcast entries + * + * Enter description here ... + * @param $showData + * @param $showId + * @param $repeatType + * @param $isRecorded */ - public function createShowRebroadcast($showData, $showId, $repeatType, $isRecorded) + public function createShowRebroadcasts($showData, $showId, $repeatType, $isRecorded) { - define("MAX_REBROADCAST_DATES", 10); - if (($isRecorded && $showData['add_show_rebroadcast']) && ($repeatType != -1)) { - for ($i=1; $i<=MAX_REBROADCAST_DATES; $i++) { + for ($i=1; $i<=self::MAX_REBROADCAST_DATES; $i++) { if ($showData['add_show_rebroadcast_date_'.$i]) { $showRebroad = new CcShowRebroadcast(); $showRebroad->setDbDayOffset($showData['add_show_rebroadcast_date_'.$i]); @@ -112,7 +126,7 @@ class Application_Service_ShowService } } } elseif ($isRecorded && $showData['add_show_rebroadcast'] && ($repeatType == -1)) { - for ($i=1; $i<=MAX_REBROADCAST_DATES; $i++) { + for ($i=1; $i<=self::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']); @@ -129,7 +143,10 @@ class Application_Service_ShowService } /** - * Creates cc_show_hosts entries + * + * Enter description here ... + * @param $showData + * @param $showId */ public function createShowHosts($showData, $showId) { @@ -174,4 +191,39 @@ class Application_Service_ShowService return Application_Common_Database::prepareAndExecute( $sql, array(":show_id" => $showId), 'all'); } + + /** + * + * 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 + * + * @return array of 2 DateTime objects, start/end time of the show in UTC + */ + public function createUTCStartEndDateTime($localStart, $duration, $timezone=null, $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")); + } + //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); + } } \ No newline at end of file From d08f6cf3e17591faa34cae0ac7a3cf63017b436c Mon Sep 17 00:00:00 2001 From: denise Date: Thu, 21 Feb 2013 17:57:56 -0500 Subject: [PATCH 07/73] CC-4961: Show linking -initial schedule service experimentation --- .../controllers/ScheduleController.php | 20 +- .../controllers/_old_ScheduleController.php | 1002 +++++++++++++ airtime_mvc/application/models/Schedule.php | 36 +- .../application/models/_old_Schedule.php | 1329 +++++++++++++++++ .../application/services/ScheduleService.php | 90 ++ 5 files changed, 2458 insertions(+), 19 deletions(-) create mode 100644 airtime_mvc/application/controllers/_old_ScheduleController.php create mode 100644 airtime_mvc/application/models/_old_Schedule.php create mode 100644 airtime_mvc/application/services/ScheduleService.php diff --git a/airtime_mvc/application/controllers/ScheduleController.php b/airtime_mvc/application/controllers/ScheduleController.php index 08fde37dc..9ca879918 100644 --- a/airtime_mvc/application/controllers/ScheduleController.php +++ b/airtime_mvc/application/controllers/ScheduleController.php @@ -5,6 +5,8 @@ class ScheduleController extends Zend_Controller_Action protected $sched_sess = null; + private $service_schedule; + public function init() { $ajaxContext = $this->_helper->getHelper('AjaxContext'); @@ -38,6 +40,8 @@ class ScheduleController extends Zend_Controller_Action ->initContext(); $this->sched_sess = new Zend_Session_Namespace("schedule"); + + $this->service_schedule = new Application_Service_ScheduleService(); } public function indexAction() @@ -90,13 +94,27 @@ class ScheduleController extends Zend_Controller_Action $this->view->headLink()->appendStylesheet($baseUrl.'css/showbuilder.css?'.$CC_CONFIG['airtime_version']); //End Show builder JS/CSS requirements + $forms = $this->service_schedule->createShowForms(); + // populate forms with default values + $this->service_schedule->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_record"]; + $this->view->rebroadcast = $forms["rebroadcast"]; + $this->view->who = $forms["who"]; + $this->view->style = $forms["style"]; - 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". diff --git a/airtime_mvc/application/controllers/_old_ScheduleController.php b/airtime_mvc/application/controllers/_old_ScheduleController.php new file mode 100644 index 000000000..08fde37dc --- /dev/null +++ b/airtime_mvc/application/controllers/_old_ScheduleController.php @@ -0,0 +1,1002 @@ +_helper->getHelper('AjaxContext'); + $ajaxContext->addActionContext('event-feed', 'json') + ->addActionContext('event-feed-preload', 'json') + ->addActionContext('make-context-menu', 'json') + ->addActionContext('add-show-dialog', 'json') + ->addActionContext('add-show', 'json') + ->addActionContext('edit-show', 'json') + ->addActionContext('move-show', 'json') + ->addActionContext('resize-show', 'json') + ->addActionContext('delete-show', '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('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('dj-edit-show', 'json') + ->addActionContext('calculate-duration', 'json') + ->addActionContext('get-current-show', 'json') + ->addActionContext('update-future-is-scheduled', 'json') + ->initContext(); + + $this->sched_sess = new Zend_Session_Namespace("schedule"); + } + + public function indexAction() + { + $CC_CONFIG = Config::getConfig(); + + $baseUrl = Application_Common_OsPath::getBaseDir(); + + $this->view->headScript()->appendFile($baseUrl.'js/contextmenu/jquery.contextMenu.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + + //full-calendar-functions.js requires this variable, so that datePicker widget can be offset to server time instead of client time + $this->view->headScript()->appendScript("var timezoneOffset = ".date("Z")."; //in seconds"); + $this->view->headScript()->appendFile($baseUrl.'js/airtime/schedule/full-calendar-functions.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + + $this->view->headScript()->appendFile($baseUrl.'js/fullcalendar/fullcalendar.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + $this->view->headScript()->appendFile($baseUrl.'js/timepicker/jquery.ui.timepicker.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + $this->view->headScript()->appendFile($baseUrl.'js/colorpicker/js/colorpicker.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + + $this->view->headScript()->appendFile($baseUrl.'js/airtime/schedule/add-show.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + $this->view->headScript()->appendFile($baseUrl.'js/airtime/schedule/schedule.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + $this->view->headScript()->appendFile($baseUrl.'js/blockui/jquery.blockUI.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + + $this->view->headLink()->appendStylesheet($baseUrl.'css/jquery.ui.timepicker.css?'.$CC_CONFIG['airtime_version']); + $this->view->headLink()->appendStylesheet($baseUrl.'css/fullcalendar.css?'.$CC_CONFIG['airtime_version']); + $this->view->headLink()->appendStylesheet($baseUrl.'css/colorpicker/css/colorpicker.css?'.$CC_CONFIG['airtime_version']); + $this->view->headLink()->appendStylesheet($baseUrl.'css/add-show.css?'.$CC_CONFIG['airtime_version']); + $this->view->headLink()->appendStylesheet($baseUrl.'css/jquery.contextMenu.css?'.$CC_CONFIG['airtime_version']); + + //Start Show builder JS/CSS requirements + $this->view->headScript()->appendFile($baseUrl.'js/contextmenu/jquery.contextMenu.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + $this->view->headScript()->appendFile($baseUrl.'js/datatables/js/jquery.dataTables.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + $this->view->headScript()->appendFile($baseUrl.'js/datatables/plugin/dataTables.pluginAPI.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + $this->view->headScript()->appendFile($baseUrl.'js/datatables/plugin/dataTables.fnSetFilteringDelay.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + $this->view->headScript()->appendFile($baseUrl.'js/datatables/plugin/dataTables.ColVis.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + $this->view->headScript()->appendFile($baseUrl.'js/datatables/plugin/dataTables.ColReorder.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + $this->view->headScript()->appendFile($baseUrl.'js/datatables/plugin/dataTables.FixedColumns.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + $this->view->headScript()->appendFile($baseUrl.'js/datatables/plugin/dataTables.TableTools.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + $this->view->headScript()->appendFile($baseUrl.'js/datatables/plugin/dataTables.columnFilter.js?'.$CC_CONFIG['airtime_version'], 'text/javascript'); + + $this->view->headScript()->appendFile($baseUrl.'js/airtime/buttons/buttons.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + $this->view->headScript()->appendFile($baseUrl.'js/airtime/library/events/library_showbuilder.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + $this->view->headScript()->appendFile($baseUrl.'js/airtime/library/library.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + $this->view->headScript()->appendFile($baseUrl.'js/airtime/showbuilder/builder.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + + $this->view->headLink()->appendStylesheet($baseUrl.'css/media_library.css?'.$CC_CONFIG['airtime_version']); + $this->view->headLink()->appendStylesheet($baseUrl.'css/jquery.contextMenu.css?'.$CC_CONFIG['airtime_version']); + $this->view->headLink()->appendStylesheet($baseUrl.'css/datatables/css/ColVis.css?'.$CC_CONFIG['airtime_version']); + $this->view->headLink()->appendStylesheet($baseUrl.'css/datatables/css/ColReorder.css?'.$CC_CONFIG['airtime_version']); + $this->view->headLink()->appendStylesheet($baseUrl.'css/TableTools.css?'.$CC_CONFIG['airtime_version']); + $this->view->headLink()->appendStylesheet($baseUrl.'css/showbuilder.css?'.$CC_CONFIG['airtime_version']); + //End Show builder JS/CSS requirements + + + 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->headScript()->appendScript( + "var calendarPref = {};\n". + "calendarPref.weekStart = ".Application_Model_Preference::GetWeekStartDay().";\n". + "calendarPref.timestamp = ".time().";\n". + "calendarPref.timezoneOffset = ".date("Z").";\n". + "calendarPref.timeScale = '".Application_Model_Preference::GetCalendarTimeScale()."';\n". + "calendarPref.timeInterval = ".Application_Model_Preference::GetCalendarTimeInterval().";\n". + "calendarPref.weekStartDay = ".Application_Model_Preference::GetWeekStartDay().";\n". + "var calendarEvents = null;" + ); + } + + public function eventFeedAction() + { + $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, $editable); + $this->view->events = $events; + } + + public function eventFeedPreloadAction() + { + $userInfo = Zend_Auth::getInstance()->getStorage()->read(); + $user = new Application_Model_User($userInfo->id); + $editable = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER)); + + $calendar_interval = Application_Model_Preference::GetCalendarTimeScale(); + Logging::info($calendar_interval); + if ($calendar_interval == "agendaDay") { + list($start, $end) = Application_Model_Show::getStartEndCurrentDayView(); + } else if ($calendar_interval == "agendaWeek") { + list($start, $end) = Application_Model_Show::getStartEndCurrentWeekView(); + } else if ($calendar_interval == "month") { + list($start, $end) = Application_Model_Show::getStartEndCurrentMonthView(); + } else { + Logging::error("Invalid Calendar Interval '$calendar_interval'"); + } + + $events = &Application_Model_Show::getFullCalendarEvents($start, $end, $editable); + $this->view->events = $events; + } + + public function getCurrentShowAction() + { + $currentShow = Application_Model_Show::getCurrentShow(); + if (!empty($currentShow)) { + $this->view->si_id = $currentShow[0]["instance_id"]; + $this->view->current_show = true; + } else { + $this->view->current_show = false; + } + } + + public function moveShowAction() + { + $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); + } + + if (isset($error)) { + $this->view->error = $error; + } + } + + public function resizeShowAction() + { + $deltaDay = $this->_getParam('day'); + $deltaMin = $this->_getParam('min'); + $showId = $this->_getParam('showId'); + + $userInfo = Zend_Auth::getInstance()->getStorage()->read(); + $user = new Application_Model_User($userInfo->id); + + if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) { + try { + $show = new Application_Model_Show($showId); + } catch (Exception $e) { + $this->view->show_error = true; + + return false; + } + $error = $show->resizeShow($deltaDay, $deltaMin); + } + + if (isset($error)) { + $this->view->error = $error; + } + } + + public function deleteShowAction() + { + $showInstanceId = $this->_getParam('id'); + + $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) { + Logging::info($e->getMessage()); + $this->view->show_error = true; + + return false; + } + + $showInstance->delete(); + + $this->view->show_id = $showInstance->getShowId(); + } + } + + public function uploadToSoundCloudAction() + { + $show_instance = $this->_getParam('id'); + try { + $show_inst = new Application_Model_ShowInstance($show_instance); + } catch (Exception $e) { + $this->view->show_error = true; + + return false; + } + + $file = $show_inst->getRecordedFile(); + $id = $file->getId(); + Application_Model_Soundcloud::uploadSoundcloud($id); + // we should die with ui info + $this->_helper->json->sendJson(null); + } + + public function makeContextMenuAction() + { + $id = $this->_getParam('id'); + $menu = array(); + $epochNow = time(); + $baseUrl = Application_Common_OsPath::getBaseDir(); + + $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; + + 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; + } + + public function clearShowAction() + { + $showInstanceId = $this->_getParam('id'); + $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->clearShow(); + } + + public function getCurrentPlaylistAction() + { + $range = Application_Model_Schedule::GetPlayOrderRange(); + $show = Application_Model_Show::getCurrentShow(); + + /* Convert all UTC times to localtime before sending back to user. */ + if (isset($range["previous"])) { + $range["previous"]["starts"] = Application_Common_DateHelper::ConvertToLocalDateTimeString($range["previous"]["starts"]); + $range["previous"]["ends"] = Application_Common_DateHelper::ConvertToLocalDateTimeString($range["previous"]["ends"]); + } + if (isset($range["current"])) { + $range["current"]["starts"] = Application_Common_DateHelper::ConvertToLocalDateTimeString($range["current"]["starts"]); + $range["current"]["ends"] = Application_Common_DateHelper::ConvertToLocalDateTimeString($range["current"]["ends"]); + } + if (isset($range["next"])) { + $range["next"]["starts"] = Application_Common_DateHelper::ConvertToLocalDateTimeString($range["next"]["starts"]); + $range["next"]["ends"] = Application_Common_DateHelper::ConvertToLocalDateTimeString($range["next"]["ends"]); + } + + Application_Model_Show::convertToLocalTimeZone($range["currentShow"], array("starts", "ends", "start_timestamp", "end_timestamp")); + Application_Model_Show::convertToLocalTimeZone($range["nextShow"], array("starts", "ends", "start_timestamp", "end_timestamp")); + + $source_status = array(); + $switch_status = array(); + $live_dj = Application_Model_Preference::GetSourceStatus("live_dj"); + $master_dj = Application_Model_Preference::GetSourceStatus("master_dj"); + + $scheduled_play_switch = Application_Model_Preference::GetSourceSwitchStatus("scheduled_play"); + $live_dj_switch = Application_Model_Preference::GetSourceSwitchStatus("live_dj"); + $master_dj_switch = Application_Model_Preference::GetSourceSwitchStatus("master_dj"); + + //might not be the correct place to implement this but for now let's just do it here + $source_status['live_dj_source'] = $live_dj; + $source_status['master_dj_source'] = $master_dj; + $this->view->source_status = $source_status; + + $switch_status['live_dj_source'] = $live_dj_switch; + $switch_status['master_dj_source'] = $master_dj_switch; + $switch_status['scheduled_play'] = $scheduled_play_switch; + $this->view->switch_status = $switch_status; + + $this->view->entries = $range; + $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'); + try { + $show = new Application_Model_ShowInstance($showInstanceId); + } catch (Exception $e) { + $this->view->show_error = true; + + return false; + } + + $originalShowId = $show->isRebroadcast(); + if (!is_null($originalShowId)) { + try { + $originalShow = new Application_Model_ShowInstance($originalShowId); + } catch (Exception $e) { + $this->view->show_error = true; + + return false; + } + $originalShowName = $originalShow->getName(); + $originalShowStart = $originalShow->getShowInstanceStart(); + + //convert from UTC to user's timezone for display. + $originalDateTime = new DateTime($originalShowStart, new DateTimeZone("UTC")); + $originalDateTime->setTimezone(new DateTimeZone(date_default_timezone_get())); + //$timestamp = Application_Common_DateHelper::ConvertToLocalDateTimeString($originalDateTime->format("Y-m-d H:i:s")); + $this->view->additionalShowInfo = + sprintf(_("Rebroadcast of show %s from %s at %s"), + $originalShowName, + $originalDateTime->format("l, F jS"), + $originalDateTime->format("G:i")); + } + $this->view->showLength = $show->getShowLength(); + $this->view->timeFilled = $show->getTimeScheduled(); + $this->view->percentFilled = $show->getPercentScheduled(); + $this->view->showContent = $show->getShowListContent(); + $this->view->dialog = $this->view->render('schedule/show-content-dialog.phtml'); + $this->view->showTitle = htmlspecialchars($show->getName()); + 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(); + + $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; + + $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->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); + + $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; + } + + // 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) { + $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(); + + $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(); + } + + if (!$isAdminOrPM) { + $formWhat->disable(); + $formWho->disable(); + $formWhen->disable(); + $formRepeats->disable(); + $formStyle->disable(); + } + + $this->view->newForm = $this->view->render('schedule/add-show-form.phtml'); + $this->view->entries = 5; + } + + public function getFormAction() + { + $user = Application_Model_User::getCurrentUser(); + + if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) { + Application_Model_Schedule::createNewFormSections($this->view); + $this->view->form = $this->view->render('schedule/add-show-form.phtml'); + } + } + + public function djEditShowAction() + { + $js = $this->_getParam('data'); + $data = array(); + + //need to convert from serialized jQuery array. + foreach ($js as $j) { + $data[$j["name"]] = $j["value"]; + } + + //update cc_show + $show = new Application_Model_Show($data["add_show_id"]); + $show->setAirtimeAuthFlag($data["cb_airtime_auth"]); + $show->setCustomAuthFlag($data["cb_custom_auth"]); + $show->setCustomUsername($data["custom_username"]); + $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 + $js = $this->_getParam('data'); + $data = array(); + + //need to convert from serialized jQuery array. + foreach ($js as $j) { + $data[$j["name"]] = $j["value"]; + } + + $data['add_show_hosts'] = $this->_getParam('hosts'); + $data['add_show_day_check'] = $this->_getParam('days'); + + if ($data['add_show_day_check'] == "") { + $data['add_show_day_check'] = null; + } + + $show = new Application_Model_Show($data['add_show_id']); + + $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"); + + 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 ($show->isRepeating()) { + $nextFutureRepeatShow = $show->getNextFutureRepeatShowTime(); + $originalShowStartDateTime = $nextFutureRepeatShow["starts"]; + } else { + $originalShowStartDateTime = Application_Common_DateHelper::ConvertToLocalDateTime( + $show->getStartDateAndTime()); + } + + $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 { + 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 addShowAction() + { + $js = $this->_getParam('data'); + $data = array(); + + //need to convert from serialized jQuery array. + foreach ($js as $j) { + $data[$j["name"]] = $j["value"]; + } + + $data['add_show_hosts'] = $this->_getParam('hosts'); + $data['add_show_day_check'] = $this->_getParam('days'); + + if ($data['add_show_day_check'] == "") { + $data['add_show_day_check'] = null; + } + + $validateStartDate = true; + $success = Application_Model_Schedule::addUpdateShow($data, $this, + $validateStartDate); + + 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'); + Logging::debug("Show creation failed"); + } + } + + public function cancelShowAction() + { + $user = Application_Model_User::getCurrentUser(); + + if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) { + $showInstanceId = $this->_getParam('id'); + + 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(); + } + } + + public function cancelCurrentShowAction() + { + $user = Application_Model_User::getCurrentUser(); + + if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) { + $id = $this->_getParam('id'); + + try { + $scheduler = new Application_Model_Scheduler(); + $scheduler->cancelShow($id); + Application_Model_StoredFile::updatePastFilesIsScheduled(); + // send kick out source stream signal to pypo + $data = array("sourcename"=>"live_dj"); + Application_Model_RabbitMq::SendMessageToPypo("disconnect_source", $data); + } catch (Exception $e) { + $this->view->error = $e->getMessage(); + Logging::info($e->getMessage()); + } + } + } + + public function contentContextMenuAction() + { + $id = $this->_getParam('id'); + + $params = '/format/json/id/#id#/'; + + $paramsPop = str_replace('#id#', $id, $params); + + // added for downlaod + $id = $this->_getParam('id'); + + $file_id = $this->_getParam('id', null); + $file = Application_Model_StoredFile::Recall($file_id); + + $baseUrl = $this->getRequest()->getBaseUrl(); + $url = $file->getRelativeFileUrl($baseUrl).'download/true'; + $menu[] = array('action' => array('type' => 'gourl', 'url' => $url), + 'title' => _('Download')); + + //returns format jjmenu is looking for. + $this->_helper->json->sendJson($menu); + } + + /** + * Sets the user specific preference for which time scale to use in Calendar. + * This is only being used by schedule.js at the moment. + */ + public function setTimeScaleAction() + { + Application_Model_Preference::SetCalendarTimeScale($this->_getParam('timeScale')); + } + +/** + * Sets the user specific preference for which time interval to use in Calendar. + * This is only being used by schedule.js at the moment. + */ + public function setTimeIntervalAction() + { + Application_Model_Preference::SetCalendarTimeInterval($this->_getParam('timeInterval')); + } + + 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"; + } + + echo Zend_Json::encode($result); + exit(); + } + + public function updateFutureIsScheduledAction() + { + $schedId = $this->_getParam('schedId'); + $redrawLibTable = Application_Model_StoredFile::setIsScheduled($schedId, false); + $this->_helper->json->sendJson(array("redrawLibTable" => $redrawLibTable)); + } +} diff --git a/airtime_mvc/application/models/Schedule.php b/airtime_mvc/application/models/Schedule.php index 1aac2566e..2778074d2 100644 --- a/airtime_mvc/application/models/Schedule.php +++ b/airtime_mvc/application/models/Schedule.php @@ -960,7 +960,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(); @@ -1005,7 +1005,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). @@ -1140,13 +1140,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); @@ -1156,18 +1156,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(); diff --git a/airtime_mvc/application/models/_old_Schedule.php b/airtime_mvc/application/models/_old_Schedule.php new file mode 100644 index 000000000..1aac2566e --- /dev/null +++ b/airtime_mvc/application/models/_old_Schedule.php @@ -0,0 +1,1329 @@ + NOW() AT TIME ZONE 'UTC' +SQL; + $count = Application_Common_Database::prepareAndExecute( $sql, array( + ':file_id'=>$p_fileId), 'column'); + return (is_numeric($count) && ($count != '0')); + } + + public static function getAllFutureScheduledFiles() + { + $con = Propel::getConnection(); + $sql = << now() AT TIME ZONE 'UTC' +AND file_id is not null +SQL; + $files = $con->query($sql)->fetchAll(); + $real_files = array(); + foreach ($files as $f) { + $real_files[] = $f['file_id']; + } + + return $real_files; + } + + public static function getAllFutureScheduledWebstreams() + { + $con = Propel::getConnection(); + $sql = << now() AT TIME ZONE 'UTC' +AND stream_id is not null +SQL; + $streams = $con->query($sql)->fetchAll(); + $real_streams = array(); + foreach ($streams as $s) { + $real_streams[] = $s['stream_id']; + } + + return $real_streams; + } + /** + * Returns data related to the scheduled items. + * + * @param int $p_prev + * @param int $p_next + * @return date + */ + public static function GetPlayOrderRange($p_prev = 1, $p_next = 1) + { + if (!is_int($p_prev) || !is_int($p_next)) { + //must enter integers to specify ranges + Logging::info("Invalid range parameters: $p_prev or $p_next"); + + return array(); + } + + $date = new Application_Common_DateHelper; + $timeNow = $date->getTimestamp(); + $utcTimeNow = $date->getUtcTimestamp(); + + $shows = Application_Model_Show::getPrevCurrentNext($utcTimeNow); + $previousShowID = count($shows['previousShow'])>0?$shows['previousShow'][0]['instance_id']:null; + $currentShowID = count($shows['currentShow'])>0?$shows['currentShow'][0]['instance_id']:null; + $nextShowID = count($shows['nextShow'])>0?$shows['nextShow'][0]['instance_id']:null; + $results = self::GetPrevCurrentNext($previousShowID, $currentShowID, $nextShowID, $utcTimeNow); + + $range = array("env"=>APPLICATION_ENV, + "schedulerTime"=>$timeNow, + "previous"=>$results['previous'] !=null?$results['previous']:(count($shows['previousShow'])>0?$shows['previousShow'][0]:null), + "current"=>$results['current'] !=null?$results['current']:((count($shows['currentShow'])>0 && $shows['currentShow'][0]['record'] == 1)?$shows['currentShow'][0]:null), + "next"=> $results['next'] !=null?$results['next']:(count($shows['nextShow'])>0?$shows['nextShow'][0]:null), + "currentShow"=>$shows['currentShow'], + "nextShow"=>$shows['nextShow'], + "timezone"=> date("T"), + "timezoneOffset"=> date("Z") + ); + + return $range; + } + + /** + * Queries the database for the set of schedules one hour before + * and after the given time. If a show starts and ends within that + * time that is considered the current show. Then the scheduled item + * before it is the previous show, and the scheduled item after it + * is the next show. This way the dashboard getCurrentPlaylist is + * very fast. But if any one of the three show types are not found + * through this mechanism a call is made to the old way of querying + * the database to find the track info. + **/ + public static function GetPrevCurrentNext($p_previousShowID, $p_currentShowID, $p_nextShowID, $p_timeNow) + { + if ($p_previousShowID == null && $p_currentShowID == null && $p_nextShowID == null) { + return; + } + + $sql = "SELECT %%columns%% st.starts as starts, st.ends as ends, + st.media_item_played as media_item_played, si.ends as show_ends + %%tables%% WHERE "; + + $fileColumns = "ft.artist_name, ft.track_title, "; + $fileJoin = "FROM cc_schedule st JOIN cc_files ft ON st.file_id = ft.id + LEFT JOIN cc_show_instances si ON st.instance_id = si.id"; + + $streamColumns = "ws.name AS artist_name, wm.liquidsoap_data AS track_title, "; + $streamJoin = << $rows[$i]["show_ends"]) { + $rows[$i]['ends'] = $rows[$i]["show_ends"]; + } + + if ((strtotime($rows[$i]['starts']) <= $timeNowAsMillis) && (strtotime($rows[$i]['ends']) >= $timeNowAsMillis)) { + if ($i - 1 >= 0) { + $results['previous'] = array("name"=>$rows[$i-1]["artist_name"]." - ".$rows[$i-1]["track_title"], + "starts"=>$rows[$i-1]["starts"], + "ends"=>$rows[$i-1]["ends"], + "type"=>'track'); + } + $results['current'] = array("name"=>$rows[$i]["artist_name"]." - ".$rows[$i]["track_title"], + "starts"=>$rows[$i]["starts"], + "ends"=> (($rows[$i]["ends"] > $rows[$i]["show_ends"]) ? $rows[$i]["show_ends"]: $rows[$i]["ends"]), + "media_item_played"=>$rows[$i]["media_item_played"], + "record"=>0, + "type"=>'track'); + if (isset($rows[$i+1])) { + $results['next'] = array("name"=>$rows[$i+1]["artist_name"]." - ".$rows[$i+1]["track_title"], + "starts"=>$rows[$i+1]["starts"], + "ends"=>$rows[$i+1]["ends"], + "type"=>'track'); + } + break; + } + if (strtotime($rows[$i]['ends']) < $timeNowAsMillis ) { + $previousIndex = $i; + } + if (strtotime($rows[$i]['starts']) > $timeNowAsMillis) { + $results['next'] = array("name"=>$rows[$i]["artist_name"]." - ".$rows[$i]["track_title"], + "starts"=>$rows[$i]["starts"], + "ends"=>$rows[$i]["ends"], + "type"=>'track'); + break; + } + } + //If we didn't find a a current show because the time didn't fit we may still have + //found a previous show so use it. + if ($results['previous'] === null && isset($previousIndex)) { + $results['previous'] = array("name"=>$rows[$previousIndex]["artist_name"]." - ".$rows[$previousIndex]["track_title"], + "starts"=>$rows[$previousIndex]["starts"], + "ends"=>$rows[$previousIndex]["ends"]);; + } + + return $results; + } + + public static function GetLastScheduleItem($p_timeNow) + { + $sql = <<= sit.starts + AND st.starts < sit.ends +ORDER BY st.ends DESC LIMIT 1; +SQL; + $row = Application_Common_Database::prepareAndExecute($sql, array(':timeNow'=>$p_timeNow)); + + return $row; + } + + public static function GetCurrentScheduleItem($p_timeNow, $p_instanceId) + { + /* Note that usually there will be one result returned. In some + * rare cases two songs are returned. This happens when a track + * that was overbooked from a previous show appears as if it + * hasnt ended yet (track end time hasn't been reached yet). For + * this reason, we need to get the track that starts later, as + * this is the *real* track that is currently playing. So this + * is why we are ordering by track start time. */ + $sql = "SELECT *" + ." FROM cc_schedule st" + ." LEFT JOIN cc_files ft" + ." ON st.file_id = ft.id" + ." WHERE st.starts <= TIMESTAMP :timeNow1" + ." AND st.instance_id = :instanceId" + ." AND st.ends > TIMESTAMP :timeNow2" + ." ORDER BY st.starts DESC" + ." LIMIT 1"; + + $row = Application_Common_Database::prepareAndExecute($sql, array(':timeNow1'=>$p_timeNow, ':instanceId'=>$p_instanceId, ':timeNow2'=>$p_timeNow,)); + + return $row; + } + + public static function GetNextScheduleItem($p_timeNow) + { + $sql = "SELECT" + ." ft.artist_name, ft.track_title," + ." st.starts as starts, st.ends as ends" + ." FROM cc_schedule st" + ." LEFT JOIN cc_files ft" + ." ON st.file_id = ft.id" + ." LEFT JOIN cc_show_instances sit" + ." ON st.instance_id = sit.id" + ." WHERE st.starts > TIMESTAMP :timeNow" + ." AND st.starts >= sit.starts" //this and the next line are necessary since we can overbook shows. + ." AND st.starts < sit.ends" + ." ORDER BY st.starts" + ." LIMIT 1"; + + $row = Application_Common_Database::prepareAndExecute($sql, array(':timeNow'=>$p_timeNow)); + + return $row; + } + + /* + * + * @param DateTime $p_startDateTime + * + * @param DateTime $p_endDateTime + * + * @return array $scheduledItems + * + */ + public static function GetScheduleDetailItems($p_start, $p_end, $p_shows) + { + $con = Propel::getConnection(); + + $p_start_str = $p_start->format("Y-m-d H:i:s"); + $p_end_str = $p_end->format("Y-m-d H:i:s"); + + + //We need to search 24 hours before and after the show times so that that we + //capture all of the show's contents. + $p_track_start= $p_start->sub(new DateInterval("PT24H"))->format("Y-m-d H:i:s"); + $p_track_end = $p_end->add(new DateInterval("PT24H"))->format("Y-m-d H:i:s"); + + $templateSql = <<= '{$p_track_start}' + AND sched.starts < '{$p_track_end}') + OR (sched.ends > '{$p_track_start}' + AND sched.ends <= '{$p_track_end}') + OR (sched.starts <= '{$p_track_start}' + AND sched.ends >= '{$p_track_end}')) + ) +SQL; + + + $filesSql = str_replace("%%columns%%", + $filesColumns, + $templateSql); + $filesSql= str_replace("%%join%%", + $filesJoin, + $filesSql); + + $streamColumns = <<= '{$p_track_start}' + AND sched.starts < '{$p_track_end}') + OR (sched.ends > '{$p_track_start}' + AND sched.ends <= '{$p_track_end}') + OR (sched.starts <= '{$p_track_start}' + AND sched.ends >= '{$p_track_end}')) + ) + LEFT JOIN cc_subjs AS sub ON (ws.creator_id = sub.id) +SQL; + + $streamSql = str_replace("%%columns%%", + $streamColumns, + $templateSql); + $streamSql = str_replace("%%join%%", + $streamJoin, + $streamSql); + + + $showPredicate = ""; + if (count($p_shows) > 0) { + $showPredicate = " AND show_id IN (".implode(",", $p_shows).")"; + } + + $sql = <<= '{$p_start_str}' + AND si.starts < '{$p_end_str}') + OR (si.ends > '{$p_start_str}' + AND si.ends <= '{$p_end_str}') + OR (si.starts <= '{$p_start_str}' + AND si.ends >= '{$p_end_str}')) +ORDER BY si_starts, + sched_starts; +SQL; + + $rows = $con->query($sql)->fetchAll(PDO::FETCH_ASSOC); + + return $rows; + } + + public static function UpdateMediaPlayedStatus($p_id) + { + $con = Propel::getConnection(); + $sql = "UPDATE cc_schedule" + ." SET media_item_played=TRUE"; + // we need to update 'broadcasted' column as well + // check the current switch status + $live_dj = Application_Model_Preference::GetSourceSwitchStatus('live_dj') == 'on'; + $master_dj = Application_Model_Preference::GetSourceSwitchStatus('master_dj') == 'on'; + $scheduled_play = Application_Model_Preference::GetSourceSwitchStatus('scheduled_play') == 'on'; + + if (!$live_dj && !$master_dj && $scheduled_play) { + $sql .= ", broadcasted=1"; + } + + $sql .= " WHERE id=$p_id"; + + $retVal = $con->exec($sql); + + return $retVal; + } + + public static function UpdateBrodcastedStatus($dateTime, $value) + { + $now = $dateTime->format("Y-m-d H:i:s"); + + $sql = <<= :ends::TIMESTAMP +SQL; + + $retVal = Application_Common_Database::prepareAndExecute($sql, array( + ':broadcastedValue' => $value, + ':starts' => $now, + ':ends' => $now), 'execute'); + return $retVal; + } + + public static function getSchduledPlaylistCount() + { + $con = Propel::getConnection(); + $sql = "SELECT count(*) as cnt FROM cc_schedule"; + + return $con->query($sql)->fetchColumn(0); + } + + /** + * Convert a time string in the format "YYYY-MM-DD HH:mm:SS" + * to "YYYY-MM-DD-HH-mm-SS". + * + * @param string $p_time + * @return string + */ + private static function AirtimeTimeToPypoTime($p_time) + { + $p_time = substr($p_time, 0, 19); + $p_time = str_replace(" ", "-", $p_time); + $p_time = str_replace(":", "-", $p_time); + + return $p_time; + } + + /** + * Convert a time string in the format "YYYY-MM-DD-HH-mm-SS" to + * "YYYY-MM-DD HH:mm:SS". + * + * @param string $p_time + * @return string + */ + private static function PypoTimeToAirtimeTime($p_time) + { + $t = explode("-", $p_time); + + return $t[0]."-".$t[1]."-".$t[2]." ".$t[3].":".$t[4].":00"; + } + + /** + * Return true if the input string is in the format YYYY-MM-DD-HH-mm + * + * @param string $p_time + * @return boolean + */ + public static function ValidPypoTimeFormat($p_time) + { + $t = explode("-", $p_time); + if (count($t) != 5) { + return false; + } + foreach ($t as $part) { + if (!is_numeric($part)) { + return false; + } + } + + return true; + } + + /** + * Converts a time value as a string (with format HH:MM:SS.mmmmmm) to + * millisecs. + * + * @param string $p_time + * @return int + */ + public static function WallTimeToMillisecs($p_time) + { + $t = explode(":", $p_time); + $millisecs = 0; + if (strpos($t[2], ".")) { + $secParts = explode(".", $t[2]); + $millisecs = $secParts[1]; + $millisecs = str_pad(substr($millisecs, 0, 3),3, '0'); + $millisecs = intval($millisecs); + $seconds = intval($secParts[0]); + } else { + $seconds = intval($t[2]); + } + $ret = $millisecs + ($seconds * 1000) + ($t[1] * 60 * 1000) + ($t[0] * 60 * 60 * 1000); + + return $ret; + } + + /** + * Compute the difference between two times in the format . + * "HH:MM:SS.mmmmmm" Note: currently only supports calculating . + * millisec differences . + * + * @param string $p_time1 + * @param string $p_time2 + * @return double + */ + private static function TimeDiff($p_time1, $p_time2) + { + $parts1 = explode(".", $p_time1); + $parts2 = explode(".", $p_time2); + $diff = 0; + if ( (count($parts1) > 1) && (count($parts2) > 1) ) { + $millisec1 = substr($parts1[1], 0, 3); + $millisec1 = str_pad($millisec1, 3, "0"); + $millisec1 = intval($millisec1); + $millisec2 = substr($parts2[1], 0, 3); + $millisec2 = str_pad($millisec2, 3, "0"); + $millisec2 = intval($millisec2); + $diff = abs($millisec1 - $millisec2)/1000; + } + + return $diff; + } + + /** + * Returns an array of schedule items from cc_schedule table. Tries + * to return at least 3 items (if they are available). The parameters + * $p_startTime and $p_endTime specify the range. Schedule items returned + * do not have to be entirely within this range. It is enough that the end + * or beginning of the scheduled item is in the range. + * + * + * @param string $p_startTime + * In the format YYYY-MM-DD HH:MM:SS.nnnnnn + * @param string $p_endTime + * In the format YYYY-MM-DD HH:MM:SS.nnnnnn + * @return array + * Returns null if nothing found, else an array of associative + * arrays representing each row. + */ + public static function getItems($p_startTime, $p_endTime) + { + $baseQuery = << :startTime1 + AND st.starts < :endTime + AND st.playout_status > 0 + AND si.ends > :startTime2 + AND si.modified_instance = 'f' +ORDER BY st.starts +SQL; + + $sql = $baseQuery." ".$predicates; + + $rows = Application_Common_Database::prepareAndExecute($sql, array( + ':startTime1' => $p_startTime, + ':endTime' => $p_endTime, + ':startTime2' => $p_startTime)); + + if (count($rows) < 3) { + $dt = new DateTime("@".time()); + $dt->add(new DateInterval("PT24H")); + $range_end = $dt->format("Y-m-d H:i:s"); + + $predicates = << :startTime1 + AND st.starts < :rangeEnd + AND st.playout_status > 0 + AND si.ends > :startTime2 + AND si.modified_instance = 'f' +ORDER BY st.starts LIMIT 3 +SQL; + + $sql = $baseQuery." ".$predicates." "; + $rows = Application_Common_Database::prepareAndExecute($sql, + array( + ':startTime1' => $p_startTime, + ':rangeEnd' => $range_end, + ':startTime2' => $p_startTime)); + } + + return $rows; + } + + /** + * This function will ensure that an existing index in the + * associative array is never overwritten, instead appending + * _0, _1, _2, ... to the end of the key to make sure it is unique + */ + private static function appendScheduleItem(&$data, $time, $item) + { + $key = $time; + $i = 0; + + while (array_key_exists($key, $data["media"])) { + $key = "{$time}_{$i}"; + $i++; + } + + $data["media"][$key] = $item; + } + + private static function createInputHarborKickTimes(&$data, $range_start, $range_end) + { + $utcTimeZone = new DateTimeZone("UTC"); + $kick_times = Application_Model_ShowInstance::GetEndTimeOfNextShowWithLiveDJ($range_start, $range_end); + foreach ($kick_times as $kick_time_info) { + $kick_time = $kick_time_info['ends']; + $temp = explode('.', Application_Model_Preference::GetDefaultTransitionFade()); + // we round down transition time since PHP cannot handle millisecond. We need to + // handle this better in the future + $transition_time = intval($temp[0]); + $switchOffDataTime = new DateTime($kick_time, $utcTimeZone); + $switch_off_time = $switchOffDataTime->sub(new DateInterval('PT'.$transition_time.'S')); + $switch_off_time = $switch_off_time->format("Y-m-d H:i:s"); + + $kick_start = self::AirtimeTimeToPypoTime($kick_time); + $data["media"][$kick_start]['start'] = $kick_start; + $data["media"][$kick_start]['end'] = $kick_start; + $data["media"][$kick_start]['event_type'] = "kick_out"; + $data["media"][$kick_start]['type'] = "event"; + $data["media"][$kick_start]['independent_event'] = true; + + if ($kick_time !== $switch_off_time) { + $switch_start = self::AirtimeTimeToPypoTime($switch_off_time); + $data["media"][$switch_start]['start'] = $switch_start; + $data["media"][$switch_start]['end'] = $switch_start; + $data["media"][$switch_start]['event_type'] = "switch_off"; + $data["media"][$switch_start]['type'] = "event"; + $data["media"][$switch_start]['independent_event'] = true; + } + } + } + + private static function createFileScheduleEvent(&$data, $item, $media_id, $uri) + { + $start = self::AirtimeTimeToPypoTime($item["start"]); + $end = self::AirtimeTimeToPypoTime($item["end"]); + + list(,,,$start_hour,,) = explode("-", $start); + list(,,,$end_hour,,) = explode("-", $end); + + $same_hour = $start_hour == $end_hour; + $independent_event = !$same_hour; + + $replay_gain = is_null($item["replay_gain"]) ? "0": $item["replay_gain"]; + $replay_gain += Application_Model_Preference::getReplayGainModifier(); + + if ( !Application_Model_Preference::GetEnableReplayGain() ) { + $replay_gain = 0; + } + + $schedule_item = array( + 'id' => $media_id, + 'type' => 'file', + 'row_id' => $item["id"], + 'uri' => $uri, + 'fade_in' => Application_Model_Schedule::WallTimeToMillisecs($item["fade_in"]), + 'fade_out' => Application_Model_Schedule::WallTimeToMillisecs($item["fade_out"]), + 'cue_in' => Application_Common_DateHelper::CalculateLengthInSeconds($item["cue_in"]), + 'cue_out' => Application_Common_DateHelper::CalculateLengthInSeconds($item["cue_out"]), + 'start' => $start, + 'end' => $end, + 'show_name' => $item["show_name"], + 'replay_gain' => $replay_gain, + 'independent_event' => $independent_event, + ); + + if ($schedule_item['cue_in'] > $schedule_item['cue_out']) { + $schedule_item['cue_in'] = $schedule_item['cue_out']; + } + self::appendScheduleItem($data, $start, $schedule_item); + } + + private static function createStreamScheduleEvent(&$data, $item, $media_id, $uri) + { + $start = self::AirtimeTimeToPypoTime($item["start"]); + $end = self::AirtimeTimeToPypoTime($item["end"]); + + //create an event to start stream buffering 5 seconds ahead of the streams actual time. + $buffer_start = new DateTime($item["start"], new DateTimeZone('UTC')); + $buffer_start->sub(new DateInterval("PT5S")); + + $stream_buffer_start = self::AirtimeTimeToPypoTime($buffer_start->format("Y-m-d H:i:s")); + + $schedule_item = array( + 'start' => $stream_buffer_start, + 'end' => $stream_buffer_start, + 'uri' => $uri, + 'row_id' => $item["id"], + 'type' => 'stream_buffer_start', + 'independent_event' => true + ); + + self::appendScheduleItem($data, $start, $schedule_item); + + $schedule_item = array( + 'id' => $media_id, + 'type' => 'stream_output_start', + 'row_id' => $item["id"], + 'uri' => $uri, + 'start' => $start, + 'end' => $end, + 'show_name' => $item["show_name"], + 'row_id' => $item["id"], + 'independent_event' => true + ); + self::appendScheduleItem($data, $start, $schedule_item); + + //since a stream never ends we have to insert an additional "kick stream" event. The "start" + //time of this event is the "end" time of the stream minus 1 second. + $dt = new DateTime($item["end"], new DateTimeZone('UTC')); + $dt->sub(new DateInterval("PT1S")); + + $stream_end = self::AirtimeTimeToPypoTime($dt->format("Y-m-d H:i:s")); + + $schedule_item = array( + 'start' => $stream_end, + 'end' => $stream_end, + 'uri' => $uri, + 'type' => 'stream_buffer_end', + 'row_id' => $item["id"], + 'independent_event' => true + ); + self::appendScheduleItem($data, $stream_end, $schedule_item); + + $schedule_item = array( + 'start' => $stream_end, + 'end' => $stream_end, + 'uri' => $uri, + 'type' => 'stream_output_end', + 'independent_event' => true + ); + self::appendScheduleItem($data, $stream_end, $schedule_item); + } + + private static function getRangeStartAndEnd($p_fromDateTime, $p_toDateTime) + { + $CC_CONFIG = Config::getConfig(); + + /* if $p_fromDateTime and $p_toDateTime function parameters are null, + then set range * from "now" to "now + 24 hours". */ + if (is_null($p_fromDateTime)) { + $t1 = new DateTime("@".time()); + $range_start = $t1->format("Y-m-d H:i:s"); + } else { + $range_start = Application_Model_Schedule::PypoTimeToAirtimeTime($p_fromDateTime); + } + if (is_null($p_fromDateTime)) { + $t2 = new DateTime("@".time()); + + $cache_ahead_hours = $CC_CONFIG["cache_ahead_hours"]; + + if (is_numeric($cache_ahead_hours)) { + //make sure we are not dealing with a float + $cache_ahead_hours = intval($cache_ahead_hours); + } else { + $cache_ahead_hours = 1; + } + + $t2->add(new DateInterval("PT".$cache_ahead_hours."H")); + $range_end = $t2->format("Y-m-d H:i:s"); + } else { + $range_end = Application_Model_Schedule::PypoTimeToAirtimeTime($p_toDateTime); + } + + return array($range_start, $range_end); + } + + + private static function createScheduledEvents(&$data, $range_start, $range_end) + { + $utcTimeZone = new DateTimeZone("UTC"); + $items = self::getItems($range_start, $range_end); + foreach ($items as $item) { + $showEndDateTime = new DateTime($item["show_end"], $utcTimeZone); + + $trackStartDateTime = new DateTime($item["start"], $utcTimeZone); + $trackEndDateTime = new DateTime($item["end"], $utcTimeZone); + + if ($trackStartDateTime->getTimestamp() > $showEndDateTime->getTimestamp()) { + //do not send any tracks that start past their show's end time + continue; + } + + if ($trackEndDateTime->getTimestamp() > $showEndDateTime->getTimestamp()) { + $di = $trackStartDateTime->diff($showEndDateTime); + + $item["cue_out"] = $di->format("%H:%i:%s").".000"; + $item["end"] = $showEndDateTime->format("Y-m-d H:i:s"); + } + + if (!is_null($item['file_id'])) { + //row is from "file" + $media_id = $item['file_id']; + $storedFile = Application_Model_StoredFile::Recall($media_id); + $uri = $storedFile->getFilePath(); + self::createFileScheduleEvent($data, $item, $media_id, $uri); + } elseif (!is_null($item['stream_id'])) { + //row is type "webstream" + $media_id = $item['stream_id']; + $uri = $item['url']; + self::createStreamScheduleEvent($data, $item, $media_id, $uri); + } else { + throw new Exception("Unknown schedule type: ".print_r($item, true)); + } + + } + } + + /* Check if two events are less than or equal to 1 second apart + */ + public static function areEventsLinked($event1, $event2) { + $dt1 = DateTime::createFromFormat("Y-m-d-H-i-s", $event1['start']); + $dt2 = DateTime::createFromFormat("Y-m-d-H-i-s", $event2['start']); + + $seconds = $dt2->getTimestamp() - $dt1->getTimestamp(); + return $seconds <= 1; + } + + /** + * Streams are a 4 stage process. + * 1) start buffering stream 5 seconds ahead of its start time + * 2) at the start time tell liquidsoap to switch to this source + * 3) at the end time, tell liquidsoap to stop reading this stream + * 4) at the end time, tell liquidsoap to switch away from input.http source. + * + * When we have two streams back-to-back, some of these steps are unnecessary + * for the second stream. Instead of sending commands 1,2,3,4,1,2,3,4 we should + * send 1,2,1,2,3,4 - We don't need to tell liquidsoap to stop reading (#3), because #1 + * of the next stream implies this when we pass in a new url. We also don't need #4. + * + * There's a special case here is well. When the back-to-back streams are the same, we + * can collapse the instructions 1,2,(3,4,1,2),3,4 to 1,2,3,4. We basically cut out the + * middle part. This function handles this. + */ + private static function foldData(&$data) + { + $previous_key = null; + $previous_val = null; + $previous_previous_key = null; + $previous_previous_val = null; + $previous_previous_previous_key = null; + $previous_previous_previous_val = null; + foreach ($data as $k => $v) { + + if ($v["type"] == "stream_output_start" + && !is_null($previous_previous_val) + && $previous_previous_val["type"] == "stream_output_end" + && self::areEventsLinked($previous_previous_val, $v)) { + + unset($data[$previous_previous_previous_key]); + unset($data[$previous_previous_key]); + unset($data[$previous_key]); + if ($previous_previous_val['uri'] == $v['uri']) { + unset($data[$k]); + } + } + + $previous_previous_previous_key = $previous_previous_key; + $previous_previous_previous_val = $previous_previous_val; + $previous_previous_key = $previous_key; + $previous_previous_val = $previous_val; + $previous_key = $k; + $previous_val = $v; + } + } + + public static function getSchedule($p_fromDateTime = null, $p_toDateTime = null) + { + list($range_start, $range_end) = self::getRangeStartAndEnd($p_fromDateTime, $p_toDateTime); + + $data = array(); + $data["media"] = array(); + + //Harbor kick times *MUST* be ahead of schedule events, so that pypo + //executes them first. + self::createInputHarborKickTimes($data, $range_start, $range_end); + self::createScheduledEvents($data, $range_start, $range_end); + + self::foldData($data["media"]); + return $data; + } + + public static function deleteAll() + { + $con = Propel::getConnection(); + $con->exec("TRUNCATE TABLE cc_schedule"); + } + + public static function deleteWithFileId($fileId) + { + $sql = "DELETE FROM cc_schedule WHERE file_id=:file_id"; + Application_Common_Database::prepareAndExecute($sql, array(':file_id'=>$fileId), 'execute'); + } + + public static function createNewFormSections($p_view) + { + $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(); + + $formWhat->removeDecorator('DtDdWrapper'); + $formWho->removeDecorator('DtDdWrapper'); + $formWhen->removeDecorator('DtDdWrapper'); + $formRepeats->removeDecorator('DtDdWrapper'); + $formStyle->removeDecorator('DtDdWrapper'); + $formLive->removeDecorator('DtDdWrapper'); + + $p_view->what = $formWhat; + $p_view->when = $formWhen; + $p_view->repeats = $formRepeats; + $p_view->who = $formWho; + $p_view->style = $formStyle; + $p_view->live = $formLive; + + $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"))); + + $formRecord = new Application_Form_AddShowRR(); + $formAbsoluteRebroadcast = new Application_Form_AddShowAbsoluteRebroadcastDates(); + $formRebroadcast = new Application_Form_AddShowRebroadcastDates(); + + $formRecord->removeDecorator('DtDdWrapper'); + $formAbsoluteRebroadcast->removeDecorator('DtDdWrapper'); + $formRebroadcast->removeDecorator('DtDdWrapper'); + + $p_view->rr = $formRecord; + $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). + * There is still lots of clean-up to do. For example we shouldn't be passing $controller into + * this method to manipulate the view (this should be done inside the controller function). With + * 2.1 deadline looming, this is OK for now. -Martin */ + public static function updateShowInstance($data, $controller) + { + $formWhat = new Application_Form_AddShowWhat(); + $formWhen = new Application_Form_AddShowWhen(); + $formRepeats = new Application_Form_AddShowRepeats(); + $formWho = new Application_Form_AddShowWho(); + $formStyle = new Application_Form_AddShowStyle(); + $formLive = new Application_Form_AddShowLiveStream(); + + $formWhat->removeDecorator('DtDdWrapper'); + $formWhen->removeDecorator('DtDdWrapper'); + $formRepeats->removeDecorator('DtDdWrapper'); + $formWho->removeDecorator('DtDdWrapper'); + $formStyle->removeDecorator('DtDdWrapper'); + $formLive->removeDecorator('DtDdWrapper'); + + $formRecord = new Application_Form_AddShowRR(); + $formAbsoluteRebroadcast = new Application_Form_AddShowAbsoluteRebroadcastDates(); + $formRebroadcast = new Application_Form_AddShowRebroadcastDates(); + + $formRecord->removeDecorator('DtDdWrapper'); + $formAbsoluteRebroadcast->removeDecorator('DtDdWrapper'); + $formRebroadcast->removeDecorator('DtDdWrapper'); + $when = $formWhen->isValid($data); + + if ($when && $formWhen->checkReliantFields($data, true, null, true)) { + $start_dt = new DateTime($data['add_show_start_date']." ".$data['add_show_start_time'], + new DateTimeZone(date_default_timezone_get())); + $start_dt->setTimezone(new DateTimeZone('UTC')); + + $end_dt = new DateTime($data['add_show_end_date_no_repeat']." ".$data['add_show_end_time'], + new DateTimeZone(date_default_timezone_get())); + $end_dt->setTimezone(new DateTimeZone('UTC')); + + $ccShowInstance = CcShowInstancesQuery::create()->findPK($data["add_show_instance_id"]); + $ccShowInstance->setDbStarts($start_dt); + $ccShowInstance->setDbEnds($end_dt); + $ccShowInstance->save(); + + Application_Model_Schedule::createNewFormSections($controller->view); + + return true; + } else { + $formWhat->disable(); + $formWhen->disableRepeatCheckbox(); + $formRepeats->disable(); + $formWho->disable(); + $formStyle->disable(); + //$formLive->disable(); + + $controller->view->what = $formWhat; + $controller->view->when = $formWhen; + $controller->view->repeats = $formRepeats; + $controller->view->who = $formWho; + $controller->view->style = $formStyle; + $controller->view->live = $formLive; + $controller->view->rr = $formRecord; + $controller->view->absoluteRebroadcast = $formAbsoluteRebroadcast; + $controller->view->rebroadcast = $formRebroadcast; + + //$formRecord->disable(); + //$formAbsoluteRebroadcast->disable(); + //$formRebroadcast->disable(); + + return false; + } + } + + /* This function is responsible for handling the case where the entire show (not a single show instance) + * was edited (via the context menu in the Calendar). + * There is still lots of clean-up to do. For example we shouldn't be passing $controller into + * this method to manipulate the view (this should be done inside the controller function). With + * 2.1 deadline looming, this is OK for now. + * Another clean-up is to move all the form manipulation to the proper form class..... + * -Martin + */ + public static function addUpdateShow($data, $controller, $validateStartDate, + $originalStartDate=null, $update=false, $instanceId=null) + { + $userInfo = Zend_Auth::getInstance()->getStorage()->read(); + $user = new Application_Model_User($userInfo->id); + $isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER)); + + $record = false; + + $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(); + + $formWhat->removeDecorator('DtDdWrapper'); + $formWho->removeDecorator('DtDdWrapper'); + $formWhen->removeDecorator('DtDdWrapper'); + $formRepeats->removeDecorator('DtDdWrapper'); + $formStyle->removeDecorator('DtDdWrapper'); + $formLive->removeDecorator('DtDdWrapper'); + + $what = $formWhat->isValid($data); + $when = $formWhen->isValid($data); + $live = $formLive->isValid($data); + if ($when) { + $when = $formWhen->checkReliantFields($data, $validateStartDate, $originalStartDate, $update, $instanceId); + } + + //The way the following code works is that is parses the hour and + //minute from a string with the format "1h 20m" or "2h" or "36m". + //So we are detecting whether an hour or minute value exists via strpos + //and then parse appropriately. A better way to do this in the future is + //actually pass the format from javascript in the format hh:mm so we don't + //have to do this extra String parsing. + $hPos = strpos($data["add_show_duration"], 'h'); + $mPos = strpos($data["add_show_duration"], 'm'); + + $hValue = 0; + $mValue = 0; + + if ($hPos !== false) { + $hValue = trim(substr($data["add_show_duration"], 0, $hPos)); + } + if ($mPos !== false) { + $hPos = $hPos === false ? 0 : $hPos+1; + $mValue = trim(substr($data["add_show_duration"], $hPos, -1 )); + } + + $data["add_show_duration"] = $hValue.":".$mValue; + + $formRecord = new Application_Form_AddShowRR(); + $formAbsoluteRebroadcast = new Application_Form_AddShowAbsoluteRebroadcastDates(); + $formRebroadcast = new Application_Form_AddShowRebroadcastDates(); + + $formRecord->removeDecorator('DtDdWrapper'); + $formAbsoluteRebroadcast->removeDecorator('DtDdWrapper'); + $formRebroadcast->removeDecorator('DtDdWrapper'); + + + $record = $formRecord->isValid($data); + + if ($data["add_show_repeats"]) { + $repeats = $formRepeats->isValid($data); + if ($repeats) { + $repeats = $formRepeats->checkReliantFields($data); + } + $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; + } + } else { + $repeats = 1; + $formRebroadcast->reset(); + //make it valid, results don't matter anyways. + $rebroad = 1; + + if ($data["add_show_rebroadcast"]) { + $rebroadAb = $formAbsoluteRebroadcast->isValid($data); + if ($rebroadAb) { + $rebroadAb = $formAbsoluteRebroadcast->checkReliantFields($data); + } + } else { + $rebroadAb = 1; + } + } + + $who = $formWho->isValid($data); + $style = $formStyle->isValid($data); + if ($what && $when && $repeats && $who && $style && $live) { + if ($record && $rebroadAb && $rebroad) { + if ($isAdminOrPM) { + Application_Model_Show::create($data); + } + + //send back a new form for the user. + Application_Model_Schedule::createNewFormSections($controller->view); + + //$controller->view->newForm = $controller->view->render('schedule/add-show-form.phtml'); + return true; + } else { + $controller->view->what = $formWhat; + $controller->view->when = $formWhen; + $controller->view->repeats = $formRepeats; + $controller->view->who = $formWho; + $controller->view->style = $formStyle; + $controller->view->rr = $formRecord; + $controller->view->absoluteRebroadcast = $formAbsoluteRebroadcast; + $controller->view->rebroadcast = $formRebroadcast; + $controller->view->live = $formLive; + //$controller->view->addNewShow = !$editShow; + + //$controller->view->form = $controller->view->render('schedule/add-show-form.phtml'); + return false; + + } + } else { + $controller->view->what = $formWhat; + $controller->view->when = $formWhen; + $controller->view->repeats = $formRepeats; + $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->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) + { + $overlapping = false; + + $params = array( + ':show_end1' => $show_end->format('Y-m-d H:i:s'), + ':show_end2' => $show_end->format('Y-m-d H:i:s'), + ':show_end3' => $show_end->format('Y-m-d H:i:s') + ); + + + /* If a show is being edited, exclude it from the query + * In both cases (new and edit) we only grab shows that + * are scheduled 2 days prior + */ + if ($update) { + $sql = <<= (date(:show_end3) - INTERVAL '2 days') + AND modified_instance = FALSE +SQL; + if (is_null($showId)) { + $sql .= <<= (date(:show_end3) - INTERVAL '2 days') + AND modified_instance = FALSE +ORDER BY ends +SQL; + + $rows = Application_Common_Database::prepareAndExecute($sql, array( + ':show_end1' => $show_end->format('Y-m-d H:i:s'), + ':show_end2' => $show_end->format('Y-m-d H:i:s'), + ':show_end3' => $show_end->format('Y-m-d H:i:s')), 'all'); + } + + foreach ($rows as $row) { + $start = new DateTime($row["starts"], new DateTimeZone('UTC')); + $end = new DateTime($row["ends"], new DateTimeZone('UTC')); + + if ($show_start->getTimestamp() < $end->getTimestamp() && + $show_end->getTimestamp() > $start->getTimestamp()) { + $overlapping = true; + break; + } + } + + return $overlapping; + } + + public static function GetType($p_scheduleId){ + $scheduledItem = CcScheduleQuery::create()->findPK($p_scheduleId); + if ($scheduledItem->getDbFileId() == null) { + return 'webstream'; + } else { + return 'file'; + } + } + + public static function GetFileId($p_scheduleId) + { + $scheduledItem = CcScheduleQuery::create()->findPK($p_scheduleId); + + return $scheduledItem->getDbFileId(); + } + + public static function GetStreamId($p_scheduleId) + { + $scheduledItem = CcScheduleQuery::create()->findPK($p_scheduleId); + + return $scheduledItem->getDbStreamId(); + } +} diff --git a/airtime_mvc/application/services/ScheduleService.php b/airtime_mvc/application/services/ScheduleService.php new file mode 100644 index 000000000..983d1bd6f --- /dev/null +++ b/airtime_mvc/application/services/ScheduleService.php @@ -0,0 +1,90 @@ +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_record"] = $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 array of booleans + */ + public function validateShowForms($forms) + { + + } + + /** + * + * Creates a new show if form data is valid + */ + public function createShow() + { + + } +} \ No newline at end of file From bdab294fce0085b99927aaa33aa5ba5f16bd4135 Mon Sep 17 00:00:00 2001 From: drigato Date: Mon, 25 Feb 2013 09:15:03 -0500 Subject: [PATCH 08/73] Added comments to Schedule Service --- .../application/controllers/ScheduleController.php | 1 + airtime_mvc/application/models/Schedule.php | 7 +++---- airtime_mvc/application/services/ScheduleService.php | 11 ++++++++++- 3 files changed, 14 insertions(+), 5 deletions(-) diff --git a/airtime_mvc/application/controllers/ScheduleController.php b/airtime_mvc/application/controllers/ScheduleController.php index 9ca879918..ae91308e4 100644 --- a/airtime_mvc/application/controllers/ScheduleController.php +++ b/airtime_mvc/application/controllers/ScheduleController.php @@ -871,6 +871,7 @@ class ScheduleController extends Zend_Controller_Action $data[$j["name"]] = $j["value"]; } + // TODO: move this to js $data['add_show_hosts'] = $this->_getParam('hosts'); $data['add_show_day_check'] = $this->_getParam('days'); diff --git a/airtime_mvc/application/models/Schedule.php b/airtime_mvc/application/models/Schedule.php index 2778074d2..36aedf96c 100644 --- a/airtime_mvc/application/models/Schedule.php +++ b/airtime_mvc/application/models/Schedule.php @@ -1220,10 +1220,9 @@ 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; diff --git a/airtime_mvc/application/services/ScheduleService.php b/airtime_mvc/application/services/ScheduleService.php index 983d1bd6f..f5f397561 100644 --- a/airtime_mvc/application/services/ScheduleService.php +++ b/airtime_mvc/application/services/ScheduleService.php @@ -2,6 +2,13 @@ class Application_Service_ScheduleService { +/* + * 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 @@ -78,7 +85,9 @@ class Application_Service_ScheduleService { } - +/* + * Form stuff ends + */ /** * * Creates a new show if form data is valid From 99c07272fd51340b7341a9ad65193b46aa9f065c Mon Sep 17 00:00:00 2001 From: denise Date: Mon, 25 Feb 2013 17:31:43 -0500 Subject: [PATCH 09/73] - Moved all form validation to it's own function in schedule service - Moved show creation to it's own function in schedule service --- .../controllers/ScheduleController.php | 29 +++-- .../forms/AddShowAbsoluteRebroadcastDates.php | 8 ++ .../forms/AddShowRebroadcastDates.php | 8 ++ .../application/forms/AddShowRepeats.php | 8 ++ airtime_mvc/application/forms/AddShowWhen.php | 8 ++ airtime_mvc/application/models/Schedule.php | 4 +- airtime_mvc/application/models/Show.php | 32 +++--- .../application/services/ScheduleService.php | 104 +++++++++++++++++- 8 files changed, 167 insertions(+), 34 deletions(-) diff --git a/airtime_mvc/application/controllers/ScheduleController.php b/airtime_mvc/application/controllers/ScheduleController.php index ae91308e4..ea95d4bc7 100644 --- a/airtime_mvc/application/controllers/ScheduleController.php +++ b/airtime_mvc/application/controllers/ScheduleController.php @@ -104,7 +104,7 @@ class ScheduleController extends Zend_Controller_Action $this->view->repeats = $forms["repeats"]; $this->view->live = $forms["live"]; $this->view->rr = $forms["record"]; - $this->view->absoluteRebroadcast = $forms["abs_record"]; + $this->view->absoluteRebroadcast = $forms["abs_rebroadcast"]; $this->view->rebroadcast = $forms["rebroadcast"]; $this->view->who = $forms["who"]; $this->view->style = $forms["style"]; @@ -879,19 +879,26 @@ class ScheduleController extends Zend_Controller_Action $data['add_show_day_check'] = null; } - $validateStartDate = true; - $success = Application_Model_Schedule::addUpdateShow($data, $this, - $validateStartDate); + $forms = $this->service_schedule->createShowForms(); - if ($success) { - $this->view->addNewShow = true; - $this->view->newForm = $this->view->render( - 'schedule/add-show-form.phtml'); + $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"]; + + $this->view->addNewShow = true; + + if ($this->service_schedule->validateShowForms($forms, $data)) { + $this->view->newForm = $this->view->render('schedule/add-show-form.phtml'); + $this->service_schedule->createShow($data); 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"); } } 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..375942894 100644 --- a/airtime_mvc/application/forms/AddShowRepeats.php +++ b/airtime_mvc/application/forms/AddShowRepeats.php @@ -66,6 +66,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..9f73affbd 100644 --- a/airtime_mvc/application/forms/AddShowWhen.php +++ b/airtime_mvc/application/forms/AddShowWhen.php @@ -87,6 +87,14 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm } + public function isWhenFormValid($formData, $validateStartDate) { + if (parent::isValid($formData)) { + return self::checkReliantFields($formData, $validateStartDate); + } else { + return false; + } + } + public function checkReliantFields($formData, $validateStartDate, $originalStartDate=null, $update=false, $instanceId=null) { $valid = true; diff --git a/airtime_mvc/application/models/Schedule.php b/airtime_mvc/application/models/Schedule.php index 36aedf96c..6b19c5e3d 100644 --- a/airtime_mvc/application/models/Schedule.php +++ b/airtime_mvc/application/models/Schedule.php @@ -1088,7 +1088,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(); @@ -1227,7 +1227,7 @@ SQL; //$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) diff --git a/airtime_mvc/application/models/Show.php b/airtime_mvc/application/models/Show.php index f485e41bc..493f3ca37 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,28 @@ 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) { - $ccShow = new CcShow(); + /*$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,11 +1162,11 @@ 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) { $show = new Application_Model_Show($showId); @@ -1178,7 +1180,7 @@ SQL; } //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,7 +1217,7 @@ 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. diff --git a/airtime_mvc/application/services/ScheduleService.php b/airtime_mvc/application/services/ScheduleService.php index f5f397561..1204f689c 100644 --- a/airtime_mvc/application/services/ScheduleService.php +++ b/airtime_mvc/application/services/ScheduleService.php @@ -43,7 +43,7 @@ class Application_Service_ScheduleService $forms["style"] = $formStyle; $forms["live"] = $formLive; $forms["record"] = $formRecord; - $forms["abs_record"] = $formAbsoluteRebroadcast; + $forms["abs_rebroadcast"] = $formAbsoluteRebroadcast; $forms["rebroadcast"] = $formRebroadcast; return $forms; @@ -79,21 +79,113 @@ class Application_Service_ScheduleService * * Validates show forms * - * @return array of booleans + * @return boolean */ - public function validateShowForms($forms) + public function validateShowForms($forms, $formData, $validateStartDate = true) { - + $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); + + $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; + } + /** * * Creates a new show if form data is valid */ - public function createShow() + public function createShow($showData) { - + $userInfo = Zend_Auth::getInstance()->getStorage()->read(); + $user = new Application_Model_User($userInfo->id); + $isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER)); + + $repeatType = ($showData['add_show_repeats']) ? $showData['add_show_repeat_type'] : -1; + $isRecorded = (isset($showData['add_show_record']) && $showData['add_show_record']) ? 1 : 0; + + $showData["add_show_duration"] = $this->formatShowDuration( + $showData["add_show_duration"]); + + if ($isAdminOrPM) { + $service_show = new Application_Service_ShowService(); + + //create ccShow + $ccShow = new CcShow(); + $ccShow = $service_show->setShow($ccShow, $showData); + + //create ccShowDay + $service_show->createShowDays( + $showData, $ccShow->getDbId(), $user->getId(), $repeatType, $isRecorded); + + //create ccShowHosts + + //create ccShowRebroadcast + + //populate ccShowInstances + } } + } \ No newline at end of file From d497cfa85791f1edf07d128e357404da1f000c0e Mon Sep 17 00:00:00 2001 From: denise Date: Tue, 26 Feb 2013 10:20:02 -0500 Subject: [PATCH 10/73] Created show service --- airtime_mvc/application/models/Show.php | 8 +- airtime_mvc/application/models/_old_Show.php | 2241 +++++++++++++++++ .../application/services/ScheduleService.php | 11 +- .../application/services/ShowService.php | 145 ++ 4 files changed, 2397 insertions(+), 8 deletions(-) create mode 100644 airtime_mvc/application/models/_old_Show.php create mode 100644 airtime_mvc/application/services/ShowService.php diff --git a/airtime_mvc/application/models/Show.php b/airtime_mvc/application/models/Show.php index 493f3ca37..d6f9db98b 100644 --- a/airtime_mvc/application/models/Show.php +++ b/airtime_mvc/application/models/Show.php @@ -1229,7 +1229,7 @@ SQL; //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(); @@ -1266,14 +1266,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) { 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(); @@ -1281,7 +1281,7 @@ SQL; $showHost->setDbHost($host); $showHost->save(); } - } + }*/ if ($data['add_show_id'] != -1) { $con = Propel::getConnection(CcSchedulePeer::DATABASE_NAME); diff --git a/airtime_mvc/application/models/_old_Show.php b/airtime_mvc/application/models/_old_Show.php new file mode 100644 index 000000000..f485e41bc --- /dev/null +++ b/airtime_mvc/application/models/_old_Show.php @@ -0,0 +1,2241 @@ +_showId = $showId; + } + + public function getName() + { + $show = CcShowQuery::create()->findPK($this->_showId); + + return $show->getDbName(); + } + + public function setName($name) + { + $show = CcShowQuery::create()->findPK($this->_showId); + $show->setDbName($name); + Application_Model_RabbitMq::PushSchedule(); + } + + public function setAirtimeAuthFlag($flag) + { + $show = CcShowQuery::create()->findPK($this->_showId); + $show->setDbLiveStreamUsingAirtimeAuth($flag); + $show->save(); + } + + public function setCustomAuthFlag($flag) + { + $show = CcShowQuery::create()->findPK($this->_showId); + $show->setDbLiveStreamUsingCustomAuth($flag); + $show->save(); + } + + public function setCustomUsername($username) + { + $show = CcShowQuery::create()->findPK($this->_showId); + $show->setDbLiveStreamUser($username); + $show->save(); + } + + public function setCustomPassword($password) + { + $show = CcShowQuery::create()->findPK($this->_showId); + $show->setDbLiveStreamPass($password); + $show->save(); + } + + public function getDescription() + { + $show = CcShowQuery::create()->findPK($this->_showId); + + return $show->getDbDescription(); + } + + public function setDescription($description) + { + $show = CcShowQuery::create()->findPK($this->_showId); + $show->setDbDescription($description); + } + + public function getColor() + { + $show = CcShowQuery::create()->findPK($this->_showId); + + return $show->getDbColor(); + } + + public function setColor($color) + { + $show = CcShowQuery::create()->findPK($this->_showId); + $show->setDbColor($color); + } + + public function getUrl() + { + $show = CcShowQuery::create()->findPK($this->_showId); + + return $show->getDbUrl(); + } + + /*TODO : This method is not actually used anywhere as far as I can tell. We + can safely remove it and probably many other superfluous methods. + --RG*/ + + public function setUrl($p_url) + { + $show = CcShowQuery::create()->findPK($this->_showId); + $show->setDbUrl($p_url); + } + + public function getGenre() + { + $show = CcShowQuery::create()->findPK($this->_showId); + + return $show->getDbGenre(); + } + + public function setGenre($p_genre) + { + $show = CcShowQuery::create()->findPK($this->_showId); + $show->setDbGenre($p_genre); + } + + public function getBackgroundColor() + { + $show = CcShowQuery::create()->findPK($this->_showId); + + return $show->getDbBackgroundColor(); + } + + public function setBackgroundColor($backgroundColor) + { + $show = CcShowQuery::create()->findPK($this->_showId); + $show->setDbBackgroundColor($backgroundColor); + } + + public function getId() + { + return $this->_showId; + } + + public function getHosts() + { + $sql = << $this->getId() ), 'all'); + + $res = array(); + foreach ($hosts as $host) { + $res[] = $host['first_name']." ".$host['last_name']; + } + return $res; + } + + public function getHostsIds() + { + $sql = << $this->getId() ), 'all'); + + return $hosts; + } + + /** + * remove everything about this show. + */ + public function delete() + { + //usually we hide the show-instance, but in this case we are deleting the show template + //so delete all show-instances as well. + CcShowInstancesQuery::create()->filterByDbOriginalShow($this->_showId)->delete(); + + $show = CcShowQuery::create()->findPK($this->_showId); + $show->delete(); + } + + public function resizeShow($deltaDay, $deltaMin) + { + $con = Propel::getConnection(); + + if ($deltaDay > 0) { + return _("Shows can have a max length of 24 hours."); + } + + $utc = new DateTimeZone("UTC"); + + $nowDateTime = new DateTime("now", $utc); + + $showInstances = CcShowInstancesQuery::create() + ->filterByDbShowId($this->_showId) + ->find($con); + + /* Check two things: + 1. If the show being resized and any of its repeats end in the past + 2. If the show being resized and any of its repeats overlap + with other scheduled shows */ + + foreach ($showInstances as $si) { + $startsDateTime = new DateTime($si->getDbStarts(), new DateTimeZone("UTC")); + $endsDateTime = new DateTime($si->getDbEnds(), new DateTimeZone("UTC")); + + /* 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 local * timestamp and + then converted back to UTC to avoid show time changes */ + $startsDateTime->setTimezone(new DateTimeZone(date_default_timezone_get())); + $endsDateTime->setTimezone(new DateTimeZone(date_default_timezone_get())); + + $newStartsDateTime = Application_Model_ShowInstance::addDeltas($startsDateTime, $deltaDay, $deltaMin); + $newEndsDateTime = Application_Model_ShowInstance::addDeltas($endsDateTime, $deltaDay, $deltaMin); + + if ($newEndsDateTime->getTimestamp() < $nowDateTime->getTimestamp()) { + return _("End date/time cannot be in the past"); + } + + //convert our new starts/ends to UTC. + $newStartsDateTime->setTimezone($utc); + $newEndsDateTime->setTimezone($utc); + + $overlapping = Application_Model_Schedule::checkOverlappingShows( + $newStartsDateTime, $newEndsDateTime, true, $si->getDbId()); + + if ($overlapping) { + return _("Cannot schedule overlapping shows.\nNote: Resizing a repeating show ". + "affects all of its repeats."); + } + } + + $hours = $deltaMin/60; + $hours = ($hours > 0) ? floor($hours) : ceil($hours); + $mins = abs($deltaMin % 60); + + //current timesamp in UTC. + $current_timestamp = gmdate("Y-m-d H:i:s"); + + $sql_gen = << :current_timestamp1) + AND ((ends + :deltaDay2::INTERVAL + :interval2::INTERVAL - starts) <= interval '24:00') +SQL; + + Application_Common_Database::prepareAndExecute($sql_gen, + array( + ':deltaDay1' => "$deltaDay days", + ':interval1' => "$hours:$mins", + ':show_id1' => $this->_showId, + ':current_timestamp1' => $current_timestamp, + ':deltaDay2' => "$deltaDay days", + ':interval2' => "$hours:$mins" + ), "execute"); + + $sql_gen = << "$deltaDay days", + ':interval3' => "$hours:$mins", + ':show_id2' => $this->_showId, + ':deltaDay4' => "$deltaDay days", + ':interval4' => "$hours:$mins" + ), "execute"); + + $con = Propel::getConnection(CcSchedulePeer::DATABASE_NAME); + $con->beginTransaction(); + + try { + //update the status flag in cc_schedule. + + /* Since we didn't use a propel object when updating + * cc_show_instances table we need to clear the instances + * so the correct information is retrieved from the db + */ + CcShowInstancesPeer::clearInstancePool(); + + $instances = CcShowInstancesQuery::create() + ->filterByDbEnds($current_timestamp, Criteria::GREATER_THAN) + ->filterByDbShowId($this->_showId) + ->find($con); + + foreach ($instances as $instance) { + $instance->updateScheduleStatus($con); + } + + $con->commit(); + } catch (Exception $e) { + $con->rollback(); + Logging::info("Couldn't update schedule status."); + Logging::info($e->getMessage()); + } + + Application_Model_RabbitMq::PushSchedule(); + } + + public function cancelShow($day_timestamp) + { + $timeinfo = explode(" ", $day_timestamp); + + CcShowDaysQuery::create() + ->filterByDbShowId($this->_showId) + ->update(array('DbLastShow' => $timeinfo[0])); + + $sql = <<= :dayTimestamp::TIMESTAMP + AND show_id = :showId +SQL; + + $rows = Application_Common_Database::prepareAndExecute( $sql, array( + ':dayTimestamp' => $day_timestamp, + ':showId' => $this->getId()), 'all'); + + foreach ($rows as $row) { + try { + $showInstance = new Application_Model_ShowInstance($row["id"]); + $showInstance->delete($rabbitmqPush = false); + } catch (Exception $e) { + Logging::info($e->getMessage()); + } + } + + Application_Model_RabbitMq::PushSchedule(); + } + + /** + * This function is called when a repeating show is edited and the + * days that is repeats on have changed. More specifically, a day + * that the show originally repeated on has been "unchecked". + * + * Removes Show Instances that occur on days of the week specified + * by input array. For example, if array contains one value of "0", + * (0 = Sunday, 1=Monday) then all show instances that occur on + * Sunday are removed. + * + * @param array p_uncheckedDays + * An array specifying which days should be removed. (in the local timezone) + */ + public function removeUncheckedDaysInstances($p_uncheckedDays) + { + //need to convert local doftw to UTC doftw (change made for 2.0 since shows are stored in UTC) + $daysRemovedUTC = array(); + + $showDays = CcShowDaysQuery::create() + ->filterByDbShowId($this->getId()) + ->find(); + + Logging::info("Unchecked days:"); + foreach ($p_uncheckedDays as $day) { + Logging::info($day); + } + + foreach ($showDays as $showDay) { + //Logging::info("Local show day is: {$showDay->getDbDay()}"); + //Logging::info("First show day is: {$showDay->getDbFirstShow()}"); + //Logging::info("Id show days is: {$showDay->getDbId()}"); + + if (in_array($showDay->getDbDay(), $p_uncheckedDays)) { + $showDay->reload(); + //Logging::info("Local show day is: {$showDay->getDbDay()}"); + //Logging::info("First show day is: {$showDay->getDbFirstShow()}"); + //Logging::info("Id show days is: {$showDay->getDbId()}"); + $startDay = new DateTime("{$showDay->getDbFirstShow()} {$showDay->getDbStartTime()}", new DateTimeZone($showDay->getDbTimezone())); + //Logging::info("Show start day: {$startDay->format('Y-m-d H:i:s')}"); + $startDay->setTimezone(new DateTimeZone("UTC")); + //Logging::info("Show start day UTC: {$startDay->format('Y-m-d H:i:s')}"); + $daysRemovedUTC[] = $startDay->format('w'); + //Logging::info("UTC show day is: {$startDay->format('w')}"); + } + } + + $uncheckedDaysImploded = implode(",", $daysRemovedUTC); + $showId = $this->getId(); + + $esc_uncheckedDays = pg_escape_string($uncheckedDaysImploded); + $timestamp = gmdate("Y-m-d H:i:s"); + + $sql = << :timestamp::TIMESTAMP + AND show_id = :showId +SQL; + + Application_Common_Database::prepareAndExecute( $sql, + array( + ":timestamp" => $timestamp, + ":showId" => $showId, + ), "execute"); + } + + /** + * Check whether the current show originated + * from a recording. + * + * @return boolean + * true if originated from recording, otherwise false. + */ + public function isRecorded() + { + $showInstancesRow = CcShowInstancesQuery::create() + ->filterByDbShowId($this->getId()) + ->filterByDbRecord(1) + ->filterByDbModifiedInstance(false) + ->findOne(); + + return !is_null($showInstancesRow); + } + + /** + * Check whether the current show has rebroadcasts of a recorded + * show. Should be used in conjunction with isRecorded(). + * + * @return boolean + * true if show has rebroadcasts, otherwise false. + */ + public function isRebroadcast() + { + $showInstancesRow = CcShowInstancesQuery::create() + ->filterByDbShowId($this->_showId) + ->filterByDbRebroadcast(1) + ->filterByDbModifiedInstance(false) + ->findOne(); + + return !is_null($showInstancesRow); + } + + /** + * Get start time and absolute start date for a recorded + * shows rebroadcasts. For example start date format would be + * YYYY-MM-DD and time would HH:MM + * + * @return array + * array of associate arrays containing "start_date" and "start_time" + */ + public function getRebroadcastsAbsolute() + { + $sql = << $this->getId() ), 'all' ); + + $rebroadcastsLocal = array(); + //get each rebroadcast show in cc_show_instances, convert to current timezone to get start date/time. + /*TODO: refactor the following code to get rid of the $i temporary + variable. -- RG*/ + $i = 0; + + $utc = new DateTimeZone("UTC"); + $dtz = new DateTimeZone( date_default_timezone_get() ); + + foreach ($rebroadcasts as $show) { + $startDateTime = new DateTime($show["starts"], $utc); + $startDateTime->setTimezone($dtz); + + $rebroadcastsLocal[$i]["start_date"] = + $startDateTime->format("Y-m-d"); + $rebroadcastsLocal[$i]["start_time"] = + $startDateTime->format("H:i"); + + $i = $i + 1; + } + + return $rebroadcastsLocal; + } + + /** + * Get start time and relative start date for a recorded + * shows rebroadcasts. For example start date format would be + * "x days" and time would HH:MM:SS + * + * @return array + * array of associate arrays containing "day_offset" and "start_time" + */ + public function getRebroadcastsRelative() + { + $sql = << $this->getId() ), 'all' ); + } + + /** + * Check whether the current show is set to repeat + * repeating shows. + * + * @return boolean + * true if repeating shows, otherwise false. + */ + public function isRepeating() + { + $showDaysRow = CcShowDaysQuery::create() + ->filterByDbShowId($this->_showId) + ->findOne(); + + if (!is_null($showDaysRow)) { + return ($showDaysRow->getDbRepeatType() != -1); + } else { + return false; + } + } + + /** + * Get the repeat type of the show. Show can have repeat + * type of "weekly", "bi-weekly" and "monthly". These values + * are represented by 0, 1, and 2 respectively. + * + * @return int + * Return the integer corresponding to the repeat type. + */ + public function getRepeatType() + { + $showDaysRow = CcShowDaysQuery::create() + ->filterByDbShowId($this->_showId) + ->findOne(); + + if (!is_null($showDaysRow)) + return $showDaysRow->getDbRepeatType(); + else + return -1; + } + + /** + * Get the end date for a repeating show in the format yyyy-mm-dd + * + * @return string + * Return the end date for the repeating show or the empty + * string if there is no end. + */ + public function getRepeatingEndDate() + { + $sql = << $this->getId() ), 'column' ); + + /* TODO: Why return empty string instead of false? very confusing --RG + */ + return ($query !== false) ? $query : ""; + } + + /** + * Deletes all future instances of the current show object + * from the show_instances table. This function is used when + * a show is being edited - in some cases, when a show is edited + * we just destroy all future show instances, and let another function + * regenerate them later on. Note that this isn't always the most + * desirable thing to do. Deleting a show instance and regenerating + * it cause any scheduled playlists within those show instances to + * be gone for good. + */ + public function deleteAllInstances() + { + $sql = << :timestamp::TIMESTAMP + AND show_id = :showId +SQL; + Application_Common_Database::prepareAndExecute( $sql, + array( ':timestamp' => gmdate("Y-m-d H:i:s"), + ':showId' => $this->getId()), 'execute'); + } + + /** + * Deletes all future rebroadcast instances of the current + * show object from the show_instances table. + */ + public function deleteAllRebroadcasts() + { + $sql = << :timestamp::TIMESTAMP + AND show_id :showId + AND rebroadcast 1 +SQL; + Application_Common_Database::prepareAndExecute( $sql, + array( ':showId' => $this->getId(), + ':timestamp' => gmdate("Y-m-d H:i:s")), 'execute'); + + $con->exec($sql); + } + + /** + * Deletes all show instances of current show after a + * certain date. Note that although not enforced, $p_date + * should never be in the past, as we never want to allow + * deletion of shows that have already occured. + * + * @param string $p_date + * The date which to delete after, if null deletes from the current timestamp. + */ + public function removeAllInstancesFromDate($p_date=null) + { + $con = Propel::getConnection(); + + $timestamp = gmdate("Y-m-d H:i:s"); + + if (is_null($p_date)) { + $date = new Application_Common_DateHelper; + $p_date = $date->getDate(); + } + + $showId = $this->getId(); + $sql = "DELETE FROM cc_show_instances " + ." WHERE date(starts) >= DATE '$p_date'" + ." AND starts > TIMESTAMP '$timestamp'" + ." AND show_id = $showId"; + + $con->exec($sql); + + } + + /** + * Deletes all show instances of current show before a + * certain date. + * + * This function is used in the case where a repeating show is being + * edited and the start date of the first show has been changed more + * into the future. In this case, delete any show instances that + * exist before the new start date. + * + * @param string $p_date + * The date which to delete before + */ + public function removeAllInstancesBeforeDate($p_date) + { + $con = Propel::getConnection(); + + $timestamp = gmdate("Y-m-d H:i:s"); + + $showId = $this->getId(); + $sql = "DELETE FROM cc_show_instances " + ." WHERE date(starts) < DATE '$p_date'" + ." AND starts > TIMESTAMP '$timestamp'" + ." AND show_id = $showId"; + + $con->exec($sql); + } + + public 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->getId() ), 'all' ); + + foreach ($result as $r) { + $show["starts"] = new DateTime($r["starts"], new DateTimeZone('UTC')); + $show["ends"] = new DateTime($r["ends"], new DateTimeZone('UTC')); + } + $currentUser = Application_Model_User::getCurrentUser(); + $currentUserId = $currentUser->getId(); + $userTimezone = Application_Model_Preference::GetUserTimezone($currentUserId); + $show["starts"]->setTimezone(new DateTimeZone($userTimezone)); + $show["ends"]->setTimezone(new DateTimeZone($userTimezone)); + return $show; + } + + /** + * Get the start date of the current show in UTC timezone. + * + * @return string + * The start date in the format YYYY-MM-DD or empty string in case + * start date could not be found + */ + public function getStartDateAndTime() + { + $con = Propel::getConnection(); + + $showId = $this->getId(); + $stmt = $con->prepare( + "SELECT first_show, start_time, timezone FROM cc_show_days" + ." WHERE show_id = :showId" + ." ORDER BY first_show" + ." LIMIT 1"); + + $stmt->bindParam(':showId', $showId); + $stmt->execute(); + + if (!$stmt) { + return ""; + } + + $rows = $stmt->fetchAll(); + $row = $rows[0]; + + $dt = new DateTime($row["first_show"]." ".$row["start_time"], new DateTimeZone($row["timezone"])); + $dt->setTimezone(new DateTimeZone("UTC")); + + return $dt->format("Y-m-d H:i"); + } + + /** + * Get the start date of the current show in UTC timezone. + * + * @return string + * The start date in the format YYYY-MM-DD + */ + public function getStartDate() + { + list($date,) = explode(" ", $this->getStartDateAndTime()); + + return $date; + } + + /** + * Get the start time of the current show in UTC timezone. + * + * @return string + * The start time in the format HH:MM + */ + + public function getStartTime() + { + list(,$time) = explode(" ", $this->getStartDateAndTime()); + + return $time; + } + + /** + * Get the end date of the current show. + * Note that this is not the end date of repeated show + * + * @return string + * The end date in the format YYYY-MM-DD + */ + public function getEndDate() + { + $startDate = $this->getStartDate(); + $startTime = $this->getStartTime(); + $duration = $this->getDuration(); + + $startDateTime = new DateTime($startDate.' '.$startTime); + $duration = explode(":", $duration); + + $endDate = $startDateTime->add(new DateInterval('PT'.$duration[0].'H'.$duration[1].'M')); + + return $endDate->format('Y-m-d'); + } + + /** + * Get the end time of the current show. + * + * @return string + * The start time in the format HH:MM:SS + */ + public function getEndTime() + { + $startDate = $this->getStartDate(); + $startTime = $this->getStartTime(); + $duration = $this->getDuration(); + + $startDateTime = new DateTime($startDate.' '.$startTime); + $duration = explode(":", $duration); + + $endDate = $startDateTime->add(new DateInterval('PT'.$duration[0].'H'.$duration[1].'M')); + + return $endDate->format('H:i:s'); + } + + /** + * Indicate whether the starting point of the show is in the + * past. + * + * @return boolean + * true if the StartDate is in the past, false otherwise + */ + public function isStartDateTimeInPast() + { + $date = new Application_Common_DateHelper; + $current_timestamp = $date->getUtcTimestamp(); + + return ($current_timestamp > ($this->getStartDate()." ".$this->getStartTime())); + } + + /** + * Get the ID's of future instance of the current show. + * + * @return array + * A simple array containing all ID's of show instance + * scheduled in the future. + */ + public function getAllFutureInstanceIds() + { + $sql = << :timestamp::TIMESTAMP + AND modified_instance != TRUE +SQL; + $rows = Application_Common_Database::prepareAndExecute($sql, + array( ':showId' => $this->getId(), + ':timestamp' => gmdate("Y-m-d H:i:s")), "all"); + + $res = array(); + foreach ($rows as $r) { + $res[] = $r['id']; + } + return $res; + } + + /* Called when a show's duration is changed (edited). + * + * @param array $p_data + * array containing the POST data about the show from the + * browser. + * + */ + private function updateDurationTime($p_data) + { + //need to update cc_show_instances, cc_show_days + $con = Propel::getConnection(); + + $date = new Application_Common_DateHelper; + $timestamp = $date->getUtcTimestamp(); + + $stmt = $con->prepare("UPDATE cc_show_days " + ."SET duration = :add_show_duration " + ."WHERE show_id = :add_show_id" ); + $stmt->execute( array( + ':add_show_duration' => $p_data['add_show_duration'], + ':add_show_id' => $p_data['add_show_id'] + )); + + + $sql = << :timestamp::TIMESTAMP +SQL; + + Application_Common_Database::prepareAndExecute( $sql, array( + ':add_show_duration' => $p_data['add_show_duration'], + ':show_id' => $p_data['add_show_id'], + ':timestamp' => $timestamp), "execute"); + } + + private function updateStartDateTime($p_data, $p_endDate) + { + //need to update cc_schedule, cc_show_instances, cc_show_days + $con = Propel::getConnection(); + + $date = new Application_Common_DateHelper; + $timestamp = $date->getTimestamp(); + + //TODO fix this from overwriting info. + $sql = "UPDATE cc_show_days " + ."SET start_time = TIME '$p_data[add_show_start_time]', " + ."first_show = DATE '$p_data[add_show_start_date]', "; + if (strlen ($p_endDate) == 0) { + $sql .= "last_show = NULL "; + } else { + $sql .= "last_show = DATE '$p_endDate' "; + } + $sql .= "WHERE show_id = $p_data[add_show_id]"; + $con->exec($sql); + + $dtOld = new DateTime($this->getStartDate()." ".$this->getStartTime(), new DateTimeZone("UTC")); + $dtNew = new DateTime($p_data['add_show_start_date']." ".$p_data['add_show_start_time'], new DateTimeZone(date_default_timezone_get())); + $diff = $dtOld->getTimestamp() - $dtNew->getTimestamp(); + + $sql = "UPDATE cc_show_instances " + ."SET starts = starts + INTERVAL '$diff sec', " + ."ends = ends + INTERVAL '$diff sec' " + ."WHERE show_id = $p_data[add_show_id] " + ."AND starts > TIMESTAMP '$timestamp'"; + $con->exec($sql); + + $showInstanceIds = $this->getAllFutureInstanceIds(); + if (count($showInstanceIds) > 0 && $diff != 0) { + $showIdsImploded = implode(",", $showInstanceIds); + $sql = "UPDATE cc_schedule " + ."SET starts = starts + INTERVAL '$diff sec', " + ."ends = ends + INTERVAL '$diff sec' " + ."WHERE instance_id IN ($showIdsImploded)"; + $con->exec($sql); + } + } + + public function getDuration($format=false) + { + $showDay = CcShowDaysQuery::create()->filterByDbShowId($this->getId())->findOne(); + if (!$format) { + return $showDay->getDbDuration(); + } else { + $info = explode(':',$showDay->getDbDuration()); + + return str_pad(intval($info[0]),2,'0',STR_PAD_LEFT).'h '.str_pad(intval($info[1]),2,'0',STR_PAD_LEFT).'m'; + } + } + + public function getShowDays() + { + $showDays = CcShowDaysQuery::create()->filterByDbShowId( + $this->getId())->find(); + $res = array(); + foreach ($showDays as $showDay) { + $res[] = $showDay->getDbDay(); + } + return $res; + } + + /* Only used for shows that aren't repeating. + * + * @return Boolean: true if show has an instance, otherwise false. */ + public function hasInstance() + { + return (!is_null($this->getInstance())); + } + + /* Only used for shows that aren't repeating. + * + * @return CcShowInstancesQuery: An propel object representing a + * row in the cc_show_instances table. */ + public function getInstance() + { + $showInstance = CcShowInstancesQuery::create() + ->filterByDbShowId($this->getId()) + ->findOne(); + + return $showInstance; + } + + /** + * returns info about live stream override info + */ + public function getLiveStreamInfo() + { + $info = array(); + if ($this->getId() == null) { + return $info; + } else { + $ccShow = CcShowQuery::create()->findPK($this->_showId); + $info['custom_username'] = $ccShow->getDbLiveStreamUser(); + $info['cb_airtime_auth'] = $ccShow->getDbLiveStreamUsingAirtimeAuth(); + $info['cb_custom_auth'] = $ccShow->getDbLiveStreamUsingCustomAuth(); + $info['custom_username'] = $ccShow->getDbLiveStreamUser(); + $info['custom_password'] = $ccShow->getDbLiveStreamPass(); + return $info; + } + } + + /* Only used for shows that are repeating. Note that this will return + * true even for dates that only have a "modified" show instance (does not + * check if the "modified_instance" column is set to true). This is intended + * behaviour. + * + * @param $p_dateTime: Date for which we are checking if instance + * exists. + * + * @return Boolean: true if show has an instance on $p_dateTime, + * otherwise false. */ + public function hasInstanceOnDate($p_dateTime) + { + return (!is_null($this->getInstanceOnDate($p_dateTime))); + } + + /* Only used for shows that are repeating. Note that this will return + * shows that have been "modified" (does not check if the "modified_instance" + * column is set to true). This is intended behaviour. + * + * @param $p_dateTime: Date for which we are getting an instance. + * + * @return CcShowInstancesQuery: An propel object representing a + * row in the cc_show_instances table. */ + public function getInstanceOnDate($p_dateTime) + { + $timestamp = $p_dateTime->format("Y-m-d H:i:s"); + $sql = << $this->getId(), + ':timestamp' => $timestamp ), 'column'); + return CcShowInstancesQuery::create() + ->findPk($row); + } catch (Exception $e) { + return null; + } + + } + + public function deletePossiblyInvalidInstances($p_data, $p_endDate, $isRecorded, $repeatType) + { + if ($p_data['add_show_repeats'] != $this->isRepeating()) { + //repeat option was toggled + $this->deleteAllInstances(); + } + + if ($p_data['add_show_duration'] != $this->getDuration()) { + //duration has changed + $this->updateDurationTime($p_data); + } + + if ($p_data['add_show_repeats']) { + if (($repeatType == 1 || $repeatType == 2) && + $p_data['add_show_start_date'] != $this->getStartDate()){ + + //start date has changed when repeat type is bi-weekly or monthly. + //This screws up the repeating positions of show instances, so lets + //just delete them for now. (CC-2351) + + $this->deleteAllInstances(); + } + + if ($repeatType != $this->getRepeatType()) { + //repeat type changed. + $this->deleteAllInstances(); + } else { + //repeat type is the same, check if the days of the week are the same + $repeatingDaysChanged = false; + $showDaysArray = $this->getShowDays(); + if (count($p_data['add_show_day_check']) == count($showDaysArray)) { + //same number of days checked, lets see if they are the same numbers + $intersect = array_intersect($p_data['add_show_day_check'], $showDaysArray); + if (count($intersect) != count($p_data['add_show_day_check'])) { + $repeatingDaysChanged = true; + } + } else { + $repeatingDaysChanged = true; + } + + if ($repeatingDaysChanged) { + $daysRemoved = array_diff($showDaysArray, $p_data['add_show_day_check']); + + if (count($daysRemoved) > 0) { + + $this->removeUncheckedDaysInstances($daysRemoved); + } + } + + if ($p_data['add_show_start_date'] != $this->getStartDate() + || $p_data['add_show_start_time'] != $this->getStartTime()){ + //start date/time has changed + + $newDate = strtotime($p_data['add_show_start_date']); + $oldDate = strtotime($this->getStartDate()); + if ($newDate > $oldDate) { + $this->removeAllInstancesBeforeDate($p_data['add_show_start_date']); + } + + $this->updateStartDateTime($p_data, $p_endDate); + } + } + + //Check if end date for the repeat option has changed. If so, need to take care + //of deleting possible invalid Show Instances. + if ((strlen($this->getRepeatingEndDate()) == 0) == $p_data['add_show_no_end']) { + //show "Never Ends" option was toggled. + if ($p_data['add_show_no_end']) { + } else { + $this->removeAllInstancesFromDate($p_endDate); + } + } + if ($this->getRepeatingEndDate() != $p_data['add_show_end_date']) { + //end date was changed. + + $newDate = strtotime($p_data['add_show_end_date']); + $oldDate = strtotime($this->getRepeatingEndDate()); + if ($newDate < $oldDate) { + $this->removeAllInstancesFromDate($p_endDate); + } + } + } + } + + /** + * Create a show. + * + * Note: end dates are non inclusive. + * + * @param array $data + * @return int + * Show ID + */ + 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')); + + if ($data['add_show_no_end']) { + $endDate = NULL; + } elseif ($data['add_show_repeats']) { + $endDateTime = new DateTime($data['add_show_end_date']); + //$endDateTime->setTimezone(new DateTimeZone('UTC')); + $endDateTime->add(new DateInterval("P1D")); + $endDate = $endDateTime->format("Y-m-d"); + } else { + $endDateTime = new DateTime($data['add_show_start_date']); + //$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()); + 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; + + 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->setDbDescription($data['add_show_description']); + $ccShow->setDbUrl($data['add_show_url']); + $ccShow->setDbGenre($data['add_show_genre']); + $ccShow->setDbColor($data['add_show_color']); + $ccShow->setDbBackgroundColor($data['add_show_background_color']); + $ccShow->setDbLiveStreamUsingAirtimeAuth($data['cb_airtime_auth'] == 1); + $ccShow->setDbLiveStreamUsingCustomAuth($data['cb_custom_auth'] == 1); + $ccShow->setDbLiveStreamUser($data['custom_username']); + $ccShow->setDbLiveStreamPass($data['custom_password']); + $ccShow->save(); + + $showId = $ccShow->getDbId(); + + $isRecorded = (isset($data['add_show_record']) && $data['add_show_record']) ? 1 : 0; + + if ($data['add_show_id'] != -1) { + $show = new Application_Model_Show($showId); + $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) { + 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) { + $showDay = new CcShowDays(); + $showDay->setDbFirstShow($startDateTime->format("Y-m-d")); + $showDay->setDbLastShow($endDate); + $showDay->setDbStartTime($startDateTime->format("H:i:s")); + $showDay->setDbTimezone(date_default_timezone_get()); + $showDay->setDbDuration($data['add_show_duration']); + $showDay->setDbRepeatType($repeatType); + $showDay->setDbShowId($showId); + $showDay->setDbRecord($isRecorded); + $showDay->save(); + } else { + foreach ($data['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(date_default_timezone_get()); + $showDay->setDbDuration($data['add_show_duration']); + $showDay->setDbDay($day); + $showDay->setDbRepeatType($repeatType); + $showDay->setDbShowId($showId); + $showDay->setDbRecord($isRecorded); + $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']) { + 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)) { + for ($i=1; $i<=10; $i++) { + if ($data['add_show_rebroadcast_date_'.$i]) { + $showRebroad = new CcShowRebroadcast(); + $showRebroad->setDbDayOffset($data['add_show_rebroadcast_date_'.$i]); + $showRebroad->setDbStartTime($data['add_show_rebroadcast_time_'.$i]); + $showRebroad->setDbShowId($showId); + $showRebroad->save(); + } + } + } elseif ($isRecorded && $data['add_show_rebroadcast'] && ($repeatType == -1)) { + for ($i=1; $i<=10; $i++) { + if ($data['add_show_rebroadcast_date_absolute_'.$i]) { + //$con = Propel::getConnection(CcShowPeer::DATABASE_NAME); + //$sql = "SELECT date '{$data['add_show_rebroadcast_date_absolute_'.$i]}' - date '{$data['add_show_start_date']}' "; + $sql = << + $data["add_show_rebroadcast_date_absolute_$i"], + 'start' => + $data['add_show_start_date']), "column" ); + + //$r = $con->query($sql); + //$offset_days = $r->fetchColumn(0); + + $showRebroad = new CcShowRebroadcast(); + $showRebroad->setDbDayOffset($offset_days." days"); + $showRebroad->setDbStartTime($data['add_show_rebroadcast_time_absolute_'.$i]); + $showRebroad->setDbShowId($showId); + $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) { + CcShowHostsQuery::create()->filterByDbShow($data['add_show_id'])->delete(); + } + 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(); + $showHost->setDbShow($showId); + $showHost->setDbHost($host); + $showHost->save(); + } + } + + if ($data['add_show_id'] != -1) { + $con = Propel::getConnection(CcSchedulePeer::DATABASE_NAME); + $con->beginTransaction(); + + + //current timesamp in UTC. + $current_timestamp = gmdate("Y-m-d H:i:s"); + + try { + //update the status flag in cc_schedule. + $instances = CcShowInstancesQuery::create() + ->filterByDbEnds($current_timestamp, Criteria::GREATER_THAN) + ->filterByDbShowId($data['add_show_id']) + ->find($con); + + foreach ($instances as $instance) { + $instance->updateScheduleStatus($con); + } + + $con->commit(); + } catch (Exception $e) { + $con->rollback(); + Logging::info("Couldn't update schedule status."); + Logging::info($e->getMessage()); + } + } + + Application_Model_Show::populateShowUntil($showId); + Application_Model_RabbitMq::PushSchedule(); + + return $showId; + } + + /** + * Generate repeating show instances for a single show up to the given date. + * It will always try to use enddate from DB but if that's empty, it will use + * time now. + * + * @param int $p_showId + */ + public static function populateShowUntil($p_showId) + { + $con = Propel::getConnection(); + $date = Application_Model_Preference::GetShowsPopulatedUntil(); + + if (is_null($date)) { + $p_populateUntilDateTime = new DateTime("now", new DateTimeZone('UTC')); + Application_Model_Preference::SetShowsPopulatedUntil($p_populateUntilDateTime); + } else { + $p_populateUntilDateTime = $date; + } + + $stmt = $con->prepare("SELECT * FROM cc_show_days WHERE show_id = :show_id"); + $stmt->bindParam(':show_id', $p_showId); + $stmt->execute(); + + $res = $stmt->fetchAll(); + + 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 + * is basically a dispatcher that looks at the show template, and sends it to the correct function + * so that Show Instance generation can begin. After the all show instances have been created, pushes + * the schedule to Pypo. + * + * @param array $p_showRow + * A row from cc_show_days table + * @param DateTime $p_populateUntilDateTime + * DateTime object in UTC time. + */ + 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 + if ($p_showDaysRow["repeat_type"] == -1) { + Application_Model_Show::populateNonRepeatingShow($p_showDaysRow, $p_populateUntilDateTime); + } elseif ($p_showDaysRow["repeat_type"] == 0) { + Application_Model_Show::populateRepeatingShow($p_showDaysRow, $p_populateUntilDateTime, 'P7D'); + } elseif ($p_showDaysRow["repeat_type"] == 1) { + Application_Model_Show::populateRepeatingShow($p_showDaysRow, $p_populateUntilDateTime, 'P14D'); + } elseif ($p_showDaysRow["repeat_type"] == 2) { + 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 + * rebroadcast dates, and so this function will create those as well. + * + * @param array $p_showRow + * A row from cc_show_days table + * @param DateTime $p_populateUntilDateTime + * DateTime object in UTC time. + */ + private static function populateNonRepeatingShow($p_showRow, $p_populateUntilDateTime) + { + $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"]; + $record = $p_showRow["record"]; + $timezone = $p_showRow["timezone"]; + $start = $first_show." ".$start_time; + + //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"); + + $show = new Application_Model_Show($show_id); + if ($show->hasInstance()) { + $ccShowInstance = $show->getInstance(); + $newInstance = false; + } else { + $ccShowInstance = new CcShowInstances(); + $newInstance = true; + } + + 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); + + if (!$newInstance) { + $showInstance->correctScheduleStartTimes(); + } + + $sql = "SELECT * FROM cc_show_rebroadcast WHERE show_id=:show_id"; + $rebroadcasts = Application_Common_Database::prepareAndExecute($sql, + array( ':show_id' => $show_id ), 'all'); + + if ($showInstance->isRecorded()) { + $showInstance->deleteRebroadcasts(); + self::createRebroadcastInstances($rebroadcasts, $currentUtcTimestamp, $show_id, $show_instance_id, $start, $duration, $timezone); + } + } + } + + /** + * Creates a 1 or more than 1 show instances (user has stated this show repeats). If the show + * is recorded, it may have multiple rebroadcast dates, and so this function will create + * those as well. + * + * @param array $p_showRow + * A row from cc_show_days table + * @param DateTime $p_populateUntilDateTime + * DateTime object in UTC time. "shows_populated_until" date YY-mm-dd in cc_pref + * @param string $p_interval + * Period of time between repeating shows (in php DateInterval notation 'P7D') + */ + private static function populateRepeatingShow($p_showDaysRow, $p_populateUntilDateTime, $p_interval) + { + $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 + $start_time = $p_showDaysRow["start_time"]; //non-UTC + $duration = $p_showDaysRow["duration"]; + $day = $p_showDaysRow["day"]; + $record = $p_showDaysRow["record"]; + $timezone = $p_showDaysRow["timezone"]; + + $currentUtcTimestamp = gmdate("Y-m-d H:i:s"); + + if (isset($next_pop_date)) { + $start = $next_pop_date." ".$start_time; + } else { + $start = $first_show." ".$start_time; + } + + $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; + + $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); + + while ($utcStartDateTime->getTimestamp() <= $p_populateUntilDateTime->getTimestamp() + && (is_null($utcLastShowDateTime) || $utcStartDateTime->getTimestamp() < $utcLastShowDateTime->getTimestamp())){ + + list($utcStartDateTime, $utcEndDateTime) = self::createUTCStartEndDateTime($start, $duration, $timezone); + + if ($show->hasInstanceOnDate($utcStartDateTime)) { + $ccShowInstance = $show->getInstanceOnDate($utcStartDateTime); + + if ($ccShowInstance->getDbModifiedInstance()) { + //show instance on this date has been deleted. + list($start, $utcStartDateTime) = self::advanceRepeatingDate($p_interval, $start, $timezone); + continue; + } + + $newInstance = false; + } 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) { + $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); + + /* If we are updating a show then make sure that the scheduled content within + * the show is updated to the correct time. */ + if (!$newInstance) { + $showInstance->correctScheduleStartTimes(); + } + + $showInstance->deleteRebroadcasts(); + self::createRebroadcastInstances($rebroadcasts, $currentUtcTimestamp, $show_id, $show_instance_id, $start, $duration, $timezone); + list($start, $utcStartDateTime) = self::advanceRepeatingDate($p_interval, $start, $timezone); + + } + + Application_Model_Show::setNextPop($start, $show_id, $day); + } + + private static function advanceRepeatingDate($p_interval, $start, $timezone) + { + $startDt = new DateTime($start, new DateTimeZone($timezone)); + if ($p_interval == 'P1M') { + /* When adding months, there is a problem if we are on January 31st and add one month with PHP. + * What ends up happening is that since February 31st doesn't exist, the date returned is + * March 3rd. For now let's ignore the day and assume we are always working with the + * first of each month, and use PHP to add 1 month to this (this will take care of rolling + * over the years 2011->2012, etc.). Then let's append the actual day, and use the php + * checkdate() function, to see if it is valid. If not, then we'll just skip this month. */ + + /* pass in only the year and month (not the day) */ + $dt = new DateTime($startDt->format("Y-m"), new DateTimeZone($timezone)); + + + /* Keep adding 1 month, until we find the next month that contains the day + * we are looking for (31st day for example) */ + do { + $dt->add(new DateInterval($p_interval)); + } while (!checkdate($dt->format("m"), $startDt->format("d"), $dt->format("Y"))); + + $dt->setDate($dt->format("Y"), $dt->format("m"), $startDt->format("d")); + + } else { + $dt = new DateTime($start, new DateTimeZone($timezone)); + $dt->add(new DateInterval($p_interval)); + } + + $start = $dt->format("Y-m-d H:i:s"); + + $dt->setTimezone(new DateTimeZone('UTC')); + $utcStartDateTime = $dt; + + return array($start, $utcStartDateTime); + } + + /* + * @param $p_start + * timestring format "Y-m-d H:i:s" (not UTC) + * @param $p_duration + * string time interval (h)h:(m)m(:ss) + * @param $p_timezone + * string "Europe/Prague" + * @param $p_offset + * array (days, hours, mins) used for rebroadcast shows. + * + * @return + * array of 2 DateTime objects, start/end time of the show in UTC. + */ + private static function createUTCStartEndDateTime($p_start, $p_duration, $p_timezone=null, $p_offset=null) + { + $timezone = $p_timezone ? $p_timezone : date_default_timezone_get(); + + $startDateTime = new DateTime($p_start, new DateTimeZone($timezone)); + if (isset($p_offset)) { + $startDateTime->add(new DateInterval("P{$p_offset["days"]}DT{$p_offset["hours"]}H{$p_offset["mins"]}M")); + } + //convert time to UTC + $startDateTime->setTimezone(new DateTimeZone('UTC')); + + $endDateTime = clone $startDateTime; + $duration = explode(":", $p_duration); + list($hours, $mins) = array_slice($duration, 0, 2); + $endDateTime->add(new DateInterval("PT{$hours}H{$mins}M")); + + return array($startDateTime, $endDateTime); + } + + /* Create rebroadcast instances for a created show marked for recording + * + * @param $p_rebroadcasts + * rows gotten from the db table cc_show_rebroadcasts, tells airtime when to schedule the rebroadcasts. + * @param $p_currentUtcTimestamp + * a timestring in format "Y-m-d H:i:s", current UTC time. + * @param $p_showId + * int of the show it belongs to (from cc_show) + * @param $p_showInstanceId + * the instance id of the created recorded show instance + * (from cc_show_instances), used to associate rebroadcasts to this show. + * @param $p_startTime + * a timestring in format "Y-m-d H:i:s" in the timezone, not UTC of the rebroadcasts' parent recorded show. + * @param $p_duration + * string time interval (h)h:(m)m:(ss) length of the show. + * @param $p_timezone + * string of user's timezone "Europe/Prague" + * + */ + private static function createRebroadcastInstances($p_rebroadcasts, $p_currentUtcTimestamp, $p_showId, $p_showInstanceId, $p_startTime, $p_duration, $p_timezone=null) + { + //Y-m-d + //use only the date part of the show start time stamp for the offsets to work properly. + $date = explode(" ", $p_startTime); + $start_date = $date[0]; + + foreach ($p_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) = Application_Model_Show::createUTCStartEndDateTime($start_date, $p_duration, $p_timezone, $offset); + + if ($utcStartDateTime->format("Y-m-d H:i:s") > $p_currentUtcTimestamp) { + + $newRebroadcastInstance = new CcShowInstances(); + $newRebroadcastInstance->setDbShowId($p_showId); + $newRebroadcastInstance->setDbStarts($utcStartDateTime); + $newRebroadcastInstance->setDbEnds($utcEndDateTime); + $newRebroadcastInstance->setDbRecord(0); + $newRebroadcastInstance->setDbRebroadcast(1); + $newRebroadcastInstance->setDbOriginalShow($p_showInstanceId); + $newRebroadcastInstance->save(); + } + } + } + + /** + * Get all the show instances in the given time range (inclusive). + * + * @param DateTime $start_timestamp + * In UTC time. + * @param DateTime $end_timestamp + * In UTC time. + * @param unknown_type $excludeInstance + * @param boolean $onlyRecord + * @return array + */ + public static function getShows($start_timestamp, $end_timestamp, $onlyRecord=FALSE) + { + //UTC DateTime object + $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); + Application_Model_Preference::SetShowsPopulatedUntil($end_timestamp); + } + + $sql = <<format("Y-m-d H:i:s"); + $end_string = $end_timestamp->format("Y-m-d H:i:s"); + if ($onlyRecord) { + $sql .= " AND (si1.starts >= :start::TIMESTAMP AND si1.starts < :end::TIMESTAMP)"; + $sql .= " AND (si1.record = 1)"; + + return Application_Common_Database::prepareAndExecute( $sql, + array( ':start' => $start_string, + ':end' => $end_string ), 'all'); + + } else { + $sql .= " ". <<= :start1::TIMESTAMP AND si1.starts < :end1::TIMESTAMP) + OR (si1.ends > :start2::TIMESTAMP AND si1.ends <= :end2::TIMESTAMP) + OR (si1.starts <= :start3::TIMESTAMP AND si1.ends >= :end3::TIMESTAMP)) +SQL; + return Application_Common_Database::prepareAndExecute( $sql, + array( + 'start1' => $start_string, + 'start2' => $start_string, + 'start3' => $start_string, + 'end1' => $end_string, + 'end2' => $end_string, + 'end3' => $end_string + ), 'all'); + } + } + + private static function setNextPop($next_date, $show_id, $day) + { + $nextInfo = explode(" ", $next_date); + + $repeatInfo = CcShowDaysQuery::create() + ->filterByDbShowId($show_id) + ->filterByDbDay($day) + ->findOne(); + + $repeatInfo->setDbNextPopDate($nextInfo[0]) + ->save(); + } + + /** + * Generate all the repeating shows in the given range. + * + * @param DateTime $p_startTimestamp + * In UTC format. + * @param DateTime $p_endTimestamp + * In UTC format. + */ + public static function populateAllShowsInRange($p_startTimestamp, $p_endTimestamp) + { + $con = Propel::getConnection(); + + $endTimeString = $p_endTimestamp->format("Y-m-d H:i:s"); + if (!is_null($p_startTimestamp)) { + $startTimeString = $p_startTimestamp->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"); + } + + $stmt = $con->prepare(" + SELECT * FROM cc_show_days + WHERE last_show IS NULL + OR first_show < :endTimeString AND last_show > :startTimeString"); + + $stmt->bindParam(':endTimeString', $endTimeString); + $stmt->bindParam(':startTimeString', $startTimeString); + $stmt->execute(); + + $res = $stmt->fetchAll(); + foreach ($res as $row) { + Application_Model_Show::populateShow($row, $p_endTimestamp); + } + } + + /** + * + * @param DateTime $start + * -in UTC time + * @param DateTime $end + * -in UTC time + * @param boolean $editable + */ + public static function &getFullCalendarEvents($p_start, $p_end, $p_editable=false) + { + $events = array(); + $interval = $p_start->diff($p_end); + $days = $interval->format('%a'); + $shows = Application_Model_Show::getShows($p_start, $p_end); + $content_count = Application_Model_ShowInstance::getContentCount( + $p_start, $p_end); + $isFull = Application_Model_ShowInstance::getIsFull($p_start, $p_end); + $timezone = date_default_timezone_get(); + $current_timezone = new DateTimeZone($timezone); + $utc = new DateTimeZone("UTC"); + $now = new DateTime("now", $utc); + + foreach ($shows as &$show) { + $options = array(); + + //only bother calculating percent for week or day view. + if (intval($days) <= 7) { + $options["percent"] = Application_Model_Show::getPercentScheduled($show["starts"], $show["ends"], $show["time_filled"]); + } + + if (isset($show["parent_starts"])) { + $parentStartsDT = new DateTime($show["parent_starts"], $utc); + } + + $startsDT = DateTime::createFromFormat("Y-m-d G:i:s", + $show["starts"],$utc); + $endsDT = DateTime::createFromFormat("Y-m-d G:i:s", + $show["ends"], $utc); + + if( $p_editable ) { + if ($show["record"] && $now > $startsDT) { + $options["editable"] = false; + } elseif ($show["rebroadcast"] && + $now > $parentStartsDT) { + $options["editable"] = false; + } elseif ($now < $endsDT) { + $options["editable"] = true; + } + } + + $startsDT->setTimezone($current_timezone); + $endsDT->setTimezone($current_timezone); + + $options["show_empty"] = (array_key_exists($show['instance_id'], + $content_count)) ? 0 : 1; + + $options["show_partial_filled"] = !$isFull[$show['instance_id']]; + + $event = array(); + + $event["id"] = intval($show["instance_id"]); + $event["title"] = $show["name"]; + $event["start"] = $startsDT->format("Y-m-d H:i:s"); + $event["end"] = $endsDT->format("Y-m-d H:i:s"); + $event["allDay"] = false; + $event["showId"] = intval($show["show_id"]); + $event["record"] = intval($show["record"]); + $event["rebroadcast"] = intval($show["rebroadcast"]); + $event["soundcloud_id"] = is_null($show["soundcloud_id"]) + ? -1 : $show["soundcloud_id"]; + + //event colouring + if ($show["color"] != "") { + $event["textColor"] = "#".$show["color"]; + } + + if ($show["background_color"] != "") { + $event["color"] = "#".$show["background_color"]; + } + + foreach ($options as $key => $value) { + $event[$key] = $value; + } + + $events[] = $event; + } + return $events; + } + + /** + * Calculates the percentage of a show scheduled given the start and end times in date/time format + * and the time_filled as the total time the schow is scheduled for in time format. + **/ + private static function getPercentScheduled($p_starts, $p_ends, $p_time_filled) + { + $durationSeconds = (strtotime($p_ends) - strtotime($p_starts)); + $time_filled = Application_Model_Schedule::WallTimeToMillisecs($p_time_filled) / 1000; + $percent = ceil(( $time_filled / $durationSeconds) * 100); + + return $percent; + } + +/* private static function &makeFullCalendarEvent(&$show, $options=array(), $startDateTime, $endDateTime, $startsEpoch, $endsEpoch) + { + $event = array(); + + $event["id"] = intval($show["instance_id"]); + $event["title"] = $show["name"]; + $event["start"] = $startDateTime->format("Y-m-d H:i:s"); + $event["startUnix"] = $startsEpoch; + $event["end"] = $endDateTime->format("Y-m-d H:i:s"); + $event["endUnix"] = $endsEpoch; + $event["allDay"] = false; + $event["showId"] = intval($show["show_id"]); + $event["record"] = intval($show["record"]); + $event["rebroadcast"] = intval($show["rebroadcast"]); + $event["soundcloud_id"] = is_null($show["soundcloud_id"]) + ? -1 : $show["soundcloud_id"]; + + //event colouring + if ($show["color"] != "") { + $event["textColor"] = "#".$show["color"]; + } + + if ($show["background_color"] != "") { + $event["color"] = "#".$show["background_color"]; + } + + foreach ($options as $key => $value) { + $event[$key] = $value; + } + + return $event; + }*/ + + /* Takes in a UTC DateTime object. + * Converts this to local time, since cc_show days + * requires local time. */ + public function setShowFirstShow($p_dt) + { + //clone object since we are modifying it and it was passed by reference. + $dt = clone $p_dt; + + $dt->setTimezone(new DateTimeZone(date_default_timezone_get())); + + $showDay = CcShowDaysQuery::create() + ->filterByDbShowId($this->_showId) + ->findOne(); + + $showDay->setDbFirstShow($dt)->setDbStartTime($dt) + ->save(); + + //Logging::info("setting show's first show."); + } + + /* Takes in a UTC DateTime object + * Converts this to local time, since cc_show days + * requires local time. */ + public function setShowLastShow($p_dt) + { + //clone object since we are modifying it and it was passed by reference. + $dt = clone $p_dt; + + $dt->setTimezone(new DateTimeZone(date_default_timezone_get())); + + //add one day since the Last Show date in CcShowDays is non-inclusive. + $dt->add(new DateInterval("P1D")); + + $showDay = CcShowDaysQuery::create() + ->filterByDbShowId($this->_showId) + ->findOne(); + + $showDay->setDbLastShow($dt) + ->save(); + } + + /** + * Given time $timeNow, returns the show being played right now. + * Times are all in UTC time. + * + * @param String $timeNow - current time (in UTC) + * @return array - show being played right now + */ + public static function getCurrentShow($timeNow=null) + { + $CC_CONFIG = Config::getConfig(); + $con = Propel::getConnection(); + if ($timeNow == null) { + $date = new Application_Common_DateHelper; + $timeNow = $date->getUtcTimestamp(); + } + //TODO, returning starts + ends twice (once with an alias). Unify this after the 2.0 release. --Martin + $sql = << :timeNow2::timestamp + AND modified_instance != TRUE +SQL; + + $stmt = $con->prepare($sql); + $stmt->bindParam(':timeNow1', $timeNow); + $stmt->bindParam(':timeNow2', $timeNow); + + if ($stmt->execute()) { + $rows = $stmt->fetchAll(); + } else { + $msg = implode(',', $stmt->errorInfo()); + throw new Exception("Error: $msg"); + } + + return $rows; + } + + /** + * Gets the current show, previous and next with an 2day window from + * the given timeNow, so timeNow-2days and timeNow+2days. + */ + public static function getPrevCurrentNext($p_timeNow) + { + $CC_CONFIG = Config::getConfig(); + $con = Propel::getConnection(); + // + //TODO, returning starts + ends twice (once with an alias). Unify this after the 2.0 release. --Martin + $sql = << :timeNow1::timestamp - INTERVAL '2 days' + AND si.ends < :timeNow2::timestamp + INTERVAL '2 days' + AND modified_instance != TRUE +ORDER BY si.starts +SQL; + + $stmt = $con->prepare($sql); + + $stmt->bindValue(':timeNow1', $p_timeNow); + $stmt->bindValue(':timeNow2', $p_timeNow); + + if ($stmt->execute()) { + $rows = $stmt->fetchAll(); + } else { + $msg = implode(',', $stmt->errorInfo()); + throw new Exception("Error: $msg"); + } + + $numberOfRows = count($rows); + + $results['previousShow'] = array(); + $results['currentShow'] = array(); + $results['nextShow'] = array(); + + $timeNowAsMillis = strtotime($p_timeNow); + + for ($i = 0; $i < $numberOfRows; ++$i) { + //Find the show that is within the current time. + if ((strtotime($rows[$i]['starts']) <= $timeNowAsMillis) + && (strtotime($rows[$i]['ends']) > $timeNowAsMillis)) { + if ($i-1 >= 0) { + $results['previousShow'][0] = array( + "id" => $rows[$i-1]['id'], + "instance_id" => $rows[$i-1]['instance_id'], + "name" => $rows[$i-1]['name'], + "url" => $rows[$i-1]['url'], + "start_timestamp" => $rows[$i-1]['start_timestamp'], + "end_timestamp" => $rows[$i-1]['end_timestamp'], + "starts" => $rows[$i-1]['starts'], + "ends" => $rows[$i-1]['ends'], + "record" => $rows[$i-1]['record'], + "type" => "show"); + } + + $results['currentShow'][0] = $rows[$i]; + + if (isset($rows[$i+1])) { + $results['nextShow'][0] = array( + "id" => $rows[$i+1]['id'], + "instance_id" => $rows[$i+1]['instance_id'], + "name" => $rows[$i+1]['name'], + "url" => $rows[$i+1]['url'], + "start_timestamp" => $rows[$i+1]['start_timestamp'], + "end_timestamp" => $rows[$i+1]['end_timestamp'], + "starts" => $rows[$i+1]['starts'], + "ends" => $rows[$i+1]['ends'], + "record" => $rows[$i+1]['record'], + "type" => "show"); + } + break; + } + //Previous is any row that ends after time now capture it in case we need it later. + if (strtotime($rows[$i]['ends']) < $timeNowAsMillis ) { + $previousShowIndex = $i; + } + //if we hit this we know we've gone to far and can stop looping. + if (strtotime($rows[$i]['starts']) > $timeNowAsMillis) { + $results['nextShow'][0] = array( + "id" => $rows[$i]['id'], + "instance_id" => $rows[$i]['instance_id'], + "name" => $rows[$i]['name'], + "url" => $rows[$i]['url'], + "start_timestamp" => $rows[$i]['start_timestamp'], + "end_timestamp" => $rows[$i]['end_timestamp'], + "starts" => $rows[$i]['starts'], + "ends" => $rows[$i]['ends'], + "record" => $rows[$i]['record'], + "type" => "show"); + break; + } + } + //If we didn't find a a current show because the time didn't fit we may still have + //found a previous show so use it. + if (count($results['previousShow']) == 0 && isset($previousShowIndex)) { + $results['previousShow'][0] = array( + "id" => $rows[$previousShowIndex]['id'], + "instance_id" => $rows[$previousShowIndex]['instance_id'], + "name" => $rows[$previousShowIndex]['name'], + "start_timestamp" => $rows[$previousShowIndex]['start_timestamp'], + "end_timestamp" => $rows[$previousShowIndex]['end_timestamp'], + "starts" => $rows[$previousShowIndex]['starts'], + "ends" => $rows[$previousShowIndex]['ends'], + "record" => $rows[$previousShowIndex]['record'], + "type" => "show"); + } + + return $results; + } + + /** + * Given a start time $timeStart and end time $timeEnd, returns the next $limit + * number of shows within the time interval + * If $timeEnd not given, shows within next 48 hours from $timeStart are returned + * If $limit not given, all shows within the intervals are returned + * Times are all in UTC time. + * + * @param String $timeStart - interval start time (in UTC) + * @param int $limit - number of shows to return + * @param String $timeEnd - interval end time (in UTC) + * @return array - the next $limit number of shows within the time interval + */ + public static function getNextShows($timeStart, $limit = "ALL", $timeEnd = "") + { + // defaults to retrieving shows from next 2 days if no end time has + // been specified + if ($timeEnd == "") { + $timeEnd = "'$timeStart' + INTERVAL '2 days'"; + } + + //TODO, returning starts + ends twice (once with an alias). Unify this after the 2.0 release. --Martin + $sql = <<= :timeStart::timestamp + AND si.starts < :timeEnd::timestamp + AND modified_instance != TRUE +ORDER BY si.starts +SQL; + + //PDO won't accept "ALL" as a limit value (complains it is not an + //integer, and so we must completely remove the limit clause if we + //want to show all results - MK + if ($limit != "ALL") { + $sql .= PHP_EOL."LIMIT :lim"; + $params = array( + ':timeStart' => $timeStart, + ':timeEnd' => $timeEnd, + ':lim' => $limit); + } else { + $params = array( + ':timeStart' => $timeStart, + ':timeEnd' => $timeEnd); + } + + return Application_Common_Database::prepareAndExecute( $sql, $params, 'all'); + } + + /** + * Convert the columns given in the array $columnsToConvert in the + * database result $rows to local timezone. + * + * @param type $rows arrays of arrays containing database query result + * @param type $columnsToConvert array of column names to convert + */ + public static function convertToLocalTimeZone(&$rows, $columnsToConvert) + { + if (!is_array($rows)) { + return; + } + foreach ($rows as &$row) { + foreach ($columnsToConvert as $column) { + $row[$column] = Application_Common_DateHelper::ConvertToLocalDateTimeString($row[$column]); + } + } + } + + public static function getMaxLengths() + { + $con = Propel::getConnection(); + $sql = << 0 +SQL; + $result = $con->query($sql)->fetchAll(); + $assocArray = array(); + foreach ($result as $row) { + $assocArray[$row['column_name']] = $row['character_maximum_length']; + } + return $assocArray; + } + + public static function getStartEndCurrentMonthView() { + $first_day_of_calendar_month_view = mktime(0, 0, 0, date("n"), 1); + $weekStart = Application_Model_Preference::GetWeekStartDay(); + while (date('w', $first_day_of_calendar_month_view) != $weekStart) { + $first_day_of_calendar_month_view -= 60*60*24; + } + $last_day_of_calendar_view = $first_day_of_calendar_month_view + 3600*24*42; + + $start = new DateTime("@".$first_day_of_calendar_month_view); + $end = new DateTime("@".$last_day_of_calendar_view); + + return array($start, $end); + } + + public static function getStartEndCurrentWeekView() { + $first_day_of_calendar_week_view = mktime(0, 0, 0, date("n"), date("j")); + $weekStart = Application_Model_Preference::GetWeekStartDay(); + while (date('w', $first_day_of_calendar_week_view) != $weekStart) { + $first_day_of_calendar_week_view -= 60*60*24; + } + $last_day_of_calendar_view = $first_day_of_calendar_week_view + 3600*24*7; + + $start = new DateTime("@".$first_day_of_calendar_week_view); + $end = new DateTime("@".$last_day_of_calendar_view); + + return array($start, $end); + } + + public static function getStartEndCurrentDayView() { + $today = mktime(0, 0, 0, date("n"), date("j")); + $tomorrow = $today + 3600*24; + + $start = new DateTime("@".$today); + $end = new DateTime("@".$tomorrow); + + return array($start, $end); + } +} diff --git a/airtime_mvc/application/services/ScheduleService.php b/airtime_mvc/application/services/ScheduleService.php index 1204f689c..e8322882b 100644 --- a/airtime_mvc/application/services/ScheduleService.php +++ b/airtime_mvc/application/services/ScheduleService.php @@ -175,15 +175,18 @@ class Application_Service_ScheduleService //create ccShow $ccShow = new CcShow(); $ccShow = $service_show->setShow($ccShow, $showData); + $showId = $ccShow->getDbId(); //create ccShowDay $service_show->createShowDays( - $showData, $ccShow->getDbId(), $user->getId(), $repeatType, $isRecorded); + $showData, $showId, $user->getId(), $repeatType, $isRecorded); + + //create ccShowRebroadcast + $service_show->createShowRebroadcast($showData, $showId, $repeatType, $isRecorded); //create ccShowHosts - - //create ccShowRebroadcast - + $service_show->createShowHosts($showData, $showId); + //populate ccShowInstances } } diff --git a/airtime_mvc/application/services/ShowService.php b/airtime_mvc/application/services/ShowService.php new file mode 100644 index 000000000..458cc4bd8 --- /dev/null +++ b/airtime_mvc/application/services/ShowService.php @@ -0,0 +1,145 @@ +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']); + + $ccShow->save(); + return $ccShow; + } + + /** + * Creates new cc_show_days entries + */ + public function createShowDays($showData, $showId, $userId, $repeatType, $isRecorded) + { + $startDateTime = new DateTime($showData['add_show_start_date']." ".$showData['add_show_start_time']); + + if ($showData['add_show_no_end']) { + $endDate = NULL; + } elseif ($showData['add_show_repeats']) { + $endDateTime = new DateTime($showData['add_show_end_date']); + $endDateTime->add(new DateInterval("P1D")); + $endDate = $endDateTime->format("Y-m-d"); + } else { + $endDateTime = new DateTime($showData['add_show_start_date']); + $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()); + 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::GetUserTimezone($userId)); + $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::GetUserTimezone($userId)); + $showDay->setDbDuration($showData['add_show_duration']); + $showDay->setDbDay($day); + $showDay->setDbRepeatType($repeatType); + $showDay->setDbShowId($showId); + $showDay->setDbRecord($isRecorded); + $showDay->save(); + } + } + } + } + + /** + * Creates new cc_show_rebroadcast entries + */ + public function createShowRebroadcast($showData, $showId, $repeatType, $isRecorded) + { + define("MAX_REBROADCAST_DATES", 10); + + if (($isRecorded && $showData['add_show_rebroadcast']) && ($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 ($isRecorded && $showData['add_show_rebroadcast'] && ($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(); + } + } + } + } + + /** + * Creates cc_show_hosts entries + */ + public function createShowHosts($showData, $showId) + { + if (is_array($showData['add_show_hosts'])) { + foreach ($showData['add_show_hosts'] as $host) { + $showHost = new CcShowHosts(); + $showHost->setDbShow($showId); + $showHost->setDbHost($host); + $showHost->save(); + } + } + } +} \ No newline at end of file From c29e11fa0f5101d30c38377f76db3580719735a8 Mon Sep 17 00:00:00 2001 From: denise Date: Tue, 26 Feb 2013 13:21:39 -0500 Subject: [PATCH 11/73] Created empty showInstance service. Split populateShowUntil into 2 new functions: getPopulateDateUntil, and getShowDays --- .../application/services/ScheduleService.php | 5 ++- .../services/ShowInstanceService.php | 8 +++++ .../application/services/ShowService.php | 32 +++++++++++++++++++ 3 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 airtime_mvc/application/services/ShowInstanceService.php diff --git a/airtime_mvc/application/services/ScheduleService.php b/airtime_mvc/application/services/ScheduleService.php index e8322882b..c0bc1a844 100644 --- a/airtime_mvc/application/services/ScheduleService.php +++ b/airtime_mvc/application/services/ScheduleService.php @@ -171,6 +171,7 @@ class Application_Service_ScheduleService if ($isAdminOrPM) { $service_show = new Application_Service_ShowService(); + $service_showInstances = new Application_Service_ShowInstanceService(); //create ccShow $ccShow = new CcShow(); @@ -187,7 +188,9 @@ class Application_Service_ScheduleService //create ccShowHosts $service_show->createShowHosts($showData, $showId); - //populate ccShowInstances + $populateShowsUntil = $service_show->getPopulateShowUntilDateTIme(); + //create ccShowInstances + $service_showInstances->createShowInstances($showId, $populateShowsUntil); } } diff --git a/airtime_mvc/application/services/ShowInstanceService.php b/airtime_mvc/application/services/ShowInstanceService.php new file mode 100644 index 000000000..1f7a2eedc --- /dev/null +++ b/airtime_mvc/application/services/ShowInstanceService.php @@ -0,0 +1,8 @@ + $showId), 'all'); + } } \ No newline at end of file From af622eb4b8f83a98a7d3c227fed5caef1c2b4d1f Mon Sep 17 00:00:00 2001 From: denise Date: Tue, 26 Feb 2013 17:41:35 -0500 Subject: [PATCH 12/73] CC-4961: Show linking Refactored some more show instance creation functions --- airtime_mvc/application/models/Show.php | 10 +-- .../application/services/ScheduleService.php | 26 +++--- .../services/ShowInstanceService.php | 81 ++++++++++++++++++- .../application/services/ShowService.php | 70 +++++++++++++--- 4 files changed, 160 insertions(+), 27 deletions(-) diff --git a/airtime_mvc/application/models/Show.php b/airtime_mvc/application/models/Show.php index d6f9db98b..23cc4d02e 100644 --- a/airtime_mvc/application/models/Show.php +++ b/airtime_mvc/application/models/Show.php @@ -1310,7 +1310,7 @@ SQL; } } - Application_Model_Show::populateShowUntil($showId); + /*Application_Model_Show::populateShowUntil($showId);*/ Application_Model_RabbitMq::PushSchedule(); return $showId; @@ -1323,7 +1323,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(); @@ -1344,7 +1344,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 @@ -1357,7 +1357,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 @@ -1371,7 +1371,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 diff --git a/airtime_mvc/application/services/ScheduleService.php b/airtime_mvc/application/services/ScheduleService.php index c0bc1a844..0e6bbf2ff 100644 --- a/airtime_mvc/application/services/ScheduleService.php +++ b/airtime_mvc/application/services/ScheduleService.php @@ -2,6 +2,14 @@ class Application_Service_ScheduleService { + private $service_show; + private $service_showInstances; + + public function __construct() + { + $this->service_show = new Application_Service_ShowService(); + $this->service_showInstances = new Application_Service_ShowInstanceService(); + } /* * Form stuff begins here * Typically I would keep form creation and validation @@ -170,27 +178,23 @@ class Application_Service_ScheduleService $showData["add_show_duration"]); if ($isAdminOrPM) { - $service_show = new Application_Service_ShowService(); - $service_showInstances = new Application_Service_ShowInstanceService(); - //create ccShow $ccShow = new CcShow(); - $ccShow = $service_show->setShow($ccShow, $showData); + $ccShow = $this->service_show->setShow($ccShow, $showData); $showId = $ccShow->getDbId(); - //create ccShowDay - $service_show->createShowDays( + //create ccShowDays + $this->service_show->createShowDays( $showData, $showId, $user->getId(), $repeatType, $isRecorded); - //create ccShowRebroadcast - $service_show->createShowRebroadcast($showData, $showId, $repeatType, $isRecorded); + //create ccShowRebroadcasts + $this->service_show->createShowRebroadcasts($showData, $showId, $repeatType, $isRecorded); //create ccShowHosts - $service_show->createShowHosts($showData, $showId); + $this->service_show->createShowHosts($showData, $showId); - $populateShowsUntil = $service_show->getPopulateShowUntilDateTIme(); //create ccShowInstances - $service_showInstances->createShowInstances($showId, $populateShowsUntil); + $this->service_showInstances->createShowInstances($showId); } } diff --git a/airtime_mvc/application/services/ShowInstanceService.php b/airtime_mvc/application/services/ShowInstanceService.php index 1f7a2eedc..2b4d9a5f8 100644 --- a/airtime_mvc/application/services/ShowInstanceService.php +++ b/airtime_mvc/application/services/ShowInstanceService.php @@ -1,8 +1,85 @@ service_show = new Application_Service_ShowService(); + } + + /** + * + * Receives a cc_show id and determines whether to create a + * single show_instance or repeating show instances + */ + public function createShowInstances($showId) + { + $populateUntil = $this->service_show->getPopulateShowUntilDateTIme(); + + $showDays = $this->service_show->getShowDays($showId); + foreach ($showDays as $day) { + switch ($day["repeat_type"]) { + case self::NO_REPEAT: + $this->createNonRepeatingShowInstance($day, $populateUntil); + break; + case self::REPEAT_WEEKLY: + $this->createRepeatingShowInstances($day, $populateUntil, "P7D"); + break; + case self::REPEAT_BI_WEEKLY: + $this->createRepeatingShowInstances($day, $populateUntil, "P14D"); + break; + case self::REPEAT_MONTHLY_MONTHLY: + $this->createRepeatingShowInstances($day, $populateUntil, "P1M"); + break; + case self::REPEAT_MONTHLY_WEEKLY: + // do something here + break; + } + } + } + + /** + * + * Enter description here ... + * @param $showDay + * @param $populateUntil + */ + private function createNonRepeatingShowInstance($showDay, $populateUntil) + { + $start = $showDay["first_show"]." ".$showDay["start_time"]; + + list($utcStartDateTime, $utcEndDateTime) = $this->service_show->createUTCStartEndDateTime( + $start, $showDay["duration"], $showDay["timezone"]); + + if ($utcStartDateTime->getTimestamp() < $populateUntil->getTimestamp()) { + $currentUtcTimestamp = gmdate("Y-m-d H:i:s"); + + $ccShowInstance = new CcShowInstances(); + if ($ccShowInstance->getTimestamp() > $currentUtcTimestamp) { + $ccShowInstance->setDbShowId($showDay["show_id"]); + $ccShowInstance->setDbStarts($utcStartDateTime); + $ccShowInstance->setDbEnds($utcEndDateTime); + $ccShowInstance->setDbRecord($showDay["record"]); + $ccShowInstance->save(); + } + } + } + + /** + * + * Enter description here ... + * @param $showDay + * @param $populateUntil + * @param $repeatInterval + */ + private function createRepeatingShowInstances($showDay, $populateUntil, $repeatInterval) + { + Logging::info("repeating"); } } \ No newline at end of file diff --git a/airtime_mvc/application/services/ShowService.php b/airtime_mvc/application/services/ShowService.php index 82153300a..f69d42e42 100644 --- a/airtime_mvc/application/services/ShowService.php +++ b/airtime_mvc/application/services/ShowService.php @@ -2,8 +2,13 @@ class Application_Service_ShowService { + const MAX_REBROADCAST_DATES = 10; + /** - * Sets a cc_show entry + * + * Enter description here ... + * @param $ccShow + * @param $showData */ public function setShow($ccShow, $showData) { @@ -23,7 +28,13 @@ class Application_Service_ShowService } /** - * Creates new cc_show_days entries + * + * Enter description here ... + * @param $showData + * @param $showId + * @param $userId + * @param $repeatType + * @param $isRecorded */ public function createShowDays($showData, $showId, $userId, $repeatType, $isRecorded) { @@ -95,14 +106,17 @@ class Application_Service_ShowService } /** - * Creates new cc_show_rebroadcast entries + * + * Enter description here ... + * @param $showData + * @param $showId + * @param $repeatType + * @param $isRecorded */ - public function createShowRebroadcast($showData, $showId, $repeatType, $isRecorded) + public function createShowRebroadcasts($showData, $showId, $repeatType, $isRecorded) { - define("MAX_REBROADCAST_DATES", 10); - if (($isRecorded && $showData['add_show_rebroadcast']) && ($repeatType != -1)) { - for ($i=1; $i<=MAX_REBROADCAST_DATES; $i++) { + for ($i=1; $i<=self::MAX_REBROADCAST_DATES; $i++) { if ($showData['add_show_rebroadcast_date_'.$i]) { $showRebroad = new CcShowRebroadcast(); $showRebroad->setDbDayOffset($showData['add_show_rebroadcast_date_'.$i]); @@ -112,7 +126,7 @@ class Application_Service_ShowService } } } elseif ($isRecorded && $showData['add_show_rebroadcast'] && ($repeatType == -1)) { - for ($i=1; $i<=MAX_REBROADCAST_DATES; $i++) { + for ($i=1; $i<=self::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']); @@ -129,7 +143,10 @@ class Application_Service_ShowService } /** - * Creates cc_show_hosts entries + * + * Enter description here ... + * @param $showData + * @param $showId */ public function createShowHosts($showData, $showId) { @@ -174,4 +191,39 @@ class Application_Service_ShowService return Application_Common_Database::prepareAndExecute( $sql, array(":show_id" => $showId), 'all'); } + + /** + * + * 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 + * + * @return array of 2 DateTime objects, start/end time of the show in UTC + */ + public function createUTCStartEndDateTime($localStart, $duration, $timezone=null, $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")); + } + //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); + } } \ No newline at end of file From 4a86da5f87386e80c5fad168e1d5a4df6a938149 Mon Sep 17 00:00:00 2001 From: denise Date: Fri, 8 Mar 2013 11:19:03 -0500 Subject: [PATCH 13/73] Created function to create repeating show instances Created function to create rebroadcast show instances --- .../application/services/ScheduleService.php | 3 +- .../services/ShowInstanceService.php | 129 +++++++++++++++--- .../application/services/ShowService.php | 8 +- 3 files changed, 118 insertions(+), 22 deletions(-) diff --git a/airtime_mvc/application/services/ScheduleService.php b/airtime_mvc/application/services/ScheduleService.php index 0e6bbf2ff..77ef24d4e 100644 --- a/airtime_mvc/application/services/ScheduleService.php +++ b/airtime_mvc/application/services/ScheduleService.php @@ -173,6 +173,7 @@ class Application_Service_ScheduleService $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"]); @@ -194,7 +195,7 @@ class Application_Service_ScheduleService $this->service_show->createShowHosts($showData, $showId); //create ccShowInstances - $this->service_showInstances->createShowInstances($showId); + $this->service_showInstances->delegateShowInstanceCreation($showId, $isRebroadcast); } } diff --git a/airtime_mvc/application/services/ShowInstanceService.php b/airtime_mvc/application/services/ShowInstanceService.php index 2b4d9a5f8..8c927d958 100644 --- a/airtime_mvc/application/services/ShowInstanceService.php +++ b/airtime_mvc/application/services/ShowInstanceService.php @@ -16,9 +16,9 @@ class Application_Service_ShowInstanceService /** * * Receives a cc_show id and determines whether to create a - * single show_instance or repeating show instances + * single show instance or repeating show instances */ - public function createShowInstances($showId) + public function delegateShowInstanceCreation($showId, $isRebroadcast) { $populateUntil = $this->service_show->getPopulateShowUntilDateTIme(); @@ -26,31 +26,32 @@ class Application_Service_ShowInstanceService foreach ($showDays as $day) { switch ($day["repeat_type"]) { case self::NO_REPEAT: - $this->createNonRepeatingShowInstance($day, $populateUntil); + $this->createNonRepeatingShowInstance($day, $populateUntil, $isRebroadcast); break; case self::REPEAT_WEEKLY: - $this->createRepeatingShowInstances($day, $populateUntil, "P7D"); + $this->createWeeklyRepeatingShowInstances($day, $populateUntil, "P7D", $isRebroadcast); break; case self::REPEAT_BI_WEEKLY: - $this->createRepeatingShowInstances($day, $populateUntil, "P14D"); + $this->createWeeklyRepeatingShowInstances($day, $populateUntil, "P14D", $isRebroadcast); break; case self::REPEAT_MONTHLY_MONTHLY: - $this->createRepeatingShowInstances($day, $populateUntil, "P1M"); + $this->createMonthlyRepeatingShowInstances($day, $populateUntil, "P1M", $isRebroadcast); break; case self::REPEAT_MONTHLY_WEEKLY: // do something here break; } } + Application_Model_RabbitMq::PushSchedule(); } /** * - * Enter description here ... + * Sets a single cc_show_instance table row * @param $showDay * @param $populateUntil */ - private function createNonRepeatingShowInstance($showDay, $populateUntil) + private function createNonRepeatingShowInstance($showDay, $populateUntil, $isRebroadcast) { $start = $showDay["first_show"]." ".$showDay["start_time"]; @@ -58,16 +59,82 @@ class Application_Service_ShowInstanceService $start, $showDay["duration"], $showDay["timezone"]); if ($utcStartDateTime->getTimestamp() < $populateUntil->getTimestamp()) { - $currentUtcTimestamp = gmdate("Y-m-d H:i:s"); - $ccShowInstance = new CcShowInstances(); - if ($ccShowInstance->getTimestamp() > $currentUtcTimestamp) { - $ccShowInstance->setDbShowId($showDay["show_id"]); + $ccShowInstance->setDbShowId($showDay["show_id"]); + $ccShowInstance->setDbStarts($utcStartDateTime); + $ccShowInstance->setDbEnds($utcEndDateTime); + $ccShowInstance->setDbRecord($showDay["record"]); + $ccShowInstance->save(); + + if ($isRebroadcast) { + self::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) + { + $show_id = $showDay["show_id"]; + $next_pop_date = $showDay["next_pop_date"]; + $first_show = $showDay["first_show"]; //non-UTC + $last_show = $showDay["last_show"]; //non-UTC + $start_time = $showDay["start_time"]; //non-UTC + $duration = $showDay["duration"]; + $day = $showDay["day"]; + $record = $showDay["record"]; + $timezone = $showDay["timezone"]; + + $currentUtcTimestamp = gmdate("Y-m-d H:i:s"); + + if (isset($next_pop_date)) { + $start = $next_pop_date." ".$start_time; + } else { + $start = $first_show." ".$start_time; + } + + /* + * Create a DatePeriod object in the user's local time + * It will get converted to UTC right before the show instance + * gets created + */ + $period = new DatePeriod(new DateTime($start, new DateTimeZone($timezone)), + new DateInterval($repeatInterval), $populateUntil); + + $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; + + foreach ($period as $date) { + /* + * 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()) { + + list($utcStartDateTime, $utcEndDateTime) = $this->service_show->createUTCStartEndDateTime( + $date->format("Y-m-d H:i:s"), $duration, $timezone); + + $ccShowInstance = new CcShowInstances(); + $ccShowInstance->setDbShowId($show_id); $ccShowInstance->setDbStarts($utcStartDateTime); $ccShowInstance->setDbEnds($utcEndDateTime); - $ccShowInstance->setDbRecord($showDay["record"]); + $ccShowInstance->setDbRecord($record); $ccShowInstance->save(); } + + if ($isRebroadcast) { + self::createRebroadcastShowInstances($showDay, $date->format("Y-m-d"), $ccShowInstance->getDbId()); + } } } @@ -75,11 +142,39 @@ class Application_Service_ShowInstanceService * * Enter description here ... * @param $showDay - * @param $populateUntil - * @param $repeatInterval */ - private function createRepeatingShowInstances($showDay, $populateUntil, $repeatInterval) + private function createRebroadcastShowInstances($showDay, $showStartDate, $instanceId) { - Logging::info("repeating"); + $currentUtcTimestamp = gmdate("Y-m-d H:i:s"); + $showId = $showDay["show_id"]; + + $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["duration"], $showDay["timezone"], $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(); + } + } + } + + private function deleteRebroadcastShowInstances() + { + } } \ No newline at end of file diff --git a/airtime_mvc/application/services/ShowService.php b/airtime_mvc/application/services/ShowService.php index f69d42e42..05eb309af 100644 --- a/airtime_mvc/application/services/ShowService.php +++ b/airtime_mvc/application/services/ShowService.php @@ -6,7 +6,7 @@ class Application_Service_ShowService /** * - * Enter description here ... + * Sets the fields for a cc_show table row * @param $ccShow * @param $showData */ @@ -29,7 +29,7 @@ class Application_Service_ShowService /** * - * Enter description here ... + * Sets the fields for a cc_show_days table row * @param $showData * @param $showId * @param $userId @@ -107,7 +107,7 @@ class Application_Service_ShowService /** * - * Enter description here ... + * Sets the fields for a cc_show_rebroadcast table row * @param $showData * @param $showId * @param $repeatType @@ -144,7 +144,7 @@ class Application_Service_ShowService /** * - * Enter description here ... + * Sets the fields for a cc_show_hosts table row * @param $showData * @param $showId */ From 9be6b82d97385f978b7420ea01e08b4926082e26 Mon Sep 17 00:00:00 2001 From: denise Date: Fri, 8 Mar 2013 12:06:45 -0500 Subject: [PATCH 14/73] Fixed rebroadcast date bug --- .../application/services/ShowInstanceService.php | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/airtime_mvc/application/services/ShowInstanceService.php b/airtime_mvc/application/services/ShowInstanceService.php index d0b512922..1c0cf13e7 100644 --- a/airtime_mvc/application/services/ShowInstanceService.php +++ b/airtime_mvc/application/services/ShowInstanceService.php @@ -103,8 +103,7 @@ class Application_Service_ShowInstanceService /* * Create a DatePeriod object in the user's local time - * It will get converted to UTC right before the show instance - * gets created + * It will get converted to UTC before the show instance gets created */ $period = new DatePeriod(new DateTime($start, new DateTimeZone($timezone)), new DateInterval($repeatInterval), $populateUntil); @@ -114,6 +113,8 @@ class Application_Service_ShowInstanceService $utcLastShowDateTime = $last_show ? Application_Common_DateHelper::ConvertToUtcDateTime($last_show, $timezone) : null; foreach ($period 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 @@ -121,19 +122,16 @@ class Application_Service_ShowInstanceService if ($utcStartDateTime->getTimestamp() <= $populateUntil->getTimestamp() && is_null($utcLastShowDateTime) || $utcStartDateTime->getTimestamp() < $utcLastShowDateTime->getTimestamp()) { - list($utcStartDateTime, $utcEndDateTime) = $this->service_show->createUTCStartEndDateTime( - $date->format("Y-m-d H:i:s"), $duration, $timezone); - $ccShowInstance = new CcShowInstances(); $ccShowInstance->setDbShowId($show_id); $ccShowInstance->setDbStarts($utcStartDateTime); $ccShowInstance->setDbEnds($utcEndDateTime); $ccShowInstance->setDbRecord($record); $ccShowInstance->save(); - } - if ($isRebroadcast) { - self::createRebroadcastShowInstances($showDay, $date->format("Y-m-d"), $ccShowInstance->getDbId()); + if ($isRebroadcast) { + self::createRebroadcastShowInstances($showDay, $date->format("Y-m-d"), $ccShowInstance->getDbId()); + } } } } From 5111f7449487a14c753c033ec262afcbdf2dffb1 Mon Sep 17 00:00:00 2001 From: denise Date: Fri, 8 Mar 2013 12:17:55 -0500 Subject: [PATCH 15/73] Created function to set the next populate until date for repeating shows --- .../application/services/ShowInstanceService.php | 1 + airtime_mvc/application/services/ShowService.php | 13 +++++++++++++ 2 files changed, 14 insertions(+) diff --git a/airtime_mvc/application/services/ShowInstanceService.php b/airtime_mvc/application/services/ShowInstanceService.php index 1c0cf13e7..1e1eeb0f4 100644 --- a/airtime_mvc/application/services/ShowInstanceService.php +++ b/airtime_mvc/application/services/ShowInstanceService.php @@ -134,6 +134,7 @@ class Application_Service_ShowInstanceService } } } + $this->service_show->setNextPopulateUntilDate($nextDate, $show_id, $day); } /** diff --git a/airtime_mvc/application/services/ShowService.php b/airtime_mvc/application/services/ShowService.php index 05eb309af..13605963d 100644 --- a/airtime_mvc/application/services/ShowService.php +++ b/airtime_mvc/application/services/ShowService.php @@ -226,4 +226,17 @@ class Application_Service_ShowService return array($startDateTime, $endDateTime); } + + public function setNextPopulateUntilDate($nextDate, $showId, $day) + { + $nextInfo = explode(" ", $nextDate); + + $repeatInfo = CcShowDaysQuery::create() + ->filterByDbShowId($showId) + ->filterByDbDay($day) + ->findOne(); + + $repeatInfo->setDbNextPopDate($nextInfo[0]) + ->save(); + } } \ No newline at end of file From 8415dfdf6f4a399d7ac2fb5057752667290759e0 Mon Sep 17 00:00:00 2001 From: denise Date: Fri, 8 Mar 2013 12:18:24 -0500 Subject: [PATCH 16/73] Add comments --- airtime_mvc/application/models/Show.php | 26 ++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/airtime_mvc/application/models/Show.php b/airtime_mvc/application/models/Show.php index 23cc4d02e..cb553c1dd 100644 --- a/airtime_mvc/application/models/Show.php +++ b/airtime_mvc/application/models/Show.php @@ -1170,6 +1170,7 @@ SQL; if ($data['add_show_id'] != -1) { $show = new Application_Model_Show($showId); + //CC-4150 CULPRIT $show->deletePossiblyInvalidInstances($data, $endDate, $isRecorded, $repeatType); } @@ -1310,8 +1311,8 @@ SQL; } } - /*Application_Model_Show::populateShowUntil($showId);*/ - Application_Model_RabbitMq::PushSchedule(); + /*Application_Model_Show::populateShowUntil($showId); + Application_Model_RabbitMq::PushSchedule();*/ return $showId; } @@ -1384,7 +1385,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"]; @@ -1395,16 +1396,16 @@ 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); if ($show->hasInstance()) { $ccShowInstance = $show->getInstance(); $newInstance = false; - } else { + } /*else { $ccShowInstance = new CcShowInstances(); $newInstance = true; - } + }*/ if ($newInstance || $ccShowInstance->getDbStarts() > $currentUtcTimestamp) { $ccShowInstance->setDbShowId($show_id); @@ -1421,15 +1422,16 @@ SQL; $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()) { + //only do this for editing $showInstance->deleteRebroadcasts(); self::createRebroadcastInstances($rebroadcasts, $currentUtcTimestamp, $show_id, $show_instance_id, $start, $duration, $timezone); } - } + /*}*/ } /** @@ -1446,7 +1448,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 @@ -1466,7 +1468,7 @@ 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"; @@ -1480,6 +1482,8 @@ SQL; list($utcStartDateTime, $utcEndDateTime) = self::createUTCStartEndDateTime($start, $duration, $timezone); + //determine if we are adding a new show + //or editing a show if ($show->hasInstanceOnDate($utcStartDateTime)) { $ccShowInstance = $show->getInstanceOnDate($utcStartDateTime); From d8ced29dd04e3e348d46fb9b372fd765800c0108 Mon Sep 17 00:00:00 2001 From: denise Date: Fri, 8 Mar 2013 16:08:43 -0500 Subject: [PATCH 17/73] Refactored adding show forms to the view --- .../controllers/ScheduleController.php | 57 +++++++++++-------- .../services/ShowInstanceService.php | 40 +++++++++---- .../application/services/ShowService.php | 13 ++++- 3 files changed, 73 insertions(+), 37 deletions(-) diff --git a/airtime_mvc/application/controllers/ScheduleController.php b/airtime_mvc/application/controllers/ScheduleController.php index ea95d4bc7..50408ff85 100644 --- a/airtime_mvc/application/controllers/ScheduleController.php +++ b/airtime_mvc/application/controllers/ScheduleController.php @@ -94,20 +94,7 @@ class ScheduleController extends Zend_Controller_Action $this->view->headLink()->appendStylesheet($baseUrl.'css/showbuilder.css?'.$CC_CONFIG['airtime_version']); //End Show builder JS/CSS requirements - $forms = $this->service_schedule->createShowForms(); - // populate forms with default values - $this->service_schedule->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"]; + $this->createShowFormAction(true); $user = Application_Model_User::getCurrentUser(); if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) { @@ -746,7 +733,8 @@ class ScheduleController extends Zend_Controller_Action $user = Application_Model_User::getCurrentUser(); if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) { - Application_Model_Schedule::createNewFormSections($this->view); + //Application_Model_Schedule::createNewFormSections($this->view); + $this->createShowFormAction(true); $this->view->form = $this->view->render('schedule/add-show-form.phtml'); } } @@ -879,8 +867,32 @@ class ScheduleController extends Zend_Controller_Action $data['add_show_day_check'] = null; } + $forms = $this->createShowFormAction(); + + $this->view->addNewShow = true; + + if ($this->service_schedule->validateShowForms($forms, $data)) { + $this->view->newForm = $this->view->render('schedule/add-show-form.phtml'); + $this->service_schedule->createShow($data); + + //send new show forms to the user + $this->createShowFormAction(true); + Logging::debug("Show creation succeeded"); + } else { + $this->view->form = $this->view->render('schedule/add-show-form.phtml'); + Logging::debug("Show creation failed"); + } + } + + public function createShowFormAction($populate=false) + { $forms = $this->service_schedule->createShowForms(); + // populate forms with default values + if ($populate) { + $this->populateNewShowFormsAction($forms); + } + $this->view->what = $forms["what"]; $this->view->when = $forms["when"]; $this->view->repeats = $forms["repeats"]; @@ -891,16 +903,13 @@ class ScheduleController extends Zend_Controller_Action $this->view->who = $forms["who"]; $this->view->style = $forms["style"]; - $this->view->addNewShow = true; + return $forms; + } - if ($this->service_schedule->validateShowForms($forms, $data)) { - $this->view->newForm = $this->view->render('schedule/add-show-form.phtml'); - $this->service_schedule->createShow($data); - Logging::debug("Show creation succeeded"); - } else { - $this->view->form = $this->view->render('schedule/add-show-form.phtml'); - Logging::debug("Show creation failed"); - } + public function populateNewShowFormsAction($forms) + { + $this->service_schedule->populateNewShowForms( + $forms["what"], $forms["when"], $forms["repeats"]); } public function cancelShowAction() diff --git a/airtime_mvc/application/services/ShowInstanceService.php b/airtime_mvc/application/services/ShowInstanceService.php index 1e1eeb0f4..09d70e9c3 100644 --- a/airtime_mvc/application/services/ShowInstanceService.php +++ b/airtime_mvc/application/services/ShowInstanceService.php @@ -67,7 +67,7 @@ class Application_Service_ShowInstanceService $ccShowInstance->save(); if ($isRebroadcast) { - self::createRebroadcastShowInstances($showDay, $start, $ccShowInstance->getDbId()); + $this->createRebroadcastShowInstances($showDay, $start, $ccShowInstance->getDbId()); } } } @@ -101,17 +101,14 @@ class Application_Service_ShowInstanceService $start = $first_show." ".$start_time; } - /* - * Create a DatePeriod object in the user's local time - * It will get converted to UTC before the show instance gets created - */ - $period = new DatePeriod(new DateTime($start, new DateTimeZone($timezone)), - new DateInterval($repeatInterval), $populateUntil); + $period = $this->getDatePeriod($start, $timezone, $last_show, + $repeatInterval, $populateUntil); $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; + $utcEndDateTime = null; foreach ($period as $date) { list($utcStartDateTime, $utcEndDateTime) = $this->service_show->createUTCStartEndDateTime( $date->format("Y-m-d H:i:s"), $duration, $timezone); @@ -120,7 +117,8 @@ class Application_Service_ShowInstanceService * 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()) { + ( is_null($utcLastShowDateTime) || + $utcStartDateTime->getTimestamp() < $utcLastShowDateTime->getTimestamp()) ) { $ccShowInstance = new CcShowInstances(); $ccShowInstance->setDbShowId($show_id); @@ -130,11 +128,12 @@ class Application_Service_ShowInstanceService $ccShowInstance->save(); if ($isRebroadcast) { - self::createRebroadcastShowInstances($showDay, $date->format("Y-m-d"), $ccShowInstance->getDbId()); + $this->createRebroadcastShowInstances($showDay, $date->format("Y-m-d"), $ccShowInstance->getDbId()); } } } - $this->service_show->setNextPopulateUntilDate($nextDate, $show_id, $day); + $nextDate = $utcEndDateTime->add(new DateInterval($repeatInterval)); + $this->service_show->setNextRepeatingShowDate($nextDate->format("Y-m-d"), $show_id, $day); } /** @@ -176,4 +175,21 @@ class Application_Service_ShowInstanceService { } + + /** + * + * 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); + } } \ No newline at end of file diff --git a/airtime_mvc/application/services/ShowService.php b/airtime_mvc/application/services/ShowService.php index 13605963d..d8a8e3b1f 100644 --- a/airtime_mvc/application/services/ShowService.php +++ b/airtime_mvc/application/services/ShowService.php @@ -227,7 +227,18 @@ class Application_Service_ShowService return array($startDateTime, $endDateTime); } - public function setNextPopulateUntilDate($nextDate, $showId, $day) + /** + * + * 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 + */ + public function setNextRepeatingShowDate($nextDate, $showId, $day) { $nextInfo = explode(" ", $nextDate); From 116d98a81b044c8e1e1e90c7e6f973a30cb79334 Mon Sep 17 00:00:00 2001 From: denise Date: Fri, 8 Mar 2013 16:10:07 -0500 Subject: [PATCH 18/73] Removed comment --- airtime_mvc/application/controllers/ScheduleController.php | 1 - 1 file changed, 1 deletion(-) diff --git a/airtime_mvc/application/controllers/ScheduleController.php b/airtime_mvc/application/controllers/ScheduleController.php index 50408ff85..abcc38d04 100644 --- a/airtime_mvc/application/controllers/ScheduleController.php +++ b/airtime_mvc/application/controllers/ScheduleController.php @@ -733,7 +733,6 @@ class ScheduleController extends Zend_Controller_Action $user = Application_Model_User::getCurrentUser(); if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) { - //Application_Model_Schedule::createNewFormSections($this->view); $this->createShowFormAction(true); $this->view->form = $this->view->render('schedule/add-show-form.phtml'); } From 1cc823ef0ea34af5602283e255b26056ff735325 Mon Sep 17 00:00:00 2001 From: denise Date: Fri, 8 Mar 2013 17:10:35 -0500 Subject: [PATCH 19/73] Inital edit show reconfiguration changes --- .../controllers/ScheduleController.php | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/airtime_mvc/application/controllers/ScheduleController.php b/airtime_mvc/application/controllers/ScheduleController.php index abcc38d04..a4f356cee 100644 --- a/airtime_mvc/application/controllers/ScheduleController.php +++ b/airtime_mvc/application/controllers/ScheduleController.php @@ -779,7 +779,6 @@ class ScheduleController extends Zend_Controller_Action public function editShowAction() { - //1) Get add_show_start_date since it might not have been sent $js = $this->_getParam('data'); $data = array(); @@ -788,6 +787,7 @@ class ScheduleController extends Zend_Controller_Action $data[$j["name"]] = $j["value"]; } + //TODO: move this to js $data['add_show_hosts'] = $this->_getParam('hosts'); $data['add_show_day_check'] = $this->_getParam('days'); @@ -795,9 +795,10 @@ class ScheduleController extends Zend_Controller_Action $data['add_show_day_check'] = null; } - $show = new Application_Model_Show($data['add_show_id']); + /*$show = new Application_Model_Show($data['add_show_id']);*/ - $validateStartDate = true; + //------- PRE EDIT SHOW CHECK ---------------// + /*$validateStartDate = true; $validateStartTime = true; if (!array_key_exists('add_show_start_date', $data)) { //Changing the start date was disabled, since the @@ -812,15 +813,18 @@ class ScheduleController extends Zend_Controller_Action } $validateStartDate = false; } - $data['add_show_record'] = $show->isRecorded(); + $data['add_show_record'] = $show->isRecorded();*/ + // -------------------------------------------// - if ($show->isRepeating()) { + //-------- ADJUST ORIGINAL START DATE -------// + /*if ($show->isRepeating()) { $nextFutureRepeatShow = $show->getNextFutureRepeatShowTime(); $originalShowStartDateTime = $nextFutureRepeatShow["starts"]; } else { $originalShowStartDateTime = Application_Common_DateHelper::ConvertToLocalDateTime( $show->getStartDateAndTime()); - } + }*/ + //-----------------------------------------// $success = Application_Model_Schedule::addUpdateShow($data, $this, $validateStartDate, $originalShowStartDateTime, true, @@ -871,11 +875,12 @@ class ScheduleController extends Zend_Controller_Action $this->view->addNewShow = true; if ($this->service_schedule->validateShowForms($forms, $data)) { - $this->view->newForm = $this->view->render('schedule/add-show-form.phtml'); $this->service_schedule->createShow($data); + $this->view->newForm = $this->view->render('schedule/add-show-form.phtml'); //send new show forms to the user $this->createShowFormAction(true); + Logging::debug("Show creation succeeded"); } else { $this->view->form = $this->view->render('schedule/add-show-form.phtml'); From 7347be35b12e57d9aea4e58e49e2523361c13db8 Mon Sep 17 00:00:00 2001 From: denise Date: Mon, 11 Mar 2013 16:18:40 -0400 Subject: [PATCH 20/73] Created a new service for show days Created a new user service Started refactoring edit show action --- .../controllers/ScheduleController.php | 38 +----- airtime_mvc/application/forms/AddShowWhen.php | 6 +- .../application/models/airtime/CcSubjs.php | 4 + .../application/services/ScheduleService.php | 86 ++++++++++-- .../application/services/ShowDaysService.php | 125 ++++++++++++++++++ .../services/ShowInstanceService.php | 39 +++++- .../application/services/ShowService.php | 92 ------------- .../application/services/UserService.php | 33 +++++ 8 files changed, 286 insertions(+), 137 deletions(-) create mode 100644 airtime_mvc/application/services/ShowDaysService.php create mode 100644 airtime_mvc/application/services/UserService.php diff --git a/airtime_mvc/application/controllers/ScheduleController.php b/airtime_mvc/application/controllers/ScheduleController.php index a4f356cee..f297537e6 100644 --- a/airtime_mvc/application/controllers/ScheduleController.php +++ b/airtime_mvc/application/controllers/ScheduleController.php @@ -795,42 +795,14 @@ class ScheduleController extends Zend_Controller_Action $data['add_show_day_check'] = null; } - /*$show = new Application_Model_Show($data['add_show_id']);*/ + $forms = $this->createShowFormAction(); - //------- PRE EDIT SHOW CHECK ---------------// - /*$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) = + $this->service_schedule->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 ($this->service_schedule->validateShowForms($forms, $data, $validateStartDate, + $originalShowStartDateTime, true, $data["add_show_instance_id"])) { - //-------- ADJUST ORIGINAL START DATE -------// - /*if ($show->isRepeating()) { - $nextFutureRepeatShow = $show->getNextFutureRepeatShowTime(); - $originalShowStartDateTime = $nextFutureRepeatShow["starts"]; - } else { - $originalShowStartDateTime = Application_Common_DateHelper::ConvertToLocalDateTime( - $show->getStartDateAndTime()); - }*/ - //-----------------------------------------// - - $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) { diff --git a/airtime_mvc/application/forms/AddShowWhen.php b/airtime_mvc/application/forms/AddShowWhen.php index 9f73affbd..ae9ffe5e3 100644 --- a/airtime_mvc/application/forms/AddShowWhen.php +++ b/airtime_mvc/application/forms/AddShowWhen.php @@ -87,9 +87,11 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm } - public function isWhenFormValid($formData, $validateStartDate) { + public function isWhenFormValid($formData, $validateStartDate, $originalStartDate, + $update, $instanceId) { if (parent::isValid($formData)) { - return self::checkReliantFields($formData, $validateStartDate); + return self::checkReliantFields($formData, $validateStartDate, + $originalStartDate, $update, $instanceId); } else { return false; } diff --git a/airtime_mvc/application/models/airtime/CcSubjs.php b/airtime_mvc/application/models/airtime/CcSubjs.php index e5fca5e27..c274e35c4 100644 --- a/airtime_mvc/application/models/airtime/CcSubjs.php +++ b/airtime_mvc/application/models/airtime/CcSubjs.php @@ -15,4 +15,8 @@ */ class CcSubjs extends BaseCcSubjs { + public function isAdminOrPM() + { + return $this->type === UTYPE_ADMIN || $this->type === UTYPE_PROGRAM_MANAGER; + } } // CcSubjs diff --git a/airtime_mvc/application/services/ScheduleService.php b/airtime_mvc/application/services/ScheduleService.php index 77ef24d4e..4450f850b 100644 --- a/airtime_mvc/application/services/ScheduleService.php +++ b/airtime_mvc/application/services/ScheduleService.php @@ -3,12 +3,15 @@ class Application_Service_ScheduleService { 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 @@ -89,14 +92,16 @@ class Application_Service_ScheduleService * * @return boolean */ - public function validateShowForms($forms, $formData, $validateStartDate = true) + 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); + $when = $forms["when"]->isWhenFormValid($formData, $validateStartDate, + $originalStartDate, $editShow, $instanceId); $repeats = true; if ($formData["add_show_repeats"]) { @@ -163,13 +168,18 @@ class Application_Service_ScheduleService /** * - * Creates a new show if form data is valid + * Creates a new show, which entails creating entries in + * the following tables: + * cc_show + * cc_show_days + * cc_show_hosts + * cc_show_rebroadcast + * cc_show_instances */ public function createShow($showData) { - $userInfo = Zend_Auth::getInstance()->getStorage()->read(); - $user = new Application_Model_User($userInfo->id); - $isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER)); + //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; @@ -178,15 +188,16 @@ class Application_Service_ScheduleService $showData["add_show_duration"] = $this->formatShowDuration( $showData["add_show_duration"]); - if ($isAdminOrPM) { + if ($currentUser->isAdminOrPM()) { //create ccShow $ccShow = new CcShow(); $ccShow = $this->service_show->setShow($ccShow, $showData); $showId = $ccShow->getDbId(); //create ccShowDays - $this->service_show->createShowDays( - $showData, $showId, $user->getId(), $repeatType, $isRecorded); + $this->service_showDays = new Application_Service_ShowDaysService($showId); + $this->service_showDays->createShowDays( + $showData, $currentUser->getDbId(), $repeatType, $isRecorded); //create ccShowRebroadcasts $this->service_show->createShowRebroadcasts($showData, $showId, $repeatType, $isRecorded); @@ -199,4 +210,61 @@ class Application_Service_ScheduleService } } + public function editShow($formData) + { + //CcSubj object + $currentUser = $this->service_user->getCurrentUser(); + } + + /** + * + * 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->getDbRepeatType() != -1) { + $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); + } + + public function editShow($showData) + { + //CcSubj object + $currentUser = $this->service_user->getCurrentUser(); + } + } \ No newline at end of file diff --git a/airtime_mvc/application/services/ShowDaysService.php b/airtime_mvc/application/services/ShowDaysService.php new file mode 100644 index 000000000..2b16b6287 --- /dev/null +++ b/airtime_mvc/application/services/ShowDaysService.php @@ -0,0 +1,125 @@ +showId = $id; + } + /** + * + * Sets the fields for a cc_show_days table row + * @param $showData + * @param $showId + * @param $userId + * @param $repeatType + * @param $isRecorded + */ + public function createShowDays($showData, $userId, $repeatType, $isRecorded) + { + $startDateTime = new DateTime($showData['add_show_start_date']." ".$showData['add_show_start_time']); + + if ($showData['add_show_no_end']) { + $endDate = NULL; + } elseif ($showData['add_show_repeats']) { + $endDateTime = new DateTime($showData['add_show_end_date']); + $endDateTime->add(new DateInterval("P1D")); + $endDate = $endDateTime->format("Y-m-d"); + } else { + $endDateTime = new DateTime($showData['add_show_start_date']); + $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()); + 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::GetUserTimezone($userId)); + $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::GetUserTimezone($userId)); + $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() + { + $sql = "SELECT * FROM cc_show_days WHERE show_id = :show_id"; + + return Application_Common_Database::prepareAndExecute( + $sql, array(":show_id" => $this->showId), 'all'); + } + + 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(); + } +} \ No newline at end of file diff --git a/airtime_mvc/application/services/ShowInstanceService.php b/airtime_mvc/application/services/ShowInstanceService.php index 09d70e9c3..b23c3e32a 100644 --- a/airtime_mvc/application/services/ShowInstanceService.php +++ b/airtime_mvc/application/services/ShowInstanceService.php @@ -2,6 +2,9 @@ class Application_Service_ShowInstanceService { private $service_show; + private $service_showDays; + private $service_user; + const NO_REPEAT = -1; const REPEAT_WEEKLY = 0; const REPEAT_BI_WEEKLY = 1; @@ -11,6 +14,7 @@ class Application_Service_ShowInstanceService public function __construct() { $this->service_show = new Application_Service_ShowService(); + $this->service_user = new Application_Service_UserService(); } /** @@ -22,7 +26,9 @@ class Application_Service_ShowInstanceService { $populateUntil = $this->service_show->getPopulateShowUntilDateTIme(); - $showDays = $this->service_show->getShowDays($showId); + $this->service_showDays = new Application_Service_ShowDaysService($showId); + $showDays = $this->service_showDays->getShowDays(); + foreach ($showDays as $day) { switch ($day["repeat_type"]) { case self::NO_REPEAT: @@ -192,4 +198,35 @@ class Application_Service_ShowInstanceService 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; + } } \ No newline at end of file diff --git a/airtime_mvc/application/services/ShowService.php b/airtime_mvc/application/services/ShowService.php index d8a8e3b1f..9669d2086 100644 --- a/airtime_mvc/application/services/ShowService.php +++ b/airtime_mvc/application/services/ShowService.php @@ -27,84 +27,6 @@ class Application_Service_ShowService return $ccShow; } - /** - * - * Sets the fields for a cc_show_days table row - * @param $showData - * @param $showId - * @param $userId - * @param $repeatType - * @param $isRecorded - */ - public function createShowDays($showData, $showId, $userId, $repeatType, $isRecorded) - { - $startDateTime = new DateTime($showData['add_show_start_date']." ".$showData['add_show_start_time']); - - if ($showData['add_show_no_end']) { - $endDate = NULL; - } elseif ($showData['add_show_repeats']) { - $endDateTime = new DateTime($showData['add_show_end_date']); - $endDateTime->add(new DateInterval("P1D")); - $endDate = $endDateTime->format("Y-m-d"); - } else { - $endDateTime = new DateTime($showData['add_show_start_date']); - $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()); - 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::GetUserTimezone($userId)); - $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::GetUserTimezone($userId)); - $showDay->setDbDuration($showData['add_show_duration']); - $showDay->setDbDay($day); - $showDay->setDbRepeatType($repeatType); - $showDay->setDbShowId($showId); - $showDay->setDbRecord($isRecorded); - $showDay->save(); - } - } - } - } - /** * * Sets the fields for a cc_show_rebroadcast table row @@ -178,20 +100,6 @@ class Application_Service_ShowService return $populateUntil; } - /** - * - * Gets the cc_show_days entries for a specific show - * - * @return array of ccShowDays objects - */ - public function getShowDays($showId) - { - $sql = "SELECT * FROM cc_show_days WHERE show_id = :show_id"; - - return Application_Common_Database::prepareAndExecute( - $sql, array(":show_id" => $showId), 'all'); - } - /** * * Enter description here ... 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 From c721b81a13d8d5379603f157e9ba5c6699c788b6 Mon Sep 17 00:00:00 2001 From: denise Date: Tue, 12 Mar 2013 10:30:31 -0400 Subject: [PATCH 21/73] CC-4961: Show linking Refactoring --- .../controllers/ScheduleController.php | 2 ++ airtime_mvc/application/models/Show.php | 7 +++-- .../application/services/ScheduleService.php | 28 +++++++++++-------- .../application/services/ShowDaysService.php | 2 +- .../application/services/ShowService.php | 12 ++++++-- 5 files changed, 32 insertions(+), 19 deletions(-) diff --git a/airtime_mvc/application/controllers/ScheduleController.php b/airtime_mvc/application/controllers/ScheduleController.php index f297537e6..bc56fd993 100644 --- a/airtime_mvc/application/controllers/ScheduleController.php +++ b/airtime_mvc/application/controllers/ScheduleController.php @@ -803,6 +803,8 @@ class ScheduleController extends Zend_Controller_Action if ($this->service_schedule->validateShowForms($forms, $data, $validateStartDate, $originalShowStartDateTime, true, $data["add_show_instance_id"])) { + $this->service_schedule->editShow($data); + $scheduler = new Application_Model_Scheduler(); $showInstances = CcShowInstancesQuery::create()->filterByDbShowId($data['add_show_id'])->find(); foreach ($showInstances as $si) { diff --git a/airtime_mvc/application/models/Show.php b/airtime_mvc/application/models/Show.php index cb553c1dd..17ee99bb2 100644 --- a/airtime_mvc/application/models/Show.php +++ b/airtime_mvc/application/models/Show.php @@ -1147,11 +1147,12 @@ SQL; //find repeat type or set to a non repeating show. /*$repeatType = ($data['add_show_repeats']) ? $data['add_show_repeat_type'] : -1;*/ - if ($data['add_show_id'] == -1) { - /*$ccShow = new CcShow();*/ + /*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->setDbDescription($data['add_show_description']); $ccShow->setDbUrl($data['add_show_url']); diff --git a/airtime_mvc/application/services/ScheduleService.php b/airtime_mvc/application/services/ScheduleService.php index 4450f850b..bf649212d 100644 --- a/airtime_mvc/application/services/ScheduleService.php +++ b/airtime_mvc/application/services/ScheduleService.php @@ -190,30 +190,40 @@ class Application_Service_ScheduleService if ($currentUser->isAdminOrPM()) { //create ccShow - $ccShow = new CcShow(); - $ccShow = $this->service_show->setShow($ccShow, $showData); + $ccShow = $this->service_show->setShow($showData, true); $showId = $ccShow->getDbId(); //create ccShowDays $this->service_showDays = new Application_Service_ShowDaysService($showId); - $this->service_showDays->createShowDays( + $this->service_showDays->setShowDays( $showData, $currentUser->getDbId(), $repeatType, $isRecorded); //create ccShowRebroadcasts - $this->service_show->createShowRebroadcasts($showData, $showId, $repeatType, $isRecorded); + $this->service_show->setShowRebroadcasts($showData, $showId, $repeatType, $isRecorded); //create ccShowHosts - $this->service_show->createShowHosts($showData, $showId); + $this->service_show->setShowHosts($showData, $showId); //create ccShowInstances $this->service_showInstances->delegateShowInstanceCreation($showId, $isRebroadcast); } } - public function editShow($formData) + public function editShow($showData) { //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"]); + + if ($currentUser->isAdminOrPM()) { + $ccShow = $this->service_show->setShow($showData, false); + } } /** @@ -261,10 +271,4 @@ class Application_Service_ScheduleService return array($formData, $validateStartDate, $validateStartTime, $originalShowStartDateTime); } - public function editShow($showData) - { - //CcSubj object - $currentUser = $this->service_user->getCurrentUser(); - } - } \ No newline at end of file diff --git a/airtime_mvc/application/services/ShowDaysService.php b/airtime_mvc/application/services/ShowDaysService.php index 2b16b6287..9876fdce5 100644 --- a/airtime_mvc/application/services/ShowDaysService.php +++ b/airtime_mvc/application/services/ShowDaysService.php @@ -17,7 +17,7 @@ class Application_Service_ShowDaysService * @param $repeatType * @param $isRecorded */ - public function createShowDays($showData, $userId, $repeatType, $isRecorded) + public function setShowDays($showData, $userId, $repeatType, $isRecorded) { $startDateTime = new DateTime($showData['add_show_start_date']." ".$showData['add_show_start_time']); diff --git a/airtime_mvc/application/services/ShowService.php b/airtime_mvc/application/services/ShowService.php index 9669d2086..e858809c8 100644 --- a/airtime_mvc/application/services/ShowService.php +++ b/airtime_mvc/application/services/ShowService.php @@ -10,8 +10,14 @@ class Application_Service_ShowService * @param $ccShow * @param $showData */ - public function setShow($ccShow, $showData) + public function setShow($showData, $isNewShow) { + if ($isNewShow) { + $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']); @@ -35,7 +41,7 @@ class Application_Service_ShowService * @param $repeatType * @param $isRecorded */ - public function createShowRebroadcasts($showData, $showId, $repeatType, $isRecorded) + public function setShowRebroadcasts($showData, $showId, $repeatType, $isRecorded) { if (($isRecorded && $showData['add_show_rebroadcast']) && ($repeatType != -1)) { for ($i=1; $i<=self::MAX_REBROADCAST_DATES; $i++) { @@ -70,7 +76,7 @@ class Application_Service_ShowService * @param $showData * @param $showId */ - public function createShowHosts($showData, $showId) + public function setShowHosts($showData, $showId) { if (is_array($showData['add_show_hosts'])) { foreach ($showData['add_show_hosts'] as $host) { From 438200425a31200b9946c758f414fe7aede863a5 Mon Sep 17 00:00:00 2001 From: denise Date: Tue, 12 Mar 2013 11:33:32 -0400 Subject: [PATCH 22/73] CC-4961: Show linking --- .../services/ShowInstanceService.php | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/airtime_mvc/application/services/ShowInstanceService.php b/airtime_mvc/application/services/ShowInstanceService.php index b23c3e32a..fcf9a6cfa 100644 --- a/airtime_mvc/application/services/ShowInstanceService.php +++ b/airtime_mvc/application/services/ShowInstanceService.php @@ -1,16 +1,16 @@ -service_show = new Application_Service_ShowService(); @@ -31,19 +31,19 @@ class Application_Service_ShowInstanceService foreach ($showDays as $day) { switch ($day["repeat_type"]) { - case self::NO_REPEAT: + case NO_REPEAT: $this->createNonRepeatingShowInstance($day, $populateUntil, $isRebroadcast); break; - case self::REPEAT_WEEKLY: + case REPEAT_WEEKLY: $this->createWeeklyRepeatingShowInstances($day, $populateUntil, "P7D", $isRebroadcast); break; - case self::REPEAT_BI_WEEKLY: + case REPEAT_BI_WEEKLY: $this->createWeeklyRepeatingShowInstances($day, $populateUntil, "P14D", $isRebroadcast); break; - case self::REPEAT_MONTHLY_MONTHLY: + case REPEAT_MONTHLY_MONTHLY: $this->createMonthlyRepeatingShowInstances($day, $populateUntil, "P1M", $isRebroadcast); break; - case self::REPEAT_MONTHLY_WEEKLY: + case REPEAT_MONTHLY_WEEKLY: // do something here break; } From f9f4e4f1fb13114f785c6b281df0f61c5eeb4e39 Mon Sep 17 00:00:00 2001 From: denise Date: Tue, 12 Mar 2013 18:01:12 -0400 Subject: [PATCH 23/73] CC-4961: Show linking Made some progress on show editing --- .../application/models/airtime/CcShowDays.php | 25 ++ .../application/services/ScheduleService.php | 4 +- .../application/services/ShowDaysService.php | 36 ++- .../services/ShowInstanceService.php | 244 +++++++++++++++++- 4 files changed, 281 insertions(+), 28 deletions(-) diff --git a/airtime_mvc/application/models/airtime/CcShowDays.php b/airtime_mvc/application/models/airtime/CcShowDays.php index 72df6047e..7dc9d98bd 100644 --- a/airtime_mvc/application/models/airtime/CcShowDays.php +++ b/airtime_mvc/application/models/airtime/CcShowDays.php @@ -15,4 +15,29 @@ */ 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; + } } // CcShowDays diff --git a/airtime_mvc/application/services/ScheduleService.php b/airtime_mvc/application/services/ScheduleService.php index bf649212d..72304cdb7 100644 --- a/airtime_mvc/application/services/ScheduleService.php +++ b/airtime_mvc/application/services/ScheduleService.php @@ -223,6 +223,8 @@ class Application_Service_ScheduleService if ($currentUser->isAdminOrPM()) { $ccShow = $this->service_show->setShow($showData, false); + + $this->service_showInstances->updateShowInstances($showData, $isRecorded, $repeatType); } } @@ -259,7 +261,7 @@ class Application_Service_ScheduleService //if the show is repeating, set the start date to the next //repeating instance in the future - if ($currentShowDay->getDbRepeatType() != -1) { + if ($currentShowDay->isRepeating()) { $nextFutureRepeatShow = $this->service_showInstances ->getNextFutureRepeatShowTime($formData["add_show_id"]); $originalShowStartDateTime = $nextFutureRepeatShow["starts"]; diff --git a/airtime_mvc/application/services/ShowDaysService.php b/airtime_mvc/application/services/ShowDaysService.php index 9876fdce5..f5cd6c906 100644 --- a/airtime_mvc/application/services/ShowDaysService.php +++ b/airtime_mvc/application/services/ShowDaysService.php @@ -8,6 +8,24 @@ class Application_Service_ShowDaysService { $this->showId = $id; } + + public function calculateEndDate($showData) + { + if ($showData['add_show_no_end']) { + $endDate = NULL; + } elseif ($showData['add_show_repeats']) { + $endDateTime = new DateTime($showData['add_show_end_date']); + $endDateTime->add(new DateInterval("P1D")); + $endDate = $endDateTime->format("Y-m-d"); + } else { + $endDateTime = new DateTime($showData['add_show_start_date']); + $endDateTime->add(new DateInterval("P1D")); + $endDate = $endDateTime->format("Y-m-d"); + } + + return $endDate; + } + /** * * Sets the fields for a cc_show_days table row @@ -21,17 +39,7 @@ class Application_Service_ShowDaysService { $startDateTime = new DateTime($showData['add_show_start_date']." ".$showData['add_show_start_time']); - if ($showData['add_show_no_end']) { - $endDate = NULL; - } elseif ($showData['add_show_repeats']) { - $endDateTime = new DateTime($showData['add_show_end_date']); - $endDateTime->add(new DateInterval("P1D")); - $endDate = $endDateTime->format("Y-m-d"); - } else { - $endDateTime = new DateTime($showData['add_show_start_date']); - $endDateTime->add(new DateInterval("P1D")); - $endDate = $endDateTime->format("Y-m-d"); - } + $endDate = $this->calculateEndDate($showData); /* What we are doing here is checking if the show repeats or if * any repeating days have been checked. If not, then by default @@ -94,10 +102,12 @@ class Application_Service_ShowDaysService */ public function getShowDays() { - $sql = "SELECT * FROM cc_show_days WHERE show_id = :show_id"; + /*$sql = "SELECT * FROM cc_show_days WHERE show_id = :show_id"; return Application_Common_Database::prepareAndExecute( - $sql, array(":show_id" => $this->showId), 'all'); + $sql, array(":show_id" => $this->showId), 'all');*/ + return CcShowDaysQuery::create()->filterByDbShowId( + $this->showId)->find(); } public function getStartDateAndTime() diff --git a/airtime_mvc/application/services/ShowInstanceService.php b/airtime_mvc/application/services/ShowInstanceService.php index fcf9a6cfa..e3de1f766 100644 --- a/airtime_mvc/application/services/ShowInstanceService.php +++ b/airtime_mvc/application/services/ShowInstanceService.php @@ -30,7 +30,7 @@ class Application_Service_ShowInstanceService $showDays = $this->service_showDays->getShowDays(); foreach ($showDays as $day) { - switch ($day["repeat_type"]) { + switch ($day->getDbRepeatType()) { case NO_REPEAT: $this->createNonRepeatingShowInstance($day, $populateUntil, $isRebroadcast); break; @@ -59,17 +59,17 @@ class Application_Service_ShowInstanceService */ private function createNonRepeatingShowInstance($showDay, $populateUntil, $isRebroadcast) { - $start = $showDay["first_show"]." ".$showDay["start_time"]; + $start = $showDay->getDbFirstShow()." ".$showDay->getDbStartTime(); list($utcStartDateTime, $utcEndDateTime) = $this->service_show->createUTCStartEndDateTime( - $start, $showDay["duration"], $showDay["timezone"]); + $start, $showDay->getDbDuration(), $showDay->getDbTimezone()); if ($utcStartDateTime->getTimestamp() < $populateUntil->getTimestamp()) { $ccShowInstance = new CcShowInstances(); - $ccShowInstance->setDbShowId($showDay["show_id"]); + $ccShowInstance->setDbShowId($showDay->getDbShowId()); $ccShowInstance->setDbStarts($utcStartDateTime); $ccShowInstance->setDbEnds($utcEndDateTime); - $ccShowInstance->setDbRecord($showDay["record"]); + $ccShowInstance->setDbRecord($showDay->getDbRecord()); $ccShowInstance->save(); if ($isRebroadcast) { @@ -89,15 +89,15 @@ class Application_Service_ShowInstanceService private function createWeeklyRepeatingShowInstances($showDay, $populateUntil, $repeatInterval, $isRebroadcast) { - $show_id = $showDay["show_id"]; - $next_pop_date = $showDay["next_pop_date"]; - $first_show = $showDay["first_show"]; //non-UTC - $last_show = $showDay["last_show"]; //non-UTC - $start_time = $showDay["start_time"]; //non-UTC - $duration = $showDay["duration"]; - $day = $showDay["day"]; - $record = $showDay["record"]; - $timezone = $showDay["timezone"]; + $show_id = $showDay->getDbShowId(); + $next_pop_date = $showDay->getDbNextPopDate(); + $first_show = $showDay->getDbFirstShow(); //non-UTC + $last_show = $showDay->getDbLastShow(); //non-UTC + $start_time = $showDay->getDbStartTime(); //non-UTC + $duration = $showDay->getDbDuration(); + $day = $showDay->getDbDay(); + $record = $showDay->getDbRecord(); + $timezone = $showDay->getDbTimezone(); $currentUtcTimestamp = gmdate("Y-m-d H:i:s"); @@ -229,4 +229,220 @@ SQL; return $show; } + + /** + * This function is messy. But sometimes there is no easy way to do it. + * + * 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 updateShowInstances($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(); + + $endDate = $this->service_showDays->calculateEndDate($showData); + + //repeat option was toggled + if ($showData['add_show_repeats'] != $currentShowDay->isRepeating()) { + $this->deleteAllRepeatInstances($currentShowDay, $showId); + } + + //duration has changed + if ($showData['add_show_duration'] != $currentShowDay->getDbDuration()) { + $this->updateDuration($showData); + } + + 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 lets + //we need to delete them (CC-2351) + $this->deleteAllInstances($showId); + } + + if ($repeatType != $currentShowDay->getDbRepeatType()) { + //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:s")){ + + //start date/time has changed + if ($showData['add_show_start_date'] > $localShowStart->format("Y-m-d")) { + $this->deleteInstancesBeforeDate($showData['add_show_start_date'], $showId); + } + + /*$this->updateStartDateTime($showData, $p_endDate);*/ + } + } +/* + //Check if end date for the repeat option has changed. If so, need to take care + //of deleting possible invalid Show Instances. + if ((strlen($this->getRepeatingEndDate()) == 0) == $showData['add_show_no_end']) { + //show "Never Ends" option was toggled. + if ($showData['add_show_no_end']) { + } else { + $this->removeAllInstancesFromDate($p_endDate); + } + } + if ($this->getRepeatingEndDate() != $showData['add_show_end_date']) { + //end date was changed. + + $newDate = strtotime($showData['add_show_end_date']); + $oldDate = strtotime($this->getRepeatingEndDate()); + if ($newDate < $oldDate) { + $this->removeAllInstancesFromDate($p_endDate); + } + }*/ + } + } + + public function deleteAllRepeatInstances($currentShowDay, $showId) + { + $firstShow = $currentShowDay->getUTCStartDateAndTime(); + + $sql = << :timestamp::TIMESTAMP + AND show_id = :showId + AND date(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")), '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 removed + * ( + * @param $showDays + * @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 updateDuration($showData) + { + $date = new Application_Common_DateHelper; + $timestamp = $date->getUtcTimestamp(); + + $sql = << :timestamp::TIMESTAMP +SQL; + + Application_Common_Database::prepareAndExecute( $sql, array( + ':add_show_duration' => $showData['add_show_duration'], + ':show_id' => $showData['add_show_id'], + ':timestamp' => $timestamp), "execute"); + } } \ No newline at end of file From 5735baf2373994010f91f5b4e93f1f3e13add57c Mon Sep 17 00:00:00 2001 From: denise Date: Wed, 13 Mar 2013 11:08:16 -0400 Subject: [PATCH 24/73] CC-4961: Show linking Made progress on ShowInstanceService --- .../application/services/ShowDaysService.php | 8 +++ .../services/ShowInstanceService.php | 57 +++++++++++++++++-- 2 files changed, 59 insertions(+), 6 deletions(-) diff --git a/airtime_mvc/application/services/ShowDaysService.php b/airtime_mvc/application/services/ShowDaysService.php index f5cd6c906..b22fd4292 100644 --- a/airtime_mvc/application/services/ShowDaysService.php +++ b/airtime_mvc/application/services/ShowDaysService.php @@ -9,6 +9,14 @@ class Application_Service_ShowDaysService $this->showId = $id; } + /** + * + * 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']) { diff --git a/airtime_mvc/application/services/ShowInstanceService.php b/airtime_mvc/application/services/ShowInstanceService.php index e3de1f766..ccd6f3c0b 100644 --- a/airtime_mvc/application/services/ShowInstanceService.php +++ b/airtime_mvc/application/services/ShowInstanceService.php @@ -275,7 +275,7 @@ SQL; $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 lets + //This screws up the repeating positions of show instances, so //we need to delete them (CC-2351) $this->deleteAllInstances($showId); } @@ -286,11 +286,13 @@ SQL; } 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); @@ -315,12 +317,13 @@ SQL; if ($showData['add_show_start_date'] != $localShowStart->format("Y-m-d") || $showData['add_show_start_time'] != $localShowStart->format("H:i:s")){ - //start date/time has changed + //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); } - /*$this->updateStartDateTime($showData, $p_endDate);*/ + $this->updateStartDateAndTime($showData, $currentShowDay); } } /* @@ -345,6 +348,47 @@ SQL; } } + /** + * + * Updates the start date and time for cc_show_instances + * and entries in cc_schedule + * + * @param $showData edit show form data + */ + public function updateStartDateAndTime($showData, $currentShowDay) + { + $date = new Application_Common_DateHelper(); + //current time in UTC + $timestamp = $date->getTimestamp(); + + $dtOld = $currentShowDay->getUTCStartDateAndTime(); + $dtNew = new DateTime($showData['add_show_start_date']." ".$showData['add_show_start_time'], + new DateTimeZone(date_default_timezone_get())); + $diff = $dtOld->getTimestamp() - $dtNew->getTimestamp(); + $sql = << :timestamp +SQL; + + Application_Common_Database::prepareAndExecute($sql, + array(':diff1' => $diff, ':diff2' => $diff, + ':showId' => $showData["add_show_id"], ':timestamp' => $timestamp), + 'execute'); + + /*$showInstanceIds = $this->getAllFutureInstanceIds(); + if (count($showInstanceIds) > 0 && $diff != 0) { + $showIdsImploded = implode(",", $showInstanceIds); + $sql = "UPDATE cc_schedule " + ."SET starts = starts + INTERVAL '$diff sec', " + ."ends = ends + INTERVAL '$diff sec' " + ."WHERE instance_id IN ($showIdsImploded)"; + $con->exec($sql); + }*/ + } + public function deleteAllRepeatInstances($currentShowDay, $showId) { $firstShow = $currentShowDay->getUTCStartDateAndTime(); @@ -378,9 +422,10 @@ SQL; /** * * Enter description here ... - * @param $daysRemoved array of days removed - * ( - * @param $showDays + * @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) From 896e03d76b0f2f0738507d2f916abc7ee67b7336 Mon Sep 17 00:00:00 2001 From: denise Date: Fri, 15 Mar 2013 16:56:22 -0400 Subject: [PATCH 25/73] CC-4961: Show linking Refactoring all services thus far --- .../controllers/ScheduleController.php | 19 +- airtime_mvc/application/models/Show.php | 81 ++--- .../application/services/CalendarService.php | 271 +++++++++++++++++ .../application/services/ScheduleService.php | 280 +---------------- .../application/services/ShowDaysService.php | 66 +++- .../services/ShowInstanceService.php | 286 ++++++++++++------ .../application/services/ShowService.php | 26 +- 7 files changed, 612 insertions(+), 417 deletions(-) create mode 100644 airtime_mvc/application/services/CalendarService.php diff --git a/airtime_mvc/application/controllers/ScheduleController.php b/airtime_mvc/application/controllers/ScheduleController.php index bc56fd993..09a2495ca 100644 --- a/airtime_mvc/application/controllers/ScheduleController.php +++ b/airtime_mvc/application/controllers/ScheduleController.php @@ -5,7 +5,7 @@ class ScheduleController extends Zend_Controller_Action protected $sched_sess = null; - private $service_schedule; + private $service_calendar; public function init() { @@ -41,7 +41,7 @@ class ScheduleController extends Zend_Controller_Action $this->sched_sess = new Zend_Session_Namespace("schedule"); - $this->service_schedule = new Application_Service_ScheduleService(); + $this->service_calendar = new Application_Service_CalendarService(); } public function indexAction() @@ -798,12 +798,13 @@ class ScheduleController extends Zend_Controller_Action $forms = $this->createShowFormAction(); list($data, $validateStartDate, $validateStartTime, $originalShowStartDateTime) = - $this->service_schedule->preEditShowValidationCheck($data); + $this->service_calendar->preEditShowValidationCheck($data); - if ($this->service_schedule->validateShowForms($forms, $data, $validateStartDate, + if ($this->service_calendar->validateShowForms($forms, $data, $validateStartDate, $originalShowStartDateTime, true, $data["add_show_instance_id"])) { - $this->service_schedule->editShow($data); + //pass in true to indicate we are updating a show + $this->service_calendar->addUpdateShow($data, true); $scheduler = new Application_Model_Scheduler(); $showInstances = CcShowInstancesQuery::create()->filterByDbShowId($data['add_show_id'])->find(); @@ -848,8 +849,8 @@ class ScheduleController extends Zend_Controller_Action $this->view->addNewShow = true; - if ($this->service_schedule->validateShowForms($forms, $data)) { - $this->service_schedule->createShow($data); + if ($this->service_calendar->validateShowForms($forms, $data)) { + $this->service_calendar->addUpdateShow($data); $this->view->newForm = $this->view->render('schedule/add-show-form.phtml'); //send new show forms to the user @@ -864,7 +865,7 @@ class ScheduleController extends Zend_Controller_Action public function createShowFormAction($populate=false) { - $forms = $this->service_schedule->createShowForms(); + $forms = $this->service_calendar->createShowForms(); // populate forms with default values if ($populate) { @@ -886,7 +887,7 @@ class ScheduleController extends Zend_Controller_Action public function populateNewShowFormsAction($forms) { - $this->service_schedule->populateNewShowForms( + $this->service_calendar->populateNewShowForms( $forms["what"], $forms["when"], $forms["repeats"]); } diff --git a/airtime_mvc/application/models/Show.php b/airtime_mvc/application/models/Show.php index 17ee99bb2..8490f6295 100644 --- a/airtime_mvc/application/models/Show.php +++ b/airtime_mvc/application/models/Show.php @@ -1169,17 +1169,17 @@ SQL; /*$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) { @@ -1223,11 +1223,11 @@ SQL; //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 */ @@ -1272,9 +1272,9 @@ SQL; //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'])) { //add selected hosts to cc_show_hosts table. foreach ($data['add_show_hosts'] as $host) { @@ -1285,7 +1285,7 @@ SQL; } }*/ - if ($data['add_show_id'] != -1) { + /*if ($data['add_show_id'] != -1) { $con = Propel::getConnection(CcSchedulePeer::DATABASE_NAME); $con->beginTransaction(); @@ -1310,12 +1310,12 @@ SQL; Logging::info("Couldn't update schedule status."); Logging::info($e->getMessage()); } - } + }*/ /*Application_Model_Show::populateShowUntil($showId); Application_Model_RabbitMq::PushSchedule();*/ - return $showId; + /*return $showId;*/ } /** @@ -1399,39 +1399,39 @@ SQL; if ($utcStartDateTime->getTimestamp() < $p_populateUntilDateTime->getTimestamp()) { $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"; $rebroadcasts = Application_Common_Database::prepareAndExecute($sql, 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); - } + }*/ /*}*/ } @@ -1471,21 +1471,21 @@ SQL; //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;*/ - $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);*/ //determine if we are adding a new show //or editing a show - if ($show->hasInstanceOnDate($utcStartDateTime)) { + /* if ($show->hasInstanceOnDate($utcStartDateTime)) { $ccShowInstance = $show->getInstanceOnDate($utcStartDateTime); if ($ccShowInstance->getDbModifiedInstance()) { @@ -1498,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); @@ -1513,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) @@ -1581,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)) { @@ -1595,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 @@ -1621,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) { @@ -1643,7 +1644,7 @@ SQL; $newRebroadcastInstance->setDbOriginalShow($p_showInstanceId); $newRebroadcastInstance->save(); } - } + }*/ } /** diff --git a/airtime_mvc/application/services/CalendarService.php b/airtime_mvc/application/services/CalendarService.php new file mode 100644 index 000000000..a03fd734b --- /dev/null +++ b/airtime_mvc/application/services/CalendarService.php @@ -0,0 +1,271 @@ +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); + $this->service_showInstances->updateScheduleStatus($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); + + $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/ScheduleService.php b/airtime_mvc/application/services/ScheduleService.php index 72304cdb7..9ff581542 100644 --- a/airtime_mvc/application/services/ScheduleService.php +++ b/airtime_mvc/application/services/ScheduleService.php @@ -1,276 +1,26 @@ 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 + * Enter description here ... + * @param array $instanceIds */ - public function createShowForms() + public static function updateScheduleStartTime($instanceIds, $diff) { - $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(); + if (count($instanceIds) > 0 && $diff != 0) { + $showIdList = implode(",", $instanceIds); + $sql = <<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; + Application_Common_Database::prepareAndExecute($sql, + array(':diff1' => $diff, ':diff2' => $diff, + ':showIds' => $showIdList), + 'execute'); } } -/* - * 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; - } - - /** - * - * Creates a new show, which entails creating entries in - * the following tables: - * cc_show - * cc_show_days - * cc_show_hosts - * cc_show_rebroadcast - * cc_show_instances - */ - public function createShow($showData) - { - //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"]); - - if ($currentUser->isAdminOrPM()) { - //create ccShow - $ccShow = $this->service_show->setShow($showData, true); - $showId = $ccShow->getDbId(); - - //create ccShowDays - $this->service_showDays = new Application_Service_ShowDaysService($showId); - $this->service_showDays->setShowDays( - $showData, $currentUser->getDbId(), $repeatType, $isRecorded); - - //create ccShowRebroadcasts - $this->service_show->setShowRebroadcasts($showData, $showId, $repeatType, $isRecorded); - - //create ccShowHosts - $this->service_show->setShowHosts($showData, $showId); - - //create ccShowInstances - $this->service_showInstances->delegateShowInstanceCreation($showId, $isRebroadcast); - } - } - - public function editShow($showData) - { - //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"]); - - if ($currentUser->isAdminOrPM()) { - $ccShow = $this->service_show->setShow($showData, false); - - $this->service_showInstances->updateShowInstances($showData, $isRecorded, $repeatType); - } - } - - /** - * - * 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 index b22fd4292..07616b552 100644 --- a/airtime_mvc/application/services/ShowDaysService.php +++ b/airtime_mvc/application/services/ShowDaysService.php @@ -9,6 +9,17 @@ class Application_Service_ShowDaysService $this->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 @@ -22,13 +33,11 @@ class Application_Service_ShowDaysService if ($showData['add_show_no_end']) { $endDate = NULL; } elseif ($showData['add_show_repeats']) { - $endDateTime = new DateTime($showData['add_show_end_date']); - $endDateTime->add(new DateInterval("P1D")); - $endDate = $endDateTime->format("Y-m-d"); + $endDate = new DateTime($showData['add_show_end_date']); + $endDate->add(new DateInterval("P1D")); } else { - $endDateTime = new DateTime($showData['add_show_start_date']); - $endDateTime->add(new DateInterval("P1D")); - $endDate = $endDateTime->format("Y-m-d"); + $endDate = new DateTime($showData['add_show_start_date']); + $endDate->add(new DateInterval("P1D")); } return $endDate; @@ -42,12 +51,18 @@ class Application_Service_ShowDaysService * @param $userId * @param $repeatType * @param $isRecorded + * @param $showDay ccShowDay object we are setting values on */ - public function setShowDays($showData, $userId, $repeatType, $isRecorded) + public function setShowDays($showData, $repeatType, $isRecorded) { $startDateTime = new DateTime($showData['add_show_start_date']." ".$showData['add_show_start_time']); - $endDate = $this->calculateEndDate($showData); + $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 @@ -67,7 +82,7 @@ class Application_Service_ShowDaysService $showDay->setDbFirstShow($startDateTime->format("Y-m-d")); $showDay->setDbLastShow($endDate); $showDay->setDbStartTime($startDateTime->format("H:i:s")); - $showDay->setDbTimezone(Application_Model_Preference::GetUserTimezone($userId)); + $showDay->setDbTimezone(Application_Model_Preference::GetTimezone()); $showDay->setDbDuration($showData['add_show_duration']); $showDay->setDbRepeatType($repeatType); $showDay->setDbShowId($this->showId); @@ -90,7 +105,7 @@ class Application_Service_ShowDaysService $showDay->setDbFirstShow($startDateTimeClone->format("Y-m-d")); $showDay->setDbLastShow($endDate); $showDay->setDbStartTime($startDateTimeClone->format("H:i")); - $showDay->setDbTimezone(Application_Model_Preference::GetUserTimezone($userId)); + $showDay->setDbTimezone(Application_Model_Preference::GetTimezone()); $showDay->setDbDuration($showData['add_show_duration']); $showDay->setDbDay($day); $showDay->setDbRepeatType($repeatType); @@ -110,10 +125,6 @@ class Application_Service_ShowDaysService */ public function getShowDays() { - /*$sql = "SELECT * FROM cc_show_days WHERE show_id = :show_id"; - - return Application_Common_Database::prepareAndExecute( - $sql, array(":show_id" => $this->showId), 'all');*/ return CcShowDaysQuery::create()->filterByDbShowId( $this->showId)->find(); } @@ -140,4 +151,31 @@ class Application_Service_ShowDaysService 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/ShowInstanceService.php b/airtime_mvc/application/services/ShowInstanceService.php index ccd6f3c0b..b6701e705 100644 --- a/airtime_mvc/application/services/ShowInstanceService.php +++ b/airtime_mvc/application/services/ShowInstanceService.php @@ -22,7 +22,7 @@ class Application_Service_ShowInstanceService * Receives a cc_show id and determines whether to create a * single show instance or repeating show instances */ - public function delegateShowInstanceCreation($showId, $isRebroadcast) + public function delegateShowInstanceCreation($showId, $isRebroadcast, $isUpdate) { $populateUntil = $this->service_show->getPopulateShowUntilDateTIme(); @@ -32,10 +32,10 @@ class Application_Service_ShowInstanceService foreach ($showDays as $day) { switch ($day->getDbRepeatType()) { case NO_REPEAT: - $this->createNonRepeatingShowInstance($day, $populateUntil, $isRebroadcast); + $this->createNonRepeatingShowInstance($day, $populateUntil, $isRebroadcast, $isUpdate); break; case REPEAT_WEEKLY: - $this->createWeeklyRepeatingShowInstances($day, $populateUntil, "P7D", $isRebroadcast); + $this->createWeeklyRepeatingShowInstances($day, $populateUntil, "P7D", $isRebroadcast, $isUpdate); break; case REPEAT_BI_WEEKLY: $this->createWeeklyRepeatingShowInstances($day, $populateUntil, "P14D", $isRebroadcast); @@ -57,7 +57,7 @@ class Application_Service_ShowInstanceService * @param $showDay * @param $populateUntil */ - private function createNonRepeatingShowInstance($showDay, $populateUntil, $isRebroadcast) + private function createNonRepeatingShowInstance($showDay, $populateUntil, $isRebroadcast, $isUpdate) { $start = $showDay->getDbFirstShow()." ".$showDay->getDbStartTime(); @@ -66,6 +66,15 @@ class Application_Service_ShowInstanceService if ($utcStartDateTime->getTimestamp() < $populateUntil->getTimestamp()) { $ccShowInstance = new CcShowInstances(); + if ($isUpdate) { + $ccShowInstance = $this->getInstance($utcStartDateTime, $showDay->getDbShowId()); + //update schedule start times + //ccShowDays object of the show being edited + $currentShowDay = $this->service_showDays->getCurrentShowDay(); + $diff = $this->calculateShowStartDiff($utcStartDateTime, + $currentShowDay->getUTCStartDateAndTime()); + Application_Service_ScheduleService::updateScheduleStartTime(array($ccShowInstance->getDbId()), $diff); + } $ccShowInstance->setDbShowId($showDay->getDbShowId()); $ccShowInstance->setDbStarts($utcStartDateTime); $ccShowInstance->setDbEnds($utcEndDateTime); @@ -87,35 +96,26 @@ class Application_Service_ShowInstanceService * @param unknown_type $isRebroadcast */ private function createWeeklyRepeatingShowInstances($showDay, $populateUntil, - $repeatInterval, $isRebroadcast) + $repeatInterval, $isRebroadcast, $isUpdate) { $show_id = $showDay->getDbShowId(); - $next_pop_date = $showDay->getDbNextPopDate(); $first_show = $showDay->getDbFirstShow(); //non-UTC $last_show = $showDay->getDbLastShow(); //non-UTC - $start_time = $showDay->getDbStartTime(); //non-UTC $duration = $showDay->getDbDuration(); $day = $showDay->getDbDay(); $record = $showDay->getDbRecord(); $timezone = $showDay->getDbTimezone(); - $currentUtcTimestamp = gmdate("Y-m-d H:i:s"); + $start = $this->service_showDays->getNextStartDateTime($showDay); - if (isset($next_pop_date)) { - $start = $next_pop_date." ".$start_time; - } else { - $start = $first_show." ".$start_time; - } - - $period = $this->getDatePeriod($start, $timezone, $last_show, + $datePeriod = $this->getDatePeriod($start, $timezone, $last_show, $repeatInterval, $populateUntil); - $utcStartDateTime = Application_Common_DateHelper::ConvertToUtcDateTime($start, $timezone); $utcLastShowDateTime = $last_show ? Application_Common_DateHelper::ConvertToUtcDateTime($last_show, $timezone) : null; $utcEndDateTime = null; - foreach ($period as $date) { + foreach ($datePeriod as $date) { list($utcStartDateTime, $utcEndDateTime) = $this->service_show->createUTCStartEndDateTime( $date->format("Y-m-d H:i:s"), $duration, $timezone); /* @@ -127,14 +127,23 @@ class Application_Service_ShowInstanceService $utcStartDateTime->getTimestamp() < $utcLastShowDateTime->getTimestamp()) ) { $ccShowInstance = new CcShowInstances(); - $ccShowInstance->setDbShowId($show_id); - $ccShowInstance->setDbStarts($utcStartDateTime); - $ccShowInstance->setDbEnds($utcEndDateTime); - $ccShowInstance->setDbRecord($record); - $ccShowInstance->save(); + if ($isUpdate) { + $ccShowInstance = $this->getInstance($utcStartDateTime, $show_id); + } + + /* 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 (!$isUpdate || $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->createRebroadcastShowInstances($showDay, $date->format("Y-m-d"), $ccShowInstance->getDbId()); + $this->createRebroadcastInstances($showDay, $date->format("Y-m-d"), $ccShowInstance->getDbId()); } } } @@ -147,10 +156,10 @@ class Application_Service_ShowInstanceService * Enter description here ... * @param $showDay */ - private function createRebroadcastShowInstances($showDay, $showStartDate, $instanceId) + private function createRebroadcastInstances($showDay, $showStartDate, $instanceId) { $currentUtcTimestamp = gmdate("Y-m-d H:i:s"); - $showId = $showDay["show_id"]; + $showId = $showDay->getDbShowId(); $sql = "SELECT * FROM cc_show_rebroadcast WHERE show_id=:show_id"; $rebroadcasts = Application_Common_Database::prepareAndExecute($sql, @@ -162,7 +171,7 @@ class Application_Service_ShowInstanceService $offset = array("days"=>$days[0], "hours"=>$time[0], "mins"=>$time[1]); list($utcStartDateTime, $utcEndDateTime) = $this->service_show->createUTCStartEndDateTime( - $showStartDate, $showDay["duration"], $showDay["timezone"], $offset); + $showStartDate, $showDay->getDbDuration(), $showDay->getDbTimezone(), $offset); if ($utcStartDateTime->format("Y-m-d H:i:s") > $currentUtcTimestamp) { $ccShowInstance = new CcShowInstances(); @@ -177,9 +186,30 @@ class Application_Service_ShowInstanceService } } - private function deleteRebroadcastShowInstances() + 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'); } /** @@ -231,7 +261,80 @@ SQL; } /** - * This function is messy. But sometimes there is no easy way to do it. + * + * 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()) { + throw new Exception("Show instance not found"); + } + + return $ccShowInstance[0]; + } + + 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 @@ -242,7 +345,7 @@ SQL; * @param $isRecorded value computed from the edit show form * @param $repeatType value computed from the edit show form */ - public function updateShowInstances($showData, $isRecorded, $repeatType) + public function deleteInvalidInstances($showData, $isRecorded, $repeatType) { $showId = $showData["add_show_id"]; @@ -250,7 +353,13 @@ SQL; //ccShowDays object of the show being edited $currentShowDay = $this->service_showDays->getCurrentShowDay(); - $endDate = $this->service_showDays->calculateEndDate($showData); + //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()) { @@ -258,9 +367,9 @@ SQL; } //duration has changed - if ($showData['add_show_duration'] != $currentShowDay->getDbDuration()) { - $this->updateDuration($showData); - } + /*if ($showData['add_show_duration'] != $currentShowDay->getDbDuration()) { + $this->updateInstanceDuration($showData); + }*/ if ($showData['add_show_repeats']) { @@ -315,7 +424,7 @@ SQL; } if ($showData['add_show_start_date'] != $localShowStart->format("Y-m-d") - || $showData['add_show_start_time'] != $localShowStart->format("H:i:s")){ + || $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 @@ -323,70 +432,65 @@ SQL; $this->deleteInstancesBeforeDate($showData['add_show_start_date'], $showId); } - $this->updateStartDateAndTime($showData, $currentShowDay); + } } -/* - //Check if end date for the repeat option has changed. If so, need to take care - //of deleting possible invalid Show Instances. - if ((strlen($this->getRepeatingEndDate()) == 0) == $showData['add_show_no_end']) { - //show "Never Ends" option was toggled. - if ($showData['add_show_no_end']) { - } else { - $this->removeAllInstancesFromDate($p_endDate); - } - } - if ($this->getRepeatingEndDate() != $showData['add_show_end_date']) { - //end date was changed. - $newDate = strtotime($showData['add_show_end_date']); - $oldDate = strtotime($this->getRepeatingEndDate()); - if ($newDate < $oldDate) { - $this->removeAllInstancesFromDate($p_endDate); + $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 + + /*$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 date and time for cc_show_instances - * and entries in cc_schedule + * Updates the start and end time for cc_show_instances * * @param $showData edit show form data */ - public function updateStartDateAndTime($showData, $currentShowDay) + public function updateInstanceStartEndTime($showId, $diff) { - $date = new Application_Common_DateHelper(); - //current time in UTC - $timestamp = $date->getTimestamp(); - - $dtOld = $currentShowDay->getUTCStartDateAndTime(); - $dtNew = new DateTime($showData['add_show_start_date']." ".$showData['add_show_start_time'], - new DateTimeZone(date_default_timezone_get())); - $diff = $dtOld->getTimestamp() - $dtNew->getTimestamp(); $sql = << :timestamp + AND starts > :timestamp::TIMESTAMP SQL; Application_Common_Database::prepareAndExecute($sql, array(':diff1' => $diff, ':diff2' => $diff, - ':showId' => $showData["add_show_id"], ':timestamp' => $timestamp), + ':showId' => $showId, ':timestamp' => gmdate("Y-m-d H:i:s")), 'execute'); - - /*$showInstanceIds = $this->getAllFutureInstanceIds(); - if (count($showInstanceIds) > 0 && $diff != 0) { - $showIdsImploded = implode(",", $showInstanceIds); - $sql = "UPDATE cc_schedule " - ."SET starts = starts + INTERVAL '$diff sec', " - ."ends = ends + INTERVAL '$diff sec' " - ."WHERE instance_id IN ($showIdsImploded)"; - $con->exec($sql); - }*/ } public function deleteAllRepeatInstances($currentShowDay, $showId) @@ -451,11 +555,9 @@ WHERE EXTRACT(DOW FROM starts) IN ($uncheckedDays) AND show_id = :showId SQL; - Application_Common_Database::prepareAndExecute( $sql, - array( - ":timestamp" => gmdate("Y-m-d H:i:s"), - ":showId" => $showId, - ), "execute"); + Application_Common_Database::prepareAndExecute( $sql, array( + ":timestamp" => gmdate("Y-m-d H:i:s"), ":showId" => $showId), + "execute"); } public function deleteInstancesBeforeDate($newStartDate, $showId) @@ -473,21 +575,31 @@ SQL; ":showId" => $showId), "execute"); } - public function updateDuration($showData) + public function deleteInstancesFromDate($endDate, $showId) { - $date = new Application_Common_DateHelper; - $timestamp = $date->getUtcTimestamp(); + $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' => $timestamp), "execute"); - } + ':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 e858809c8..7747a32af 100644 --- a/airtime_mvc/application/services/ShowService.php +++ b/airtime_mvc/application/services/ShowService.php @@ -10,9 +10,9 @@ class Application_Service_ShowService * @param $ccShow * @param $showData */ - public function setShow($showData, $isNewShow) + public function setShow($showData, $isUpdate) { - if ($isNewShow) { + if (!$isUpdate) { $ccShow = new CcShow(); } else { $ccShow = CcShowQuery::create()->findPk($showData["add_show_id"]); @@ -33,6 +33,17 @@ class Application_Service_ShowService return $ccShow; } + /** + * + * 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 + */ + public function deleteShowRebroadcasts($showId) + { + CcShowRebroadcastQuery::create()->filterByDbShowId($showId)>delete(); + } + /** * * Sets the fields for a cc_show_rebroadcast table row @@ -70,6 +81,17 @@ class Application_Service_ShowService } } + /** + * + * 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 + */ + public function deleteShowHosts($showId) + { + CcShowHostsQuery::create()->filterByDbShow($showId)->delete(); + } + /** * * Sets the fields for a cc_show_hosts table row From 4bdd89f747af4d75d098b6e27861b423f67f4c82 Mon Sep 17 00:00:00 2001 From: denise Date: Mon, 18 Mar 2013 12:34:27 -0400 Subject: [PATCH 26/73] CC-4961: Show linking Fixed edit show start/end time bug --- .../application/services/CalendarService.php | 10 ++++- .../services/ShowInstanceService.php | 39 ++++++++++++------- 2 files changed, 34 insertions(+), 15 deletions(-) diff --git a/airtime_mvc/application/services/CalendarService.php b/airtime_mvc/application/services/CalendarService.php index a03fd734b..9988c149b 100644 --- a/airtime_mvc/application/services/CalendarService.php +++ b/airtime_mvc/application/services/CalendarService.php @@ -190,7 +190,9 @@ class Application_Service_CalendarService if ($isUpdate) { $this->service_showInstances->deleteInvalidInstances($showData, $isRecorded, $repeatType); - $this->service_showInstances->updateScheduleStatus($showId); + // 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); @@ -213,6 +215,12 @@ class Application_Service_CalendarService //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) { diff --git a/airtime_mvc/application/services/ShowInstanceService.php b/airtime_mvc/application/services/ShowInstanceService.php index b6701e705..93072f2d1 100644 --- a/airtime_mvc/application/services/ShowInstanceService.php +++ b/airtime_mvc/application/services/ShowInstanceService.php @@ -68,12 +68,6 @@ class Application_Service_ShowInstanceService $ccShowInstance = new CcShowInstances(); if ($isUpdate) { $ccShowInstance = $this->getInstance($utcStartDateTime, $showDay->getDbShowId()); - //update schedule start times - //ccShowDays object of the show being edited - $currentShowDay = $this->service_showDays->getCurrentShowDay(); - $diff = $this->calculateShowStartDiff($utcStartDateTime, - $currentShowDay->getUTCStartDateAndTime()); - Application_Service_ScheduleService::updateScheduleStartTime(array($ccShowInstance->getDbId()), $diff); } $ccShowInstance->setDbShowId($showDay->getDbShowId()); $ccShowInstance->setDbStarts($utcStartDateTime); @@ -126,15 +120,22 @@ class Application_Service_ShowInstanceService ( is_null($utcLastShowDateTime) || $utcStartDateTime->getTimestamp() < $utcLastShowDateTime->getTimestamp()) ) { - $ccShowInstance = new CcShowInstances(); - if ($isUpdate) { + /* 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 (!$isUpdate || $ccShowInstance->getDbStarts() > gmdate("Y-m-d H:i:s")) { + if ($newInstance || $ccShowInstance->getDbStarts() > gmdate("Y-m-d H:i:s")) { $ccShowInstance->setDbShowId($show_id); $ccShowInstance->setDbStarts($utcStartDateTime); $ccShowInstance->setDbEnds($utcEndDateTime); @@ -294,10 +295,15 @@ SQL; ->find(); if ($ccShowInstance->isEmpty()) { - throw new Exception("Show instance not found"); + return false; + } else { + return $ccShowInstance[0]; } + } - return $ccShowInstance[0]; + public function hasInstance($starts, $showId) + { + return $this->getInstance($starts, $showId) ? true : false; } public function getAllFutureInstanceIds($showId) @@ -458,9 +464,14 @@ SQL; } } }//if repeats + } - /*$newStartDateTime = new DateTime($showData["add_show_start_date"]." ". - $showData["add_show_start_time"], + 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, @@ -468,7 +479,7 @@ SQL; $this->updateInstanceStartEndTime($showId, $diff); $instanceIds = $this->getAllFutureInstanceIds($showId); - Application_Service_ScheduleService::updateScheduleStartTime($instanceIds, $diff);*/ + Application_Service_ScheduleService::updateScheduleStartTime($instanceIds, $diff); } /** From bae9f1202aeb8e113ed2091f34954f39270facf3 Mon Sep 17 00:00:00 2001 From: denise Date: Tue, 19 Mar 2013 10:09:28 -0400 Subject: [PATCH 27/73] CC-4961: Show linking Removed unused schedule controller actions Fix bug where changing a show to repeat deletes the original show's content --- .../controllers/ScheduleController.php | 63 +++---------------- .../services/ShowInstanceService.php | 14 ++--- 2 files changed, 13 insertions(+), 64 deletions(-) diff --git a/airtime_mvc/application/controllers/ScheduleController.php b/airtime_mvc/application/controllers/ScheduleController.php index 09a2495ca..87e3c4c4e 100644 --- a/airtime_mvc/application/controllers/ScheduleController.php +++ b/airtime_mvc/application/controllers/ScheduleController.php @@ -6,6 +6,7 @@ class ScheduleController extends Zend_Controller_Action protected $sched_sess = null; private $service_calendar; + private $currentUser; public function init() { @@ -42,6 +43,9 @@ 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(); } public function indexAction() @@ -121,11 +125,9 @@ class ScheduleController extends Zend_Controller_Action $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, + $this->currentUser->isAdminOrPM()); - $events = &Application_Model_Show::getFullCalendarEvents($start, $end, $editable); $this->view->events = $events; } @@ -421,32 +423,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'); @@ -730,9 +706,7 @@ class ScheduleController extends Zend_Controller_Action public function getFormAction() { - $user = Application_Model_User::getCurrentUser(); - - if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) { + if ($this->currentUser->isAdminOrPM()) { $this->createShowFormAction(true); $this->view->form = $this->view->render('schedule/add-show-form.phtml'); } @@ -933,29 +907,6 @@ class ScheduleController extends Zend_Controller_Action } } - public function contentContextMenuAction() - { - $id = $this->_getParam('id'); - - $params = '/format/json/id/#id#/'; - - $paramsPop = str_replace('#id#', $id, $params); - - // added for downlaod - $id = $this->_getParam('id'); - - $file_id = $this->_getParam('id', null); - $file = Application_Model_StoredFile::Recall($file_id); - - $baseUrl = $this->getRequest()->getBaseUrl(); - $url = $file->getRelativeFileUrl($baseUrl).'download/true'; - $menu[] = array('action' => array('type' => 'gourl', 'url' => $url), - 'title' => _('Download')); - - //returns format jjmenu is looking for. - $this->_helper->json->sendJson($menu); - } - /** * Sets the user specific preference for which time scale to use in Calendar. * This is only being used by schedule.js at the moment. diff --git a/airtime_mvc/application/services/ShowInstanceService.php b/airtime_mvc/application/services/ShowInstanceService.php index 93072f2d1..bf9d2b392 100644 --- a/airtime_mvc/application/services/ShowInstanceService.php +++ b/airtime_mvc/application/services/ShowInstanceService.php @@ -372,11 +372,6 @@ SQL; $this->deleteAllRepeatInstances($currentShowDay, $showId); } - //duration has changed - /*if ($showData['add_show_duration'] != $currentShowDay->getDbDuration()) { - $this->updateInstanceDuration($showData); - }*/ - if ($showData['add_show_repeats']) { $localShowStart = $currentShowDay->getLocalStartDateAndTime(); @@ -395,7 +390,10 @@ SQL; $this->deleteAllInstances($showId); } - if ($repeatType != $currentShowDay->getDbRepeatType()) { + $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 { @@ -513,12 +511,12 @@ DELETE FROM cc_show_instances WHERE starts > :timestamp::TIMESTAMP AND show_id = :showId - AND date(starts) != :firstShow + 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")), 'execute'); + ':firstShow' => $firstShow->format("Y-m-d H:i:s")), 'execute'); } public function deleteAllInstances($showId) From a7601d290ff07ea344b9c15bf47bab910017968b Mon Sep 17 00:00:00 2001 From: denise Date: Thu, 21 Mar 2013 10:05:11 -0400 Subject: [PATCH 28/73] 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); }); }; From 6766d208aa094f365b97ddbdff0bc057554c31cf Mon Sep 17 00:00:00 2001 From: denise Date: Thu, 21 Mar 2013 16:31:05 -0400 Subject: [PATCH 29/73] CC-4961: Show linking Removed logic out of edit-show action Created new SchedulerService Fixed overlapping show bug --- .../controllers/ScheduleController.php | 101 +----------------- airtime_mvc/application/forms/AddShowWhen.php | 3 +- airtime_mvc/application/models/Schedule.php | 14 +-- .../application/models/airtime/CcShow.php | 79 ++++++++------ .../application/models/airtime/CcShowDays.php | 5 +- .../application/services/ScheduleService.php | 26 ----- .../application/services/SchedulerService.php | 85 +++++++++++++++ .../application/services/ShowFormService.php | 21 +++- .../application/services/ShowService.php | 37 +++++-- 9 files changed, 189 insertions(+), 182 deletions(-) delete mode 100644 airtime_mvc/application/services/ScheduleService.php create mode 100644 airtime_mvc/application/services/SchedulerService.php diff --git a/airtime_mvc/application/controllers/ScheduleController.php b/airtime_mvc/application/controllers/ScheduleController.php index 7f53fe798..1d55f282e 100644 --- a/airtime_mvc/application/controllers/ScheduleController.php +++ b/airtime_mvc/application/controllers/ScheduleController.php @@ -550,105 +550,11 @@ class ScheduleController extends Zend_Controller_Action $service_showForm->delegateFormPopulation($forms); - /*$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->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) { foreach ($forms as $form) { $form->disable(); } - }*/ + } $this->view->newForm = $this->view->render('schedule/add-show-form.phtml'); $this->view->entries = 5; @@ -734,11 +640,6 @@ class ScheduleController extends Zend_Controller_Action //pass in true to indicate we are updating a show $service_show->addUpdateShow($data, true); - $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 { diff --git a/airtime_mvc/application/forms/AddShowWhen.php b/airtime_mvc/application/forms/AddShowWhen.php index ae9ffe5e3..007852ba4 100644 --- a/airtime_mvc/application/forms/AddShowWhen.php +++ b/airtime_mvc/application/forms/AddShowWhen.php @@ -295,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 6b19c5e3d..0796740f3 100644 --- a/airtime_mvc/application/models/Schedule.php +++ b/airtime_mvc/application/models/Schedule.php @@ -1256,19 +1256,19 @@ WHERE (ends <= :show_end1 AND date(starts) >= (date(:show_end3) - INTERVAL '2 days') AND modified_instance = FALSE SQL; - if (is_null($showId)) { - $sql .= <<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; - } + /** + * 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() { @@ -119,4 +118,14 @@ class CcShow extends BaseCcShow { ->orderByDbDayOffset() ->find(); } + + public function getRebroadcastsAbsolute() + { + return CcShowInstancesQuery::create() + ->filterByDbShowId($this->getDbId()) + ->filterByDbRebroadcast(1) + ->filterByDbModifiedInstance(false) + ->orderByDbStarts() + ->find(); + } } // CcShow diff --git a/airtime_mvc/application/models/airtime/CcShowDays.php b/airtime_mvc/application/models/airtime/CcShowDays.php index 4ed9bd6bc..cef0b333f 100644 --- a/airtime_mvc/application/models/airtime/CcShowDays.php +++ b/airtime_mvc/application/models/airtime/CcShowDays.php @@ -46,8 +46,9 @@ class CcShowDays extends BaseCcShowDays { * Enter description here ... * @param DateTime $startDateTime first show in user's local time */ - public function getLocalEndDateAndTime($startDateTime) + public function getLocalEndDateAndTime($showStart) { + $startDateTime = clone $showStart; $duration = explode(":", $this->getDbDuration()); return $startDateTime->add(new DateInterval('PT'.$duration[0].'H'.$duration[1].'M')); @@ -55,7 +56,7 @@ class CcShowDays extends BaseCcShowDays { public function isShowStartInPast() { - return $this->getUTCStartDateAndTime() > gmdate("Y-m-d H:i:s"); + return $this->getUTCStartDateAndTime()->format("Y-m-d H:i:s") < gmdate("Y-m-d H:i:s"); } public function formatDuration() diff --git a/airtime_mvc/application/services/ScheduleService.php b/airtime_mvc/application/services/ScheduleService.php deleted file mode 100644 index 9ff581542..000000000 --- a/airtime_mvc/application/services/ScheduleService.php +++ /dev/null @@ -1,26 +0,0 @@ - 0 && $diff != 0) { - $showIdList = implode(",", $instanceIds); - $sql = << $diff, ':diff2' => $diff, - ':showIds' => $showIdList), - 'execute'); - } - } -} \ 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..4a4f9172b --- /dev/null +++ b/airtime_mvc/application/services/SchedulerService.php @@ -0,0 +1,85 @@ + 0 && $diff != 0) { + $showIdList = implode(",", $instanceIds); + $sql = << $diff, ':diff2' => $diff, + ':showIds' => $showIdList), + 'execute'); + } + } + + /** + * + * 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 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; + } +} \ No newline at end of file diff --git a/airtime_mvc/application/services/ShowFormService.php b/airtime_mvc/application/services/ShowFormService.php index 38f4129ff..6202f4862 100644 --- a/airtime_mvc/application/services/ShowFormService.php +++ b/airtime_mvc/application/services/ShowFormService.php @@ -89,6 +89,7 @@ class Application_Service_ShowFormService $this->populateFormStyle($forms["style"]); $this->populateFormRecord($forms["record"]); $this->populateFormRebroadcastRelative($forms["rebroadcast"]); + $this->populateFormRebroadcastAbsolute($forms["abs_rebroadcast"]); } private function populateFormWhat($form) @@ -186,7 +187,7 @@ class Application_Service_ShowFormService $form->getElement('add_show_record')->setOptions(array('disabled' => true)); } - public function populateFormRebroadcastRelative($form) + private function populateFormRebroadcastRelative($form) { $relativeRebroadcasts = $this->ccShow->getRebroadcastsRelative(); @@ -202,6 +203,24 @@ class Application_Service_ShowFormService $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 diff --git a/airtime_mvc/application/services/ShowService.php b/airtime_mvc/application/services/ShowService.php index 746264bdf..982f17b35 100644 --- a/airtime_mvc/application/services/ShowService.php +++ b/airtime_mvc/application/services/ShowService.php @@ -65,6 +65,11 @@ class Application_Service_ShowService //create new ccShowInstances $this->delegateInstanceCreation($isRebroadcast, $isUpdate); + if ($isUpdate) { + $service_scheduler = new Application_Service_SchedulerService(); + $service_scheduler->removeGaps($this->ccShow->getDbId()); + } + $con->commit(); Application_Model_RabbitMq::PushSchedule(); } catch (Exception $e) { @@ -89,16 +94,16 @@ class Application_Service_ShowService foreach ($ccShowDays as $day) { switch ($day->getDbRepeatType()) { case NO_REPEAT: - $this->createNonRepeatingShowInstance($day, $populateUntil, $isRebroadcast, $isUpdate); + $this->createNonRepeatingInstance($day, $populateUntil, $isRebroadcast, $isUpdate); break; case REPEAT_WEEKLY: - $this->createWeeklyRepeatingShowInstances($day, $populateUntil, "P7D", $isRebroadcast, $isUpdate); + $this->createRepeatingInstances($day, $populateUntil, "P7D", $isRebroadcast, $isUpdate); break; case REPEAT_BI_WEEKLY: - $this->createWeeklyRepeatingShowInstances($day, $populateUntil, "P14D", $isRebroadcast, $isUpdate); + $this->createRepeatingInstances($day, $populateUntil, "P14D", $isRebroadcast, $isUpdate); break; case REPEAT_MONTHLY_MONTHLY: - $this->createMonthlyRepeatingShowInstances($day, $populateUntil, "P1M", $isRebroadcast); + $this->createRepeatingInstances($day, $populateUntil, "P1M", $isRebroadcast, $isUpdate); break; case REPEAT_MONTHLY_WEEKLY: // do something here @@ -426,7 +431,7 @@ SQL; foreach ($ccShowInstances as $ccShowInstance) { array_push($instanceIds, $ccShowInstance->getDbId()); } - Application_Service_ScheduleService::updateScheduleStartTime($instanceIds, $diff); + Application_Service_SchedulerService::updateScheduleStartTime($instanceIds, $diff); } /** @@ -507,7 +512,7 @@ SQL; * @param $showDay * @param $populateUntil */ - private function createNonRepeatingShowInstance($showDay, $populateUntil, $isRebroadcast, $isUpdate) + private function createNonRepeatingInstance($showDay, $populateUntil, $isRebroadcast, $isUpdate) { //DateTime object $start = $showDay->getLocalStartDateAndTime(); @@ -545,7 +550,7 @@ SQL; * @param unknown_type $repeatInterval * @param unknown_type $isRebroadcast */ - private function createWeeklyRepeatingShowInstances($showDay, $populateUntil, + private function createRepeatingInstances($showDay, $populateUntil, $repeatInterval, $isRebroadcast, $isUpdate) { $show_id = $showDay->getDbShowId(); @@ -617,6 +622,12 @@ SQL; $this->setNextRepeatingShowDate($nextDate->format("Y-m-d"), $day); } + private function createMonthlyRepeatingInstances($showDay, $populateUntil, + $repeatInterval, $isRebroadcast, $isUpdate) + { + + } + private function getNextRepeatingPopulateStartDateTime($showDay) { $nextPopDate = $showDay->getDbNextPopDate(); @@ -882,17 +893,23 @@ SQL; /** * * Enter description here ... - * @param DateTime $startDateTime user's local time + * @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($startDateTime, $duration, $offset=null) + private function createUTCStartEndDateTime($showStart, $duration, $offset=null) { + $startDateTime = clone $showStart; + if (isset($offset)) { - $startDateTime->add(new DateInterval("P{$offset["days"]}DT{$offset["hours"]}H{$offset["mins"]}M")); + //$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')); From 187e49e4b2e41a750914afdf9018b47705cd0843 Mon Sep 17 00:00:00 2001 From: denise Date: Fri, 22 Mar 2013 14:57:02 -0400 Subject: [PATCH 30/73] CC-4961: Show linking Added back-end functionality for creating monthly repeating shows on the same day of the week --- .../application/services/ShowService.php | 164 ++++++++++++++++-- 1 file changed, 150 insertions(+), 14 deletions(-) diff --git a/airtime_mvc/application/services/ShowService.php b/airtime_mvc/application/services/ShowService.php index 982f17b35..4ac671541 100644 --- a/airtime_mvc/application/services/ShowService.php +++ b/airtime_mvc/application/services/ShowService.php @@ -97,16 +97,19 @@ class Application_Service_ShowService $this->createNonRepeatingInstance($day, $populateUntil, $isRebroadcast, $isUpdate); break; case REPEAT_WEEKLY: - $this->createRepeatingInstances($day, $populateUntil, "P7D", $isRebroadcast, $isUpdate); + $this->createRepeatingInstances($day, $populateUntil, REPEAT_WEEKLY, + new DateInterval("P7D"), $isRebroadcast, $isUpdate); break; case REPEAT_BI_WEEKLY: - $this->createRepeatingInstances($day, $populateUntil, "P14D", $isRebroadcast, $isUpdate); + $this->createRepeatingInstances($day, $populateUntil, REPEAT_BI_WEEKLY, + new DateInterval("P14D"), $isRebroadcast, $isUpdate); break; case REPEAT_MONTHLY_MONTHLY: - $this->createRepeatingInstances($day, $populateUntil, "P1M", $isRebroadcast, $isUpdate); + $this->createMonthlyMonthlyRepeatInstances($day, $populateUntil, $isRebroadcast, $isUpdate); break; case REPEAT_MONTHLY_WEEKLY: - // do something here + $this->createRepeatingInstances($day, $populateUntil, REPEAT_MONTHLY_WEEKLY, + null, $isRebroadcast, $isUpdate); break; } } @@ -551,7 +554,7 @@ SQL; * @param unknown_type $isRebroadcast */ private function createRepeatingInstances($showDay, $populateUntil, - $repeatInterval, $isRebroadcast, $isUpdate) + $repeatType, $repeatInterval, $isRebroadcast, $isUpdate) { $show_id = $showDay->getDbShowId(); $first_show = $showDay->getDbFirstShow(); //non-UTC @@ -561,9 +564,13 @@ SQL; $record = $showDay->getDbRecord(); $timezone = $showDay->getDbTimezone(); - //string + //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); @@ -618,14 +625,144 @@ SQL; } } } - $nextDate = $utcEndDateTime->add(new DateInterval($repeatInterval)); + $nextDate = $utcEndDateTime->add($repeatInterval); $this->setNextRepeatingShowDate($nextDate->format("Y-m-d"), $day); } - private function createMonthlyRepeatingInstances($showDay, $populateUntil, - $repeatInterval, $isRebroadcast, $isUpdate) + private function createMonthlyMonthlyRepeatInstances($showDay, $populateUntil, + $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(); + + //DateTime local + $start = $this->getNextRepeatingPopulateStartDateTime($showDay); + if (isset($last_how)) { + $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 ($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()); + } + } + $start = $this->getNextMonthlyMonthlyRepeatDate($start, $timezone); + } + $this->setNextRepeatingShowDate($start->format("Y-m-d"), $day); + } + + /** + * + * 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, $timezone) + { + $start = new DateTime($showStart, new DateTimeZone($timezone)); + + $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) @@ -634,9 +771,9 @@ SQL; $startTime = $showDay->getDbStartTime(); if (isset($nextPopDate)) { - return $nextPopDate." ".$startTime; + return new DateTime($nextPopDate." ".$startTime, new DateTimeZone($showDay->getDbTimezone())); } else { - return $showDay->getDbFirstShow()." ".$startTime; + return new DateTime($showDay->getDbFirstShow()." ".$startTime, new DateTimeZone($showDay->getDbTimezone())); } } @@ -653,8 +790,7 @@ SQL; $endDatePeriod = $populateUntil; } - return new DatePeriod(new DateTime($start, new DateTimeZone($timezone)), - new DateInterval($repeatInterval), $endDatePeriod); + return new DatePeriod($start, $repeatInterval, $endDatePeriod); } private function hasInstance($starts) From 327d0dd6c9fe45d05cab0578e41f97ad909b99d5 Mon Sep 17 00:00:00 2001 From: denise Date: Fri, 22 Mar 2013 15:57:15 -0400 Subject: [PATCH 31/73] CC-4961: Show linking Add front-end for creating a show with monthly repeats on same day of week --- airtime_mvc/application/forms/AddShowRepeats.php | 9 +++++++++ airtime_mvc/application/services/ShowService.php | 14 +++++++++++--- airtime_mvc/public/js/airtime/schedule/add-show.js | 11 +++++++++++ 3 files changed, 31 insertions(+), 3 deletions(-) diff --git a/airtime_mvc/application/forms/AddShowRepeats.php b/airtime_mvc/application/forms/AddShowRepeats.php index 375942894..3319a7a4d 100644 --- a/airtime_mvc/application/forms/AddShowRepeats.php +++ b/airtime_mvc/application/forms/AddShowRepeats.php @@ -35,6 +35,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:'), diff --git a/airtime_mvc/application/services/ShowService.php b/airtime_mvc/application/services/ShowService.php index 4ac671541..12ae5e4ae 100644 --- a/airtime_mvc/application/services/ShowService.php +++ b/airtime_mvc/application/services/ShowService.php @@ -23,7 +23,15 @@ class Application_Service_ShowService public function addUpdateShow($showData, $isUpdate=false) { - $repeatType = ($showData['add_show_repeats']) ? $showData['add_show_repeat_type'] : -1; + if ($showData["add_show_repeats"]) { + $repeatType = $showData["add_show_repeat_type"]; + if ($showData["add_show_repeat_type"] == 2) { + $repeatType = $showData["add_show_monthly_repeat_type"]; + } + } else { + $repeatType = -1; + } + //$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; @@ -709,9 +717,9 @@ SQL; * @param string $showStart * @param string $timezone user's local timezone */ - private function getMonthlyWeeklyRepeatInterval($showStart, $timezone) + private function getMonthlyWeeklyRepeatInterval($showStart) { - $start = new DateTime($showStart, new DateTimeZone($timezone)); + $start = clone $showStart; $dayOfMonth = $start->format("j"); $dayOfWeek = $start->format("l"); diff --git a/airtime_mvc/public/js/airtime/schedule/add-show.js b/airtime_mvc/public/js/airtime/schedule/add-show.js index a1f053699..3fc150797 100644 --- a/airtime_mvc/public/js/airtime/schedule/add-show.js +++ b/airtime_mvc/public/js/airtime/schedule/add-show.js @@ -216,11 +216,22 @@ function setAddShowEvents() { form.find("#add_show_repeat_type").change(function(){ if($(this).val() == 2) { form.find("#add_show_day_check-label, #add_show_day_check-element").hide(); + //form.find("#add_show_monthly_repeat_type-label, #add_show_monthly_repeat_type-element").show(); } else { form.find("#add_show_day_check-label, #add_show_day_check-element").show(); + //form.find("#add_show_monthly_repeat_type-label, #add_show_monthly_repeat_type-element").hide(); } + toggleMonthlyRepeatType(); }); + toggleMonthlyRepeatType(); + function toggleMonthlyRepeatType() { + if (form.find("#add_show_repeat_type").val() == 2) { + form.find("#add_show_monthly_repeat_type-label, #add_show_monthly_repeat_type-element").show(); + } else { + form.find("#add_show_monthly_repeat_type-label, #add_show_monthly_repeat_type-element").hide(); + } + } form.find("#add_show_day_check-label").addClass("block-display"); form.find("#add_show_day_check-element").addClass("block-display clearfix"); From 5b69761833e098184a495ef246d59318aa9b1ac8 Mon Sep 17 00:00:00 2001 From: denise Date: Mon, 25 Mar 2013 13:48:11 -0400 Subject: [PATCH 32/73] CC-4961: Show linking Populate repeat show form correctly when a show is repeating monthly on the same day of the week --- .../application/services/ShowFormService.php | 14 ++++++++++++-- airtime_mvc/public/js/airtime/schedule/add-show.js | 12 ++++++++---- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/airtime_mvc/application/services/ShowFormService.php b/airtime_mvc/application/services/ShowFormService.php index 6202f4862..e8a085b08 100644 --- a/airtime_mvc/application/services/ShowFormService.php +++ b/airtime_mvc/application/services/ShowFormService.php @@ -149,12 +149,22 @@ class Application_Service_ShowFormService //subtract one day $repeatEndDate->sub(new DateInterval("P1D")); + $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_repeat_type' => $ccShowDays[0]->getDbRepeatType(), + '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_no_end' => (!$service_show->getRepeatingEndDate()), + 'add_show_monthly_repeat_type' => $monthlyRepeatType)); } private function populateFormWho($form) diff --git a/airtime_mvc/public/js/airtime/schedule/add-show.js b/airtime_mvc/public/js/airtime/schedule/add-show.js index 3fc150797..7f0d0e29f 100644 --- a/airtime_mvc/public/js/airtime/schedule/add-show.js +++ b/airtime_mvc/public/js/airtime/schedule/add-show.js @@ -214,7 +214,13 @@ function setAddShowEvents() { }); form.find("#add_show_repeat_type").change(function(){ - if($(this).val() == 2) { + toggleRepeatDays(); + toggleMonthlyRepeatType(); + }); + toggleMonthlyRepeatType(); + toggleRepeatDays(); + function toggleRepeatDays() { + if(form.find("#add_show_repeat_type").val() >= 2) { form.find("#add_show_day_check-label, #add_show_day_check-element").hide(); //form.find("#add_show_monthly_repeat_type-label, #add_show_monthly_repeat_type-element").show(); } @@ -222,9 +228,7 @@ function setAddShowEvents() { form.find("#add_show_day_check-label, #add_show_day_check-element").show(); //form.find("#add_show_monthly_repeat_type-label, #add_show_monthly_repeat_type-element").hide(); } - toggleMonthlyRepeatType(); - }); - toggleMonthlyRepeatType(); + } function toggleMonthlyRepeatType() { if (form.find("#add_show_repeat_type").val() == 2) { form.find("#add_show_monthly_repeat_type-label, #add_show_monthly_repeat_type-element").show(); From ef8f87df5d3d245b874abcae2f32b90fbeef0cea Mon Sep 17 00:00:00 2001 From: denise Date: Mon, 25 Mar 2013 16:28:53 -0400 Subject: [PATCH 33/73] Show linking --- airtime_mvc/application/models/Show.php | 4 +- .../application/services/ShowService.php | 38 +++++++++++++++++-- 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/airtime_mvc/application/models/Show.php b/airtime_mvc/application/models/Show.php index 8490f6295..da71f3a21 100644 --- a/airtime_mvc/application/models/Show.php +++ b/airtime_mvc/application/models/Show.php @@ -1664,7 +1664,9 @@ 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); + //Application_Model_Show::populateAllShowsInRange($showsPopUntil, $end_timestamp); + $service_show = new Application_Service_ShowService(); + $service_show->delegateInstanceCreation(null, false, $end_timestamp); Application_Model_Preference::SetShowsPopulatedUntil($end_timestamp); } diff --git a/airtime_mvc/application/services/ShowService.php b/airtime_mvc/application/services/ShowService.php index 12ae5e4ae..f44c2c64d 100644 --- a/airtime_mvc/application/services/ShowService.php +++ b/airtime_mvc/application/services/ShowService.php @@ -93,11 +93,15 @@ class Application_Service_ShowService * Receives a cc_show id and determines whether to create a * single show instance or repeating show instances */ - private function delegateInstanceCreation($isRebroadcast, $isUpdate) + public function delegateInstanceCreation($isRebroadcast=null, $isUpdate=false, $end=null) { $populateUntil = $this->getPopulateShowUntilDateTIme(); - $ccShowDays = $this->ccShow->getCcShowDays(); + if (is_null($this->ccShow)) { + $ccShowDays = $this->getShowDaysInRange($populateUntil, $end); + } else { + $ccShowDays = $this->ccShow->getCcShowDays(); + } foreach ($ccShowDays as $day) { switch ($day->getDbRepeatType()) { @@ -123,6 +127,32 @@ class Application_Service_ShowService } } + 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"); + } + + return CcShowDaysQuery::create() + ->add("last_show", null, "=") + ->addOr("first_show", $endTimeString, "<") + ->add("last_show", $startTimeString, ">") + ->find(); + /*$sql = <<< SQL +SELECT * FROM cc_show_days +WHERE last_show IS NULL + OR first_show < :endTimeString + AND last_show > :startTimeString +SQL; + + return Application_Common_Database::prepareAndExecute($sql, + array( ':endTimeString' => $endTimeString, ':startTimeString' => $startTimeString ), 'all');*/ + } + public static function formatShowDuration($duration) { $hPos = strpos($duration, 'h'); @@ -650,7 +680,7 @@ SQL; //DateTime local $start = $this->getNextRepeatingPopulateStartDateTime($showDay); - if (isset($last_how)) { + if (isset($last_show)) { $end = new DateTime($last_show, new DateTimeZone($timezone)); } else { $end = $populateUntil; @@ -1023,7 +1053,7 @@ SQL; * * @return DateTime object */ - private function getPopulateShowUntilDateTIme() + private static function getPopulateShowUntilDateTIme() { $populateUntil = Application_Model_Preference::GetShowsPopulatedUntil(); From 230d1a6aa9f51fe21bae360a232766313f9207c1 Mon Sep 17 00:00:00 2001 From: denise Date: Tue, 26 Mar 2013 10:33:06 -0400 Subject: [PATCH 34/73] Fixed bug where shows weren't populating when moving forward in the calendar --- .../application/services/ShowService.php | 30 ++++++++----------- 1 file changed, 13 insertions(+), 17 deletions(-) diff --git a/airtime_mvc/application/services/ShowService.php b/airtime_mvc/application/services/ShowService.php index f44c2c64d..fadda8e6b 100644 --- a/airtime_mvc/application/services/ShowService.php +++ b/airtime_mvc/application/services/ShowService.php @@ -103,6 +103,10 @@ class Application_Service_ShowService $ccShowDays = $this->ccShow->getCcShowDays(); } + if (!is_null($end)) { + $populateUntil = $end; + } + foreach ($ccShowDays as $day) { switch ($day->getDbRepeatType()) { case NO_REPEAT: @@ -137,20 +141,12 @@ class Application_Service_ShowService $startTimeString = $today_timestamp->format("Y-m-d H:i:s"); } - return CcShowDaysQuery::create() - ->add("last_show", null, "=") - ->addOr("first_show", $endTimeString, "<") - ->add("last_show", $startTimeString, ">") - ->find(); - /*$sql = <<< SQL -SELECT * FROM cc_show_days -WHERE last_show IS NULL - OR first_show < :endTimeString - AND last_show > :startTimeString -SQL; + $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 Application_Common_Database::prepareAndExecute($sql, - array( ':endTimeString' => $endTimeString, ':startTimeString' => $startTimeString ), 'all');*/ + return CcShowDaysPeer::doSelect($c); } public static function formatShowDuration($duration) @@ -664,7 +660,7 @@ SQL; } } $nextDate = $utcEndDateTime->add($repeatInterval); - $this->setNextRepeatingShowDate($nextDate->format("Y-m-d"), $day); + $this->setNextRepeatingShowDate($nextDate->format("Y-m-d"), $day, $show_id); } private function createMonthlyMonthlyRepeatInstances($showDay, $populateUntil, @@ -736,7 +732,7 @@ SQL; } $start = $this->getNextMonthlyMonthlyRepeatDate($start, $timezone); } - $this->setNextRepeatingShowDate($start->format("Y-m-d"), $day); + $this->setNextRepeatingShowDate($start->format("Y-m-d"), $day, $show_id); } /** @@ -1107,12 +1103,12 @@ SQL; * @param $showId * @param $day */ - private function setNextRepeatingShowDate($nextDate, $day) + private function setNextRepeatingShowDate($nextDate, $day, $showId) { $nextInfo = explode(" ", $nextDate); $repeatInfo = CcShowDaysQuery::create() - ->filterByDbShowId($this->ccShow->getDbId()) + ->filterByDbShowId($showId) ->filterByDbDay($day) ->findOne(); From 418bf0b5ff3a545d1dc539b1d11bf6e33ed85d3f Mon Sep 17 00:00:00 2001 From: denise Date: Tue, 26 Mar 2013 16:03:53 -0400 Subject: [PATCH 35/73] Created calendar service and moved the context menu creation there --- airtime_mvc/application/common/DateHelper.php | 2 +- .../controllers/ScheduleController.php | 146 ++-------------- .../models/airtime/CcShowInstances.php | 10 ++ .../application/services/CalendarService.php | 164 +++++++++++++++++- .../application/services/ShowFormService.php | 29 ++++ .../public/js/airtime/schedule/schedule.js | 6 +- 6 files changed, 218 insertions(+), 139 deletions(-) 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/ScheduleController.php b/airtime_mvc/application/controllers/ScheduleController.php index 1d55f282e..0702ede49 100644 --- a/airtime_mvc/application/controllers/ScheduleController.php +++ b/airtime_mvc/application/controllers/ScheduleController.php @@ -255,107 +255,12 @@ 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'); + $showId = $this->_getParam('showId'); - $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() @@ -462,9 +367,7 @@ 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(){ + public function populateShowInstanceFormAction(){ $formWhat = new Application_Form_AddShowWhat(); $formWho = new Application_Form_AddShowWho(); $formWhen = new Application_Form_AddShowWhen(); @@ -527,7 +430,7 @@ class ScheduleController extends Zend_Controller_Action $this->view->action = "edit-show-instance"; $this->view->newForm = $this->view->render('schedule/add-show-form.phtml'); - }*/ + } public function populateShowFormAction() { @@ -538,13 +441,13 @@ class ScheduleController extends Zend_Controller_Action $this->view->action = "edit-show"; $isAdminOrPM = $this->currentUser->isAdminOrPM(); - $isHostOfShow = $this->currentUser->isHostOfShow($showId); + /*$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 ($isHostOfShow && !$isAdminOrPM) { $this->view->action = "dj-edit-show"; - } + }*/ $forms = $this->createShowFormAction(); @@ -568,7 +471,7 @@ class ScheduleController extends Zend_Controller_Action } } - public function djEditShowAction() + /*public function djEditShowAction() { $js = $this->_getParam('data'); $data = array(); @@ -586,7 +489,7 @@ class ScheduleController extends Zend_Controller_Action $show->setCustomPassword($data["custom_password"]); $this->view->edit = true; - } + }*/ /*public function editShowInstanceAction(){ $js = $this->_getParam('data'); @@ -782,32 +685,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/models/airtime/CcShowInstances.php b/airtime_mvc/application/models/airtime/CcShowInstances.php index 4625d1f91..fb886f684 100644 --- a/airtime_mvc/application/models/airtime/CcShowInstances.php +++ b/airtime_mvc/application/models/airtime/CcShowInstances.php @@ -175,4 +175,14 @@ class CcShowInstances extends BaseCcShowInstances { return true; } + public function isRecorded() + { + return $this->getDbRecord() == 1 ? true : false; + } + + public function isRebroadcast() + { + return $this->getDbRebroadcast() == 1 ? true : false; + } + } // CcShowInstances diff --git a/airtime_mvc/application/services/CalendarService.php b/airtime_mvc/application/services/CalendarService.php index 0541ed57b..c1f0a0057 100644 --- a/airtime_mvc/application/services/CalendarService.php +++ b/airtime_mvc/application/services/CalendarService.php @@ -2,9 +2,169 @@ class Application_Service_CalendarService { - public function __construct() + private $currentUser; + private $ccShowInstance; + private $showId; + + public function __construct($instanceId = null) { - + if (!is_null($instanceId)) { + $this->ccShowInstance = CcShowInstancesQuery::create()->findPk($instanceId); + $this->showId = $this->ccShowInstance->getDbShowId(); + } + + $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->showId); + + //DateTime objects in UTC + $startDT = new DateTime($this->ccShowInstance->getDbStarts(), + new DateTimeZone("UTC")); + $endDT = new DateTime($this->ccShowInstance->getDbEnds(), + new DateTimeZone("UTC")); + + //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->ccShowInstance->getCcShow()->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-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) { + //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"); + } else { + $menu["del"] = array( + "name"=> _("Delete"), + "icon" => "delete", + "url" => $baseUrl."schedule/delete-show"); + } + } + } + return $menu; } } \ No newline at end of file diff --git a/airtime_mvc/application/services/ShowFormService.php b/airtime_mvc/application/services/ShowFormService.php index e8a085b08..4d0f099ee 100644 --- a/airtime_mvc/application/services/ShowFormService.php +++ b/airtime_mvc/application/services/ShowFormService.php @@ -149,6 +149,8 @@ class Application_Service_ShowFormService //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; @@ -360,4 +362,31 @@ SQL; 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('%r%Hh %Im'); + } + } catch (Exception $e) { + return "Invalid Date"; + } + } } \ No newline at end of file diff --git a/airtime_mvc/public/js/airtime/schedule/schedule.js b/airtime_mvc/public/js/airtime/schedule/schedule.js index a4fd1851e..ac5e2dcc1 100644 --- a/airtime_mvc/public/js/airtime/schedule/schedule.js +++ b/airtime_mvc/public/js/airtime/schedule/schedule.js @@ -379,7 +379,7 @@ $(document).ready(function() { //edit a single instance callback = function() { - $.get(edit.instance.url, {format: "json", id: data.id, type: "instance"}, function(json){ + $.get(edit.instance.url, {format: "json", showId: data.showId, instanceId: data.id, type: "instance"}, function(json){ beginEditShow(json); }); }; @@ -497,11 +497,11 @@ $(document).ready(function() { items = oItems; } - + $.ajax({ url: baseUrl+"schedule/make-context-menu", type: "GET", - data: {id : data.id, format: "json"}, + data: {instanceId : data.id, showId: data.showId, format: "json"}, dataType: "json", async: false, success: function(json){ From e259639d1a9ce7683f86a601ae69c1b100460f90 Mon Sep 17 00:00:00 2001 From: denise Date: Wed, 27 Mar 2013 09:02:49 -0400 Subject: [PATCH 36/73] Removed scheduleController private variable, currentUser Removed showService private variable, currentUser --- .../controllers/ScheduleController.php | 93 +++++-------------- .../application/services/ShowFormService.php | 7 +- .../application/services/ShowService.php | 7 +- 3 files changed, 32 insertions(+), 75 deletions(-) diff --git a/airtime_mvc/application/controllers/ScheduleController.php b/airtime_mvc/application/controllers/ScheduleController.php index 0702ede49..9555504ac 100644 --- a/airtime_mvc/application/controllers/ScheduleController.php +++ b/airtime_mvc/application/controllers/ScheduleController.php @@ -5,8 +5,6 @@ class ScheduleController extends Zend_Controller_Action protected $sched_sess = null; - private $currentUser; - public function init() { $ajaxContext = $this->_helper->getHelper('AjaxContext'); @@ -40,9 +38,6 @@ class ScheduleController extends Zend_Controller_Action ->initContext(); $this->sched_sess = new Zend_Session_Namespace("schedule"); - - $service_user = new Application_Service_UserService(); - $this->currentUser = $service_user->getCurrentUser(); } public function indexAction() @@ -117,13 +112,16 @@ 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")); $events = &Application_Model_Show::getFullCalendarEvents($start, $end, - $this->currentUser->isAdminOrPM()); + $currentUser->isAdminOrPM()); $this->view->events = $events; } @@ -367,81 +365,32 @@ class ScheduleController extends Zend_Controller_Action unset($this->view->showContent); } - 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 populateShowInstanceFormAction() + { + $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->newForm = $this->view->render('schedule/add-show-form.phtml'); } public function populateShowFormAction() { + $service_user = new Application_Service_UserService(); + $currentUser = $service_user->getCurrentUser(); + $showId = $this->_getParam('showId'); $instanceId = $this->_getParam('instanceId'); $service_showForm = new Application_Service_ShowFormService($showId, $instanceId); - $this->view->action = "edit-show"; - - $isAdminOrPM = $this->currentUser->isAdminOrPM(); - /*$isHostOfShow = $this->currentUser->isHostOfShow($showId); + $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) @@ -451,7 +400,7 @@ class ScheduleController extends Zend_Controller_Action $forms = $this->createShowFormAction(); - $service_showForm->delegateFormPopulation($forms); + $service_showForm->delegateShowFormPopulation($forms); if (!$isAdminOrPM) { foreach ($forms as $form) { @@ -459,13 +408,17 @@ class ScheduleController extends Zend_Controller_Action } } + $this->view->action = "edit-show"; $this->view->newForm = $this->view->render('schedule/add-show-form.phtml'); $this->view->entries = 5; } public function getFormAction() { - if ($this->currentUser->isAdminOrPM()) { + $service_user = new Application_Service_UserService(); + $currentUser = $service_user->getCurrentUser(); + + if ($currentUser->isAdminOrPM()) { $this->createShowFormAction(true); $this->view->form = $this->view->render('schedule/add-show-form.phtml'); } diff --git a/airtime_mvc/application/services/ShowFormService.php b/airtime_mvc/application/services/ShowFormService.php index 4d0f099ee..bdf41d78c 100644 --- a/airtime_mvc/application/services/ShowFormService.php +++ b/airtime_mvc/application/services/ShowFormService.php @@ -73,6 +73,11 @@ class Application_Service_ShowFormService $formRepeats->populate(array('add_show_end_date' => date("Y-m-d"))); } + public function delegateShowInstanceFormPopulation($forms) + { + $this->populateFormWhat($forms["what"]); + } + /** * * Delegates populating each show form with the appropriate @@ -80,7 +85,7 @@ class Application_Service_ShowFormService * * @param $forms */ - public function delegateFormPopulation($forms) + public function delegateShowFormPopulation($forms) { $this->populateFormWhat($forms["what"]); $this->populateFormWhen($forms["when"]); diff --git a/airtime_mvc/application/services/ShowService.php b/airtime_mvc/application/services/ShowService.php index fadda8e6b..e589786b2 100644 --- a/airtime_mvc/application/services/ShowService.php +++ b/airtime_mvc/application/services/ShowService.php @@ -9,20 +9,19 @@ define("REPEAT_MONTHLY_WEEKLY", 3); class Application_Service_ShowService { private $ccShow; - private $currentUser; public function __construct($showId=null) { if (!is_null($showId)) { $this->ccShow = CcShowQuery::create()->findPk($showId); } - - $service_user = new Application_Service_UserService(); - $this->currentUser = $service_user->getCurrentUser(); } public function addUpdateShow($showData, $isUpdate=false) { + $service_user = new Application_Service_UserService(); + $currentUser = $service_user->getCurrentUser(); + if ($showData["add_show_repeats"]) { $repeatType = $showData["add_show_repeat_type"]; if ($showData["add_show_repeat_type"] == 2) { From 731b86b36c7859aabb43c04dbeb0dd1b7b91128d Mon Sep 17 00:00:00 2001 From: denise Date: Wed, 27 Mar 2013 16:25:39 -0400 Subject: [PATCH 37/73] Added back editing a repeating show instance feature --- .../controllers/ScheduleController.php | 40 ++++++++--- .../application/services/CalendarService.php | 9 +-- .../application/services/SchedulerService.php | 10 ++- .../application/services/ShowFormService.php | 54 ++++++++++++++- .../application/services/ShowService.php | 68 +++++++++++++++++-- 5 files changed, 158 insertions(+), 23 deletions(-) diff --git a/airtime_mvc/application/controllers/ScheduleController.php b/airtime_mvc/application/controllers/ScheduleController.php index 9555504ac..473e54e13 100644 --- a/airtime_mvc/application/controllers/ScheduleController.php +++ b/airtime_mvc/application/controllers/ScheduleController.php @@ -22,7 +22,7 @@ class ScheduleController extends Zend_Controller_Action ->addActionContext('get-current-playlist', 'json') ->addActionContext('remove-group', 'json') ->addActionContext('populate-show-form', 'json') - ->addActionContext('populate-show-instance-form', 'json') + ->addActionContext('populate-repeating-show-instance-form', 'json') ->addActionContext('cancel-show', 'json') ->addActionContext('cancel-current-show', 'json') ->addActionContext('get-form', 'json') @@ -30,7 +30,7 @@ class ScheduleController extends Zend_Controller_Action ->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') @@ -365,7 +365,7 @@ class ScheduleController extends Zend_Controller_Action unset($this->view->showContent); } - public function populateShowInstanceFormAction() + public function populateRepeatingShowInstanceFormAction() { $showId = $this->_getParam('showId'); $instanceId = $this->_getParam('instanceId'); @@ -376,7 +376,7 @@ class ScheduleController extends Zend_Controller_Action $service_showForm->delegateShowInstanceFormPopulation($forms); $this->view->addNewShow = false; - $this->view->action = "edit-show-instance"; + $this->view->action = "edit-repeating-show-instance"; $this->view->newForm = $this->view->render('schedule/add-show-form.phtml'); } @@ -444,7 +444,7 @@ class ScheduleController extends Zend_Controller_Action $this->view->edit = true; }*/ - /*public function editShowInstanceAction(){ + public function editRepeatingShowInstanceAction(){ $js = $this->_getParam('data'); $data = array(); @@ -453,15 +453,39 @@ class ScheduleController extends Zend_Controller_Action $data[$j["name"]] = $j["value"]; } - $success = Application_Model_Schedule::updateShowInstance($data, $this); - if ($success) { + $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(); + + $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"])) { + + //treat repeating instance has a new and separate show + $service_show->deleteRepeatingInstance($data["add_show_instance_id"]); + $service_show->addUpdateShow($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() { diff --git a/airtime_mvc/application/services/CalendarService.php b/airtime_mvc/application/services/CalendarService.php index c1f0a0057..0d60e8a1f 100644 --- a/airtime_mvc/application/services/CalendarService.php +++ b/airtime_mvc/application/services/CalendarService.php @@ -30,10 +30,8 @@ class Application_Service_CalendarService $isHostOfShow = $this->currentUser->isHostOfShow($this->showId); //DateTime objects in UTC - $startDT = new DateTime($this->ccShowInstance->getDbStarts(), - new DateTimeZone("UTC")); - $endDT = new DateTime($this->ccShowInstance->getDbEnds(), - new DateTimeZone("UTC")); + $startDT = $this->ccShowInstance->getDbStarts(null); + $endDT = $this->ccShowInstance->getDbEnds(null); //timestamps $start = $startDT->getTimestamp(); @@ -126,7 +124,7 @@ class Application_Service_CalendarService $menu["edit"]["items"]["instance"] = array( "name" => _("Edit This Instance"), "icon" => "edit", - "url" => $baseUrl."Schedule/populate-show-instance-form"); + "url" => $baseUrl."Schedule/populate-repeating-show-instance-form"); } else { $menu["edit"] = array( "name"=> _("Edit Show"), @@ -141,7 +139,6 @@ class Application_Service_CalendarService //show is repeating so give user the option to delete all //repeating instances or just the one if ($isRepeating) { - //create delete sub menu. $menu["del"] = array( "name"=> _("Delete"), "icon" => "delete", diff --git a/airtime_mvc/application/services/SchedulerService.php b/airtime_mvc/application/services/SchedulerService.php index 4a4f9172b..097e1f3ae 100644 --- a/airtime_mvc/application/services/SchedulerService.php +++ b/airtime_mvc/application/services/SchedulerService.php @@ -8,9 +8,10 @@ class Application_Service_SchedulerService */ public static function updateScheduleStartTime($instanceIds, $diff) { + $con = Propel::getConnection(); if (count($instanceIds) > 0 && $diff != 0) { $showIdList = implode(",", $instanceIds); - $sql = << $diff, ':diff2' => $diff, ':showIds' => $showIdList), - 'execute'); + 'execute');*/ + $sql = "UPDATE cc_schedule " + ."SET starts = starts + INTERVAL '$diff sec', " + ."ends = ends + INTERVAL '$diff sec' " + ."WHERE instance_id IN ($showIdList)"; + $con->exec($sql); } } diff --git a/airtime_mvc/application/services/ShowFormService.php b/airtime_mvc/application/services/ShowFormService.php index bdf41d78c..eaaf4da1d 100644 --- a/airtime_mvc/application/services/ShowFormService.php +++ b/airtime_mvc/application/services/ShowFormService.php @@ -76,6 +76,17 @@ class Application_Service_ShowFormService 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(); } /** @@ -92,6 +103,7 @@ class Application_Service_ShowFormService $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"]); @@ -137,6 +149,36 @@ class Application_Service_ShowFormService '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(); @@ -194,6 +236,16 @@ class Application_Service_ShowFormService '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( @@ -388,7 +440,7 @@ SQL; $sign = $duration->format('%r'); return sprintf('%s%02dh %02dm', $sign, $hour, $min); } else { - return $duration->format('%r%Hh %Im'); + return $duration->format('%Hh %Im'); } } catch (Exception $e) { return "Invalid Date"; diff --git a/airtime_mvc/application/services/ShowService.php b/airtime_mvc/application/services/ShowService.php index e589786b2..671b3971a 100644 --- a/airtime_mvc/application/services/ShowService.php +++ b/airtime_mvc/application/services/ShowService.php @@ -17,6 +17,19 @@ class Application_Service_ShowService } } + /** + * + * When the user is editing a single instance of a repeating show + * we want to treat it as a completely new show so we need to delete + * the instance first + * + * @param $instanceId + */ + public function deleteRepeatingInstance($instanceId) + { + CcShowInstancesQuery::create()->findPk($instanceId)->delete(); + } + public function addUpdateShow($showData, $isUpdate=false) { $service_user = new Application_Service_UserService(); @@ -30,7 +43,6 @@ class Application_Service_ShowService } else { $repeatType = -1; } - //$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; @@ -40,7 +52,7 @@ class Application_Service_ShowService $con = Propel::getConnection(); $con->beginTransaction(); try { - if (!$this->currentUser->isAdminOrPM()) { + if (!$currentUser->isAdminOrPM()) { throw new Exception("Permission denied"); } //update ccShow @@ -52,7 +64,7 @@ class Application_Service_ShowService // schedule start/end times $this->applyShowStartEndDifference($showData); $this->deleteRebroadcastInstances(); - $this->deleteCcShowDays(); + //$this->deleteCcShowDays(); $this->deleteCcShowHosts(); if ($isRebroadcast) { //delete entry in cc_show_rebroadcast @@ -105,7 +117,7 @@ class Application_Service_ShowService if (!is_null($end)) { $populateUntil = $end; } - +Logging::info($ccShowDays); foreach ($ccShowDays as $day) { switch ($day->getDbRepeatType()) { case NO_REPEAT: @@ -379,6 +391,14 @@ SQL; } } + 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 = << gmdate("Y-m-d H:i:s"), ":showId" => $showId), "execute"); + } private function deleteAllInstances($showId) @@ -857,6 +878,27 @@ SQL; } } + 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 @@ -923,7 +965,11 @@ SQL; // 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(); + if ($this->hasCcShowDay($repeatType, null)) { + $showDay = $this->getCcShowDay($repeatType, null); + } else { + $showDay = new CcShowDays(); + } $showDay->setDbFirstShow($startDateTime->format("Y-m-d")); $showDay->setDbLastShow($endDate); $showDay->setDbStartTime($startDateTime->format("H:i:s")); @@ -932,6 +978,9 @@ SQL; $showDay->setDbRepeatType($repeatType); $showDay->setDbShowId($showId); $showDay->setDbRecord($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) { @@ -946,7 +995,11 @@ SQL; $startDateTimeClone->add(new DateInterval("P".$daysAdd."D")); } if (is_null($endDate) || $startDateTimeClone->getTimestamp() <= $endDateTime->getTimestamp()) { - $showDay = new CcShowDays(); + if ($this->hasCcShowDay($repeatType, $day)) { + $showDay = $this->getCcShowDay($repeatType, $day); + } else { + $showDay = new CcShowDays(); + } $showDay->setDbFirstShow($startDateTimeClone->format("Y-m-d")); $showDay->setDbLastShow($endDate); $showDay->setDbStartTime($startDateTimeClone->format("H:i")); @@ -956,6 +1009,9 @@ SQL; $showDay->setDbRepeatType($repeatType); $showDay->setDbShowId($showId); $showDay->setDbRecord($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(); } } From d0691b114cb128ddcf38036e671caea547ed5352 Mon Sep 17 00:00:00 2001 From: denise Date: Thu, 28 Mar 2013 14:25:40 -0400 Subject: [PATCH 38/73] Show linking --- .../application/services/ShowService.php | 27 ++++++++++++++----- 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/airtime_mvc/application/services/ShowService.php b/airtime_mvc/application/services/ShowService.php index 671b3971a..8ba8fd0f9 100644 --- a/airtime_mvc/application/services/ShowService.php +++ b/airtime_mvc/application/services/ShowService.php @@ -73,7 +73,7 @@ class Application_Service_ShowService } //update ccShowDays - $this->setCcShowDays($showData, $repeatType, $isRecorded); + $this->setCcShowDays($showData, $repeatType, $isRecorded, $isRebroadcast, $isUpdate); //update ccShowRebroadcasts $this->setCcShowRebroadcasts($showData, $repeatType, $isRecorded); @@ -104,12 +104,14 @@ class Application_Service_ShowService * Receives a cc_show id and determines whether to create a * single show instance or repeating show instances */ - public function delegateInstanceCreation($isRebroadcast=null, $isUpdate=false, $end=null) + public function delegateInstanceCreation($isRebroadcast=null, $isUpdate=false, $end=null, $ccShowDay=null) { $populateUntil = $this->getPopulateShowUntilDateTIme(); if (is_null($this->ccShow)) { $ccShowDays = $this->getShowDaysInRange($populateUntil, $end); + } elseif ($isUpdate && !is_null($ccShowDay)) { + $ccShowDays = array(0 => $ccShowDay); } else { $ccShowDays = $this->ccShow->getCcShowDays(); } @@ -117,7 +119,7 @@ class Application_Service_ShowService if (!is_null($end)) { $populateUntil = $end; } -Logging::info($ccShowDays); + foreach ($ccShowDays as $day) { switch ($day->getDbRepeatType()) { case NO_REPEAT: @@ -679,8 +681,10 @@ SQL; } } } - $nextDate = $utcEndDateTime->add($repeatInterval); - $this->setNextRepeatingShowDate($nextDate->format("Y-m-d"), $day, $show_id); + if (!$isUpdate) { + $nextDate = $utcEndDateTime->add($repeatInterval); + $this->setNextRepeatingShowDate($nextDate->format("Y-m-d"), $day, $show_id); + } } private function createMonthlyMonthlyRepeatInstances($showDay, $populateUntil, @@ -822,6 +826,7 @@ SQL; private function getNextRepeatingPopulateStartDateTime($showDay) { $nextPopDate = $showDay->getDbNextPopDate(); + Logging::info($nextPopDate); $startTime = $showDay->getDbStartTime(); if (isset($nextPopDate)) { @@ -938,7 +943,7 @@ SQL; * @param $isRecorded * @param $showDay ccShowDay object we are setting values on */ - private function setCcShowDays($showData, $repeatType, $isRecorded) + private function setCcShowDays($showData, $repeatType, $isRecorded, $isRebroadcast, $isUpdate) { $showId = $this->ccShow->getDbId(); @@ -967,8 +972,10 @@ SQL; if ($showData['add_show_repeats'] && $showData['add_show_repeat_type'] == 2) { if ($this->hasCcShowDay($repeatType, null)) { $showDay = $this->getCcShowDay($repeatType, null); + $newShowDay = false; } else { $showDay = new CcShowDays(); + $newShowDay = true; } $showDay->setDbFirstShow($startDateTime->format("Y-m-d")); $showDay->setDbLastShow($endDate); @@ -982,6 +989,9 @@ SQL; //so when editing, the date period iterator will start from the beginning $showDay->setDbNextPopDate($startDateTime->format("Y-m-d")); $showDay->save(); + if ($newShowDay && $isUpdate) { + $this->delegateInstanceCreation($isRebroadcast, $isUpdate, $endDateTime, $showDay); + } } else { foreach ($showData['add_show_day_check'] as $day) { $daysAdd=0; @@ -997,8 +1007,10 @@ SQL; if (is_null($endDate) || $startDateTimeClone->getTimestamp() <= $endDateTime->getTimestamp()) { if ($this->hasCcShowDay($repeatType, $day)) { $showDay = $this->getCcShowDay($repeatType, $day); + $newShowDay = false; } else { $showDay = new CcShowDays(); + $newShowDay = true; } $showDay->setDbFirstShow($startDateTimeClone->format("Y-m-d")); $showDay->setDbLastShow($endDate); @@ -1013,6 +1025,9 @@ SQL; //so when editing, the date period iterator will start from the beginning $showDay->setDbNextPopDate($startDateTimeClone->format("Y-m-d")); $showDay->save(); + if ($newShowDay && $isUpdate) { + $this->delegateInstanceCreation($isRebroadcast, $isUpdate, $endDateTime, $showDay); + } } } } From 1eba09fc4cd63664bdc6c47f4afda489fa4859d3 Mon Sep 17 00:00:00 2001 From: denise Date: Thu, 28 Mar 2013 16:19:05 -0400 Subject: [PATCH 39/73] Show linking --- .../application/services/ShowService.php | 38 ++++--------------- 1 file changed, 8 insertions(+), 30 deletions(-) diff --git a/airtime_mvc/application/services/ShowService.php b/airtime_mvc/application/services/ShowService.php index 8ba8fd0f9..3665febe0 100644 --- a/airtime_mvc/application/services/ShowService.php +++ b/airtime_mvc/application/services/ShowService.php @@ -64,7 +64,7 @@ class Application_Service_ShowService // schedule start/end times $this->applyShowStartEndDifference($showData); $this->deleteRebroadcastInstances(); - //$this->deleteCcShowDays(); + $this->deleteCcShowDays(); $this->deleteCcShowHosts(); if ($isRebroadcast) { //delete entry in cc_show_rebroadcast @@ -73,7 +73,7 @@ class Application_Service_ShowService } //update ccShowDays - $this->setCcShowDays($showData, $repeatType, $isRecorded, $isRebroadcast, $isUpdate); + $this->setCcShowDays($showData, $repeatType, $isRecorded); //update ccShowRebroadcasts $this->setCcShowRebroadcasts($showData, $repeatType, $isRecorded); @@ -104,14 +104,12 @@ class Application_Service_ShowService * Receives a cc_show id and determines whether to create a * single show instance or repeating show instances */ - public function delegateInstanceCreation($isRebroadcast=null, $isUpdate=false, $end=null, $ccShowDay=null) + public function delegateInstanceCreation($isRebroadcast=null, $isUpdate=false, $end=null) { $populateUntil = $this->getPopulateShowUntilDateTIme(); if (is_null($this->ccShow)) { $ccShowDays = $this->getShowDaysInRange($populateUntil, $end); - } elseif ($isUpdate && !is_null($ccShowDay)) { - $ccShowDays = array(0 => $ccShowDay); } else { $ccShowDays = $this->ccShow->getCcShowDays(); } @@ -681,10 +679,8 @@ SQL; } } } - if (!$isUpdate) { - $nextDate = $utcEndDateTime->add($repeatInterval); - $this->setNextRepeatingShowDate($nextDate->format("Y-m-d"), $day, $show_id); - } + $nextDate = $utcEndDateTime->add($repeatInterval); + $this->setNextRepeatingShowDate($nextDate->format("Y-m-d"), $day, $show_id); } private function createMonthlyMonthlyRepeatInstances($showDay, $populateUntil, @@ -943,7 +939,7 @@ SQL; * @param $isRecorded * @param $showDay ccShowDay object we are setting values on */ - private function setCcShowDays($showData, $repeatType, $isRecorded, $isRebroadcast, $isUpdate) + private function setCcShowDays($showData, $repeatType, $isRecorded) { $showId = $this->ccShow->getDbId(); @@ -970,13 +966,7 @@ SQL; // Don't set day for monthly repeat type, it's invalid if ($showData['add_show_repeats'] && $showData['add_show_repeat_type'] == 2) { - if ($this->hasCcShowDay($repeatType, null)) { - $showDay = $this->getCcShowDay($repeatType, null); - $newShowDay = false; - } else { - $showDay = new CcShowDays(); - $newShowDay = true; - } + $showDay = new CcShowDays(); $showDay->setDbFirstShow($startDateTime->format("Y-m-d")); $showDay->setDbLastShow($endDate); $showDay->setDbStartTime($startDateTime->format("H:i:s")); @@ -989,9 +979,6 @@ SQL; //so when editing, the date period iterator will start from the beginning $showDay->setDbNextPopDate($startDateTime->format("Y-m-d")); $showDay->save(); - if ($newShowDay && $isUpdate) { - $this->delegateInstanceCreation($isRebroadcast, $isUpdate, $endDateTime, $showDay); - } } else { foreach ($showData['add_show_day_check'] as $day) { $daysAdd=0; @@ -1005,13 +992,7 @@ SQL; $startDateTimeClone->add(new DateInterval("P".$daysAdd."D")); } if (is_null($endDate) || $startDateTimeClone->getTimestamp() <= $endDateTime->getTimestamp()) { - if ($this->hasCcShowDay($repeatType, $day)) { - $showDay = $this->getCcShowDay($repeatType, $day); - $newShowDay = false; - } else { - $showDay = new CcShowDays(); - $newShowDay = true; - } + $showDay = new CcShowDays(); $showDay->setDbFirstShow($startDateTimeClone->format("Y-m-d")); $showDay->setDbLastShow($endDate); $showDay->setDbStartTime($startDateTimeClone->format("H:i")); @@ -1025,9 +1006,6 @@ SQL; //so when editing, the date period iterator will start from the beginning $showDay->setDbNextPopDate($startDateTimeClone->format("Y-m-d")); $showDay->save(); - if ($newShowDay && $isUpdate) { - $this->delegateInstanceCreation($isRebroadcast, $isUpdate, $endDateTime, $showDay); - } } } } From ab10ae68a279a1a749fc5f5db4c3138693a31eec Mon Sep 17 00:00:00 2001 From: denise Date: Mon, 1 Apr 2013 14:42:35 -0400 Subject: [PATCH 40/73] CC-5036: Add back edit show instance functionality --- .../controllers/ScheduleController.php | 4 +- airtime_mvc/application/models/Show.php | 2 +- .../application/services/ShowService.php | 128 ++++++++++++++---- 3 files changed, 105 insertions(+), 29 deletions(-) diff --git a/airtime_mvc/application/controllers/ScheduleController.php b/airtime_mvc/application/controllers/ScheduleController.php index 473e54e13..3a30319e7 100644 --- a/airtime_mvc/application/controllers/ScheduleController.php +++ b/airtime_mvc/application/controllers/ScheduleController.php @@ -467,9 +467,7 @@ class ScheduleController extends Zend_Controller_Action if ($service_showForm->validateShowForms($forms, $data, $validateStartDate, $originalShowStartDateTime, true, $data["add_show_instance_id"])) { - //treat repeating instance has a new and separate show - $service_show->deleteRepeatingInstance($data["add_show_instance_id"]); - $service_show->addUpdateShow($data); + $service_show->createShowFromRepeatingInstance($data); $this->view->addNewShow = true; $this->view->newForm = $this->view->render('schedule/add-show-form.phtml'); diff --git a/airtime_mvc/application/models/Show.php b/airtime_mvc/application/models/Show.php index da71f3a21..5cd0d727d 100644 --- a/airtime_mvc/application/models/Show.php +++ b/airtime_mvc/application/models/Show.php @@ -1666,7 +1666,7 @@ SQL; if (is_null($showsPopUntil) || $showsPopUntil->getTimestamp() < $end_timestamp->getTimestamp()) { //Application_Model_Show::populateAllShowsInRange($showsPopUntil, $end_timestamp); $service_show = new Application_Service_ShowService(); - $service_show->delegateInstanceCreation(null, false, $end_timestamp); + $service_show->delegateInstanceCreation(null, false, null, $end_timestamp); Application_Model_Preference::SetShowsPopulatedUntil($end_timestamp); } diff --git a/airtime_mvc/application/services/ShowService.php b/airtime_mvc/application/services/ShowService.php index 3665febe0..614e28d37 100644 --- a/airtime_mvc/application/services/ShowService.php +++ b/airtime_mvc/application/services/ShowService.php @@ -17,17 +17,71 @@ class Application_Service_ShowService } } - /** - * - * When the user is editing a single instance of a repeating show - * we want to treat it as a completely new show so we need to delete - * the instance first - * - * @param $instanceId - */ - public function deleteRepeatingInstance($instanceId) - { - CcShowInstancesQuery::create()->findPk($instanceId)->delete(); + 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"]); + $currentShowDay = $oldCcShow->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()); + + 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(); + } + + //delete the edited instance from the repeating sequence + CcShowInstancesQuery::create()->findPk($showData["add_show_instance_id"])->delete(); + + $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, $isUpdate=false) @@ -58,8 +112,9 @@ class Application_Service_ShowService //update ccShow $this->setCcShow($showData, $isUpdate); + $daysAdded = array(); if ($isUpdate) { - $this->delegateInstanceCleanup($showData, $isRecorded, $repeatType); + $daysAdded = $this->delegateInstanceCleanup($showData, $isRecorded, $repeatType); // updates cc_show_instances start/end times, and updates // schedule start/end times $this->applyShowStartEndDifference($showData); @@ -82,7 +137,7 @@ class Application_Service_ShowService $this->setCcShowHosts($showData); //create new ccShowInstances - $this->delegateInstanceCreation($isRebroadcast, $isUpdate); + $this->delegateInstanceCreation($isRebroadcast, $isUpdate, $daysAdded); if ($isUpdate) { $service_scheduler = new Application_Service_SchedulerService(); @@ -104,7 +159,7 @@ class Application_Service_ShowService * Receives a cc_show id and determines whether to create a * single show instance or repeating show instances */ - public function delegateInstanceCreation($isRebroadcast=null, $isUpdate=false, $end=null) + public function delegateInstanceCreation($isRebroadcast=null, $isUpdate=false, $daysAdded=null, $end=null) { $populateUntil = $this->getPopulateShowUntilDateTIme(); @@ -125,11 +180,11 @@ class Application_Service_ShowService break; case REPEAT_WEEKLY: $this->createRepeatingInstances($day, $populateUntil, REPEAT_WEEKLY, - new DateInterval("P7D"), $isRebroadcast, $isUpdate); + new DateInterval("P7D"), $isRebroadcast, $isUpdate, $daysAdded); break; case REPEAT_BI_WEEKLY: $this->createRepeatingInstances($day, $populateUntil, REPEAT_BI_WEEKLY, - new DateInterval("P14D"), $isRebroadcast, $isUpdate); + new DateInterval("P14D"), $isRebroadcast, $isUpdate, $daysAdded); break; case REPEAT_MONTHLY_MONTHLY: $this->createMonthlyMonthlyRepeatInstances($day, $populateUntil, $isRebroadcast, $isUpdate); @@ -219,6 +274,8 @@ SQL; { $showId = $this->ccShow->getDbId(); + $daysAdded = array(); + //CcShowDay object $currentShowDay = $this->ccShow->getFirstCcShowDay(); @@ -233,6 +290,12 @@ SQL; //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']) { @@ -280,6 +343,10 @@ SQL; 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 @@ -324,6 +391,8 @@ SQL; } } }//if repeats + + return $daysAdded; } public function getRepeatingEndDate() @@ -608,7 +677,7 @@ SQL; * @param unknown_type $isRebroadcast */ private function createRepeatingInstances($showDay, $populateUntil, - $repeatType, $repeatInterval, $isRebroadcast, $isUpdate) + $repeatType, $repeatInterval, $isRebroadcast, $isUpdate, $daysAdded=null) { $show_id = $showDay->getDbShowId(); $first_show = $showDay->getDbFirstShow(); //non-UTC @@ -648,11 +717,21 @@ SQL; * 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 { + if ($isUpdate) { + if ($this->hasInstance($utcStartDateTime)) { + $ccShowInstance = $this->getInstance($utcStartDateTime); + $newInstance = false; + $updateScheduleStatus = true; + } elseif (in_array($day, $daysAdded)) { + $newInstance = true; + $ccShowInstance = new CcShowInstances(); + $updateScheduleStatus = false; + } else { + //if we get here, an instance was edited on it's own and + //thus became it's own show so there is nothing to update + break 1; + } + } else { $newInstance = true; $ccShowInstance = new CcShowInstances(); $updateScheduleStatus = false; @@ -822,7 +901,6 @@ SQL; private function getNextRepeatingPopulateStartDateTime($showDay) { $nextPopDate = $showDay->getDbNextPopDate(); - Logging::info($nextPopDate); $startTime = $showDay->getDbStartTime(); if (isset($nextPopDate)) { @@ -906,7 +984,7 @@ SQL; * @param $ccShow * @param $showData */ - private function setCcShow($showData, $isUpdate) + private function setCcShow($showData, $isUpdate=false) { if (!$isUpdate) { $ccShow = new CcShow(); @@ -939,7 +1017,7 @@ SQL; * @param $isRecorded * @param $showDay ccShowDay object we are setting values on */ - private function setCcShowDays($showData, $repeatType, $isRecorded) + private function setCcShowDays($showData, $repeatType=-1, $isRecorded=0) { $showId = $this->ccShow->getDbId(); From 81dbb17922e75526bb367f19bbb64f907d4648e4 Mon Sep 17 00:00:00 2001 From: denise Date: Wed, 3 Apr 2013 11:46:46 -0400 Subject: [PATCH 41/73] CC-4961: Show linking -moved show deletion into show service --- .../controllers/ScheduleController.php | 52 +++----- .../application/services/CalendarService.php | 42 +++++- .../application/services/ShowFormService.php | 1 + .../application/services/ShowService.php | 123 +++++++++++++++++- 4 files changed, 179 insertions(+), 39 deletions(-) diff --git a/airtime_mvc/application/controllers/ScheduleController.php b/airtime_mvc/application/controllers/ScheduleController.php index 3a30319e7..02ed93dfa 100644 --- a/airtime_mvc/application/controllers/ScheduleController.php +++ b/airtime_mvc/application/controllers/ScheduleController.php @@ -16,14 +16,14 @@ 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-repeating-show-instance-form', 'json') - ->addActionContext('cancel-show', 'json') + ->addActionContext('delete-show', 'json') ->addActionContext('cancel-current-show', 'json') ->addActionContext('get-form', 'json') ->addActionContext('upload-to-sound-cloud', 'json') @@ -209,28 +209,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() @@ -254,7 +243,6 @@ class ScheduleController extends Zend_Controller_Action public function makeContextMenuAction() { $instanceId = $this->_getParam('instanceId'); - $showId = $this->_getParam('showId'); $service_calendar = new Application_Service_CalendarService($instanceId); @@ -598,25 +586,17 @@ class ScheduleController extends Zend_Controller_Action return $forms; } - public function cancelShowAction() + public function deleteShowAction() { - $user = Application_Model_User::getCurrentUser(); + $instanceId = $this->_getParam('id'); - if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) { - $showInstanceId = $this->_getParam('id'); + $service_show = new Application_Service_ShowService(); + $showId = $service_show->deleteShow($instanceId); - 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(); + if (!$showId) { + $this->view->show_error = true; } + $this->view->show_id = $showId; } public function cancelCurrentShowAction() diff --git a/airtime_mvc/application/services/CalendarService.php b/airtime_mvc/application/services/CalendarService.php index 0d60e8a1f..876b3566a 100644 --- a/airtime_mvc/application/services/CalendarService.php +++ b/airtime_mvc/application/services/CalendarService.php @@ -147,12 +147,12 @@ class Application_Service_CalendarService $menu["del"]["items"]["single"] = array( "name"=> _("Delete This Instance"), "icon" => "delete", - "url" => $baseUrl."schedule/delete-show"); + "url" => $baseUrl."schedule/delete-show-instance"); $menu["del"]["items"]["following"] = array( "name"=> _("Delete This Instance and All Following"), "icon" => "delete", - "url" => $baseUrl."schedule/cancel-show"); + "url" => $baseUrl."schedule/delete-show"); } else { $menu["del"] = array( "name"=> _("Delete"), @@ -164,4 +164,42 @@ class Application_Service_CalendarService return $menu; } + /* + * @param $dateTime + * php Datetime object to add deltas to + * + * @param $deltaDay + * php int, delta days show moved + * + * @param $deltaMin + * php int, delta mins show moved + * + * @return $newDateTime + * php DateTime, $dateTime with the added time deltas. + */ + 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; + } + } \ No newline at end of file diff --git a/airtime_mvc/application/services/ShowFormService.php b/airtime_mvc/application/services/ShowFormService.php index eaaf4da1d..8240c9488 100644 --- a/airtime_mvc/application/services/ShowFormService.php +++ b/airtime_mvc/application/services/ShowFormService.php @@ -342,6 +342,7 @@ class Application_Service_ShowFormService SELECT starts, ends FROM cc_show_instances WHERE ends > now() at time zone 'UTC' AND show_id = :showId +AND modified_instance = FALSE ORDER BY starts LIMIT 1 SQL; diff --git a/airtime_mvc/application/services/ShowService.php b/airtime_mvc/application/services/ShowService.php index 614e28d37..0d99854c2 100644 --- a/airtime_mvc/application/services/ShowService.php +++ b/airtime_mvc/application/services/ShowService.php @@ -73,7 +73,10 @@ class Application_Service_ShowService } //delete the edited instance from the repeating sequence - CcShowInstancesQuery::create()->findPk($showData["add_show_instance_id"])->delete(); + CcShowInstancesQuery::create() + ->findPk($showData["add_show_instance_id"]) + ->setDbModifiedInstance(true) + ->save(); $con->commit(); Application_Model_RabbitMq::PushSchedule(); @@ -484,6 +487,124 @@ SQL; } + 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 = << Date: Wed, 3 Apr 2013 16:21:30 -0400 Subject: [PATCH 42/73] Add comment to schema.xml to indicate what the broadcasted column is of cc_schedule --- airtime_mvc/build/schema.xml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/airtime_mvc/build/schema.xml b/airtime_mvc/build/schema.xml index b9a8a6951..c8c31b8f2 100644 --- a/airtime_mvc/build/schema.xml +++ b/airtime_mvc/build/schema.xml @@ -322,6 +322,10 @@ + + @@ -472,4 +478,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/airtime_mvc/build/sql/schema.sql b/airtime_mvc/build/sql/schema.sql index cf73470b9..9d9040164 100644 --- a/airtime_mvc/build/sql/schema.sql +++ b/airtime_mvc/build/sql/schema.sql @@ -156,6 +156,7 @@ CREATE TABLE "cc_show" "live_stream_using_custom_auth" BOOLEAN default 'f', "live_stream_user" VARCHAR(255), "live_stream_pass" VARCHAR(255), + "linked" BOOLEAN default 'f' NOT NULL, PRIMARY KEY ("id") ); @@ -426,6 +427,7 @@ CREATE TABLE "cc_schedule" "instance_id" INTEGER NOT NULL, "playout_status" INT2 default 1 NOT NULL, "broadcasted" INT2 default 0 NOT NULL, + "stamp_id" INTEGER default 0 NOT NULL, PRIMARY KEY ("id") ); @@ -747,6 +749,35 @@ CREATE TABLE "cc_locale" COMMENT ON TABLE "cc_locale" IS ''; +SET search_path TO public; +----------------------------------------------------------------------------- +-- cc_show_stamp +----------------------------------------------------------------------------- + +DROP TABLE "cc_show_stamp" CASCADE; + + +CREATE TABLE "cc_show_stamp" +( + "id" serial NOT NULL, + "show_id" INTEGER NOT NULL, + "instance_id" INTEGER, + "file_id" INTEGER, + "stream_id" INTEGER, + "block_id" INTEGER, + "playlist_id" INTEGER, + "position" INTEGER NOT NULL, + "clip_length" interval default '00:00:00', + "cue_in" interval default '00:00:00', + "cue_out" interval default '00:00:00', + "fade_in" interval default '00:00:00', + "fade_out" interval default '00:00:00', + PRIMARY KEY ("id") +); + +COMMENT ON TABLE "cc_show_stamp" IS ''; + + SET search_path TO public; ALTER TABLE "cc_files" ADD CONSTRAINT "cc_files_owner_fkey" FOREIGN KEY ("owner_id") REFERENCES "cc_subjs" ("id"); @@ -803,3 +834,15 @@ ALTER TABLE "cc_webstream_metadata" ADD CONSTRAINT "cc_schedule_inst_fkey" FOREI ALTER TABLE "cc_listener_count" ADD CONSTRAINT "cc_timestamp_inst_fkey" FOREIGN KEY ("timestamp_id") REFERENCES "cc_timestamp" ("id") ON DELETE CASCADE; ALTER TABLE "cc_listener_count" ADD CONSTRAINT "cc_mount_name_inst_fkey" FOREIGN KEY ("mount_name_id") REFERENCES "cc_mount_name" ("id") ON DELETE CASCADE; + +ALTER TABLE "cc_show_stamp" ADD CONSTRAINT "cc_show_stamp_show_id_fkey" FOREIGN KEY ("show_id") REFERENCES "cc_show" ("id") ON DELETE CASCADE; + +ALTER TABLE "cc_show_stamp" ADD CONSTRAINT "cc_show_stamp_instance_id_fkey" FOREIGN KEY ("instance_id") REFERENCES "cc_show_instances" ("id") ON DELETE CASCADE; + +ALTER TABLE "cc_show_stamp" ADD CONSTRAINT "cc_show_stamp_file_id_fkey" FOREIGN KEY ("file_id") REFERENCES "cc_files" ("id") ON DELETE CASCADE; + +ALTER TABLE "cc_show_stamp" ADD CONSTRAINT "cc_show_stamp_stream_id_fkey" FOREIGN KEY ("stream_id") REFERENCES "cc_webstream" ("id") ON DELETE CASCADE; + +ALTER TABLE "cc_show_stamp" ADD CONSTRAINT "cc_show_stamp_block_id_fkey" FOREIGN KEY ("block_id") REFERENCES "cc_block" ("id") ON DELETE CASCADE; + +ALTER TABLE "cc_show_stamp" ADD CONSTRAINT "cc_show_stamp_playlist_id_fkey" FOREIGN KEY ("playlist_id") REFERENCES "cc_playlist" ("id") ON DELETE CASCADE; From 62d1b22fcc27d485b7966990042a17f765406e43 Mon Sep 17 00:00:00 2001 From: denise Date: Fri, 5 Apr 2013 12:27:54 -0400 Subject: [PATCH 44/73] CC-4961: Show linking created new cc_show_stamp table --- .../models/airtime/CcShowStamp.php | 18 + .../models/airtime/CcShowStampPeer.php | 18 + .../models/airtime/CcShowStampQuery.php | 18 + .../airtime/map/CcShowStampTableMap.php | 70 + .../models/airtime/om/BaseCcShowStamp.php | 1783 ++++++++++ .../models/airtime/om/BaseCcShowStampPeer.php | 3095 +++++++++++++++++ .../airtime/om/BaseCcShowStampQuery.php | 948 +++++ airtime_mvc/build/schema.xml | 3 +- 8 files changed, 5951 insertions(+), 2 deletions(-) create mode 100644 airtime_mvc/application/models/airtime/CcShowStamp.php create mode 100644 airtime_mvc/application/models/airtime/CcShowStampPeer.php create mode 100644 airtime_mvc/application/models/airtime/CcShowStampQuery.php create mode 100644 airtime_mvc/application/models/airtime/map/CcShowStampTableMap.php create mode 100644 airtime_mvc/application/models/airtime/om/BaseCcShowStamp.php create mode 100644 airtime_mvc/application/models/airtime/om/BaseCcShowStampPeer.php create mode 100644 airtime_mvc/application/models/airtime/om/BaseCcShowStampQuery.php diff --git a/airtime_mvc/application/models/airtime/CcShowStamp.php b/airtime_mvc/application/models/airtime/CcShowStamp.php new file mode 100644 index 000000000..19ced4a05 --- /dev/null +++ b/airtime_mvc/application/models/airtime/CcShowStamp.php @@ -0,0 +1,18 @@ +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/om/BaseCcShowStamp.php b/airtime_mvc/application/models/airtime/om/BaseCcShowStamp.php new file mode 100644 index 000000000..c4e55cf59 --- /dev/null +++ b/airtime_mvc/application/models/airtime/om/BaseCcShowStamp.php @@ -0,0 +1,1783 @@ +clip_length = '00:00:00'; + $this->cue_in = '00:00:00'; + $this->cue_out = '00:00:00'; + $this->fade_in = '00:00:00'; + $this->fade_out = '00:00:00'; + } + + /** + * Initializes internal state of BaseCcShowStamp object. + * @see applyDefaults() + */ + public function __construct() + { + parent::__construct(); + $this->applyDefaultValues(); + } + + /** + * Get the [id] column value. + * + * @return int + */ + public function getDbId() + { + return $this->id; + } + + /** + * Get the [show_id] column value. + * + * @return int + */ + public function getDbShowId() + { + return $this->show_id; + } + + /** + * Get the [instance_id] column value. + * + * @return int + */ + public function getDbInstanceId() + { + return $this->instance_id; + } + + /** + * Get the [file_id] column value. + * + * @return int + */ + public function getDbFileId() + { + return $this->file_id; + } + + /** + * Get the [stream_id] column value. + * + * @return int + */ + public function getDbStreamId() + { + return $this->stream_id; + } + + /** + * Get the [block_id] column value. + * + * @return int + */ + public function getDbBlockId() + { + return $this->block_id; + } + + /** + * Get the [playlist_id] column value. + * + * @return int + */ + public function getDbPlaylistId() + { + return $this->playlist_id; + } + + /** + * Get the [position] column value. + * + * @return int + */ + public function getDbPosition() + { + return $this->position; + } + + /** + * Get the [clip_length] column value. + * + * @return string + */ + public function getDbClipLength() + { + return $this->clip_length; + } + + /** + * Get the [cue_in] column value. + * + * @return string + */ + public function getDbCueIn() + { + return $this->cue_in; + } + + /** + * Get the [cue_out] column value. + * + * @return string + */ + public function getDbCueOut() + { + return $this->cue_out; + } + + /** + * Get the [fade_in] column value. + * + * @return string + */ + public function getDbFadeIn() + { + return $this->fade_in; + } + + /** + * Get the [fade_out] column value. + * + * @return string + */ + public function getDbFadeOut() + { + return $this->fade_out; + } + + /** + * Set the value of [id] column. + * + * @param int $v new value + * @return CcShowStamp The current object (for fluent API support) + */ + public function setDbId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->id !== $v) { + $this->id = $v; + $this->modifiedColumns[] = CcShowStampPeer::ID; + } + + return $this; + } // setDbId() + + /** + * Set the value of [show_id] column. + * + * @param int $v new value + * @return CcShowStamp The current object (for fluent API support) + */ + public function setDbShowId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->show_id !== $v) { + $this->show_id = $v; + $this->modifiedColumns[] = CcShowStampPeer::SHOW_ID; + } + + if ($this->aCcShow !== null && $this->aCcShow->getDbId() !== $v) { + $this->aCcShow = null; + } + + return $this; + } // setDbShowId() + + /** + * Set the value of [instance_id] column. + * + * @param int $v new value + * @return CcShowStamp The current object (for fluent API support) + */ + public function setDbInstanceId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->instance_id !== $v) { + $this->instance_id = $v; + $this->modifiedColumns[] = CcShowStampPeer::INSTANCE_ID; + } + + if ($this->aCcShowInstances !== null && $this->aCcShowInstances->getDbId() !== $v) { + $this->aCcShowInstances = null; + } + + return $this; + } // setDbInstanceId() + + /** + * Set the value of [file_id] column. + * + * @param int $v new value + * @return CcShowStamp The current object (for fluent API support) + */ + public function setDbFileId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->file_id !== $v) { + $this->file_id = $v; + $this->modifiedColumns[] = CcShowStampPeer::FILE_ID; + } + + if ($this->aCcFiles !== null && $this->aCcFiles->getDbId() !== $v) { + $this->aCcFiles = null; + } + + return $this; + } // setDbFileId() + + /** + * Set the value of [stream_id] column. + * + * @param int $v new value + * @return CcShowStamp The current object (for fluent API support) + */ + public function setDbStreamId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->stream_id !== $v) { + $this->stream_id = $v; + $this->modifiedColumns[] = CcShowStampPeer::STREAM_ID; + } + + if ($this->aCcWebstream !== null && $this->aCcWebstream->getDbId() !== $v) { + $this->aCcWebstream = null; + } + + return $this; + } // setDbStreamId() + + /** + * Set the value of [block_id] column. + * + * @param int $v new value + * @return CcShowStamp The current object (for fluent API support) + */ + public function setDbBlockId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->block_id !== $v) { + $this->block_id = $v; + $this->modifiedColumns[] = CcShowStampPeer::BLOCK_ID; + } + + if ($this->aCcBlock !== null && $this->aCcBlock->getDbId() !== $v) { + $this->aCcBlock = null; + } + + return $this; + } // setDbBlockId() + + /** + * Set the value of [playlist_id] column. + * + * @param int $v new value + * @return CcShowStamp The current object (for fluent API support) + */ + public function setDbPlaylistId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->playlist_id !== $v) { + $this->playlist_id = $v; + $this->modifiedColumns[] = CcShowStampPeer::PLAYLIST_ID; + } + + if ($this->aCcPlaylist !== null && $this->aCcPlaylist->getDbId() !== $v) { + $this->aCcPlaylist = null; + } + + return $this; + } // setDbPlaylistId() + + /** + * Set the value of [position] column. + * + * @param int $v new value + * @return CcShowStamp The current object (for fluent API support) + */ + public function setDbPosition($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->position !== $v) { + $this->position = $v; + $this->modifiedColumns[] = CcShowStampPeer::POSITION; + } + + return $this; + } // setDbPosition() + + /** + * Set the value of [clip_length] column. + * + * @param string $v new value + * @return CcShowStamp The current object (for fluent API support) + */ + public function setDbClipLength($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->clip_length !== $v || $this->isNew()) { + $this->clip_length = $v; + $this->modifiedColumns[] = CcShowStampPeer::CLIP_LENGTH; + } + + return $this; + } // setDbClipLength() + + /** + * Set the value of [cue_in] column. + * + * @param string $v new value + * @return CcShowStamp The current object (for fluent API support) + */ + public function setDbCueIn($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->cue_in !== $v || $this->isNew()) { + $this->cue_in = $v; + $this->modifiedColumns[] = CcShowStampPeer::CUE_IN; + } + + return $this; + } // setDbCueIn() + + /** + * Set the value of [cue_out] column. + * + * @param string $v new value + * @return CcShowStamp The current object (for fluent API support) + */ + public function setDbCueOut($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->cue_out !== $v || $this->isNew()) { + $this->cue_out = $v; + $this->modifiedColumns[] = CcShowStampPeer::CUE_OUT; + } + + return $this; + } // setDbCueOut() + + /** + * Set the value of [fade_in] column. + * + * @param string $v new value + * @return CcShowStamp The current object (for fluent API support) + */ + public function setDbFadeIn($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->fade_in !== $v || $this->isNew()) { + $this->fade_in = $v; + $this->modifiedColumns[] = CcShowStampPeer::FADE_IN; + } + + return $this; + } // setDbFadeIn() + + /** + * Set the value of [fade_out] column. + * + * @param string $v new value + * @return CcShowStamp The current object (for fluent API support) + */ + public function setDbFadeOut($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->fade_out !== $v || $this->isNew()) { + $this->fade_out = $v; + $this->modifiedColumns[] = CcShowStampPeer::FADE_OUT; + } + + return $this; + } // setDbFadeOut() + + /** + * Indicates whether the columns in this object are only set to default values. + * + * This method can be used in conjunction with isModified() to indicate whether an object is both + * modified _and_ has some values set which are non-default. + * + * @return boolean Whether the columns in this object are only been set with default values. + */ + public function hasOnlyDefaultValues() + { + if ($this->clip_length !== '00:00:00') { + return false; + } + + if ($this->cue_in !== '00:00:00') { + return false; + } + + if ($this->cue_out !== '00:00:00') { + return false; + } + + if ($this->fade_in !== '00:00:00') { + return false; + } + + if ($this->fade_out !== '00:00:00') { + return false; + } + + // otherwise, everything was equal, so return TRUE + return true; + } // hasOnlyDefaultValues() + + /** + * Hydrates (populates) the object variables with values from the database resultset. + * + * An offset (0-based "start column") is specified so that objects can be hydrated + * with a subset of the columns in the resultset rows. This is needed, for example, + * for results of JOIN queries where the resultset row includes columns from two or + * more tables. + * + * @param array $row The row returned by PDOStatement->fetch(PDO::FETCH_NUM) + * @param int $startcol 0-based offset column which indicates which restultset column to start with. + * @param boolean $rehydrate Whether this object is being re-hydrated from the database. + * @return int next starting column + * @throws PropelException - Any caught Exception will be rewrapped as a PropelException. + */ + public function hydrate($row, $startcol = 0, $rehydrate = false) + { + try { + + $this->id = ($row[$startcol + 0] !== null) ? (int) $row[$startcol + 0] : null; + $this->show_id = ($row[$startcol + 1] !== null) ? (int) $row[$startcol + 1] : null; + $this->instance_id = ($row[$startcol + 2] !== null) ? (int) $row[$startcol + 2] : null; + $this->file_id = ($row[$startcol + 3] !== null) ? (int) $row[$startcol + 3] : null; + $this->stream_id = ($row[$startcol + 4] !== null) ? (int) $row[$startcol + 4] : null; + $this->block_id = ($row[$startcol + 5] !== null) ? (int) $row[$startcol + 5] : null; + $this->playlist_id = ($row[$startcol + 6] !== null) ? (int) $row[$startcol + 6] : null; + $this->position = ($row[$startcol + 7] !== null) ? (int) $row[$startcol + 7] : null; + $this->clip_length = ($row[$startcol + 8] !== null) ? (string) $row[$startcol + 8] : null; + $this->cue_in = ($row[$startcol + 9] !== null) ? (string) $row[$startcol + 9] : null; + $this->cue_out = ($row[$startcol + 10] !== null) ? (string) $row[$startcol + 10] : null; + $this->fade_in = ($row[$startcol + 11] !== null) ? (string) $row[$startcol + 11] : null; + $this->fade_out = ($row[$startcol + 12] !== null) ? (string) $row[$startcol + 12] : null; + $this->resetModified(); + + $this->setNew(false); + + if ($rehydrate) { + $this->ensureConsistency(); + } + + return $startcol + 13; // 13 = CcShowStampPeer::NUM_COLUMNS - CcShowStampPeer::NUM_LAZY_LOAD_COLUMNS). + + } catch (Exception $e) { + throw new PropelException("Error populating CcShowStamp object", $e); + } + } + + /** + * Checks and repairs the internal consistency of the object. + * + * This method is executed after an already-instantiated object is re-hydrated + * from the database. It exists to check any foreign keys to make sure that + * the objects related to the current object are correct based on foreign key. + * + * You can override this method in the stub class, but you should always invoke + * the base method from the overridden method (i.e. parent::ensureConsistency()), + * in case your model changes. + * + * @throws PropelException + */ + public function ensureConsistency() + { + + if ($this->aCcShow !== null && $this->show_id !== $this->aCcShow->getDbId()) { + $this->aCcShow = null; + } + if ($this->aCcShowInstances !== null && $this->instance_id !== $this->aCcShowInstances->getDbId()) { + $this->aCcShowInstances = null; + } + if ($this->aCcFiles !== null && $this->file_id !== $this->aCcFiles->getDbId()) { + $this->aCcFiles = null; + } + if ($this->aCcWebstream !== null && $this->stream_id !== $this->aCcWebstream->getDbId()) { + $this->aCcWebstream = null; + } + if ($this->aCcBlock !== null && $this->block_id !== $this->aCcBlock->getDbId()) { + $this->aCcBlock = null; + } + if ($this->aCcPlaylist !== null && $this->playlist_id !== $this->aCcPlaylist->getDbId()) { + $this->aCcPlaylist = null; + } + } // ensureConsistency + + /** + * Reloads this object from datastore based on primary key and (optionally) resets all associated objects. + * + * This will only work if the object has been saved and has a valid primary key set. + * + * @param boolean $deep (optional) Whether to also de-associated any related objects. + * @param PropelPDO $con (optional) The PropelPDO connection to use. + * @return void + * @throws PropelException - if this object is deleted, unsaved or doesn't have pk match in db + */ + public function reload($deep = false, PropelPDO $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("Cannot reload a deleted object."); + } + + if ($this->isNew()) { + throw new PropelException("Cannot reload an unsaved object."); + } + + if ($con === null) { + $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + // We don't need to alter the object instance pool; we're just modifying this instance + // already in the pool. + + $stmt = CcShowStampPeer::doSelectStmt($this->buildPkeyCriteria(), $con); + $row = $stmt->fetch(PDO::FETCH_NUM); + $stmt->closeCursor(); + if (!$row) { + throw new PropelException('Cannot find matching row in the database to reload object values.'); + } + $this->hydrate($row, 0, true); // rehydrate + + if ($deep) { // also de-associate any related objects? + + $this->aCcShow = null; + $this->aCcShowInstances = null; + $this->aCcFiles = null; + $this->aCcWebstream = null; + $this->aCcBlock = null; + $this->aCcPlaylist = null; + } // if (deep) + } + + /** + * Removes this object from datastore and sets delete attribute. + * + * @param PropelPDO $con + * @return void + * @throws PropelException + * @see BaseObject::setDeleted() + * @see BaseObject::isDeleted() + */ + public function delete(PropelPDO $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("This object has already been deleted."); + } + + if ($con === null) { + $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + } + + $con->beginTransaction(); + try { + $ret = $this->preDelete($con); + if ($ret) { + CcShowStampQuery::create() + ->filterByPrimaryKey($this->getPrimaryKey()) + ->delete($con); + $this->postDelete($con); + $con->commit(); + $this->setDeleted(true); + } else { + $con->commit(); + } + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Persists this object to the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All modified related objects will also be persisted in the doSave() + * method. This method wraps all precipitate database operations in a + * single transaction. + * + * @param PropelPDO $con + * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. + * @throws PropelException + * @see doSave() + */ + public function save(PropelPDO $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("You cannot save an object that has been deleted."); + } + + if ($con === null) { + $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + } + + $con->beginTransaction(); + $isInsert = $this->isNew(); + try { + $ret = $this->preSave($con); + if ($isInsert) { + $ret = $ret && $this->preInsert($con); + } else { + $ret = $ret && $this->preUpdate($con); + } + if ($ret) { + $affectedRows = $this->doSave($con); + if ($isInsert) { + $this->postInsert($con); + } else { + $this->postUpdate($con); + } + $this->postSave($con); + CcShowStampPeer::addInstanceToPool($this); + } else { + $affectedRows = 0; + } + $con->commit(); + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Performs the work of inserting or updating the row in the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All related objects are also updated in this method. + * + * @param PropelPDO $con + * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. + * @throws PropelException + * @see save() + */ + protected function doSave(PropelPDO $con) + { + $affectedRows = 0; // initialize var to track total num of affected rows + if (!$this->alreadyInSave) { + $this->alreadyInSave = true; + + // We call the save method on the following object(s) if they + // were passed to this object by their coresponding set + // method. This object relates to these object(s) by a + // foreign key reference. + + if ($this->aCcShow !== null) { + if ($this->aCcShow->isModified() || $this->aCcShow->isNew()) { + $affectedRows += $this->aCcShow->save($con); + } + $this->setCcShow($this->aCcShow); + } + + if ($this->aCcShowInstances !== null) { + if ($this->aCcShowInstances->isModified() || $this->aCcShowInstances->isNew()) { + $affectedRows += $this->aCcShowInstances->save($con); + } + $this->setCcShowInstances($this->aCcShowInstances); + } + + if ($this->aCcFiles !== null) { + if ($this->aCcFiles->isModified() || $this->aCcFiles->isNew()) { + $affectedRows += $this->aCcFiles->save($con); + } + $this->setCcFiles($this->aCcFiles); + } + + if ($this->aCcWebstream !== null) { + if ($this->aCcWebstream->isModified() || $this->aCcWebstream->isNew()) { + $affectedRows += $this->aCcWebstream->save($con); + } + $this->setCcWebstream($this->aCcWebstream); + } + + if ($this->aCcBlock !== null) { + if ($this->aCcBlock->isModified() || $this->aCcBlock->isNew()) { + $affectedRows += $this->aCcBlock->save($con); + } + $this->setCcBlock($this->aCcBlock); + } + + if ($this->aCcPlaylist !== null) { + if ($this->aCcPlaylist->isModified() || $this->aCcPlaylist->isNew()) { + $affectedRows += $this->aCcPlaylist->save($con); + } + $this->setCcPlaylist($this->aCcPlaylist); + } + + if ($this->isNew() ) { + $this->modifiedColumns[] = CcShowStampPeer::ID; + } + + // If this object has been modified, then save it to the database. + if ($this->isModified()) { + if ($this->isNew()) { + $criteria = $this->buildCriteria(); + if ($criteria->keyContainsValue(CcShowStampPeer::ID) ) { + throw new PropelException('Cannot insert a value for auto-increment primary key ('.CcShowStampPeer::ID.')'); + } + + $pk = BasePeer::doInsert($criteria, $con); + $affectedRows += 1; + $this->setDbId($pk); //[IMV] update autoincrement primary key + $this->setNew(false); + } else { + $affectedRows += CcShowStampPeer::doUpdate($this, $con); + } + + $this->resetModified(); // [HL] After being saved an object is no longer 'modified' + } + + $this->alreadyInSave = false; + + } + return $affectedRows; + } // doSave() + + /** + * Array of ValidationFailed objects. + * @var array ValidationFailed[] + */ + protected $validationFailures = array(); + + /** + * Gets any ValidationFailed objects that resulted from last call to validate(). + * + * + * @return array ValidationFailed[] + * @see validate() + */ + public function getValidationFailures() + { + return $this->validationFailures; + } + + /** + * Validates the objects modified field values and all objects related to this table. + * + * If $columns is either a column name or an array of column names + * only those columns are validated. + * + * @param mixed $columns Column name or an array of column names. + * @return boolean Whether all columns pass validation. + * @see doValidate() + * @see getValidationFailures() + */ + public function validate($columns = null) + { + $res = $this->doValidate($columns); + if ($res === true) { + $this->validationFailures = array(); + return true; + } else { + $this->validationFailures = $res; + return false; + } + } + + /** + * This function performs the validation work for complex object models. + * + * In addition to checking the current object, all related objects will + * also be validated. If all pass then true is returned; otherwise + * an aggreagated array of ValidationFailed objects will be returned. + * + * @param array $columns Array of column names to validate. + * @return mixed true if all validations pass; array of ValidationFailed objets otherwise. + */ + protected function doValidate($columns = null) + { + if (!$this->alreadyInValidation) { + $this->alreadyInValidation = true; + $retval = null; + + $failureMap = array(); + + + // We call the validate method on the following object(s) if they + // were passed to this object by their coresponding set + // method. This object relates to these object(s) by a + // foreign key reference. + + if ($this->aCcShow !== null) { + if (!$this->aCcShow->validate($columns)) { + $failureMap = array_merge($failureMap, $this->aCcShow->getValidationFailures()); + } + } + + if ($this->aCcShowInstances !== null) { + if (!$this->aCcShowInstances->validate($columns)) { + $failureMap = array_merge($failureMap, $this->aCcShowInstances->getValidationFailures()); + } + } + + if ($this->aCcFiles !== null) { + if (!$this->aCcFiles->validate($columns)) { + $failureMap = array_merge($failureMap, $this->aCcFiles->getValidationFailures()); + } + } + + if ($this->aCcWebstream !== null) { + if (!$this->aCcWebstream->validate($columns)) { + $failureMap = array_merge($failureMap, $this->aCcWebstream->getValidationFailures()); + } + } + + if ($this->aCcBlock !== null) { + if (!$this->aCcBlock->validate($columns)) { + $failureMap = array_merge($failureMap, $this->aCcBlock->getValidationFailures()); + } + } + + if ($this->aCcPlaylist !== null) { + if (!$this->aCcPlaylist->validate($columns)) { + $failureMap = array_merge($failureMap, $this->aCcPlaylist->getValidationFailures()); + } + } + + + if (($retval = CcShowStampPeer::doValidate($this, $columns)) !== true) { + $failureMap = array_merge($failureMap, $retval); + } + + + + $this->alreadyInValidation = false; + } + + return (!empty($failureMap) ? $failureMap : true); + } + + /** + * Retrieves a field from the object by name passed in as a string. + * + * @param string $name name + * @param string $type The type of fieldname the $name is of: + * one of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME + * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM + * @return mixed Value of field. + */ + public function getByName($name, $type = BasePeer::TYPE_PHPNAME) + { + $pos = CcShowStampPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); + $field = $this->getByPosition($pos); + return $field; + } + + /** + * Retrieves a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @return mixed Value of field at $pos + */ + public function getByPosition($pos) + { + switch($pos) { + case 0: + return $this->getDbId(); + break; + case 1: + return $this->getDbShowId(); + break; + case 2: + return $this->getDbInstanceId(); + break; + case 3: + return $this->getDbFileId(); + break; + case 4: + return $this->getDbStreamId(); + break; + case 5: + return $this->getDbBlockId(); + break; + case 6: + return $this->getDbPlaylistId(); + break; + case 7: + return $this->getDbPosition(); + break; + case 8: + return $this->getDbClipLength(); + break; + case 9: + return $this->getDbCueIn(); + break; + case 10: + return $this->getDbCueOut(); + break; + case 11: + return $this->getDbFadeIn(); + break; + case 12: + return $this->getDbFadeOut(); + break; + default: + return null; + break; + } // switch() + } + + /** + * Exports the object as an array. + * + * You can specify the key type of the array by passing one of the class + * type constants. + * + * @param string $keyType (optional) One of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME, + * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. + * Defaults to BasePeer::TYPE_PHPNAME. + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy loaded columns. Defaults to TRUE. + * @param boolean $includeForeignObjects (optional) Whether to include hydrated related objects. Default to FALSE. + * + * @return array an associative array containing the field names (as keys) and field values + */ + public function toArray($keyType = BasePeer::TYPE_PHPNAME, $includeLazyLoadColumns = true, $includeForeignObjects = false) + { + $keys = CcShowStampPeer::getFieldNames($keyType); + $result = array( + $keys[0] => $this->getDbId(), + $keys[1] => $this->getDbShowId(), + $keys[2] => $this->getDbInstanceId(), + $keys[3] => $this->getDbFileId(), + $keys[4] => $this->getDbStreamId(), + $keys[5] => $this->getDbBlockId(), + $keys[6] => $this->getDbPlaylistId(), + $keys[7] => $this->getDbPosition(), + $keys[8] => $this->getDbClipLength(), + $keys[9] => $this->getDbCueIn(), + $keys[10] => $this->getDbCueOut(), + $keys[11] => $this->getDbFadeIn(), + $keys[12] => $this->getDbFadeOut(), + ); + if ($includeForeignObjects) { + if (null !== $this->aCcShow) { + $result['CcShow'] = $this->aCcShow->toArray($keyType, $includeLazyLoadColumns, true); + } + if (null !== $this->aCcShowInstances) { + $result['CcShowInstances'] = $this->aCcShowInstances->toArray($keyType, $includeLazyLoadColumns, true); + } + if (null !== $this->aCcFiles) { + $result['CcFiles'] = $this->aCcFiles->toArray($keyType, $includeLazyLoadColumns, true); + } + if (null !== $this->aCcWebstream) { + $result['CcWebstream'] = $this->aCcWebstream->toArray($keyType, $includeLazyLoadColumns, true); + } + if (null !== $this->aCcBlock) { + $result['CcBlock'] = $this->aCcBlock->toArray($keyType, $includeLazyLoadColumns, true); + } + if (null !== $this->aCcPlaylist) { + $result['CcPlaylist'] = $this->aCcPlaylist->toArray($keyType, $includeLazyLoadColumns, true); + } + } + return $result; + } + + /** + * Sets a field from the object by name passed in as a string. + * + * @param string $name peer name + * @param mixed $value field value + * @param string $type The type of fieldname the $name is of: + * one of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME + * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM + * @return void + */ + public function setByName($name, $value, $type = BasePeer::TYPE_PHPNAME) + { + $pos = CcShowStampPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); + return $this->setByPosition($pos, $value); + } + + /** + * Sets a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @param mixed $value field value + * @return void + */ + public function setByPosition($pos, $value) + { + switch($pos) { + case 0: + $this->setDbId($value); + break; + case 1: + $this->setDbShowId($value); + break; + case 2: + $this->setDbInstanceId($value); + break; + case 3: + $this->setDbFileId($value); + break; + case 4: + $this->setDbStreamId($value); + break; + case 5: + $this->setDbBlockId($value); + break; + case 6: + $this->setDbPlaylistId($value); + break; + case 7: + $this->setDbPosition($value); + break; + case 8: + $this->setDbClipLength($value); + break; + case 9: + $this->setDbCueIn($value); + break; + case 10: + $this->setDbCueOut($value); + break; + case 11: + $this->setDbFadeIn($value); + break; + case 12: + $this->setDbFadeOut($value); + break; + } // switch() + } + + /** + * Populates the object using an array. + * + * This is particularly useful when populating an object from one of the + * request arrays (e.g. $_POST). This method goes through the column + * names, checking to see whether a matching key exists in populated + * array. If so the setByName() method is called for that column. + * + * You can specify the key type of the array by additionally passing one + * of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME, + * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. + * The default key type is the column's phpname (e.g. 'AuthorId') + * + * @param array $arr An array to populate the object from. + * @param string $keyType The type of keys the array uses. + * @return void + */ + public function fromArray($arr, $keyType = BasePeer::TYPE_PHPNAME) + { + $keys = CcShowStampPeer::getFieldNames($keyType); + + if (array_key_exists($keys[0], $arr)) $this->setDbId($arr[$keys[0]]); + if (array_key_exists($keys[1], $arr)) $this->setDbShowId($arr[$keys[1]]); + if (array_key_exists($keys[2], $arr)) $this->setDbInstanceId($arr[$keys[2]]); + if (array_key_exists($keys[3], $arr)) $this->setDbFileId($arr[$keys[3]]); + if (array_key_exists($keys[4], $arr)) $this->setDbStreamId($arr[$keys[4]]); + if (array_key_exists($keys[5], $arr)) $this->setDbBlockId($arr[$keys[5]]); + if (array_key_exists($keys[6], $arr)) $this->setDbPlaylistId($arr[$keys[6]]); + if (array_key_exists($keys[7], $arr)) $this->setDbPosition($arr[$keys[7]]); + if (array_key_exists($keys[8], $arr)) $this->setDbClipLength($arr[$keys[8]]); + if (array_key_exists($keys[9], $arr)) $this->setDbCueIn($arr[$keys[9]]); + if (array_key_exists($keys[10], $arr)) $this->setDbCueOut($arr[$keys[10]]); + if (array_key_exists($keys[11], $arr)) $this->setDbFadeIn($arr[$keys[11]]); + if (array_key_exists($keys[12], $arr)) $this->setDbFadeOut($arr[$keys[12]]); + } + + /** + * Build a Criteria object containing the values of all modified columns in this object. + * + * @return Criteria The Criteria object containing all modified values. + */ + public function buildCriteria() + { + $criteria = new Criteria(CcShowStampPeer::DATABASE_NAME); + + if ($this->isColumnModified(CcShowStampPeer::ID)) $criteria->add(CcShowStampPeer::ID, $this->id); + if ($this->isColumnModified(CcShowStampPeer::SHOW_ID)) $criteria->add(CcShowStampPeer::SHOW_ID, $this->show_id); + if ($this->isColumnModified(CcShowStampPeer::INSTANCE_ID)) $criteria->add(CcShowStampPeer::INSTANCE_ID, $this->instance_id); + if ($this->isColumnModified(CcShowStampPeer::FILE_ID)) $criteria->add(CcShowStampPeer::FILE_ID, $this->file_id); + if ($this->isColumnModified(CcShowStampPeer::STREAM_ID)) $criteria->add(CcShowStampPeer::STREAM_ID, $this->stream_id); + if ($this->isColumnModified(CcShowStampPeer::BLOCK_ID)) $criteria->add(CcShowStampPeer::BLOCK_ID, $this->block_id); + if ($this->isColumnModified(CcShowStampPeer::PLAYLIST_ID)) $criteria->add(CcShowStampPeer::PLAYLIST_ID, $this->playlist_id); + if ($this->isColumnModified(CcShowStampPeer::POSITION)) $criteria->add(CcShowStampPeer::POSITION, $this->position); + if ($this->isColumnModified(CcShowStampPeer::CLIP_LENGTH)) $criteria->add(CcShowStampPeer::CLIP_LENGTH, $this->clip_length); + if ($this->isColumnModified(CcShowStampPeer::CUE_IN)) $criteria->add(CcShowStampPeer::CUE_IN, $this->cue_in); + if ($this->isColumnModified(CcShowStampPeer::CUE_OUT)) $criteria->add(CcShowStampPeer::CUE_OUT, $this->cue_out); + if ($this->isColumnModified(CcShowStampPeer::FADE_IN)) $criteria->add(CcShowStampPeer::FADE_IN, $this->fade_in); + if ($this->isColumnModified(CcShowStampPeer::FADE_OUT)) $criteria->add(CcShowStampPeer::FADE_OUT, $this->fade_out); + + return $criteria; + } + + /** + * Builds a Criteria object containing the primary key for this object. + * + * Unlike buildCriteria() this method includes the primary key values regardless + * of whether or not they have been modified. + * + * @return Criteria The Criteria object containing value(s) for primary key(s). + */ + public function buildPkeyCriteria() + { + $criteria = new Criteria(CcShowStampPeer::DATABASE_NAME); + $criteria->add(CcShowStampPeer::ID, $this->id); + + return $criteria; + } + + /** + * Returns the primary key for this object (row). + * @return int + */ + public function getPrimaryKey() + { + return $this->getDbId(); + } + + /** + * Generic method to set the primary key (id column). + * + * @param int $key Primary key. + * @return void + */ + public function setPrimaryKey($key) + { + $this->setDbId($key); + } + + /** + * Returns true if the primary key for this object is null. + * @return boolean + */ + public function isPrimaryKeyNull() + { + return null === $this->getDbId(); + } + + /** + * Sets contents of passed object to values from current object. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param object $copyObj An object of CcShowStamp (or compatible) type. + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @throws PropelException + */ + public function copyInto($copyObj, $deepCopy = false) + { + $copyObj->setDbShowId($this->show_id); + $copyObj->setDbInstanceId($this->instance_id); + $copyObj->setDbFileId($this->file_id); + $copyObj->setDbStreamId($this->stream_id); + $copyObj->setDbBlockId($this->block_id); + $copyObj->setDbPlaylistId($this->playlist_id); + $copyObj->setDbPosition($this->position); + $copyObj->setDbClipLength($this->clip_length); + $copyObj->setDbCueIn($this->cue_in); + $copyObj->setDbCueOut($this->cue_out); + $copyObj->setDbFadeIn($this->fade_in); + $copyObj->setDbFadeOut($this->fade_out); + + $copyObj->setNew(true); + $copyObj->setDbId(NULL); // this is a auto-increment column, so set to default value + } + + /** + * Makes a copy of this object that will be inserted as a new row in table when saved. + * It creates a new object filling in the simple attributes, but skipping any primary + * keys that are defined for the table. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @return CcShowStamp Clone of current object. + * @throws PropelException + */ + public function copy($deepCopy = false) + { + // we use get_class(), because this might be a subclass + $clazz = get_class($this); + $copyObj = new $clazz(); + $this->copyInto($copyObj, $deepCopy); + return $copyObj; + } + + /** + * Returns a peer instance associated with this om. + * + * Since Peer classes are not to have any instance attributes, this method returns the + * same instance for all member of this class. The method could therefore + * be static, but this would prevent one from overriding the behavior. + * + * @return CcShowStampPeer + */ + public function getPeer() + { + if (self::$peer === null) { + self::$peer = new CcShowStampPeer(); + } + return self::$peer; + } + + /** + * Declares an association between this object and a CcShow object. + * + * @param CcShow $v + * @return CcShowStamp The current object (for fluent API support) + * @throws PropelException + */ + public function setCcShow(CcShow $v = null) + { + if ($v === null) { + $this->setDbShowId(NULL); + } else { + $this->setDbShowId($v->getDbId()); + } + + $this->aCcShow = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the CcShow object, it will not be re-added. + if ($v !== null) { + $v->addCcShowStamp($this); + } + + return $this; + } + + + /** + * Get the associated CcShow object + * + * @param PropelPDO Optional Connection object. + * @return CcShow The associated CcShow object. + * @throws PropelException + */ + public function getCcShow(PropelPDO $con = null) + { + if ($this->aCcShow === null && ($this->show_id !== null)) { + $this->aCcShow = CcShowQuery::create()->findPk($this->show_id, $con); + /* The following can be used additionally to + guarantee the related object contains a reference + to this object. This level of coupling may, however, be + undesirable since it could result in an only partially populated collection + in the referenced object. + $this->aCcShow->addCcShowStamps($this); + */ + } + return $this->aCcShow; + } + + /** + * Declares an association between this object and a CcShowInstances object. + * + * @param CcShowInstances $v + * @return CcShowStamp The current object (for fluent API support) + * @throws PropelException + */ + public function setCcShowInstances(CcShowInstances $v = null) + { + if ($v === null) { + $this->setDbInstanceId(NULL); + } else { + $this->setDbInstanceId($v->getDbId()); + } + + $this->aCcShowInstances = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the CcShowInstances object, it will not be re-added. + if ($v !== null) { + $v->addCcShowStamp($this); + } + + return $this; + } + + + /** + * Get the associated CcShowInstances object + * + * @param PropelPDO Optional Connection object. + * @return CcShowInstances The associated CcShowInstances object. + * @throws PropelException + */ + public function getCcShowInstances(PropelPDO $con = null) + { + if ($this->aCcShowInstances === null && ($this->instance_id !== null)) { + $this->aCcShowInstances = CcShowInstancesQuery::create()->findPk($this->instance_id, $con); + /* The following can be used additionally to + guarantee the related object contains a reference + to this object. This level of coupling may, however, be + undesirable since it could result in an only partially populated collection + in the referenced object. + $this->aCcShowInstances->addCcShowStamps($this); + */ + } + return $this->aCcShowInstances; + } + + /** + * Declares an association between this object and a CcFiles object. + * + * @param CcFiles $v + * @return CcShowStamp The current object (for fluent API support) + * @throws PropelException + */ + public function setCcFiles(CcFiles $v = null) + { + if ($v === null) { + $this->setDbFileId(NULL); + } else { + $this->setDbFileId($v->getDbId()); + } + + $this->aCcFiles = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the CcFiles object, it will not be re-added. + if ($v !== null) { + $v->addCcShowStamp($this); + } + + return $this; + } + + + /** + * Get the associated CcFiles object + * + * @param PropelPDO Optional Connection object. + * @return CcFiles The associated CcFiles object. + * @throws PropelException + */ + public function getCcFiles(PropelPDO $con = null) + { + if ($this->aCcFiles === null && ($this->file_id !== null)) { + $this->aCcFiles = CcFilesQuery::create()->findPk($this->file_id, $con); + /* The following can be used additionally to + guarantee the related object contains a reference + to this object. This level of coupling may, however, be + undesirable since it could result in an only partially populated collection + in the referenced object. + $this->aCcFiles->addCcShowStamps($this); + */ + } + return $this->aCcFiles; + } + + /** + * Declares an association between this object and a CcWebstream object. + * + * @param CcWebstream $v + * @return CcShowStamp The current object (for fluent API support) + * @throws PropelException + */ + public function setCcWebstream(CcWebstream $v = null) + { + if ($v === null) { + $this->setDbStreamId(NULL); + } else { + $this->setDbStreamId($v->getDbId()); + } + + $this->aCcWebstream = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the CcWebstream object, it will not be re-added. + if ($v !== null) { + $v->addCcShowStamp($this); + } + + return $this; + } + + + /** + * Get the associated CcWebstream object + * + * @param PropelPDO Optional Connection object. + * @return CcWebstream The associated CcWebstream object. + * @throws PropelException + */ + public function getCcWebstream(PropelPDO $con = null) + { + if ($this->aCcWebstream === null && ($this->stream_id !== null)) { + $this->aCcWebstream = CcWebstreamQuery::create()->findPk($this->stream_id, $con); + /* The following can be used additionally to + guarantee the related object contains a reference + to this object. This level of coupling may, however, be + undesirable since it could result in an only partially populated collection + in the referenced object. + $this->aCcWebstream->addCcShowStamps($this); + */ + } + return $this->aCcWebstream; + } + + /** + * Declares an association between this object and a CcBlock object. + * + * @param CcBlock $v + * @return CcShowStamp The current object (for fluent API support) + * @throws PropelException + */ + public function setCcBlock(CcBlock $v = null) + { + if ($v === null) { + $this->setDbBlockId(NULL); + } else { + $this->setDbBlockId($v->getDbId()); + } + + $this->aCcBlock = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the CcBlock object, it will not be re-added. + if ($v !== null) { + $v->addCcShowStamp($this); + } + + return $this; + } + + + /** + * Get the associated CcBlock object + * + * @param PropelPDO Optional Connection object. + * @return CcBlock The associated CcBlock object. + * @throws PropelException + */ + public function getCcBlock(PropelPDO $con = null) + { + if ($this->aCcBlock === null && ($this->block_id !== null)) { + $this->aCcBlock = CcBlockQuery::create()->findPk($this->block_id, $con); + /* The following can be used additionally to + guarantee the related object contains a reference + to this object. This level of coupling may, however, be + undesirable since it could result in an only partially populated collection + in the referenced object. + $this->aCcBlock->addCcShowStamps($this); + */ + } + return $this->aCcBlock; + } + + /** + * Declares an association between this object and a CcPlaylist object. + * + * @param CcPlaylist $v + * @return CcShowStamp The current object (for fluent API support) + * @throws PropelException + */ + public function setCcPlaylist(CcPlaylist $v = null) + { + if ($v === null) { + $this->setDbPlaylistId(NULL); + } else { + $this->setDbPlaylistId($v->getDbId()); + } + + $this->aCcPlaylist = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the CcPlaylist object, it will not be re-added. + if ($v !== null) { + $v->addCcShowStamp($this); + } + + return $this; + } + + + /** + * Get the associated CcPlaylist object + * + * @param PropelPDO Optional Connection object. + * @return CcPlaylist The associated CcPlaylist object. + * @throws PropelException + */ + public function getCcPlaylist(PropelPDO $con = null) + { + if ($this->aCcPlaylist === null && ($this->playlist_id !== null)) { + $this->aCcPlaylist = CcPlaylistQuery::create()->findPk($this->playlist_id, $con); + /* The following can be used additionally to + guarantee the related object contains a reference + to this object. This level of coupling may, however, be + undesirable since it could result in an only partially populated collection + in the referenced object. + $this->aCcPlaylist->addCcShowStamps($this); + */ + } + return $this->aCcPlaylist; + } + + /** + * Clears the current object and sets all attributes to their default values + */ + public function clear() + { + $this->id = null; + $this->show_id = null; + $this->instance_id = null; + $this->file_id = null; + $this->stream_id = null; + $this->block_id = null; + $this->playlist_id = null; + $this->position = null; + $this->clip_length = null; + $this->cue_in = null; + $this->cue_out = null; + $this->fade_in = null; + $this->fade_out = null; + $this->alreadyInSave = false; + $this->alreadyInValidation = false; + $this->clearAllReferences(); + $this->applyDefaultValues(); + $this->resetModified(); + $this->setNew(true); + $this->setDeleted(false); + } + + /** + * Resets all collections of referencing foreign keys. + * + * This method is a user-space workaround for PHP's inability to garbage collect objects + * with circular references. This is currently necessary when using Propel in certain + * daemon or large-volumne/high-memory operations. + * + * @param boolean $deep Whether to also clear the references on all associated objects. + */ + public function clearAllReferences($deep = false) + { + if ($deep) { + } // if ($deep) + + $this->aCcShow = null; + $this->aCcShowInstances = null; + $this->aCcFiles = null; + $this->aCcWebstream = null; + $this->aCcBlock = null; + $this->aCcPlaylist = null; + } + + /** + * Catches calls to virtual methods + */ + public function __call($name, $params) + { + if (preg_match('/get(\w+)/', $name, $matches)) { + $virtualColumn = $matches[1]; + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + // no lcfirst in php<5.3... + $virtualColumn[0] = strtolower($virtualColumn[0]); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + } + throw new PropelException('Call to undefined method: ' . $name); + } + +} // BaseCcShowStamp diff --git a/airtime_mvc/application/models/airtime/om/BaseCcShowStampPeer.php b/airtime_mvc/application/models/airtime/om/BaseCcShowStampPeer.php new file mode 100644 index 000000000..fb96eb0a7 --- /dev/null +++ b/airtime_mvc/application/models/airtime/om/BaseCcShowStampPeer.php @@ -0,0 +1,3095 @@ + array ('DbId', 'DbShowId', 'DbInstanceId', 'DbFileId', 'DbStreamId', 'DbBlockId', 'DbPlaylistId', 'DbPosition', 'DbClipLength', 'DbCueIn', 'DbCueOut', 'DbFadeIn', 'DbFadeOut', ), + BasePeer::TYPE_STUDLYPHPNAME => array ('dbId', 'dbShowId', 'dbInstanceId', 'dbFileId', 'dbStreamId', 'dbBlockId', 'dbPlaylistId', 'dbPosition', 'dbClipLength', 'dbCueIn', 'dbCueOut', 'dbFadeIn', 'dbFadeOut', ), + BasePeer::TYPE_COLNAME => array (self::ID, self::SHOW_ID, self::INSTANCE_ID, self::FILE_ID, self::STREAM_ID, self::BLOCK_ID, self::PLAYLIST_ID, self::POSITION, self::CLIP_LENGTH, self::CUE_IN, self::CUE_OUT, self::FADE_IN, self::FADE_OUT, ), + BasePeer::TYPE_RAW_COLNAME => array ('ID', 'SHOW_ID', 'INSTANCE_ID', 'FILE_ID', 'STREAM_ID', 'BLOCK_ID', 'PLAYLIST_ID', 'POSITION', 'CLIP_LENGTH', 'CUE_IN', 'CUE_OUT', 'FADE_IN', 'FADE_OUT', ), + BasePeer::TYPE_FIELDNAME => array ('id', 'show_id', 'instance_id', 'file_id', 'stream_id', 'block_id', 'playlist_id', 'position', 'clip_length', 'cue_in', 'cue_out', 'fade_in', 'fade_out', ), + BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, ) + ); + + /** + * holds an array of keys for quick access to the fieldnames array + * + * first dimension keys are the type constants + * e.g. self::$fieldNames[BasePeer::TYPE_PHPNAME]['Id'] = 0 + */ + private static $fieldKeys = array ( + BasePeer::TYPE_PHPNAME => array ('DbId' => 0, 'DbShowId' => 1, 'DbInstanceId' => 2, 'DbFileId' => 3, 'DbStreamId' => 4, 'DbBlockId' => 5, 'DbPlaylistId' => 6, 'DbPosition' => 7, 'DbClipLength' => 8, 'DbCueIn' => 9, 'DbCueOut' => 10, 'DbFadeIn' => 11, 'DbFadeOut' => 12, ), + BasePeer::TYPE_STUDLYPHPNAME => array ('dbId' => 0, 'dbShowId' => 1, 'dbInstanceId' => 2, 'dbFileId' => 3, 'dbStreamId' => 4, 'dbBlockId' => 5, 'dbPlaylistId' => 6, 'dbPosition' => 7, 'dbClipLength' => 8, 'dbCueIn' => 9, 'dbCueOut' => 10, 'dbFadeIn' => 11, 'dbFadeOut' => 12, ), + BasePeer::TYPE_COLNAME => array (self::ID => 0, self::SHOW_ID => 1, self::INSTANCE_ID => 2, self::FILE_ID => 3, self::STREAM_ID => 4, self::BLOCK_ID => 5, self::PLAYLIST_ID => 6, self::POSITION => 7, self::CLIP_LENGTH => 8, self::CUE_IN => 9, self::CUE_OUT => 10, self::FADE_IN => 11, self::FADE_OUT => 12, ), + BasePeer::TYPE_RAW_COLNAME => array ('ID' => 0, 'SHOW_ID' => 1, 'INSTANCE_ID' => 2, 'FILE_ID' => 3, 'STREAM_ID' => 4, 'BLOCK_ID' => 5, 'PLAYLIST_ID' => 6, 'POSITION' => 7, 'CLIP_LENGTH' => 8, 'CUE_IN' => 9, 'CUE_OUT' => 10, 'FADE_IN' => 11, 'FADE_OUT' => 12, ), + BasePeer::TYPE_FIELDNAME => array ('id' => 0, 'show_id' => 1, 'instance_id' => 2, 'file_id' => 3, 'stream_id' => 4, 'block_id' => 5, 'playlist_id' => 6, 'position' => 7, 'clip_length' => 8, 'cue_in' => 9, 'cue_out' => 10, 'fade_in' => 11, 'fade_out' => 12, ), + BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, ) + ); + + /** + * Translates a fieldname to another type + * + * @param string $name field name + * @param string $fromType One of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME + * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM + * @param string $toType One of the class type constants + * @return string translated name of the field. + * @throws PropelException - if the specified name could not be found in the fieldname mappings. + */ + static public function translateFieldName($name, $fromType, $toType) + { + $toNames = self::getFieldNames($toType); + $key = isset(self::$fieldKeys[$fromType][$name]) ? self::$fieldKeys[$fromType][$name] : null; + if ($key === null) { + throw new PropelException("'$name' could not be found in the field names of type '$fromType'. These are: " . print_r(self::$fieldKeys[$fromType], true)); + } + return $toNames[$key]; + } + + /** + * Returns an array of field names. + * + * @param string $type The type of fieldnames to return: + * One of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME + * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM + * @return array A list of field names + */ + + static public function getFieldNames($type = BasePeer::TYPE_PHPNAME) + { + if (!array_key_exists($type, self::$fieldNames)) { + throw new PropelException('Method getFieldNames() expects the parameter $type to be one of the class constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME, BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. ' . $type . ' was given.'); + } + return self::$fieldNames[$type]; + } + + /** + * Convenience method which changes table.column to alias.column. + * + * Using this method you can maintain SQL abstraction while using column aliases. + * + * $c->addAlias("alias1", TablePeer::TABLE_NAME); + * $c->addJoin(TablePeer::alias("alias1", TablePeer::PRIMARY_KEY_COLUMN), TablePeer::PRIMARY_KEY_COLUMN); + * + * @param string $alias The alias for the current table. + * @param string $column The column name for current table. (i.e. CcShowStampPeer::COLUMN_NAME). + * @return string + */ + public static function alias($alias, $column) + { + return str_replace(CcShowStampPeer::TABLE_NAME.'.', $alias.'.', $column); + } + + /** + * Add all the columns needed to create a new object. + * + * Note: any columns that were marked with lazyLoad="true" in the + * XML schema will not be added to the select list and only loaded + * on demand. + * + * @param Criteria $criteria object containing the columns to add. + * @param string $alias optional table alias + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function addSelectColumns(Criteria $criteria, $alias = null) + { + if (null === $alias) { + $criteria->addSelectColumn(CcShowStampPeer::ID); + $criteria->addSelectColumn(CcShowStampPeer::SHOW_ID); + $criteria->addSelectColumn(CcShowStampPeer::INSTANCE_ID); + $criteria->addSelectColumn(CcShowStampPeer::FILE_ID); + $criteria->addSelectColumn(CcShowStampPeer::STREAM_ID); + $criteria->addSelectColumn(CcShowStampPeer::BLOCK_ID); + $criteria->addSelectColumn(CcShowStampPeer::PLAYLIST_ID); + $criteria->addSelectColumn(CcShowStampPeer::POSITION); + $criteria->addSelectColumn(CcShowStampPeer::CLIP_LENGTH); + $criteria->addSelectColumn(CcShowStampPeer::CUE_IN); + $criteria->addSelectColumn(CcShowStampPeer::CUE_OUT); + $criteria->addSelectColumn(CcShowStampPeer::FADE_IN); + $criteria->addSelectColumn(CcShowStampPeer::FADE_OUT); + } else { + $criteria->addSelectColumn($alias . '.ID'); + $criteria->addSelectColumn($alias . '.SHOW_ID'); + $criteria->addSelectColumn($alias . '.INSTANCE_ID'); + $criteria->addSelectColumn($alias . '.FILE_ID'); + $criteria->addSelectColumn($alias . '.STREAM_ID'); + $criteria->addSelectColumn($alias . '.BLOCK_ID'); + $criteria->addSelectColumn($alias . '.PLAYLIST_ID'); + $criteria->addSelectColumn($alias . '.POSITION'); + $criteria->addSelectColumn($alias . '.CLIP_LENGTH'); + $criteria->addSelectColumn($alias . '.CUE_IN'); + $criteria->addSelectColumn($alias . '.CUE_OUT'); + $criteria->addSelectColumn($alias . '.FADE_IN'); + $criteria->addSelectColumn($alias . '.FADE_OUT'); + } + } + + /** + * Returns the number of rows matching criteria. + * + * @param Criteria $criteria + * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. + * @param PropelPDO $con + * @return int Number of matching rows. + */ + public static function doCount(Criteria $criteria, $distinct = false, PropelPDO $con = null) + { + // we may modify criteria, so copy it first + $criteria = clone $criteria; + + // We need to set the primary table name, since in the case that there are no WHERE columns + // it will be impossible for the BasePeer::createSelectSql() method to determine which + // tables go into the FROM clause. + $criteria->setPrimaryTableName(CcShowStampPeer::TABLE_NAME); + + if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->setDistinct(); + } + + if (!$criteria->hasSelectClause()) { + CcShowStampPeer::addSelectColumns($criteria); + } + + $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count + $criteria->setDbName(self::DATABASE_NAME); // Set the correct dbName + + if ($con === null) { + $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + // BasePeer returns a PDOStatement + $stmt = BasePeer::doCount($criteria, $con); + + if ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $count = (int) $row[0]; + } else { + $count = 0; // no rows returned; we infer that means 0 matches. + } + $stmt->closeCursor(); + return $count; + } + /** + * Method to select one object from the DB. + * + * @param Criteria $criteria object used to create the SELECT statement. + * @param PropelPDO $con + * @return CcShowStamp + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelectOne(Criteria $criteria, PropelPDO $con = null) + { + $critcopy = clone $criteria; + $critcopy->setLimit(1); + $objects = CcShowStampPeer::doSelect($critcopy, $con); + if ($objects) { + return $objects[0]; + } + return null; + } + /** + * Method to do selects. + * + * @param Criteria $criteria The Criteria object used to build the SELECT statement. + * @param PropelPDO $con + * @return array Array of selected Objects + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelect(Criteria $criteria, PropelPDO $con = null) + { + return CcShowStampPeer::populateObjects(CcShowStampPeer::doSelectStmt($criteria, $con)); + } + /** + * Prepares the Criteria object and uses the parent doSelect() method to execute a PDOStatement. + * + * Use this method directly if you want to work with an executed statement durirectly (for example + * to perform your own object hydration). + * + * @param Criteria $criteria The Criteria object used to build the SELECT statement. + * @param PropelPDO $con The connection to use + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + * @return PDOStatement The executed PDOStatement object. + * @see BasePeer::doSelect() + */ + public static function doSelectStmt(Criteria $criteria, PropelPDO $con = null) + { + if ($con === null) { + $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + if (!$criteria->hasSelectClause()) { + $criteria = clone $criteria; + CcShowStampPeer::addSelectColumns($criteria); + } + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + // BasePeer returns a PDOStatement + return BasePeer::doSelect($criteria, $con); + } + /** + * Adds an object to the instance pool. + * + * Propel keeps cached copies of objects in an instance pool when they are retrieved + * from the database. In some cases -- especially when you override doSelect*() + * methods in your stub classes -- you may need to explicitly add objects + * to the cache in order to ensure that the same objects are always returned by doSelect*() + * and retrieveByPK*() calls. + * + * @param CcShowStamp $value A CcShowStamp object. + * @param string $key (optional) key to use for instance map (for performance boost if key was already calculated externally). + */ + public static function addInstanceToPool(CcShowStamp $obj, $key = null) + { + if (Propel::isInstancePoolingEnabled()) { + if ($key === null) { + $key = (string) $obj->getDbId(); + } // if key === null + self::$instances[$key] = $obj; + } + } + + /** + * Removes an object from the instance pool. + * + * Propel keeps cached copies of objects in an instance pool when they are retrieved + * from the database. In some cases -- especially when you override doDelete + * methods in your stub classes -- you may need to explicitly remove objects + * from the cache in order to prevent returning objects that no longer exist. + * + * @param mixed $value A CcShowStamp object or a primary key value. + */ + public static function removeInstanceFromPool($value) + { + if (Propel::isInstancePoolingEnabled() && $value !== null) { + if (is_object($value) && $value instanceof CcShowStamp) { + $key = (string) $value->getDbId(); + } elseif (is_scalar($value)) { + // assume we've been passed a primary key + $key = (string) $value; + } else { + $e = new PropelException("Invalid value passed to removeInstanceFromPool(). Expected primary key or CcShowStamp object; got " . (is_object($value) ? get_class($value) . ' object.' : var_export($value,true))); + throw $e; + } + + unset(self::$instances[$key]); + } + } // removeInstanceFromPool() + + /** + * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table. + * + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, a serialize()d version of the primary key will be returned. + * + * @param string $key The key (@see getPrimaryKeyHash()) for this instance. + * @return CcShowStamp Found object or NULL if 1) no instance exists for specified key or 2) instance pooling has been disabled. + * @see getPrimaryKeyHash() + */ + public static function getInstanceFromPool($key) + { + if (Propel::isInstancePoolingEnabled()) { + if (isset(self::$instances[$key])) { + return self::$instances[$key]; + } + } + return null; // just to be explicit + } + + /** + * Clear the instance pool. + * + * @return void + */ + public static function clearInstancePool() + { + self::$instances = array(); + } + + /** + * Method to invalidate the instance pool of all tables related to cc_show_stamp + * by a foreign key with ON DELETE CASCADE + */ + public static function clearRelatedInstancePool() + { + } + + /** + * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table. + * + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, a serialize()d version of the primary key will be returned. + * + * @param array $row PropelPDO resultset row. + * @param int $startcol The 0-based offset for reading from the resultset row. + * @return string A string version of PK or NULL if the components of primary key in result array are all null. + */ + public static function getPrimaryKeyHashFromRow($row, $startcol = 0) + { + // If the PK cannot be derived from the row, return NULL. + if ($row[$startcol] === null) { + return null; + } + return (string) $row[$startcol]; + } + + /** + * Retrieves the primary key from the DB resultset row + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, an array of the primary key columns will be returned. + * + * @param array $row PropelPDO resultset row. + * @param int $startcol The 0-based offset for reading from the resultset row. + * @return mixed The primary key of the row + */ + public static function getPrimaryKeyFromRow($row, $startcol = 0) + { + return (int) $row[$startcol]; + } + + /** + * The returned array will contain objects of the default type or + * objects that inherit from the default. + * + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function populateObjects(PDOStatement $stmt) + { + $results = array(); + + // set the class once to avoid overhead in the loop + $cls = CcShowStampPeer::getOMClass(false); + // populate the object(s) + while ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $key = CcShowStampPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj = CcShowStampPeer::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, 0, true); // rehydrate + $results[] = $obj; + } else { + $obj = new $cls(); + $obj->hydrate($row); + $results[] = $obj; + CcShowStampPeer::addInstanceToPool($obj, $key); + } // if key exists + } + $stmt->closeCursor(); + return $results; + } + /** + * Populates an object of the default type or an object that inherit from the default. + * + * @param array $row PropelPDO resultset row. + * @param int $startcol The 0-based offset for reading from the resultset row. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + * @return array (CcShowStamp object, last column rank) + */ + public static function populateObject($row, $startcol = 0) + { + $key = CcShowStampPeer::getPrimaryKeyHashFromRow($row, $startcol); + if (null !== ($obj = CcShowStampPeer::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, $startcol, true); // rehydrate + $col = $startcol + CcShowStampPeer::NUM_COLUMNS; + } else { + $cls = CcShowStampPeer::OM_CLASS; + $obj = new $cls(); + $col = $obj->hydrate($row, $startcol); + CcShowStampPeer::addInstanceToPool($obj, $key); + } + return array($obj, $col); + } + + /** + * Returns the number of rows matching criteria, joining the related CcShow table + * + * @param Criteria $criteria + * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return int Number of matching rows. + */ + public static function doCountJoinCcShow(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + // we're going to modify criteria, so copy it first + $criteria = clone $criteria; + + // We need to set the primary table name, since in the case that there are no WHERE columns + // it will be impossible for the BasePeer::createSelectSql() method to determine which + // tables go into the FROM clause. + $criteria->setPrimaryTableName(CcShowStampPeer::TABLE_NAME); + + if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->setDistinct(); + } + + if (!$criteria->hasSelectClause()) { + CcShowStampPeer::addSelectColumns($criteria); + } + + $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + if ($con === null) { + $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $criteria->addJoin(CcShowStampPeer::SHOW_ID, CcShowPeer::ID, $join_behavior); + + $stmt = BasePeer::doCount($criteria, $con); + + if ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $count = (int) $row[0]; + } else { + $count = 0; // no rows returned; we infer that means 0 matches. + } + $stmt->closeCursor(); + return $count; + } + + + /** + * Returns the number of rows matching criteria, joining the related CcShowInstances table + * + * @param Criteria $criteria + * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return int Number of matching rows. + */ + public static function doCountJoinCcShowInstances(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + // we're going to modify criteria, so copy it first + $criteria = clone $criteria; + + // We need to set the primary table name, since in the case that there are no WHERE columns + // it will be impossible for the BasePeer::createSelectSql() method to determine which + // tables go into the FROM clause. + $criteria->setPrimaryTableName(CcShowStampPeer::TABLE_NAME); + + if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->setDistinct(); + } + + if (!$criteria->hasSelectClause()) { + CcShowStampPeer::addSelectColumns($criteria); + } + + $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + if ($con === null) { + $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $criteria->addJoin(CcShowStampPeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); + + $stmt = BasePeer::doCount($criteria, $con); + + if ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $count = (int) $row[0]; + } else { + $count = 0; // no rows returned; we infer that means 0 matches. + } + $stmt->closeCursor(); + return $count; + } + + + /** + * Returns the number of rows matching criteria, joining the related CcFiles table + * + * @param Criteria $criteria + * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return int Number of matching rows. + */ + public static function doCountJoinCcFiles(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + // we're going to modify criteria, so copy it first + $criteria = clone $criteria; + + // We need to set the primary table name, since in the case that there are no WHERE columns + // it will be impossible for the BasePeer::createSelectSql() method to determine which + // tables go into the FROM clause. + $criteria->setPrimaryTableName(CcShowStampPeer::TABLE_NAME); + + if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->setDistinct(); + } + + if (!$criteria->hasSelectClause()) { + CcShowStampPeer::addSelectColumns($criteria); + } + + $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + if ($con === null) { + $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $criteria->addJoin(CcShowStampPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + + $stmt = BasePeer::doCount($criteria, $con); + + if ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $count = (int) $row[0]; + } else { + $count = 0; // no rows returned; we infer that means 0 matches. + } + $stmt->closeCursor(); + return $count; + } + + + /** + * Returns the number of rows matching criteria, joining the related CcWebstream table + * + * @param Criteria $criteria + * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return int Number of matching rows. + */ + public static function doCountJoinCcWebstream(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + // we're going to modify criteria, so copy it first + $criteria = clone $criteria; + + // We need to set the primary table name, since in the case that there are no WHERE columns + // it will be impossible for the BasePeer::createSelectSql() method to determine which + // tables go into the FROM clause. + $criteria->setPrimaryTableName(CcShowStampPeer::TABLE_NAME); + + if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->setDistinct(); + } + + if (!$criteria->hasSelectClause()) { + CcShowStampPeer::addSelectColumns($criteria); + } + + $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + if ($con === null) { + $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $criteria->addJoin(CcShowStampPeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); + + $stmt = BasePeer::doCount($criteria, $con); + + if ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $count = (int) $row[0]; + } else { + $count = 0; // no rows returned; we infer that means 0 matches. + } + $stmt->closeCursor(); + return $count; + } + + + /** + * Returns the number of rows matching criteria, joining the related CcBlock table + * + * @param Criteria $criteria + * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return int Number of matching rows. + */ + public static function doCountJoinCcBlock(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + // we're going to modify criteria, so copy it first + $criteria = clone $criteria; + + // We need to set the primary table name, since in the case that there are no WHERE columns + // it will be impossible for the BasePeer::createSelectSql() method to determine which + // tables go into the FROM clause. + $criteria->setPrimaryTableName(CcShowStampPeer::TABLE_NAME); + + if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->setDistinct(); + } + + if (!$criteria->hasSelectClause()) { + CcShowStampPeer::addSelectColumns($criteria); + } + + $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + if ($con === null) { + $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $criteria->addJoin(CcShowStampPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); + + $stmt = BasePeer::doCount($criteria, $con); + + if ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $count = (int) $row[0]; + } else { + $count = 0; // no rows returned; we infer that means 0 matches. + } + $stmt->closeCursor(); + return $count; + } + + + /** + * Returns the number of rows matching criteria, joining the related CcPlaylist table + * + * @param Criteria $criteria + * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return int Number of matching rows. + */ + public static function doCountJoinCcPlaylist(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + // we're going to modify criteria, so copy it first + $criteria = clone $criteria; + + // We need to set the primary table name, since in the case that there are no WHERE columns + // it will be impossible for the BasePeer::createSelectSql() method to determine which + // tables go into the FROM clause. + $criteria->setPrimaryTableName(CcShowStampPeer::TABLE_NAME); + + if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->setDistinct(); + } + + if (!$criteria->hasSelectClause()) { + CcShowStampPeer::addSelectColumns($criteria); + } + + $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + if ($con === null) { + $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $criteria->addJoin(CcShowStampPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); + + $stmt = BasePeer::doCount($criteria, $con); + + if ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $count = (int) $row[0]; + } else { + $count = 0; // no rows returned; we infer that means 0 matches. + } + $stmt->closeCursor(); + return $count; + } + + + /** + * Selects a collection of CcShowStamp objects pre-filled with their CcShow objects. + * @param Criteria $criteria + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return array Array of CcShowStamp objects. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelectJoinCcShow(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $criteria = clone $criteria; + + // Set the correct dbName if it has not been overridden + if ($criteria->getDbName() == Propel::getDefaultDB()) { + $criteria->setDbName(self::DATABASE_NAME); + } + + CcShowStampPeer::addSelectColumns($criteria); + $startcol = (CcShowStampPeer::NUM_COLUMNS - CcShowStampPeer::NUM_LAZY_LOAD_COLUMNS); + CcShowPeer::addSelectColumns($criteria); + + $criteria->addJoin(CcShowStampPeer::SHOW_ID, CcShowPeer::ID, $join_behavior); + + $stmt = BasePeer::doSelect($criteria, $con); + $results = array(); + + while ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $key1 = CcShowStampPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcShowStampPeer::getInstanceFromPool($key1))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj1->hydrate($row, 0, true); // rehydrate + } else { + + $cls = CcShowStampPeer::getOMClass(false); + + $obj1 = new $cls(); + $obj1->hydrate($row); + CcShowStampPeer::addInstanceToPool($obj1, $key1); + } // if $obj1 already loaded + + $key2 = CcShowPeer::getPrimaryKeyHashFromRow($row, $startcol); + if ($key2 !== null) { + $obj2 = CcShowPeer::getInstanceFromPool($key2); + if (!$obj2) { + + $cls = CcShowPeer::getOMClass(false); + + $obj2 = new $cls(); + $obj2->hydrate($row, $startcol); + CcShowPeer::addInstanceToPool($obj2, $key2); + } // if obj2 already loaded + + // Add the $obj1 (CcShowStamp) to $obj2 (CcShow) + $obj2->addCcShowStamp($obj1); + + } // if joined row was not null + + $results[] = $obj1; + } + $stmt->closeCursor(); + return $results; + } + + + /** + * Selects a collection of CcShowStamp objects pre-filled with their CcShowInstances objects. + * @param Criteria $criteria + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return array Array of CcShowStamp objects. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelectJoinCcShowInstances(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $criteria = clone $criteria; + + // Set the correct dbName if it has not been overridden + if ($criteria->getDbName() == Propel::getDefaultDB()) { + $criteria->setDbName(self::DATABASE_NAME); + } + + CcShowStampPeer::addSelectColumns($criteria); + $startcol = (CcShowStampPeer::NUM_COLUMNS - CcShowStampPeer::NUM_LAZY_LOAD_COLUMNS); + CcShowInstancesPeer::addSelectColumns($criteria); + + $criteria->addJoin(CcShowStampPeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); + + $stmt = BasePeer::doSelect($criteria, $con); + $results = array(); + + while ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $key1 = CcShowStampPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcShowStampPeer::getInstanceFromPool($key1))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj1->hydrate($row, 0, true); // rehydrate + } else { + + $cls = CcShowStampPeer::getOMClass(false); + + $obj1 = new $cls(); + $obj1->hydrate($row); + CcShowStampPeer::addInstanceToPool($obj1, $key1); + } // if $obj1 already loaded + + $key2 = CcShowInstancesPeer::getPrimaryKeyHashFromRow($row, $startcol); + if ($key2 !== null) { + $obj2 = CcShowInstancesPeer::getInstanceFromPool($key2); + if (!$obj2) { + + $cls = CcShowInstancesPeer::getOMClass(false); + + $obj2 = new $cls(); + $obj2->hydrate($row, $startcol); + CcShowInstancesPeer::addInstanceToPool($obj2, $key2); + } // if obj2 already loaded + + // Add the $obj1 (CcShowStamp) to $obj2 (CcShowInstances) + $obj2->addCcShowStamp($obj1); + + } // if joined row was not null + + $results[] = $obj1; + } + $stmt->closeCursor(); + return $results; + } + + + /** + * Selects a collection of CcShowStamp objects pre-filled with their CcFiles objects. + * @param Criteria $criteria + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return array Array of CcShowStamp objects. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelectJoinCcFiles(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $criteria = clone $criteria; + + // Set the correct dbName if it has not been overridden + if ($criteria->getDbName() == Propel::getDefaultDB()) { + $criteria->setDbName(self::DATABASE_NAME); + } + + CcShowStampPeer::addSelectColumns($criteria); + $startcol = (CcShowStampPeer::NUM_COLUMNS - CcShowStampPeer::NUM_LAZY_LOAD_COLUMNS); + CcFilesPeer::addSelectColumns($criteria); + + $criteria->addJoin(CcShowStampPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + + $stmt = BasePeer::doSelect($criteria, $con); + $results = array(); + + while ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $key1 = CcShowStampPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcShowStampPeer::getInstanceFromPool($key1))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj1->hydrate($row, 0, true); // rehydrate + } else { + + $cls = CcShowStampPeer::getOMClass(false); + + $obj1 = new $cls(); + $obj1->hydrate($row); + CcShowStampPeer::addInstanceToPool($obj1, $key1); + } // if $obj1 already loaded + + $key2 = CcFilesPeer::getPrimaryKeyHashFromRow($row, $startcol); + if ($key2 !== null) { + $obj2 = CcFilesPeer::getInstanceFromPool($key2); + if (!$obj2) { + + $cls = CcFilesPeer::getOMClass(false); + + $obj2 = new $cls(); + $obj2->hydrate($row, $startcol); + CcFilesPeer::addInstanceToPool($obj2, $key2); + } // if obj2 already loaded + + // Add the $obj1 (CcShowStamp) to $obj2 (CcFiles) + $obj2->addCcShowStamp($obj1); + + } // if joined row was not null + + $results[] = $obj1; + } + $stmt->closeCursor(); + return $results; + } + + + /** + * Selects a collection of CcShowStamp objects pre-filled with their CcWebstream objects. + * @param Criteria $criteria + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return array Array of CcShowStamp objects. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelectJoinCcWebstream(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $criteria = clone $criteria; + + // Set the correct dbName if it has not been overridden + if ($criteria->getDbName() == Propel::getDefaultDB()) { + $criteria->setDbName(self::DATABASE_NAME); + } + + CcShowStampPeer::addSelectColumns($criteria); + $startcol = (CcShowStampPeer::NUM_COLUMNS - CcShowStampPeer::NUM_LAZY_LOAD_COLUMNS); + CcWebstreamPeer::addSelectColumns($criteria); + + $criteria->addJoin(CcShowStampPeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); + + $stmt = BasePeer::doSelect($criteria, $con); + $results = array(); + + while ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $key1 = CcShowStampPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcShowStampPeer::getInstanceFromPool($key1))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj1->hydrate($row, 0, true); // rehydrate + } else { + + $cls = CcShowStampPeer::getOMClass(false); + + $obj1 = new $cls(); + $obj1->hydrate($row); + CcShowStampPeer::addInstanceToPool($obj1, $key1); + } // if $obj1 already loaded + + $key2 = CcWebstreamPeer::getPrimaryKeyHashFromRow($row, $startcol); + if ($key2 !== null) { + $obj2 = CcWebstreamPeer::getInstanceFromPool($key2); + if (!$obj2) { + + $cls = CcWebstreamPeer::getOMClass(false); + + $obj2 = new $cls(); + $obj2->hydrate($row, $startcol); + CcWebstreamPeer::addInstanceToPool($obj2, $key2); + } // if obj2 already loaded + + // Add the $obj1 (CcShowStamp) to $obj2 (CcWebstream) + $obj2->addCcShowStamp($obj1); + + } // if joined row was not null + + $results[] = $obj1; + } + $stmt->closeCursor(); + return $results; + } + + + /** + * Selects a collection of CcShowStamp objects pre-filled with their CcBlock objects. + * @param Criteria $criteria + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return array Array of CcShowStamp objects. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelectJoinCcBlock(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $criteria = clone $criteria; + + // Set the correct dbName if it has not been overridden + if ($criteria->getDbName() == Propel::getDefaultDB()) { + $criteria->setDbName(self::DATABASE_NAME); + } + + CcShowStampPeer::addSelectColumns($criteria); + $startcol = (CcShowStampPeer::NUM_COLUMNS - CcShowStampPeer::NUM_LAZY_LOAD_COLUMNS); + CcBlockPeer::addSelectColumns($criteria); + + $criteria->addJoin(CcShowStampPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); + + $stmt = BasePeer::doSelect($criteria, $con); + $results = array(); + + while ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $key1 = CcShowStampPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcShowStampPeer::getInstanceFromPool($key1))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj1->hydrate($row, 0, true); // rehydrate + } else { + + $cls = CcShowStampPeer::getOMClass(false); + + $obj1 = new $cls(); + $obj1->hydrate($row); + CcShowStampPeer::addInstanceToPool($obj1, $key1); + } // if $obj1 already loaded + + $key2 = CcBlockPeer::getPrimaryKeyHashFromRow($row, $startcol); + if ($key2 !== null) { + $obj2 = CcBlockPeer::getInstanceFromPool($key2); + if (!$obj2) { + + $cls = CcBlockPeer::getOMClass(false); + + $obj2 = new $cls(); + $obj2->hydrate($row, $startcol); + CcBlockPeer::addInstanceToPool($obj2, $key2); + } // if obj2 already loaded + + // Add the $obj1 (CcShowStamp) to $obj2 (CcBlock) + $obj2->addCcShowStamp($obj1); + + } // if joined row was not null + + $results[] = $obj1; + } + $stmt->closeCursor(); + return $results; + } + + + /** + * Selects a collection of CcShowStamp objects pre-filled with their CcPlaylist objects. + * @param Criteria $criteria + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return array Array of CcShowStamp objects. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelectJoinCcPlaylist(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $criteria = clone $criteria; + + // Set the correct dbName if it has not been overridden + if ($criteria->getDbName() == Propel::getDefaultDB()) { + $criteria->setDbName(self::DATABASE_NAME); + } + + CcShowStampPeer::addSelectColumns($criteria); + $startcol = (CcShowStampPeer::NUM_COLUMNS - CcShowStampPeer::NUM_LAZY_LOAD_COLUMNS); + CcPlaylistPeer::addSelectColumns($criteria); + + $criteria->addJoin(CcShowStampPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); + + $stmt = BasePeer::doSelect($criteria, $con); + $results = array(); + + while ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $key1 = CcShowStampPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcShowStampPeer::getInstanceFromPool($key1))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj1->hydrate($row, 0, true); // rehydrate + } else { + + $cls = CcShowStampPeer::getOMClass(false); + + $obj1 = new $cls(); + $obj1->hydrate($row); + CcShowStampPeer::addInstanceToPool($obj1, $key1); + } // if $obj1 already loaded + + $key2 = CcPlaylistPeer::getPrimaryKeyHashFromRow($row, $startcol); + if ($key2 !== null) { + $obj2 = CcPlaylistPeer::getInstanceFromPool($key2); + if (!$obj2) { + + $cls = CcPlaylistPeer::getOMClass(false); + + $obj2 = new $cls(); + $obj2->hydrate($row, $startcol); + CcPlaylistPeer::addInstanceToPool($obj2, $key2); + } // if obj2 already loaded + + // Add the $obj1 (CcShowStamp) to $obj2 (CcPlaylist) + $obj2->addCcShowStamp($obj1); + + } // if joined row was not null + + $results[] = $obj1; + } + $stmt->closeCursor(); + return $results; + } + + + /** + * Returns the number of rows matching criteria, joining all related tables + * + * @param Criteria $criteria + * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return int Number of matching rows. + */ + public static function doCountJoinAll(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + // we're going to modify criteria, so copy it first + $criteria = clone $criteria; + + // We need to set the primary table name, since in the case that there are no WHERE columns + // it will be impossible for the BasePeer::createSelectSql() method to determine which + // tables go into the FROM clause. + $criteria->setPrimaryTableName(CcShowStampPeer::TABLE_NAME); + + if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->setDistinct(); + } + + if (!$criteria->hasSelectClause()) { + CcShowStampPeer::addSelectColumns($criteria); + } + + $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + if ($con === null) { + $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $criteria->addJoin(CcShowStampPeer::SHOW_ID, CcShowPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); + + $stmt = BasePeer::doCount($criteria, $con); + + if ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $count = (int) $row[0]; + } else { + $count = 0; // no rows returned; we infer that means 0 matches. + } + $stmt->closeCursor(); + return $count; + } + + /** + * Selects a collection of CcShowStamp objects pre-filled with all related objects. + * + * @param Criteria $criteria + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return array Array of CcShowStamp objects. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelectJoinAll(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $criteria = clone $criteria; + + // Set the correct dbName if it has not been overridden + if ($criteria->getDbName() == Propel::getDefaultDB()) { + $criteria->setDbName(self::DATABASE_NAME); + } + + CcShowStampPeer::addSelectColumns($criteria); + $startcol2 = (CcShowStampPeer::NUM_COLUMNS - CcShowStampPeer::NUM_LAZY_LOAD_COLUMNS); + + CcShowPeer::addSelectColumns($criteria); + $startcol3 = $startcol2 + (CcShowPeer::NUM_COLUMNS - CcShowPeer::NUM_LAZY_LOAD_COLUMNS); + + CcShowInstancesPeer::addSelectColumns($criteria); + $startcol4 = $startcol3 + (CcShowInstancesPeer::NUM_COLUMNS - CcShowInstancesPeer::NUM_LAZY_LOAD_COLUMNS); + + CcFilesPeer::addSelectColumns($criteria); + $startcol5 = $startcol4 + (CcFilesPeer::NUM_COLUMNS - CcFilesPeer::NUM_LAZY_LOAD_COLUMNS); + + CcWebstreamPeer::addSelectColumns($criteria); + $startcol6 = $startcol5 + (CcWebstreamPeer::NUM_COLUMNS - CcWebstreamPeer::NUM_LAZY_LOAD_COLUMNS); + + CcBlockPeer::addSelectColumns($criteria); + $startcol7 = $startcol6 + (CcBlockPeer::NUM_COLUMNS - CcBlockPeer::NUM_LAZY_LOAD_COLUMNS); + + CcPlaylistPeer::addSelectColumns($criteria); + $startcol8 = $startcol7 + (CcPlaylistPeer::NUM_COLUMNS - CcPlaylistPeer::NUM_LAZY_LOAD_COLUMNS); + + $criteria->addJoin(CcShowStampPeer::SHOW_ID, CcShowPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); + + $stmt = BasePeer::doSelect($criteria, $con); + $results = array(); + + while ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $key1 = CcShowStampPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcShowStampPeer::getInstanceFromPool($key1))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj1->hydrate($row, 0, true); // rehydrate + } else { + $cls = CcShowStampPeer::getOMClass(false); + + $obj1 = new $cls(); + $obj1->hydrate($row); + CcShowStampPeer::addInstanceToPool($obj1, $key1); + } // if obj1 already loaded + + // Add objects for joined CcShow rows + + $key2 = CcShowPeer::getPrimaryKeyHashFromRow($row, $startcol2); + if ($key2 !== null) { + $obj2 = CcShowPeer::getInstanceFromPool($key2); + if (!$obj2) { + + $cls = CcShowPeer::getOMClass(false); + + $obj2 = new $cls(); + $obj2->hydrate($row, $startcol2); + CcShowPeer::addInstanceToPool($obj2, $key2); + } // if obj2 loaded + + // Add the $obj1 (CcShowStamp) to the collection in $obj2 (CcShow) + $obj2->addCcShowStamp($obj1); + } // if joined row not null + + // Add objects for joined CcShowInstances rows + + $key3 = CcShowInstancesPeer::getPrimaryKeyHashFromRow($row, $startcol3); + if ($key3 !== null) { + $obj3 = CcShowInstancesPeer::getInstanceFromPool($key3); + if (!$obj3) { + + $cls = CcShowInstancesPeer::getOMClass(false); + + $obj3 = new $cls(); + $obj3->hydrate($row, $startcol3); + CcShowInstancesPeer::addInstanceToPool($obj3, $key3); + } // if obj3 loaded + + // Add the $obj1 (CcShowStamp) to the collection in $obj3 (CcShowInstances) + $obj3->addCcShowStamp($obj1); + } // if joined row not null + + // Add objects for joined CcFiles rows + + $key4 = CcFilesPeer::getPrimaryKeyHashFromRow($row, $startcol4); + if ($key4 !== null) { + $obj4 = CcFilesPeer::getInstanceFromPool($key4); + if (!$obj4) { + + $cls = CcFilesPeer::getOMClass(false); + + $obj4 = new $cls(); + $obj4->hydrate($row, $startcol4); + CcFilesPeer::addInstanceToPool($obj4, $key4); + } // if obj4 loaded + + // Add the $obj1 (CcShowStamp) to the collection in $obj4 (CcFiles) + $obj4->addCcShowStamp($obj1); + } // if joined row not null + + // Add objects for joined CcWebstream rows + + $key5 = CcWebstreamPeer::getPrimaryKeyHashFromRow($row, $startcol5); + if ($key5 !== null) { + $obj5 = CcWebstreamPeer::getInstanceFromPool($key5); + if (!$obj5) { + + $cls = CcWebstreamPeer::getOMClass(false); + + $obj5 = new $cls(); + $obj5->hydrate($row, $startcol5); + CcWebstreamPeer::addInstanceToPool($obj5, $key5); + } // if obj5 loaded + + // Add the $obj1 (CcShowStamp) to the collection in $obj5 (CcWebstream) + $obj5->addCcShowStamp($obj1); + } // if joined row not null + + // Add objects for joined CcBlock rows + + $key6 = CcBlockPeer::getPrimaryKeyHashFromRow($row, $startcol6); + if ($key6 !== null) { + $obj6 = CcBlockPeer::getInstanceFromPool($key6); + if (!$obj6) { + + $cls = CcBlockPeer::getOMClass(false); + + $obj6 = new $cls(); + $obj6->hydrate($row, $startcol6); + CcBlockPeer::addInstanceToPool($obj6, $key6); + } // if obj6 loaded + + // Add the $obj1 (CcShowStamp) to the collection in $obj6 (CcBlock) + $obj6->addCcShowStamp($obj1); + } // if joined row not null + + // Add objects for joined CcPlaylist rows + + $key7 = CcPlaylistPeer::getPrimaryKeyHashFromRow($row, $startcol7); + if ($key7 !== null) { + $obj7 = CcPlaylistPeer::getInstanceFromPool($key7); + if (!$obj7) { + + $cls = CcPlaylistPeer::getOMClass(false); + + $obj7 = new $cls(); + $obj7->hydrate($row, $startcol7); + CcPlaylistPeer::addInstanceToPool($obj7, $key7); + } // if obj7 loaded + + // Add the $obj1 (CcShowStamp) to the collection in $obj7 (CcPlaylist) + $obj7->addCcShowStamp($obj1); + } // if joined row not null + + $results[] = $obj1; + } + $stmt->closeCursor(); + return $results; + } + + + /** + * Returns the number of rows matching criteria, joining the related CcShow table + * + * @param Criteria $criteria + * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return int Number of matching rows. + */ + public static function doCountJoinAllExceptCcShow(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + // we're going to modify criteria, so copy it first + $criteria = clone $criteria; + + // We need to set the primary table name, since in the case that there are no WHERE columns + // it will be impossible for the BasePeer::createSelectSql() method to determine which + // tables go into the FROM clause. + $criteria->setPrimaryTableName(CcShowStampPeer::TABLE_NAME); + + if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->setDistinct(); + } + + if (!$criteria->hasSelectClause()) { + CcShowStampPeer::addSelectColumns($criteria); + } + + $criteria->clearOrderByColumns(); // ORDER BY should not affect count + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + if ($con === null) { + $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $criteria->addJoin(CcShowStampPeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); + + $stmt = BasePeer::doCount($criteria, $con); + + if ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $count = (int) $row[0]; + } else { + $count = 0; // no rows returned; we infer that means 0 matches. + } + $stmt->closeCursor(); + return $count; + } + + + /** + * Returns the number of rows matching criteria, joining the related CcShowInstances table + * + * @param Criteria $criteria + * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return int Number of matching rows. + */ + public static function doCountJoinAllExceptCcShowInstances(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + // we're going to modify criteria, so copy it first + $criteria = clone $criteria; + + // We need to set the primary table name, since in the case that there are no WHERE columns + // it will be impossible for the BasePeer::createSelectSql() method to determine which + // tables go into the FROM clause. + $criteria->setPrimaryTableName(CcShowStampPeer::TABLE_NAME); + + if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->setDistinct(); + } + + if (!$criteria->hasSelectClause()) { + CcShowStampPeer::addSelectColumns($criteria); + } + + $criteria->clearOrderByColumns(); // ORDER BY should not affect count + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + if ($con === null) { + $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $criteria->addJoin(CcShowStampPeer::SHOW_ID, CcShowPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); + + $stmt = BasePeer::doCount($criteria, $con); + + if ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $count = (int) $row[0]; + } else { + $count = 0; // no rows returned; we infer that means 0 matches. + } + $stmt->closeCursor(); + return $count; + } + + + /** + * Returns the number of rows matching criteria, joining the related CcFiles table + * + * @param Criteria $criteria + * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return int Number of matching rows. + */ + public static function doCountJoinAllExceptCcFiles(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + // we're going to modify criteria, so copy it first + $criteria = clone $criteria; + + // We need to set the primary table name, since in the case that there are no WHERE columns + // it will be impossible for the BasePeer::createSelectSql() method to determine which + // tables go into the FROM clause. + $criteria->setPrimaryTableName(CcShowStampPeer::TABLE_NAME); + + if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->setDistinct(); + } + + if (!$criteria->hasSelectClause()) { + CcShowStampPeer::addSelectColumns($criteria); + } + + $criteria->clearOrderByColumns(); // ORDER BY should not affect count + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + if ($con === null) { + $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $criteria->addJoin(CcShowStampPeer::SHOW_ID, CcShowPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); + + $stmt = BasePeer::doCount($criteria, $con); + + if ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $count = (int) $row[0]; + } else { + $count = 0; // no rows returned; we infer that means 0 matches. + } + $stmt->closeCursor(); + return $count; + } + + + /** + * Returns the number of rows matching criteria, joining the related CcWebstream table + * + * @param Criteria $criteria + * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return int Number of matching rows. + */ + public static function doCountJoinAllExceptCcWebstream(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + // we're going to modify criteria, so copy it first + $criteria = clone $criteria; + + // We need to set the primary table name, since in the case that there are no WHERE columns + // it will be impossible for the BasePeer::createSelectSql() method to determine which + // tables go into the FROM clause. + $criteria->setPrimaryTableName(CcShowStampPeer::TABLE_NAME); + + if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->setDistinct(); + } + + if (!$criteria->hasSelectClause()) { + CcShowStampPeer::addSelectColumns($criteria); + } + + $criteria->clearOrderByColumns(); // ORDER BY should not affect count + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + if ($con === null) { + $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $criteria->addJoin(CcShowStampPeer::SHOW_ID, CcShowPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); + + $stmt = BasePeer::doCount($criteria, $con); + + if ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $count = (int) $row[0]; + } else { + $count = 0; // no rows returned; we infer that means 0 matches. + } + $stmt->closeCursor(); + return $count; + } + + + /** + * Returns the number of rows matching criteria, joining the related CcBlock table + * + * @param Criteria $criteria + * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return int Number of matching rows. + */ + public static function doCountJoinAllExceptCcBlock(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + // we're going to modify criteria, so copy it first + $criteria = clone $criteria; + + // We need to set the primary table name, since in the case that there are no WHERE columns + // it will be impossible for the BasePeer::createSelectSql() method to determine which + // tables go into the FROM clause. + $criteria->setPrimaryTableName(CcShowStampPeer::TABLE_NAME); + + if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->setDistinct(); + } + + if (!$criteria->hasSelectClause()) { + CcShowStampPeer::addSelectColumns($criteria); + } + + $criteria->clearOrderByColumns(); // ORDER BY should not affect count + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + if ($con === null) { + $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $criteria->addJoin(CcShowStampPeer::SHOW_ID, CcShowPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); + + $stmt = BasePeer::doCount($criteria, $con); + + if ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $count = (int) $row[0]; + } else { + $count = 0; // no rows returned; we infer that means 0 matches. + } + $stmt->closeCursor(); + return $count; + } + + + /** + * Returns the number of rows matching criteria, joining the related CcPlaylist table + * + * @param Criteria $criteria + * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return int Number of matching rows. + */ + public static function doCountJoinAllExceptCcPlaylist(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + // we're going to modify criteria, so copy it first + $criteria = clone $criteria; + + // We need to set the primary table name, since in the case that there are no WHERE columns + // it will be impossible for the BasePeer::createSelectSql() method to determine which + // tables go into the FROM clause. + $criteria->setPrimaryTableName(CcShowStampPeer::TABLE_NAME); + + if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->setDistinct(); + } + + if (!$criteria->hasSelectClause()) { + CcShowStampPeer::addSelectColumns($criteria); + } + + $criteria->clearOrderByColumns(); // ORDER BY should not affect count + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + if ($con === null) { + $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $criteria->addJoin(CcShowStampPeer::SHOW_ID, CcShowPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); + + $stmt = BasePeer::doCount($criteria, $con); + + if ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $count = (int) $row[0]; + } else { + $count = 0; // no rows returned; we infer that means 0 matches. + } + $stmt->closeCursor(); + return $count; + } + + + /** + * Selects a collection of CcShowStamp objects pre-filled with all related objects except CcShow. + * + * @param Criteria $criteria + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return array Array of CcShowStamp objects. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelectJoinAllExceptCcShow(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $criteria = clone $criteria; + + // Set the correct dbName if it has not been overridden + // $criteria->getDbName() will return the same object if not set to another value + // so == check is okay and faster + if ($criteria->getDbName() == Propel::getDefaultDB()) { + $criteria->setDbName(self::DATABASE_NAME); + } + + CcShowStampPeer::addSelectColumns($criteria); + $startcol2 = (CcShowStampPeer::NUM_COLUMNS - CcShowStampPeer::NUM_LAZY_LOAD_COLUMNS); + + CcShowInstancesPeer::addSelectColumns($criteria); + $startcol3 = $startcol2 + (CcShowInstancesPeer::NUM_COLUMNS - CcShowInstancesPeer::NUM_LAZY_LOAD_COLUMNS); + + CcFilesPeer::addSelectColumns($criteria); + $startcol4 = $startcol3 + (CcFilesPeer::NUM_COLUMNS - CcFilesPeer::NUM_LAZY_LOAD_COLUMNS); + + CcWebstreamPeer::addSelectColumns($criteria); + $startcol5 = $startcol4 + (CcWebstreamPeer::NUM_COLUMNS - CcWebstreamPeer::NUM_LAZY_LOAD_COLUMNS); + + CcBlockPeer::addSelectColumns($criteria); + $startcol6 = $startcol5 + (CcBlockPeer::NUM_COLUMNS - CcBlockPeer::NUM_LAZY_LOAD_COLUMNS); + + CcPlaylistPeer::addSelectColumns($criteria); + $startcol7 = $startcol6 + (CcPlaylistPeer::NUM_COLUMNS - CcPlaylistPeer::NUM_LAZY_LOAD_COLUMNS); + + $criteria->addJoin(CcShowStampPeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); + + + $stmt = BasePeer::doSelect($criteria, $con); + $results = array(); + + while ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $key1 = CcShowStampPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcShowStampPeer::getInstanceFromPool($key1))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj1->hydrate($row, 0, true); // rehydrate + } else { + $cls = CcShowStampPeer::getOMClass(false); + + $obj1 = new $cls(); + $obj1->hydrate($row); + CcShowStampPeer::addInstanceToPool($obj1, $key1); + } // if obj1 already loaded + + // Add objects for joined CcShowInstances rows + + $key2 = CcShowInstancesPeer::getPrimaryKeyHashFromRow($row, $startcol2); + if ($key2 !== null) { + $obj2 = CcShowInstancesPeer::getInstanceFromPool($key2); + if (!$obj2) { + + $cls = CcShowInstancesPeer::getOMClass(false); + + $obj2 = new $cls(); + $obj2->hydrate($row, $startcol2); + CcShowInstancesPeer::addInstanceToPool($obj2, $key2); + } // if $obj2 already loaded + + // Add the $obj1 (CcShowStamp) to the collection in $obj2 (CcShowInstances) + $obj2->addCcShowStamp($obj1); + + } // if joined row is not null + + // Add objects for joined CcFiles rows + + $key3 = CcFilesPeer::getPrimaryKeyHashFromRow($row, $startcol3); + if ($key3 !== null) { + $obj3 = CcFilesPeer::getInstanceFromPool($key3); + if (!$obj3) { + + $cls = CcFilesPeer::getOMClass(false); + + $obj3 = new $cls(); + $obj3->hydrate($row, $startcol3); + CcFilesPeer::addInstanceToPool($obj3, $key3); + } // if $obj3 already loaded + + // Add the $obj1 (CcShowStamp) to the collection in $obj3 (CcFiles) + $obj3->addCcShowStamp($obj1); + + } // if joined row is not null + + // Add objects for joined CcWebstream rows + + $key4 = CcWebstreamPeer::getPrimaryKeyHashFromRow($row, $startcol4); + if ($key4 !== null) { + $obj4 = CcWebstreamPeer::getInstanceFromPool($key4); + if (!$obj4) { + + $cls = CcWebstreamPeer::getOMClass(false); + + $obj4 = new $cls(); + $obj4->hydrate($row, $startcol4); + CcWebstreamPeer::addInstanceToPool($obj4, $key4); + } // if $obj4 already loaded + + // Add the $obj1 (CcShowStamp) to the collection in $obj4 (CcWebstream) + $obj4->addCcShowStamp($obj1); + + } // if joined row is not null + + // Add objects for joined CcBlock rows + + $key5 = CcBlockPeer::getPrimaryKeyHashFromRow($row, $startcol5); + if ($key5 !== null) { + $obj5 = CcBlockPeer::getInstanceFromPool($key5); + if (!$obj5) { + + $cls = CcBlockPeer::getOMClass(false); + + $obj5 = new $cls(); + $obj5->hydrate($row, $startcol5); + CcBlockPeer::addInstanceToPool($obj5, $key5); + } // if $obj5 already loaded + + // Add the $obj1 (CcShowStamp) to the collection in $obj5 (CcBlock) + $obj5->addCcShowStamp($obj1); + + } // if joined row is not null + + // Add objects for joined CcPlaylist rows + + $key6 = CcPlaylistPeer::getPrimaryKeyHashFromRow($row, $startcol6); + if ($key6 !== null) { + $obj6 = CcPlaylistPeer::getInstanceFromPool($key6); + if (!$obj6) { + + $cls = CcPlaylistPeer::getOMClass(false); + + $obj6 = new $cls(); + $obj6->hydrate($row, $startcol6); + CcPlaylistPeer::addInstanceToPool($obj6, $key6); + } // if $obj6 already loaded + + // Add the $obj1 (CcShowStamp) to the collection in $obj6 (CcPlaylist) + $obj6->addCcShowStamp($obj1); + + } // if joined row is not null + + $results[] = $obj1; + } + $stmt->closeCursor(); + return $results; + } + + + /** + * Selects a collection of CcShowStamp objects pre-filled with all related objects except CcShowInstances. + * + * @param Criteria $criteria + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return array Array of CcShowStamp objects. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelectJoinAllExceptCcShowInstances(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $criteria = clone $criteria; + + // Set the correct dbName if it has not been overridden + // $criteria->getDbName() will return the same object if not set to another value + // so == check is okay and faster + if ($criteria->getDbName() == Propel::getDefaultDB()) { + $criteria->setDbName(self::DATABASE_NAME); + } + + CcShowStampPeer::addSelectColumns($criteria); + $startcol2 = (CcShowStampPeer::NUM_COLUMNS - CcShowStampPeer::NUM_LAZY_LOAD_COLUMNS); + + CcShowPeer::addSelectColumns($criteria); + $startcol3 = $startcol2 + (CcShowPeer::NUM_COLUMNS - CcShowPeer::NUM_LAZY_LOAD_COLUMNS); + + CcFilesPeer::addSelectColumns($criteria); + $startcol4 = $startcol3 + (CcFilesPeer::NUM_COLUMNS - CcFilesPeer::NUM_LAZY_LOAD_COLUMNS); + + CcWebstreamPeer::addSelectColumns($criteria); + $startcol5 = $startcol4 + (CcWebstreamPeer::NUM_COLUMNS - CcWebstreamPeer::NUM_LAZY_LOAD_COLUMNS); + + CcBlockPeer::addSelectColumns($criteria); + $startcol6 = $startcol5 + (CcBlockPeer::NUM_COLUMNS - CcBlockPeer::NUM_LAZY_LOAD_COLUMNS); + + CcPlaylistPeer::addSelectColumns($criteria); + $startcol7 = $startcol6 + (CcPlaylistPeer::NUM_COLUMNS - CcPlaylistPeer::NUM_LAZY_LOAD_COLUMNS); + + $criteria->addJoin(CcShowStampPeer::SHOW_ID, CcShowPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); + + + $stmt = BasePeer::doSelect($criteria, $con); + $results = array(); + + while ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $key1 = CcShowStampPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcShowStampPeer::getInstanceFromPool($key1))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj1->hydrate($row, 0, true); // rehydrate + } else { + $cls = CcShowStampPeer::getOMClass(false); + + $obj1 = new $cls(); + $obj1->hydrate($row); + CcShowStampPeer::addInstanceToPool($obj1, $key1); + } // if obj1 already loaded + + // Add objects for joined CcShow rows + + $key2 = CcShowPeer::getPrimaryKeyHashFromRow($row, $startcol2); + if ($key2 !== null) { + $obj2 = CcShowPeer::getInstanceFromPool($key2); + if (!$obj2) { + + $cls = CcShowPeer::getOMClass(false); + + $obj2 = new $cls(); + $obj2->hydrate($row, $startcol2); + CcShowPeer::addInstanceToPool($obj2, $key2); + } // if $obj2 already loaded + + // Add the $obj1 (CcShowStamp) to the collection in $obj2 (CcShow) + $obj2->addCcShowStamp($obj1); + + } // if joined row is not null + + // Add objects for joined CcFiles rows + + $key3 = CcFilesPeer::getPrimaryKeyHashFromRow($row, $startcol3); + if ($key3 !== null) { + $obj3 = CcFilesPeer::getInstanceFromPool($key3); + if (!$obj3) { + + $cls = CcFilesPeer::getOMClass(false); + + $obj3 = new $cls(); + $obj3->hydrate($row, $startcol3); + CcFilesPeer::addInstanceToPool($obj3, $key3); + } // if $obj3 already loaded + + // Add the $obj1 (CcShowStamp) to the collection in $obj3 (CcFiles) + $obj3->addCcShowStamp($obj1); + + } // if joined row is not null + + // Add objects for joined CcWebstream rows + + $key4 = CcWebstreamPeer::getPrimaryKeyHashFromRow($row, $startcol4); + if ($key4 !== null) { + $obj4 = CcWebstreamPeer::getInstanceFromPool($key4); + if (!$obj4) { + + $cls = CcWebstreamPeer::getOMClass(false); + + $obj4 = new $cls(); + $obj4->hydrate($row, $startcol4); + CcWebstreamPeer::addInstanceToPool($obj4, $key4); + } // if $obj4 already loaded + + // Add the $obj1 (CcShowStamp) to the collection in $obj4 (CcWebstream) + $obj4->addCcShowStamp($obj1); + + } // if joined row is not null + + // Add objects for joined CcBlock rows + + $key5 = CcBlockPeer::getPrimaryKeyHashFromRow($row, $startcol5); + if ($key5 !== null) { + $obj5 = CcBlockPeer::getInstanceFromPool($key5); + if (!$obj5) { + + $cls = CcBlockPeer::getOMClass(false); + + $obj5 = new $cls(); + $obj5->hydrate($row, $startcol5); + CcBlockPeer::addInstanceToPool($obj5, $key5); + } // if $obj5 already loaded + + // Add the $obj1 (CcShowStamp) to the collection in $obj5 (CcBlock) + $obj5->addCcShowStamp($obj1); + + } // if joined row is not null + + // Add objects for joined CcPlaylist rows + + $key6 = CcPlaylistPeer::getPrimaryKeyHashFromRow($row, $startcol6); + if ($key6 !== null) { + $obj6 = CcPlaylistPeer::getInstanceFromPool($key6); + if (!$obj6) { + + $cls = CcPlaylistPeer::getOMClass(false); + + $obj6 = new $cls(); + $obj6->hydrate($row, $startcol6); + CcPlaylistPeer::addInstanceToPool($obj6, $key6); + } // if $obj6 already loaded + + // Add the $obj1 (CcShowStamp) to the collection in $obj6 (CcPlaylist) + $obj6->addCcShowStamp($obj1); + + } // if joined row is not null + + $results[] = $obj1; + } + $stmt->closeCursor(); + return $results; + } + + + /** + * Selects a collection of CcShowStamp objects pre-filled with all related objects except CcFiles. + * + * @param Criteria $criteria + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return array Array of CcShowStamp objects. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelectJoinAllExceptCcFiles(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $criteria = clone $criteria; + + // Set the correct dbName if it has not been overridden + // $criteria->getDbName() will return the same object if not set to another value + // so == check is okay and faster + if ($criteria->getDbName() == Propel::getDefaultDB()) { + $criteria->setDbName(self::DATABASE_NAME); + } + + CcShowStampPeer::addSelectColumns($criteria); + $startcol2 = (CcShowStampPeer::NUM_COLUMNS - CcShowStampPeer::NUM_LAZY_LOAD_COLUMNS); + + CcShowPeer::addSelectColumns($criteria); + $startcol3 = $startcol2 + (CcShowPeer::NUM_COLUMNS - CcShowPeer::NUM_LAZY_LOAD_COLUMNS); + + CcShowInstancesPeer::addSelectColumns($criteria); + $startcol4 = $startcol3 + (CcShowInstancesPeer::NUM_COLUMNS - CcShowInstancesPeer::NUM_LAZY_LOAD_COLUMNS); + + CcWebstreamPeer::addSelectColumns($criteria); + $startcol5 = $startcol4 + (CcWebstreamPeer::NUM_COLUMNS - CcWebstreamPeer::NUM_LAZY_LOAD_COLUMNS); + + CcBlockPeer::addSelectColumns($criteria); + $startcol6 = $startcol5 + (CcBlockPeer::NUM_COLUMNS - CcBlockPeer::NUM_LAZY_LOAD_COLUMNS); + + CcPlaylistPeer::addSelectColumns($criteria); + $startcol7 = $startcol6 + (CcPlaylistPeer::NUM_COLUMNS - CcPlaylistPeer::NUM_LAZY_LOAD_COLUMNS); + + $criteria->addJoin(CcShowStampPeer::SHOW_ID, CcShowPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); + + + $stmt = BasePeer::doSelect($criteria, $con); + $results = array(); + + while ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $key1 = CcShowStampPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcShowStampPeer::getInstanceFromPool($key1))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj1->hydrate($row, 0, true); // rehydrate + } else { + $cls = CcShowStampPeer::getOMClass(false); + + $obj1 = new $cls(); + $obj1->hydrate($row); + CcShowStampPeer::addInstanceToPool($obj1, $key1); + } // if obj1 already loaded + + // Add objects for joined CcShow rows + + $key2 = CcShowPeer::getPrimaryKeyHashFromRow($row, $startcol2); + if ($key2 !== null) { + $obj2 = CcShowPeer::getInstanceFromPool($key2); + if (!$obj2) { + + $cls = CcShowPeer::getOMClass(false); + + $obj2 = new $cls(); + $obj2->hydrate($row, $startcol2); + CcShowPeer::addInstanceToPool($obj2, $key2); + } // if $obj2 already loaded + + // Add the $obj1 (CcShowStamp) to the collection in $obj2 (CcShow) + $obj2->addCcShowStamp($obj1); + + } // if joined row is not null + + // Add objects for joined CcShowInstances rows + + $key3 = CcShowInstancesPeer::getPrimaryKeyHashFromRow($row, $startcol3); + if ($key3 !== null) { + $obj3 = CcShowInstancesPeer::getInstanceFromPool($key3); + if (!$obj3) { + + $cls = CcShowInstancesPeer::getOMClass(false); + + $obj3 = new $cls(); + $obj3->hydrate($row, $startcol3); + CcShowInstancesPeer::addInstanceToPool($obj3, $key3); + } // if $obj3 already loaded + + // Add the $obj1 (CcShowStamp) to the collection in $obj3 (CcShowInstances) + $obj3->addCcShowStamp($obj1); + + } // if joined row is not null + + // Add objects for joined CcWebstream rows + + $key4 = CcWebstreamPeer::getPrimaryKeyHashFromRow($row, $startcol4); + if ($key4 !== null) { + $obj4 = CcWebstreamPeer::getInstanceFromPool($key4); + if (!$obj4) { + + $cls = CcWebstreamPeer::getOMClass(false); + + $obj4 = new $cls(); + $obj4->hydrate($row, $startcol4); + CcWebstreamPeer::addInstanceToPool($obj4, $key4); + } // if $obj4 already loaded + + // Add the $obj1 (CcShowStamp) to the collection in $obj4 (CcWebstream) + $obj4->addCcShowStamp($obj1); + + } // if joined row is not null + + // Add objects for joined CcBlock rows + + $key5 = CcBlockPeer::getPrimaryKeyHashFromRow($row, $startcol5); + if ($key5 !== null) { + $obj5 = CcBlockPeer::getInstanceFromPool($key5); + if (!$obj5) { + + $cls = CcBlockPeer::getOMClass(false); + + $obj5 = new $cls(); + $obj5->hydrate($row, $startcol5); + CcBlockPeer::addInstanceToPool($obj5, $key5); + } // if $obj5 already loaded + + // Add the $obj1 (CcShowStamp) to the collection in $obj5 (CcBlock) + $obj5->addCcShowStamp($obj1); + + } // if joined row is not null + + // Add objects for joined CcPlaylist rows + + $key6 = CcPlaylistPeer::getPrimaryKeyHashFromRow($row, $startcol6); + if ($key6 !== null) { + $obj6 = CcPlaylistPeer::getInstanceFromPool($key6); + if (!$obj6) { + + $cls = CcPlaylistPeer::getOMClass(false); + + $obj6 = new $cls(); + $obj6->hydrate($row, $startcol6); + CcPlaylistPeer::addInstanceToPool($obj6, $key6); + } // if $obj6 already loaded + + // Add the $obj1 (CcShowStamp) to the collection in $obj6 (CcPlaylist) + $obj6->addCcShowStamp($obj1); + + } // if joined row is not null + + $results[] = $obj1; + } + $stmt->closeCursor(); + return $results; + } + + + /** + * Selects a collection of CcShowStamp objects pre-filled with all related objects except CcWebstream. + * + * @param Criteria $criteria + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return array Array of CcShowStamp objects. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelectJoinAllExceptCcWebstream(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $criteria = clone $criteria; + + // Set the correct dbName if it has not been overridden + // $criteria->getDbName() will return the same object if not set to another value + // so == check is okay and faster + if ($criteria->getDbName() == Propel::getDefaultDB()) { + $criteria->setDbName(self::DATABASE_NAME); + } + + CcShowStampPeer::addSelectColumns($criteria); + $startcol2 = (CcShowStampPeer::NUM_COLUMNS - CcShowStampPeer::NUM_LAZY_LOAD_COLUMNS); + + CcShowPeer::addSelectColumns($criteria); + $startcol3 = $startcol2 + (CcShowPeer::NUM_COLUMNS - CcShowPeer::NUM_LAZY_LOAD_COLUMNS); + + CcShowInstancesPeer::addSelectColumns($criteria); + $startcol4 = $startcol3 + (CcShowInstancesPeer::NUM_COLUMNS - CcShowInstancesPeer::NUM_LAZY_LOAD_COLUMNS); + + CcFilesPeer::addSelectColumns($criteria); + $startcol5 = $startcol4 + (CcFilesPeer::NUM_COLUMNS - CcFilesPeer::NUM_LAZY_LOAD_COLUMNS); + + CcBlockPeer::addSelectColumns($criteria); + $startcol6 = $startcol5 + (CcBlockPeer::NUM_COLUMNS - CcBlockPeer::NUM_LAZY_LOAD_COLUMNS); + + CcPlaylistPeer::addSelectColumns($criteria); + $startcol7 = $startcol6 + (CcPlaylistPeer::NUM_COLUMNS - CcPlaylistPeer::NUM_LAZY_LOAD_COLUMNS); + + $criteria->addJoin(CcShowStampPeer::SHOW_ID, CcShowPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); + + + $stmt = BasePeer::doSelect($criteria, $con); + $results = array(); + + while ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $key1 = CcShowStampPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcShowStampPeer::getInstanceFromPool($key1))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj1->hydrate($row, 0, true); // rehydrate + } else { + $cls = CcShowStampPeer::getOMClass(false); + + $obj1 = new $cls(); + $obj1->hydrate($row); + CcShowStampPeer::addInstanceToPool($obj1, $key1); + } // if obj1 already loaded + + // Add objects for joined CcShow rows + + $key2 = CcShowPeer::getPrimaryKeyHashFromRow($row, $startcol2); + if ($key2 !== null) { + $obj2 = CcShowPeer::getInstanceFromPool($key2); + if (!$obj2) { + + $cls = CcShowPeer::getOMClass(false); + + $obj2 = new $cls(); + $obj2->hydrate($row, $startcol2); + CcShowPeer::addInstanceToPool($obj2, $key2); + } // if $obj2 already loaded + + // Add the $obj1 (CcShowStamp) to the collection in $obj2 (CcShow) + $obj2->addCcShowStamp($obj1); + + } // if joined row is not null + + // Add objects for joined CcShowInstances rows + + $key3 = CcShowInstancesPeer::getPrimaryKeyHashFromRow($row, $startcol3); + if ($key3 !== null) { + $obj3 = CcShowInstancesPeer::getInstanceFromPool($key3); + if (!$obj3) { + + $cls = CcShowInstancesPeer::getOMClass(false); + + $obj3 = new $cls(); + $obj3->hydrate($row, $startcol3); + CcShowInstancesPeer::addInstanceToPool($obj3, $key3); + } // if $obj3 already loaded + + // Add the $obj1 (CcShowStamp) to the collection in $obj3 (CcShowInstances) + $obj3->addCcShowStamp($obj1); + + } // if joined row is not null + + // Add objects for joined CcFiles rows + + $key4 = CcFilesPeer::getPrimaryKeyHashFromRow($row, $startcol4); + if ($key4 !== null) { + $obj4 = CcFilesPeer::getInstanceFromPool($key4); + if (!$obj4) { + + $cls = CcFilesPeer::getOMClass(false); + + $obj4 = new $cls(); + $obj4->hydrate($row, $startcol4); + CcFilesPeer::addInstanceToPool($obj4, $key4); + } // if $obj4 already loaded + + // Add the $obj1 (CcShowStamp) to the collection in $obj4 (CcFiles) + $obj4->addCcShowStamp($obj1); + + } // if joined row is not null + + // Add objects for joined CcBlock rows + + $key5 = CcBlockPeer::getPrimaryKeyHashFromRow($row, $startcol5); + if ($key5 !== null) { + $obj5 = CcBlockPeer::getInstanceFromPool($key5); + if (!$obj5) { + + $cls = CcBlockPeer::getOMClass(false); + + $obj5 = new $cls(); + $obj5->hydrate($row, $startcol5); + CcBlockPeer::addInstanceToPool($obj5, $key5); + } // if $obj5 already loaded + + // Add the $obj1 (CcShowStamp) to the collection in $obj5 (CcBlock) + $obj5->addCcShowStamp($obj1); + + } // if joined row is not null + + // Add objects for joined CcPlaylist rows + + $key6 = CcPlaylistPeer::getPrimaryKeyHashFromRow($row, $startcol6); + if ($key6 !== null) { + $obj6 = CcPlaylistPeer::getInstanceFromPool($key6); + if (!$obj6) { + + $cls = CcPlaylistPeer::getOMClass(false); + + $obj6 = new $cls(); + $obj6->hydrate($row, $startcol6); + CcPlaylistPeer::addInstanceToPool($obj6, $key6); + } // if $obj6 already loaded + + // Add the $obj1 (CcShowStamp) to the collection in $obj6 (CcPlaylist) + $obj6->addCcShowStamp($obj1); + + } // if joined row is not null + + $results[] = $obj1; + } + $stmt->closeCursor(); + return $results; + } + + + /** + * Selects a collection of CcShowStamp objects pre-filled with all related objects except CcBlock. + * + * @param Criteria $criteria + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return array Array of CcShowStamp objects. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelectJoinAllExceptCcBlock(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $criteria = clone $criteria; + + // Set the correct dbName if it has not been overridden + // $criteria->getDbName() will return the same object if not set to another value + // so == check is okay and faster + if ($criteria->getDbName() == Propel::getDefaultDB()) { + $criteria->setDbName(self::DATABASE_NAME); + } + + CcShowStampPeer::addSelectColumns($criteria); + $startcol2 = (CcShowStampPeer::NUM_COLUMNS - CcShowStampPeer::NUM_LAZY_LOAD_COLUMNS); + + CcShowPeer::addSelectColumns($criteria); + $startcol3 = $startcol2 + (CcShowPeer::NUM_COLUMNS - CcShowPeer::NUM_LAZY_LOAD_COLUMNS); + + CcShowInstancesPeer::addSelectColumns($criteria); + $startcol4 = $startcol3 + (CcShowInstancesPeer::NUM_COLUMNS - CcShowInstancesPeer::NUM_LAZY_LOAD_COLUMNS); + + CcFilesPeer::addSelectColumns($criteria); + $startcol5 = $startcol4 + (CcFilesPeer::NUM_COLUMNS - CcFilesPeer::NUM_LAZY_LOAD_COLUMNS); + + CcWebstreamPeer::addSelectColumns($criteria); + $startcol6 = $startcol5 + (CcWebstreamPeer::NUM_COLUMNS - CcWebstreamPeer::NUM_LAZY_LOAD_COLUMNS); + + CcPlaylistPeer::addSelectColumns($criteria); + $startcol7 = $startcol6 + (CcPlaylistPeer::NUM_COLUMNS - CcPlaylistPeer::NUM_LAZY_LOAD_COLUMNS); + + $criteria->addJoin(CcShowStampPeer::SHOW_ID, CcShowPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); + + + $stmt = BasePeer::doSelect($criteria, $con); + $results = array(); + + while ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $key1 = CcShowStampPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcShowStampPeer::getInstanceFromPool($key1))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj1->hydrate($row, 0, true); // rehydrate + } else { + $cls = CcShowStampPeer::getOMClass(false); + + $obj1 = new $cls(); + $obj1->hydrate($row); + CcShowStampPeer::addInstanceToPool($obj1, $key1); + } // if obj1 already loaded + + // Add objects for joined CcShow rows + + $key2 = CcShowPeer::getPrimaryKeyHashFromRow($row, $startcol2); + if ($key2 !== null) { + $obj2 = CcShowPeer::getInstanceFromPool($key2); + if (!$obj2) { + + $cls = CcShowPeer::getOMClass(false); + + $obj2 = new $cls(); + $obj2->hydrate($row, $startcol2); + CcShowPeer::addInstanceToPool($obj2, $key2); + } // if $obj2 already loaded + + // Add the $obj1 (CcShowStamp) to the collection in $obj2 (CcShow) + $obj2->addCcShowStamp($obj1); + + } // if joined row is not null + + // Add objects for joined CcShowInstances rows + + $key3 = CcShowInstancesPeer::getPrimaryKeyHashFromRow($row, $startcol3); + if ($key3 !== null) { + $obj3 = CcShowInstancesPeer::getInstanceFromPool($key3); + if (!$obj3) { + + $cls = CcShowInstancesPeer::getOMClass(false); + + $obj3 = new $cls(); + $obj3->hydrate($row, $startcol3); + CcShowInstancesPeer::addInstanceToPool($obj3, $key3); + } // if $obj3 already loaded + + // Add the $obj1 (CcShowStamp) to the collection in $obj3 (CcShowInstances) + $obj3->addCcShowStamp($obj1); + + } // if joined row is not null + + // Add objects for joined CcFiles rows + + $key4 = CcFilesPeer::getPrimaryKeyHashFromRow($row, $startcol4); + if ($key4 !== null) { + $obj4 = CcFilesPeer::getInstanceFromPool($key4); + if (!$obj4) { + + $cls = CcFilesPeer::getOMClass(false); + + $obj4 = new $cls(); + $obj4->hydrate($row, $startcol4); + CcFilesPeer::addInstanceToPool($obj4, $key4); + } // if $obj4 already loaded + + // Add the $obj1 (CcShowStamp) to the collection in $obj4 (CcFiles) + $obj4->addCcShowStamp($obj1); + + } // if joined row is not null + + // Add objects for joined CcWebstream rows + + $key5 = CcWebstreamPeer::getPrimaryKeyHashFromRow($row, $startcol5); + if ($key5 !== null) { + $obj5 = CcWebstreamPeer::getInstanceFromPool($key5); + if (!$obj5) { + + $cls = CcWebstreamPeer::getOMClass(false); + + $obj5 = new $cls(); + $obj5->hydrate($row, $startcol5); + CcWebstreamPeer::addInstanceToPool($obj5, $key5); + } // if $obj5 already loaded + + // Add the $obj1 (CcShowStamp) to the collection in $obj5 (CcWebstream) + $obj5->addCcShowStamp($obj1); + + } // if joined row is not null + + // Add objects for joined CcPlaylist rows + + $key6 = CcPlaylistPeer::getPrimaryKeyHashFromRow($row, $startcol6); + if ($key6 !== null) { + $obj6 = CcPlaylistPeer::getInstanceFromPool($key6); + if (!$obj6) { + + $cls = CcPlaylistPeer::getOMClass(false); + + $obj6 = new $cls(); + $obj6->hydrate($row, $startcol6); + CcPlaylistPeer::addInstanceToPool($obj6, $key6); + } // if $obj6 already loaded + + // Add the $obj1 (CcShowStamp) to the collection in $obj6 (CcPlaylist) + $obj6->addCcShowStamp($obj1); + + } // if joined row is not null + + $results[] = $obj1; + } + $stmt->closeCursor(); + return $results; + } + + + /** + * Selects a collection of CcShowStamp objects pre-filled with all related objects except CcPlaylist. + * + * @param Criteria $criteria + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return array Array of CcShowStamp objects. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelectJoinAllExceptCcPlaylist(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $criteria = clone $criteria; + + // Set the correct dbName if it has not been overridden + // $criteria->getDbName() will return the same object if not set to another value + // so == check is okay and faster + if ($criteria->getDbName() == Propel::getDefaultDB()) { + $criteria->setDbName(self::DATABASE_NAME); + } + + CcShowStampPeer::addSelectColumns($criteria); + $startcol2 = (CcShowStampPeer::NUM_COLUMNS - CcShowStampPeer::NUM_LAZY_LOAD_COLUMNS); + + CcShowPeer::addSelectColumns($criteria); + $startcol3 = $startcol2 + (CcShowPeer::NUM_COLUMNS - CcShowPeer::NUM_LAZY_LOAD_COLUMNS); + + CcShowInstancesPeer::addSelectColumns($criteria); + $startcol4 = $startcol3 + (CcShowInstancesPeer::NUM_COLUMNS - CcShowInstancesPeer::NUM_LAZY_LOAD_COLUMNS); + + CcFilesPeer::addSelectColumns($criteria); + $startcol5 = $startcol4 + (CcFilesPeer::NUM_COLUMNS - CcFilesPeer::NUM_LAZY_LOAD_COLUMNS); + + CcWebstreamPeer::addSelectColumns($criteria); + $startcol6 = $startcol5 + (CcWebstreamPeer::NUM_COLUMNS - CcWebstreamPeer::NUM_LAZY_LOAD_COLUMNS); + + CcBlockPeer::addSelectColumns($criteria); + $startcol7 = $startcol6 + (CcBlockPeer::NUM_COLUMNS - CcBlockPeer::NUM_LAZY_LOAD_COLUMNS); + + $criteria->addJoin(CcShowStampPeer::SHOW_ID, CcShowPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); + + $criteria->addJoin(CcShowStampPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); + + + $stmt = BasePeer::doSelect($criteria, $con); + $results = array(); + + while ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $key1 = CcShowStampPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcShowStampPeer::getInstanceFromPool($key1))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj1->hydrate($row, 0, true); // rehydrate + } else { + $cls = CcShowStampPeer::getOMClass(false); + + $obj1 = new $cls(); + $obj1->hydrate($row); + CcShowStampPeer::addInstanceToPool($obj1, $key1); + } // if obj1 already loaded + + // Add objects for joined CcShow rows + + $key2 = CcShowPeer::getPrimaryKeyHashFromRow($row, $startcol2); + if ($key2 !== null) { + $obj2 = CcShowPeer::getInstanceFromPool($key2); + if (!$obj2) { + + $cls = CcShowPeer::getOMClass(false); + + $obj2 = new $cls(); + $obj2->hydrate($row, $startcol2); + CcShowPeer::addInstanceToPool($obj2, $key2); + } // if $obj2 already loaded + + // Add the $obj1 (CcShowStamp) to the collection in $obj2 (CcShow) + $obj2->addCcShowStamp($obj1); + + } // if joined row is not null + + // Add objects for joined CcShowInstances rows + + $key3 = CcShowInstancesPeer::getPrimaryKeyHashFromRow($row, $startcol3); + if ($key3 !== null) { + $obj3 = CcShowInstancesPeer::getInstanceFromPool($key3); + if (!$obj3) { + + $cls = CcShowInstancesPeer::getOMClass(false); + + $obj3 = new $cls(); + $obj3->hydrate($row, $startcol3); + CcShowInstancesPeer::addInstanceToPool($obj3, $key3); + } // if $obj3 already loaded + + // Add the $obj1 (CcShowStamp) to the collection in $obj3 (CcShowInstances) + $obj3->addCcShowStamp($obj1); + + } // if joined row is not null + + // Add objects for joined CcFiles rows + + $key4 = CcFilesPeer::getPrimaryKeyHashFromRow($row, $startcol4); + if ($key4 !== null) { + $obj4 = CcFilesPeer::getInstanceFromPool($key4); + if (!$obj4) { + + $cls = CcFilesPeer::getOMClass(false); + + $obj4 = new $cls(); + $obj4->hydrate($row, $startcol4); + CcFilesPeer::addInstanceToPool($obj4, $key4); + } // if $obj4 already loaded + + // Add the $obj1 (CcShowStamp) to the collection in $obj4 (CcFiles) + $obj4->addCcShowStamp($obj1); + + } // if joined row is not null + + // Add objects for joined CcWebstream rows + + $key5 = CcWebstreamPeer::getPrimaryKeyHashFromRow($row, $startcol5); + if ($key5 !== null) { + $obj5 = CcWebstreamPeer::getInstanceFromPool($key5); + if (!$obj5) { + + $cls = CcWebstreamPeer::getOMClass(false); + + $obj5 = new $cls(); + $obj5->hydrate($row, $startcol5); + CcWebstreamPeer::addInstanceToPool($obj5, $key5); + } // if $obj5 already loaded + + // Add the $obj1 (CcShowStamp) to the collection in $obj5 (CcWebstream) + $obj5->addCcShowStamp($obj1); + + } // if joined row is not null + + // Add objects for joined CcBlock rows + + $key6 = CcBlockPeer::getPrimaryKeyHashFromRow($row, $startcol6); + if ($key6 !== null) { + $obj6 = CcBlockPeer::getInstanceFromPool($key6); + if (!$obj6) { + + $cls = CcBlockPeer::getOMClass(false); + + $obj6 = new $cls(); + $obj6->hydrate($row, $startcol6); + CcBlockPeer::addInstanceToPool($obj6, $key6); + } // if $obj6 already loaded + + // Add the $obj1 (CcShowStamp) to the collection in $obj6 (CcBlock) + $obj6->addCcShowStamp($obj1); + + } // if joined row is not null + + $results[] = $obj1; + } + $stmt->closeCursor(); + return $results; + } + + /** + * Returns the TableMap related to this peer. + * This method is not needed for general use but a specific application could have a need. + * @return TableMap + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function getTableMap() + { + return Propel::getDatabaseMap(self::DATABASE_NAME)->getTable(self::TABLE_NAME); + } + + /** + * Add a TableMap instance to the database for this peer class. + */ + public static function buildTableMap() + { + $dbMap = Propel::getDatabaseMap(BaseCcShowStampPeer::DATABASE_NAME); + if (!$dbMap->hasTable(BaseCcShowStampPeer::TABLE_NAME)) + { + $dbMap->addTableObject(new CcShowStampTableMap()); + } + } + + /** + * The class that the Peer will make instances of. + * + * If $withPrefix is true, the returned path + * uses a dot-path notation which is tranalted into a path + * relative to a location on the PHP include_path. + * (e.g. path.to.MyClass -> 'path/to/MyClass.php') + * + * @param boolean $withPrefix Whether or not to return the path with the class name + * @return string path.to.ClassName + */ + public static function getOMClass($withPrefix = true) + { + return $withPrefix ? CcShowStampPeer::CLASS_DEFAULT : CcShowStampPeer::OM_CLASS; + } + + /** + * Method perform an INSERT on the database, given a CcShowStamp or Criteria object. + * + * @param mixed $values Criteria or CcShowStamp object containing data that is used to create the INSERT statement. + * @param PropelPDO $con the PropelPDO connection to use + * @return mixed The new primary key. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doInsert($values, PropelPDO $con = null) + { + if ($con === null) { + $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + } + + if ($values instanceof Criteria) { + $criteria = clone $values; // rename for clarity + } else { + $criteria = $values->buildCriteria(); // build Criteria from CcShowStamp object + } + + if ($criteria->containsKey(CcShowStampPeer::ID) && $criteria->keyContainsValue(CcShowStampPeer::ID) ) { + throw new PropelException('Cannot insert a value for auto-increment primary key ('.CcShowStampPeer::ID.')'); + } + + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + try { + // use transaction because $criteria could contain info + // for more than one table (I guess, conceivably) + $con->beginTransaction(); + $pk = BasePeer::doInsert($criteria, $con); + $con->commit(); + } catch(PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $pk; + } + + /** + * Method perform an UPDATE on the database, given a CcShowStamp or Criteria object. + * + * @param mixed $values Criteria or CcShowStamp object containing data that is used to create the UPDATE statement. + * @param PropelPDO $con The connection to use (specify PropelPDO connection object to exert more control over transactions). + * @return int The number of affected rows (if supported by underlying database driver). + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doUpdate($values, PropelPDO $con = null) + { + if ($con === null) { + $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + } + + $selectCriteria = new Criteria(self::DATABASE_NAME); + + if ($values instanceof Criteria) { + $criteria = clone $values; // rename for clarity + + $comparison = $criteria->getComparison(CcShowStampPeer::ID); + $value = $criteria->remove(CcShowStampPeer::ID); + if ($value) { + $selectCriteria->add(CcShowStampPeer::ID, $value, $comparison); + } else { + $selectCriteria->setPrimaryTableName(CcShowStampPeer::TABLE_NAME); + } + + } else { // $values is CcShowStamp object + $criteria = $values->buildCriteria(); // gets full criteria + $selectCriteria = $values->buildPkeyCriteria(); // gets criteria w/ primary key(s) + } + + // set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + return BasePeer::doUpdate($selectCriteria, $criteria, $con); + } + + /** + * Method to DELETE all rows from the cc_show_stamp table. + * + * @return int The number of affected rows (if supported by underlying database driver). + */ + public static function doDeleteAll($con = null) + { + if ($con === null) { + $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + } + $affectedRows = 0; // initialize var to track total num of affected rows + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->beginTransaction(); + $affectedRows += BasePeer::doDeleteAll(CcShowStampPeer::TABLE_NAME, $con, CcShowStampPeer::DATABASE_NAME); + // Because this db requires some delete cascade/set null emulation, we have to + // clear the cached instance *after* the emulation has happened (since + // instances get re-added by the select statement contained therein). + CcShowStampPeer::clearInstancePool(); + CcShowStampPeer::clearRelatedInstancePool(); + $con->commit(); + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Method perform a DELETE on the database, given a CcShowStamp or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or CcShowStamp object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param PropelPDO $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows + * if supported by native driver or if emulated using Propel. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doDelete($values, PropelPDO $con = null) + { + if ($con === null) { + $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + } + + if ($values instanceof Criteria) { + // invalidate the cache for all objects of this type, since we have no + // way of knowing (without running a query) what objects should be invalidated + // from the cache based on this Criteria. + CcShowStampPeer::clearInstancePool(); + // rename for clarity + $criteria = clone $values; + } elseif ($values instanceof CcShowStamp) { // it's a model object + // invalidate the cache for this single object + CcShowStampPeer::removeInstanceFromPool($values); + // create criteria based on pk values + $criteria = $values->buildPkeyCriteria(); + } else { // it's a primary key, or an array of pks + $criteria = new Criteria(self::DATABASE_NAME); + $criteria->add(CcShowStampPeer::ID, (array) $values, Criteria::IN); + // invalidate the cache for this object(s) + foreach ((array) $values as $singleval) { + CcShowStampPeer::removeInstanceFromPool($singleval); + } + } + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + $affectedRows = 0; // initialize var to track total num of affected rows + + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->beginTransaction(); + + $affectedRows += BasePeer::doDelete($criteria, $con); + CcShowStampPeer::clearRelatedInstancePool(); + $con->commit(); + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Validates all modified columns of given CcShowStamp object. + * If parameter $columns is either a single column name or an array of column names + * than only those columns are validated. + * + * NOTICE: This does not apply to primary or foreign keys for now. + * + * @param CcShowStamp $obj The object to validate. + * @param mixed $cols Column name or array of column names. + * + * @return mixed TRUE if all columns are valid or the error message of the first invalid column. + */ + public static function doValidate(CcShowStamp $obj, $cols = null) + { + $columns = array(); + + if ($cols) { + $dbMap = Propel::getDatabaseMap(CcShowStampPeer::DATABASE_NAME); + $tableMap = $dbMap->getTable(CcShowStampPeer::TABLE_NAME); + + if (! is_array($cols)) { + $cols = array($cols); + } + + foreach ($cols as $colName) { + if ($tableMap->containsColumn($colName)) { + $get = 'get' . $tableMap->getColumn($colName)->getPhpName(); + $columns[$colName] = $obj->$get(); + } + } + } else { + + } + + return BasePeer::doValidate(CcShowStampPeer::DATABASE_NAME, CcShowStampPeer::TABLE_NAME, $columns); + } + + /** + * Retrieve a single object by pkey. + * + * @param int $pk the primary key. + * @param PropelPDO $con the connection to use + * @return CcShowStamp + */ + public static function retrieveByPK($pk, PropelPDO $con = null) + { + + if (null !== ($obj = CcShowStampPeer::getInstanceFromPool((string) $pk))) { + return $obj; + } + + if ($con === null) { + $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $criteria = new Criteria(CcShowStampPeer::DATABASE_NAME); + $criteria->add(CcShowStampPeer::ID, $pk); + + $v = CcShowStampPeer::doSelect($criteria, $con); + + return !empty($v) > 0 ? $v[0] : null; + } + + /** + * Retrieve multiple objects by pkey. + * + * @param array $pks List of primary keys + * @param PropelPDO $con the connection to use + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function retrieveByPKs($pks, PropelPDO $con = null) + { + if ($con === null) { + $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $objs = null; + if (empty($pks)) { + $objs = array(); + } else { + $criteria = new Criteria(CcShowStampPeer::DATABASE_NAME); + $criteria->add(CcShowStampPeer::ID, $pks, Criteria::IN); + $objs = CcShowStampPeer::doSelect($criteria, $con); + } + return $objs; + } + +} // BaseCcShowStampPeer + +// This is the static code needed to register the TableMap for this table with the main Propel class. +// +BaseCcShowStampPeer::buildTableMap(); + diff --git a/airtime_mvc/application/models/airtime/om/BaseCcShowStampQuery.php b/airtime_mvc/application/models/airtime/om/BaseCcShowStampQuery.php new file mode 100644 index 000000000..dacdcbffa --- /dev/null +++ b/airtime_mvc/application/models/airtime/om/BaseCcShowStampQuery.php @@ -0,0 +1,948 @@ +setModelAlias($modelAlias); + } + if ($criteria instanceof Criteria) { + $query->mergeWith($criteria); + } + return $query; + } + + /** + * Find object by primary key + * Use instance pooling to avoid a database query if the object exists + * + * $obj = $c->findPk(12, $con); + * + * @param mixed $key Primary key to use for the query + * @param PropelPDO $con an optional connection object + * + * @return CcShowStamp|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ((null !== ($obj = CcShowStampPeer::getInstanceFromPool((string) $key))) && $this->getFormatter()->isObjectFormatter()) { + // the object is alredy in the instance pool + return $obj; + } else { + // the object has not been requested yet, or the formatter is not an object formatter + $criteria = $this->isKeepQuery() ? clone $this : $this; + $stmt = $criteria + ->filterByPrimaryKey($key) + ->getSelectStatement($con); + return $criteria->getFormatter()->init($criteria)->formatOne($stmt); + } + } + + /** + * Find objects by primary key + * + * $objs = $c->findPks(array(12, 56, 832), $con); + * + * @param array $keys Primary keys to use for the query + * @param PropelPDO $con an optional connection object + * + * @return PropelObjectCollection|array|mixed the list of results, formatted by the current formatter + */ + public function findPks($keys, $con = null) + { + $criteria = $this->isKeepQuery() ? clone $this : $this; + return $this + ->filterByPrimaryKeys($keys) + ->find($con); + } + + /** + * Filter the query by primary key + * + * @param mixed $key Primary key to use for the query + * + * @return CcShowStampQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + return $this->addUsingAlias(CcShowStampPeer::ID, $key, Criteria::EQUAL); + } + + /** + * Filter the query by a list of primary keys + * + * @param array $keys The list of primary key to use for the query + * + * @return CcShowStampQuery The current query, for fluid interface + */ + public function filterByPrimaryKeys($keys) + { + return $this->addUsingAlias(CcShowStampPeer::ID, $keys, Criteria::IN); + } + + /** + * Filter the query on the id column + * + * @param int|array $dbId 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 CcShowStampQuery The current query, for fluid interface + */ + public function filterByDbId($dbId = null, $comparison = null) + { + if (is_array($dbId) && null === $comparison) { + $comparison = Criteria::IN; + } + return $this->addUsingAlias(CcShowStampPeer::ID, $dbId, $comparison); + } + + /** + * Filter the query on the show_id column + * + * @param int|array $dbShowId 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 CcShowStampQuery The current query, for fluid interface + */ + public function filterByDbShowId($dbShowId = null, $comparison = null) + { + if (is_array($dbShowId)) { + $useMinMax = false; + if (isset($dbShowId['min'])) { + $this->addUsingAlias(CcShowStampPeer::SHOW_ID, $dbShowId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbShowId['max'])) { + $this->addUsingAlias(CcShowStampPeer::SHOW_ID, $dbShowId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcShowStampPeer::SHOW_ID, $dbShowId, $comparison); + } + + /** + * Filter the query on the instance_id column + * + * @param int|array $dbInstanceId 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 CcShowStampQuery The current query, for fluid interface + */ + public function filterByDbInstanceId($dbInstanceId = null, $comparison = null) + { + if (is_array($dbInstanceId)) { + $useMinMax = false; + if (isset($dbInstanceId['min'])) { + $this->addUsingAlias(CcShowStampPeer::INSTANCE_ID, $dbInstanceId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbInstanceId['max'])) { + $this->addUsingAlias(CcShowStampPeer::INSTANCE_ID, $dbInstanceId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcShowStampPeer::INSTANCE_ID, $dbInstanceId, $comparison); + } + + /** + * Filter the query on the file_id column + * + * @param int|array $dbFileId 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 CcShowStampQuery The current query, for fluid interface + */ + public function filterByDbFileId($dbFileId = null, $comparison = null) + { + if (is_array($dbFileId)) { + $useMinMax = false; + if (isset($dbFileId['min'])) { + $this->addUsingAlias(CcShowStampPeer::FILE_ID, $dbFileId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbFileId['max'])) { + $this->addUsingAlias(CcShowStampPeer::FILE_ID, $dbFileId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcShowStampPeer::FILE_ID, $dbFileId, $comparison); + } + + /** + * Filter the query on the stream_id column + * + * @param int|array $dbStreamId 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 CcShowStampQuery The current query, for fluid interface + */ + public function filterByDbStreamId($dbStreamId = null, $comparison = null) + { + if (is_array($dbStreamId)) { + $useMinMax = false; + if (isset($dbStreamId['min'])) { + $this->addUsingAlias(CcShowStampPeer::STREAM_ID, $dbStreamId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbStreamId['max'])) { + $this->addUsingAlias(CcShowStampPeer::STREAM_ID, $dbStreamId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcShowStampPeer::STREAM_ID, $dbStreamId, $comparison); + } + + /** + * Filter the query on the block_id column + * + * @param int|array $dbBlockId 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 CcShowStampQuery The current query, for fluid interface + */ + public function filterByDbBlockId($dbBlockId = null, $comparison = null) + { + if (is_array($dbBlockId)) { + $useMinMax = false; + if (isset($dbBlockId['min'])) { + $this->addUsingAlias(CcShowStampPeer::BLOCK_ID, $dbBlockId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbBlockId['max'])) { + $this->addUsingAlias(CcShowStampPeer::BLOCK_ID, $dbBlockId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcShowStampPeer::BLOCK_ID, $dbBlockId, $comparison); + } + + /** + * Filter the query on the playlist_id column + * + * @param int|array $dbPlaylistId 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 CcShowStampQuery The current query, for fluid interface + */ + public function filterByDbPlaylistId($dbPlaylistId = null, $comparison = null) + { + if (is_array($dbPlaylistId)) { + $useMinMax = false; + if (isset($dbPlaylistId['min'])) { + $this->addUsingAlias(CcShowStampPeer::PLAYLIST_ID, $dbPlaylistId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbPlaylistId['max'])) { + $this->addUsingAlias(CcShowStampPeer::PLAYLIST_ID, $dbPlaylistId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcShowStampPeer::PLAYLIST_ID, $dbPlaylistId, $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 CcShowStampQuery 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(CcShowStampPeer::POSITION, $dbPosition['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbPosition['max'])) { + $this->addUsingAlias(CcShowStampPeer::POSITION, $dbPosition['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcShowStampPeer::POSITION, $dbPosition, $comparison); + } + + /** + * Filter the query on the clip_length column + * + * @param string $dbClipLength The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return CcShowStampQuery The current query, for fluid interface + */ + public function filterByDbClipLength($dbClipLength = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($dbClipLength)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $dbClipLength)) { + $dbClipLength = str_replace('*', '%', $dbClipLength); + $comparison = Criteria::LIKE; + } + } + return $this->addUsingAlias(CcShowStampPeer::CLIP_LENGTH, $dbClipLength, $comparison); + } + + /** + * Filter the query on the cue_in column + * + * @param string $dbCueIn The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return CcShowStampQuery The current query, for fluid interface + */ + public function filterByDbCueIn($dbCueIn = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($dbCueIn)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $dbCueIn)) { + $dbCueIn = str_replace('*', '%', $dbCueIn); + $comparison = Criteria::LIKE; + } + } + return $this->addUsingAlias(CcShowStampPeer::CUE_IN, $dbCueIn, $comparison); + } + + /** + * Filter the query on the cue_out column + * + * @param string $dbCueOut The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return CcShowStampQuery The current query, for fluid interface + */ + public function filterByDbCueOut($dbCueOut = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($dbCueOut)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $dbCueOut)) { + $dbCueOut = str_replace('*', '%', $dbCueOut); + $comparison = Criteria::LIKE; + } + } + return $this->addUsingAlias(CcShowStampPeer::CUE_OUT, $dbCueOut, $comparison); + } + + /** + * Filter the query on the fade_in column + * + * @param string $dbFadeIn The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return CcShowStampQuery The current query, for fluid interface + */ + public function filterByDbFadeIn($dbFadeIn = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($dbFadeIn)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $dbFadeIn)) { + $dbFadeIn = str_replace('*', '%', $dbFadeIn); + $comparison = Criteria::LIKE; + } + } + return $this->addUsingAlias(CcShowStampPeer::FADE_IN, $dbFadeIn, $comparison); + } + + /** + * Filter the query on the fade_out column + * + * @param string $dbFadeOut The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return CcShowStampQuery The current query, for fluid interface + */ + public function filterByDbFadeOut($dbFadeOut = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($dbFadeOut)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $dbFadeOut)) { + $dbFadeOut = str_replace('*', '%', $dbFadeOut); + $comparison = Criteria::LIKE; + } + } + return $this->addUsingAlias(CcShowStampPeer::FADE_OUT, $dbFadeOut, $comparison); + } + + /** + * Filter the query by a related CcShow object + * + * @param CcShow $ccShow the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return CcShowStampQuery The current query, for fluid interface + */ + public function filterByCcShow($ccShow, $comparison = null) + { + return $this + ->addUsingAlias(CcShowStampPeer::SHOW_ID, $ccShow->getDbId(), $comparison); + } + + /** + * Adds a JOIN clause to the query using the CcShow relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return CcShowStampQuery The current query, for fluid interface + */ + public function joinCcShow($relationAlias = '', $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('CcShow'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'CcShow'); + } + + return $this; + } + + /** + * Use the CcShow relation CcShow object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return CcShowQuery A secondary query class using the current class as primary query + */ + public function useCcShowQuery($relationAlias = '', $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinCcShow($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'CcShow', 'CcShowQuery'); + } + + /** + * Filter the query by a related CcShowInstances object + * + * @param CcShowInstances $ccShowInstances the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return CcShowStampQuery The current query, for fluid interface + */ + public function filterByCcShowInstances($ccShowInstances, $comparison = null) + { + return $this + ->addUsingAlias(CcShowStampPeer::INSTANCE_ID, $ccShowInstances->getDbId(), $comparison); + } + + /** + * Adds a JOIN clause to the query using the CcShowInstances relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return CcShowStampQuery The current query, for fluid interface + */ + public function joinCcShowInstances($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('CcShowInstances'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'CcShowInstances'); + } + + return $this; + } + + /** + * Use the CcShowInstances relation CcShowInstances object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return CcShowInstancesQuery A secondary query class using the current class as primary query + */ + public function useCcShowInstancesQuery($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + { + return $this + ->joinCcShowInstances($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'CcShowInstances', 'CcShowInstancesQuery'); + } + + /** + * Filter the query by a related CcFiles object + * + * @param CcFiles $ccFiles the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return CcShowStampQuery The current query, for fluid interface + */ + public function filterByCcFiles($ccFiles, $comparison = null) + { + return $this + ->addUsingAlias(CcShowStampPeer::FILE_ID, $ccFiles->getDbId(), $comparison); + } + + /** + * Adds a JOIN clause to the query using the CcFiles relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return CcShowStampQuery The current query, for fluid interface + */ + public function joinCcFiles($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('CcFiles'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'CcFiles'); + } + + return $this; + } + + /** + * Use the CcFiles relation CcFiles object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return CcFilesQuery A secondary query class using the current class as primary query + */ + public function useCcFilesQuery($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + { + return $this + ->joinCcFiles($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'CcFiles', 'CcFilesQuery'); + } + + /** + * Filter the query by a related CcWebstream object + * + * @param CcWebstream $ccWebstream the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return CcShowStampQuery The current query, for fluid interface + */ + public function filterByCcWebstream($ccWebstream, $comparison = null) + { + return $this + ->addUsingAlias(CcShowStampPeer::STREAM_ID, $ccWebstream->getDbId(), $comparison); + } + + /** + * Adds a JOIN clause to the query using the CcWebstream relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return CcShowStampQuery The current query, for fluid interface + */ + public function joinCcWebstream($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('CcWebstream'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'CcWebstream'); + } + + return $this; + } + + /** + * Use the CcWebstream relation CcWebstream object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return CcWebstreamQuery A secondary query class using the current class as primary query + */ + public function useCcWebstreamQuery($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + { + return $this + ->joinCcWebstream($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'CcWebstream', 'CcWebstreamQuery'); + } + + /** + * Filter the query by a related CcBlock object + * + * @param CcBlock $ccBlock the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return CcShowStampQuery The current query, for fluid interface + */ + public function filterByCcBlock($ccBlock, $comparison = null) + { + return $this + ->addUsingAlias(CcShowStampPeer::BLOCK_ID, $ccBlock->getDbId(), $comparison); + } + + /** + * Adds a JOIN clause to the query using the CcBlock relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return CcShowStampQuery The current query, for fluid interface + */ + public function joinCcBlock($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('CcBlock'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'CcBlock'); + } + + return $this; + } + + /** + * Use the CcBlock relation CcBlock object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return CcBlockQuery A secondary query class using the current class as primary query + */ + public function useCcBlockQuery($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + { + return $this + ->joinCcBlock($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'CcBlock', 'CcBlockQuery'); + } + + /** + * Filter the query by a related CcPlaylist object + * + * @param CcPlaylist $ccPlaylist the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return CcShowStampQuery The current query, for fluid interface + */ + public function filterByCcPlaylist($ccPlaylist, $comparison = null) + { + return $this + ->addUsingAlias(CcShowStampPeer::PLAYLIST_ID, $ccPlaylist->getDbId(), $comparison); + } + + /** + * Adds a JOIN clause to the query using the CcPlaylist relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return CcShowStampQuery The current query, for fluid interface + */ + public function joinCcPlaylist($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('CcPlaylist'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'CcPlaylist'); + } + + return $this; + } + + /** + * Use the CcPlaylist relation CcPlaylist object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return CcPlaylistQuery A secondary query class using the current class as primary query + */ + public function useCcPlaylistQuery($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + { + return $this + ->joinCcPlaylist($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'CcPlaylist', 'CcPlaylistQuery'); + } + + /** + * Exclude object from result + * + * @param CcShowStamp $ccShowStamp Object to remove from the list of results + * + * @return CcShowStampQuery The current query, for fluid interface + */ + public function prune($ccShowStamp = null) + { + if ($ccShowStamp) { + $this->addUsingAlias(CcShowStampPeer::ID, $ccShowStamp->getDbId(), Criteria::NOT_EQUAL); + } + + return $this; + } + +} // BaseCcShowStampQuery diff --git a/airtime_mvc/build/schema.xml b/airtime_mvc/build/schema.xml index c16063ad9..2633c2938 100644 --- a/airtime_mvc/build/schema.xml +++ b/airtime_mvc/build/schema.xml @@ -341,10 +341,9 @@ - + From cfee74693b2e5a9bcd0c06f0758b404e1934766b Mon Sep 17 00:00:00 2001 From: denise Date: Fri, 5 Apr 2013 17:44:30 -0400 Subject: [PATCH 45/73] CC-4961: Show linking moved move-show to calendar service --- .../controllers/ScheduleController.php | 20 +-- .../application/services/CalendarService.php | 153 ++++++++++++++++-- .../application/services/SchedulerService.php | 39 +++-- airtime_mvc/build/schema.xml | 4 +- 4 files changed, 168 insertions(+), 48 deletions(-) diff --git a/airtime_mvc/application/controllers/ScheduleController.php b/airtime_mvc/application/controllers/ScheduleController.php index 02ed93dfa..e9a97b788 100644 --- a/airtime_mvc/application/controllers/ScheduleController.php +++ b/airtime_mvc/application/controllers/ScheduleController.php @@ -163,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; } diff --git a/airtime_mvc/application/services/CalendarService.php b/airtime_mvc/application/services/CalendarService.php index 876b3566a..1c963fc45 100644 --- a/airtime_mvc/application/services/CalendarService.php +++ b/airtime_mvc/application/services/CalendarService.php @@ -4,13 +4,16 @@ class Application_Service_CalendarService { private $currentUser; private $ccShowInstance; - private $showId; + private $ccShow; public function __construct($instanceId = null) { if (!is_null($instanceId)) { $this->ccShowInstance = CcShowInstancesQuery::create()->findPk($instanceId); - $this->showId = $this->ccShowInstance->getDbShowId(); + if (is_null($this->ccShowInstance)) { + throw new Exception("Instance does not exist"); + } + $this->ccShow = $this->ccShowInstance->getCcShow(); } $service_user = new Application_Service_UserService(); @@ -27,7 +30,7 @@ class Application_Service_CalendarService $now = time(); $baseUrl = Application_Common_OsPath::getBaseDir(); $isAdminOrPM = $this->currentUser->isAdminOrPM(); - $isHostOfShow = $this->currentUser->isHostOfShow($this->showId); + $isHostOfShow = $this->currentUser->isHostOfShow($this->ccShow->getDbId()); //DateTime objects in UTC $startDT = $this->ccShowInstance->getDbStarts(null); @@ -108,7 +111,7 @@ class Application_Service_CalendarService } } - $isRepeating = $this->ccShowInstance->getCcShow()->getFirstCcShowDay()->isRepeating(); + $isRepeating = $this->ccShow->getFirstCcShowDay()->isRepeating(); if (!$this->ccShowInstance->isRebroadcast()) { if ($isRepeating) { $menu["edit"] = array( @@ -164,18 +167,12 @@ class Application_Service_CalendarService return $menu; } - /* - * @param $dateTime - * php Datetime object to add deltas to - * - * @param $deltaDay - * php int, delta days show moved - * - * @param $deltaMin - * php int, delta mins show moved - * - * @return $newDateTime - * php DateTime, $dateTime with the added time deltas. + /** + * + * 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) { @@ -202,4 +199,128 @@ class Application_Service_CalendarService 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 index 5b3fa995e..635569f55 100644 --- a/airtime_mvc/application/services/SchedulerService.php +++ b/airtime_mvc/application/services/SchedulerService.php @@ -44,27 +44,32 @@ class Application_Service_SchedulerService * Enter description here ... * @param array $instanceIds */ - public static function updateScheduleStartTime($instanceIds, $diff) + public static function updateScheduleStartTime($instanceIds, $diff=null, $newStart=null) { $con = Propel::getConnection(); - if (count($instanceIds) > 0 && $diff != 0) { + if (count($instanceIds) > 0) { $showIdList = implode(",", $instanceIds); - /*$sql = << $diff, ':diff2' => $diff, - ':showIds' => $showIdList), - 'execute');*/ - $sql = "UPDATE cc_schedule " - ."SET starts = starts + INTERVAL '$diff sec', " - ."ends = ends + INTERVAL '$diff sec' " - ."WHERE instance_id IN ($showIdList)"; - $con->exec($sql); + 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; + } + + $sql = "UPDATE cc_schedule " + ."SET starts = starts + INTERVAL '$diff sec', " + ."ends = ends + INTERVAL '$diff sec' " + ."WHERE instance_id IN ($showIdList)"; + $con->exec($sql); + } } } diff --git a/airtime_mvc/build/schema.xml b/airtime_mvc/build/schema.xml index 2633c2938..49ff7cffa 100644 --- a/airtime_mvc/build/schema.xml +++ b/airtime_mvc/build/schema.xml @@ -341,9 +341,9 @@ - + From 76bfce21b12d353028ebfde59429347972386716 Mon Sep 17 00:00:00 2001 From: denise Date: Mon, 8 Apr 2013 14:42:37 -0400 Subject: [PATCH 46/73] CC-4961: Show linking -modified db --- .../configs/classmap-airtime-conf.php | 21 +- .../models/airtime/map/CcBlockTableMap.php | 2 +- .../models/airtime/map/CcFilesTableMap.php | 2 +- .../models/airtime/map/CcPlaylistTableMap.php | 2 +- .../airtime/map/CcShowInstancesTableMap.php | 2 +- .../models/airtime/map/CcShowTableMap.php | 2 +- .../airtime/map/CcWebstreamTableMap.php | 2 +- .../models/airtime/om/BaseCcBlock.php | 159 ++++++-------- .../models/airtime/om/BaseCcBlockPeer.php | 4 +- .../models/airtime/om/BaseCcBlockQuery.php | 32 +-- .../models/airtime/om/BaseCcFiles.php | 159 ++++++-------- .../models/airtime/om/BaseCcFilesPeer.php | 4 +- .../models/airtime/om/BaseCcFilesQuery.php | 32 +-- .../models/airtime/om/BaseCcPlaylist.php | 159 ++++++-------- .../models/airtime/om/BaseCcPlaylistPeer.php | 4 +- .../models/airtime/om/BaseCcPlaylistQuery.php | 32 +-- .../models/airtime/om/BaseCcShow.php | 202 +++++------------- .../models/airtime/om/BaseCcShowInstances.php | 202 +++++------------- .../airtime/om/BaseCcShowInstancesPeer.php | 4 +- .../airtime/om/BaseCcShowInstancesQuery.php | 32 +-- .../models/airtime/om/BaseCcShowPeer.php | 4 +- .../models/airtime/om/BaseCcShowQuery.php | 32 +-- .../models/airtime/om/BaseCcWebstream.php | 159 ++++++-------- .../models/airtime/om/BaseCcWebstreamPeer.php | 4 +- .../airtime/om/BaseCcWebstreamQuery.php | 32 +-- airtime_mvc/build/schema.xml | 33 +-- airtime_mvc/build/sql/schema.sql | 44 ++-- 27 files changed, 550 insertions(+), 816 deletions(-) diff --git a/airtime_mvc/application/configs/classmap-airtime-conf.php b/airtime_mvc/application/configs/classmap-airtime-conf.php index 9eacbf563..7f5e03d42 100644 --- a/airtime_mvc/application/configs/classmap-airtime-conf.php +++ b/airtime_mvc/application/configs/classmap-airtime-conf.php @@ -204,11 +204,18 @@ return array ( 'BaseCcLocalePeer' => 'airtime/om/BaseCcLocalePeer.php', 'BaseCcLocale' => 'airtime/om/BaseCcLocale.php', 'BaseCcLocaleQuery' => 'airtime/om/BaseCcLocaleQuery.php', - 'CcShowStampTableMap' => 'airtime/map/CcShowStampTableMap.php', - 'CcShowStampPeer' => 'airtime/CcShowStampPeer.php', - 'CcShowStamp' => 'airtime/CcShowStamp.php', - 'CcShowStampQuery' => 'airtime/CcShowStampQuery.php', - 'BaseCcShowStampPeer' => 'airtime/om/BaseCcShowStampPeer.php', - 'BaseCcShowStamp' => 'airtime/om/BaseCcShowStamp.php', - 'BaseCcShowStampQuery' => 'airtime/om/BaseCcShowStampQuery.php', + 'CcStampContentsTableMap' => 'airtime/map/CcStampContentsTableMap.php', + 'CcStampContentsPeer' => 'airtime/CcStampContentsPeer.php', + 'CcStampContents' => 'airtime/CcStampContents.php', + 'CcStampContentsQuery' => 'airtime/CcStampContentsQuery.php', + 'BaseCcStampContentsPeer' => 'airtime/om/BaseCcStampContentsPeer.php', + 'BaseCcStampContents' => 'airtime/om/BaseCcStampContents.php', + 'BaseCcStampContentsQuery' => 'airtime/om/BaseCcStampContentsQuery.php', + 'CcStampTableMap' => 'airtime/map/CcStampTableMap.php', + 'CcStampPeer' => 'airtime/CcStampPeer.php', + 'CcStamp' => 'airtime/CcStamp.php', + 'CcStampQuery' => 'airtime/CcStampQuery.php', + 'BaseCcStampPeer' => 'airtime/om/BaseCcStampPeer.php', + 'BaseCcStamp' => 'airtime/om/BaseCcStamp.php', + 'BaseCcStampQuery' => 'airtime/om/BaseCcStampQuery.php', ); \ No newline at end of file diff --git a/airtime_mvc/application/models/airtime/map/CcBlockTableMap.php b/airtime_mvc/application/models/airtime/map/CcBlockTableMap.php index b5d31f72e..558bb9a6e 100644 --- a/airtime_mvc/application/models/airtime/map/CcBlockTableMap.php +++ b/airtime_mvc/application/models/airtime/map/CcBlockTableMap.php @@ -58,7 +58,7 @@ class CcBlockTableMap extends TableMap { $this->addRelation('CcPlaylistcontents', 'CcPlaylistcontents', RelationMap::ONE_TO_MANY, array('id' => 'block_id', ), 'CASCADE', null); $this->addRelation('CcBlockcontents', 'CcBlockcontents', RelationMap::ONE_TO_MANY, array('id' => 'block_id', ), 'CASCADE', null); $this->addRelation('CcBlockcriteria', 'CcBlockcriteria', RelationMap::ONE_TO_MANY, array('id' => 'block_id', ), 'CASCADE', null); - $this->addRelation('CcShowStamp', 'CcShowStamp', RelationMap::ONE_TO_MANY, array('id' => 'block_id', ), 'CASCADE', null); + $this->addRelation('CcStampContents', 'CcStampContents', RelationMap::ONE_TO_MANY, array('id' => 'block_id', ), 'CASCADE', null); } // buildRelations() /** diff --git a/airtime_mvc/application/models/airtime/map/CcFilesTableMap.php b/airtime_mvc/application/models/airtime/map/CcFilesTableMap.php index 7f0a33679..295372810 100644 --- a/airtime_mvc/application/models/airtime/map/CcFilesTableMap.php +++ b/airtime_mvc/application/models/airtime/map/CcFilesTableMap.php @@ -123,7 +123,7 @@ class CcFilesTableMap extends TableMap { $this->addRelation('CcPlaylistcontents', 'CcPlaylistcontents', RelationMap::ONE_TO_MANY, array('id' => 'file_id', ), 'CASCADE', null); $this->addRelation('CcBlockcontents', 'CcBlockcontents', RelationMap::ONE_TO_MANY, array('id' => 'file_id', ), 'CASCADE', null); $this->addRelation('CcSchedule', 'CcSchedule', RelationMap::ONE_TO_MANY, array('id' => 'file_id', ), 'CASCADE', null); - $this->addRelation('CcShowStamp', 'CcShowStamp', RelationMap::ONE_TO_MANY, array('id' => 'file_id', ), 'CASCADE', null); + $this->addRelation('CcStampContents', 'CcStampContents', RelationMap::ONE_TO_MANY, array('id' => 'file_id', ), 'CASCADE', null); } // buildRelations() } // CcFilesTableMap diff --git a/airtime_mvc/application/models/airtime/map/CcPlaylistTableMap.php b/airtime_mvc/application/models/airtime/map/CcPlaylistTableMap.php index 3ba124cb6..ddaa78192 100644 --- a/airtime_mvc/application/models/airtime/map/CcPlaylistTableMap.php +++ b/airtime_mvc/application/models/airtime/map/CcPlaylistTableMap.php @@ -55,7 +55,7 @@ class CcPlaylistTableMap extends TableMap { { $this->addRelation('CcSubjs', 'CcSubjs', RelationMap::MANY_TO_ONE, array('creator_id' => 'id', ), 'CASCADE', null); $this->addRelation('CcPlaylistcontents', 'CcPlaylistcontents', RelationMap::ONE_TO_MANY, array('id' => 'playlist_id', ), 'CASCADE', null); - $this->addRelation('CcShowStamp', 'CcShowStamp', RelationMap::ONE_TO_MANY, array('id' => 'playlist_id', ), 'CASCADE', null); + $this->addRelation('CcStampContents', 'CcStampContents', RelationMap::ONE_TO_MANY, array('id' => 'playlist_id', ), 'CASCADE', null); } // buildRelations() /** diff --git a/airtime_mvc/application/models/airtime/map/CcShowInstancesTableMap.php b/airtime_mvc/application/models/airtime/map/CcShowInstancesTableMap.php index f556b1853..2ecb4f1db 100644 --- a/airtime_mvc/application/models/airtime/map/CcShowInstancesTableMap.php +++ b/airtime_mvc/application/models/airtime/map/CcShowInstancesTableMap.php @@ -63,7 +63,7 @@ class CcShowInstancesTableMap extends TableMap { $this->addRelation('CcFiles', 'CcFiles', RelationMap::MANY_TO_ONE, array('file_id' => 'id', ), 'CASCADE', null); $this->addRelation('CcShowInstancesRelatedByDbId', 'CcShowInstances', RelationMap::ONE_TO_MANY, array('id' => 'instance_id', ), 'CASCADE', null); $this->addRelation('CcSchedule', 'CcSchedule', RelationMap::ONE_TO_MANY, array('id' => 'instance_id', ), 'CASCADE', null); - $this->addRelation('CcShowStamp', 'CcShowStamp', RelationMap::ONE_TO_MANY, array('id' => 'instance_id', ), 'CASCADE', null); + $this->addRelation('CcStamp', 'CcStamp', RelationMap::ONE_TO_MANY, array('id' => 'instance_id', ), 'CASCADE', null); } // buildRelations() } // CcShowInstancesTableMap diff --git a/airtime_mvc/application/models/airtime/map/CcShowTableMap.php b/airtime_mvc/application/models/airtime/map/CcShowTableMap.php index 6acde02cd..ba62c1647 100644 --- a/airtime_mvc/application/models/airtime/map/CcShowTableMap.php +++ b/airtime_mvc/application/models/airtime/map/CcShowTableMap.php @@ -62,7 +62,7 @@ class CcShowTableMap extends TableMap { $this->addRelation('CcShowDays', 'CcShowDays', RelationMap::ONE_TO_MANY, array('id' => 'show_id', ), 'CASCADE', null); $this->addRelation('CcShowRebroadcast', 'CcShowRebroadcast', RelationMap::ONE_TO_MANY, array('id' => 'show_id', ), 'CASCADE', null); $this->addRelation('CcShowHosts', 'CcShowHosts', RelationMap::ONE_TO_MANY, array('id' => 'show_id', ), 'CASCADE', null); - $this->addRelation('CcShowStamp', 'CcShowStamp', RelationMap::ONE_TO_MANY, array('id' => 'show_id', ), 'CASCADE', null); + $this->addRelation('CcStamp', 'CcStamp', RelationMap::ONE_TO_MANY, array('id' => 'show_id', ), 'CASCADE', null); } // buildRelations() } // CcShowTableMap diff --git a/airtime_mvc/application/models/airtime/map/CcWebstreamTableMap.php b/airtime_mvc/application/models/airtime/map/CcWebstreamTableMap.php index 979c7034e..5370e7952 100644 --- a/airtime_mvc/application/models/airtime/map/CcWebstreamTableMap.php +++ b/airtime_mvc/application/models/airtime/map/CcWebstreamTableMap.php @@ -57,7 +57,7 @@ class CcWebstreamTableMap extends TableMap { public function buildRelations() { $this->addRelation('CcSchedule', 'CcSchedule', RelationMap::ONE_TO_MANY, array('id' => 'stream_id', ), 'CASCADE', null); - $this->addRelation('CcShowStamp', 'CcShowStamp', RelationMap::ONE_TO_MANY, array('id' => 'stream_id', ), 'CASCADE', null); + $this->addRelation('CcStampContents', 'CcStampContents', RelationMap::ONE_TO_MANY, array('id' => 'stream_id', ), 'CASCADE', null); } // buildRelations() } // CcWebstreamTableMap diff --git a/airtime_mvc/application/models/airtime/om/BaseCcBlock.php b/airtime_mvc/application/models/airtime/om/BaseCcBlock.php index 4314af05f..89a9cfbf1 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcBlock.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcBlock.php @@ -96,9 +96,9 @@ abstract class BaseCcBlock extends BaseObject implements Persistent protected $collCcBlockcriterias; /** - * @var array CcShowStamp[] Collection to store aggregation of CcShowStamp objects. + * @var array CcStampContents[] Collection to store aggregation of CcStampContents objects. */ - protected $collCcShowStamps; + protected $collCcStampContentss; /** * Flag to prevent endless save loop, if this object is referenced @@ -617,7 +617,7 @@ abstract class BaseCcBlock extends BaseObject implements Persistent $this->collCcBlockcriterias = null; - $this->collCcShowStamps = null; + $this->collCcStampContentss = null; } // if (deep) } @@ -788,8 +788,8 @@ abstract class BaseCcBlock extends BaseObject implements Persistent } } - if ($this->collCcShowStamps !== null) { - foreach ($this->collCcShowStamps as $referrerFK) { + if ($this->collCcStampContentss !== null) { + foreach ($this->collCcStampContentss as $referrerFK) { if (!$referrerFK->isDeleted()) { $affectedRows += $referrerFK->save($con); } @@ -903,8 +903,8 @@ abstract class BaseCcBlock extends BaseObject implements Persistent } } - if ($this->collCcShowStamps !== null) { - foreach ($this->collCcShowStamps as $referrerFK) { + if ($this->collCcStampContentss !== null) { + foreach ($this->collCcStampContentss as $referrerFK) { if (!$referrerFK->validate($columns)) { $failureMap = array_merge($failureMap, $referrerFK->getValidationFailures()); } @@ -1203,9 +1203,9 @@ abstract class BaseCcBlock extends BaseObject implements Persistent } } - foreach ($this->getCcShowStamps() as $relObj) { + foreach ($this->getCcStampContentss() as $relObj) { if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves - $copyObj->addCcShowStamp($relObj->copy($deepCopy)); + $copyObj->addCcStampContents($relObj->copy($deepCopy)); } } @@ -1706,36 +1706,36 @@ abstract class BaseCcBlock extends BaseObject implements Persistent } /** - * Clears out the collCcShowStamps collection + * Clears out the collCcStampContentss collection * * This does not modify the database; however, it will remove any associated objects, causing * them to be refetched by subsequent calls to accessor method. * * @return void - * @see addCcShowStamps() + * @see addCcStampContentss() */ - public function clearCcShowStamps() + public function clearCcStampContentss() { - $this->collCcShowStamps = null; // important to set this to NULL since that means it is uninitialized + $this->collCcStampContentss = null; // important to set this to NULL since that means it is uninitialized } /** - * Initializes the collCcShowStamps collection. + * Initializes the collCcStampContentss collection. * - * By default this just sets the collCcShowStamps collection to an empty array (like clearcollCcShowStamps()); + * By default this just sets the collCcStampContentss collection to an empty array (like clearcollCcStampContentss()); * however, you may wish to override this method in your stub class to provide setting appropriate * to your application -- for example, setting the initial array to the values stored in database. * * @return void */ - public function initCcShowStamps() + public function initCcStampContentss() { - $this->collCcShowStamps = new PropelObjectCollection(); - $this->collCcShowStamps->setModel('CcShowStamp'); + $this->collCcStampContentss = new PropelObjectCollection(); + $this->collCcStampContentss->setModel('CcStampContents'); } /** - * Gets an array of CcShowStamp objects which contain a foreign key that references this object. + * Gets an array of CcStampContents 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. @@ -1745,44 +1745,44 @@ abstract class BaseCcBlock extends BaseObject implements Persistent * * @param Criteria $criteria optional Criteria object to narrow the query * @param PropelPDO $con optional connection object - * @return PropelCollection|array CcShowStamp[] List of CcShowStamp objects + * @return PropelCollection|array CcStampContents[] List of CcStampContents objects * @throws PropelException */ - public function getCcShowStamps($criteria = null, PropelPDO $con = null) + public function getCcStampContentss($criteria = null, PropelPDO $con = null) { - if(null === $this->collCcShowStamps || null !== $criteria) { - if ($this->isNew() && null === $this->collCcShowStamps) { + if(null === $this->collCcStampContentss || null !== $criteria) { + if ($this->isNew() && null === $this->collCcStampContentss) { // return empty collection - $this->initCcShowStamps(); + $this->initCcStampContentss(); } else { - $collCcShowStamps = CcShowStampQuery::create(null, $criteria) + $collCcStampContentss = CcStampContentsQuery::create(null, $criteria) ->filterByCcBlock($this) ->find($con); if (null !== $criteria) { - return $collCcShowStamps; + return $collCcStampContentss; } - $this->collCcShowStamps = $collCcShowStamps; + $this->collCcStampContentss = $collCcStampContentss; } } - return $this->collCcShowStamps; + return $this->collCcStampContentss; } /** - * Returns the number of related CcShowStamp objects. + * Returns the number of related CcStampContents objects. * * @param Criteria $criteria * @param boolean $distinct * @param PropelPDO $con - * @return int Count of related CcShowStamp objects. + * @return int Count of related CcStampContents objects. * @throws PropelException */ - public function countCcShowStamps(Criteria $criteria = null, $distinct = false, PropelPDO $con = null) + public function countCcStampContentss(Criteria $criteria = null, $distinct = false, PropelPDO $con = null) { - if(null === $this->collCcShowStamps || null !== $criteria) { - if ($this->isNew() && null === $this->collCcShowStamps) { + if(null === $this->collCcStampContentss || null !== $criteria) { + if ($this->isNew() && null === $this->collCcStampContentss) { return 0; } else { - $query = CcShowStampQuery::create(null, $criteria); + $query = CcStampContentsQuery::create(null, $criteria); if($distinct) { $query->distinct(); } @@ -1791,25 +1791,25 @@ abstract class BaseCcBlock extends BaseObject implements Persistent ->count($con); } } else { - return count($this->collCcShowStamps); + return count($this->collCcStampContentss); } } /** - * Method called to associate a CcShowStamp object to this object - * through the CcShowStamp foreign key attribute. + * Method called to associate a CcStampContents object to this object + * through the CcStampContents foreign key attribute. * - * @param CcShowStamp $l CcShowStamp + * @param CcStampContents $l CcStampContents * @return void * @throws PropelException */ - public function addCcShowStamp(CcShowStamp $l) + public function addCcStampContents(CcStampContents $l) { - if ($this->collCcShowStamps === null) { - $this->initCcShowStamps(); + if ($this->collCcStampContentss === null) { + $this->initCcStampContentss(); } - if (!$this->collCcShowStamps->contains($l)) { // only add it if the **same** object is not already associated - $this->collCcShowStamps[]= $l; + if (!$this->collCcStampContentss->contains($l)) { // only add it if the **same** object is not already associated + $this->collCcStampContentss[]= $l; $l->setCcBlock($this); } } @@ -1820,7 +1820,7 @@ abstract class BaseCcBlock extends BaseObject implements Persistent * an identical criteria, it returns the collection. * Otherwise if this CcBlock is new, it will return * an empty collection; or if this CcBlock has previously - * been saved, it will retrieve related CcShowStamps from storage. + * been saved, it will retrieve related CcStampContentss from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you @@ -1829,14 +1829,14 @@ abstract class BaseCcBlock extends BaseObject implements Persistent * @param Criteria $criteria optional Criteria object to narrow the query * @param PropelPDO $con optional connection object * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) - * @return PropelCollection|array CcShowStamp[] List of CcShowStamp objects + * @return PropelCollection|array CcStampContents[] List of CcStampContents objects */ - public function getCcShowStampsJoinCcShow($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) + public function getCcStampContentssJoinCcStamp($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { - $query = CcShowStampQuery::create(null, $criteria); - $query->joinWith('CcShow', $join_behavior); + $query = CcStampContentsQuery::create(null, $criteria); + $query->joinWith('CcStamp', $join_behavior); - return $this->getCcShowStamps($query, $con); + return $this->getCcStampContentss($query, $con); } @@ -1845,7 +1845,7 @@ abstract class BaseCcBlock extends BaseObject implements Persistent * an identical criteria, it returns the collection. * Otherwise if this CcBlock is new, it will return * an empty collection; or if this CcBlock has previously - * been saved, it will retrieve related CcShowStamps from storage. + * been saved, it will retrieve related CcStampContentss from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you @@ -1854,39 +1854,14 @@ abstract class BaseCcBlock extends BaseObject implements Persistent * @param Criteria $criteria optional Criteria object to narrow the query * @param PropelPDO $con optional connection object * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) - * @return PropelCollection|array CcShowStamp[] List of CcShowStamp objects + * @return PropelCollection|array CcStampContents[] List of CcStampContents objects */ - public function getCcShowStampsJoinCcShowInstances($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) + public function getCcStampContentssJoinCcFiles($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { - $query = CcShowStampQuery::create(null, $criteria); - $query->joinWith('CcShowInstances', $join_behavior); - - return $this->getCcShowStamps($query, $con); - } - - - /** - * If this collection has already been initialized with - * an identical criteria, it returns the collection. - * Otherwise if this CcBlock is new, it will return - * an empty collection; or if this CcBlock has previously - * been saved, it will retrieve related CcShowStamps from storage. - * - * This method is protected by default in order to keep the public - * api reasonable. You can provide public methods for those you - * actually need in CcBlock. - * - * @param Criteria $criteria optional Criteria object to narrow the query - * @param PropelPDO $con optional connection object - * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) - * @return PropelCollection|array CcShowStamp[] List of CcShowStamp objects - */ - public function getCcShowStampsJoinCcFiles($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) - { - $query = CcShowStampQuery::create(null, $criteria); + $query = CcStampContentsQuery::create(null, $criteria); $query->joinWith('CcFiles', $join_behavior); - return $this->getCcShowStamps($query, $con); + return $this->getCcStampContentss($query, $con); } @@ -1895,7 +1870,7 @@ abstract class BaseCcBlock extends BaseObject implements Persistent * an identical criteria, it returns the collection. * Otherwise if this CcBlock is new, it will return * an empty collection; or if this CcBlock has previously - * been saved, it will retrieve related CcShowStamps from storage. + * been saved, it will retrieve related CcStampContentss from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you @@ -1904,14 +1879,14 @@ abstract class BaseCcBlock extends BaseObject implements Persistent * @param Criteria $criteria optional Criteria object to narrow the query * @param PropelPDO $con optional connection object * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) - * @return PropelCollection|array CcShowStamp[] List of CcShowStamp objects + * @return PropelCollection|array CcStampContents[] List of CcStampContents objects */ - public function getCcShowStampsJoinCcWebstream($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) + public function getCcStampContentssJoinCcWebstream($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { - $query = CcShowStampQuery::create(null, $criteria); + $query = CcStampContentsQuery::create(null, $criteria); $query->joinWith('CcWebstream', $join_behavior); - return $this->getCcShowStamps($query, $con); + return $this->getCcStampContentss($query, $con); } @@ -1920,7 +1895,7 @@ abstract class BaseCcBlock extends BaseObject implements Persistent * an identical criteria, it returns the collection. * Otherwise if this CcBlock is new, it will return * an empty collection; or if this CcBlock has previously - * been saved, it will retrieve related CcShowStamps from storage. + * been saved, it will retrieve related CcStampContentss from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you @@ -1929,14 +1904,14 @@ abstract class BaseCcBlock extends BaseObject implements Persistent * @param Criteria $criteria optional Criteria object to narrow the query * @param PropelPDO $con optional connection object * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) - * @return PropelCollection|array CcShowStamp[] List of CcShowStamp objects + * @return PropelCollection|array CcStampContents[] List of CcStampContents objects */ - public function getCcShowStampsJoinCcPlaylist($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) + public function getCcStampContentssJoinCcPlaylist($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { - $query = CcShowStampQuery::create(null, $criteria); + $query = CcStampContentsQuery::create(null, $criteria); $query->joinWith('CcPlaylist', $join_behavior); - return $this->getCcShowStamps($query, $con); + return $this->getCcStampContentss($query, $con); } /** @@ -1988,8 +1963,8 @@ abstract class BaseCcBlock extends BaseObject implements Persistent $o->clearAllReferences($deep); } } - if ($this->collCcShowStamps) { - foreach ((array) $this->collCcShowStamps as $o) { + if ($this->collCcStampContentss) { + foreach ((array) $this->collCcStampContentss as $o) { $o->clearAllReferences($deep); } } @@ -1998,7 +1973,7 @@ abstract class BaseCcBlock extends BaseObject implements Persistent $this->collCcPlaylistcontentss = null; $this->collCcBlockcontentss = null; $this->collCcBlockcriterias = null; - $this->collCcShowStamps = null; + $this->collCcStampContentss = null; $this->aCcSubjs = null; } diff --git a/airtime_mvc/application/models/airtime/om/BaseCcBlockPeer.php b/airtime_mvc/application/models/airtime/om/BaseCcBlockPeer.php index a5063dd8b..965069d3b 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcBlockPeer.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcBlockPeer.php @@ -382,9 +382,9 @@ abstract class BaseCcBlockPeer { // Invalidate objects in CcBlockcriteriaPeer instance pool, // since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule. CcBlockcriteriaPeer::clearInstancePool(); - // Invalidate objects in CcShowStampPeer instance pool, + // Invalidate objects in CcStampContentsPeer instance pool, // since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule. - CcShowStampPeer::clearInstancePool(); + CcStampContentsPeer::clearInstancePool(); } /** diff --git a/airtime_mvc/application/models/airtime/om/BaseCcBlockQuery.php b/airtime_mvc/application/models/airtime/om/BaseCcBlockQuery.php index ac160a1d2..eeecf413f 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcBlockQuery.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcBlockQuery.php @@ -44,9 +44,9 @@ * @method CcBlockQuery rightJoinCcBlockcriteria($relationAlias = '') Adds a RIGHT JOIN clause to the query using the CcBlockcriteria relation * @method CcBlockQuery innerJoinCcBlockcriteria($relationAlias = '') Adds a INNER JOIN clause to the query using the CcBlockcriteria relation * - * @method CcBlockQuery leftJoinCcShowStamp($relationAlias = '') Adds a LEFT JOIN clause to the query using the CcShowStamp relation - * @method CcBlockQuery rightJoinCcShowStamp($relationAlias = '') Adds a RIGHT JOIN clause to the query using the CcShowStamp relation - * @method CcBlockQuery innerJoinCcShowStamp($relationAlias = '') Adds a INNER JOIN clause to the query using the CcShowStamp relation + * @method CcBlockQuery leftJoinCcStampContents($relationAlias = '') Adds a LEFT JOIN clause to the query using the CcStampContents relation + * @method CcBlockQuery rightJoinCcStampContents($relationAlias = '') Adds a RIGHT JOIN clause to the query using the CcStampContents relation + * @method CcBlockQuery innerJoinCcStampContents($relationAlias = '') Adds a INNER JOIN clause to the query using the CcStampContents relation * * @method CcBlock findOne(PropelPDO $con = null) Return the first CcBlock matching the query * @method CcBlock findOneOrCreate(PropelPDO $con = null) Return the first CcBlock matching the query, or a new CcBlock object populated from the query conditions when no match is found @@ -632,31 +632,31 @@ abstract class BaseCcBlockQuery extends ModelCriteria } /** - * Filter the query by a related CcShowStamp object + * Filter the query by a related CcStampContents object * - * @param CcShowStamp $ccShowStamp the related object to use as filter + * @param CcStampContents $ccStampContents the related object to use as filter * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return CcBlockQuery The current query, for fluid interface */ - public function filterByCcShowStamp($ccShowStamp, $comparison = null) + public function filterByCcStampContents($ccStampContents, $comparison = null) { return $this - ->addUsingAlias(CcBlockPeer::ID, $ccShowStamp->getDbBlockId(), $comparison); + ->addUsingAlias(CcBlockPeer::ID, $ccStampContents->getDbBlockId(), $comparison); } /** - * Adds a JOIN clause to the query using the CcShowStamp relation + * Adds a JOIN clause to the query using the CcStampContents relation * * @param string $relationAlias optional alias for the relation * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' * * @return CcBlockQuery The current query, for fluid interface */ - public function joinCcShowStamp($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + public function joinCcStampContents($relationAlias = '', $joinType = Criteria::LEFT_JOIN) { $tableMap = $this->getTableMap(); - $relationMap = $tableMap->getRelation('CcShowStamp'); + $relationMap = $tableMap->getRelation('CcStampContents'); // create a ModelJoin object for this join $join = new ModelJoin(); @@ -671,14 +671,14 @@ abstract class BaseCcBlockQuery extends ModelCriteria $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); $this->addJoinObject($join, $relationAlias); } else { - $this->addJoinObject($join, 'CcShowStamp'); + $this->addJoinObject($join, 'CcStampContents'); } return $this; } /** - * Use the CcShowStamp relation CcShowStamp object + * Use the CcStampContents relation CcStampContents object * * @see useQuery() * @@ -686,13 +686,13 @@ abstract class BaseCcBlockQuery extends ModelCriteria * to be used as main alias in the secondary query * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' * - * @return CcShowStampQuery A secondary query class using the current class as primary query + * @return CcStampContentsQuery A secondary query class using the current class as primary query */ - public function useCcShowStampQuery($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + public function useCcStampContentsQuery($relationAlias = '', $joinType = Criteria::LEFT_JOIN) { return $this - ->joinCcShowStamp($relationAlias, $joinType) - ->useQuery($relationAlias ? $relationAlias : 'CcShowStamp', 'CcShowStampQuery'); + ->joinCcStampContents($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'CcStampContents', 'CcStampContentsQuery'); } /** diff --git a/airtime_mvc/application/models/airtime/om/BaseCcFiles.php b/airtime_mvc/application/models/airtime/om/BaseCcFiles.php index 6d995eaac..a8bed0eaa 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcFiles.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcFiles.php @@ -494,9 +494,9 @@ abstract class BaseCcFiles extends BaseObject implements Persistent protected $collCcSchedules; /** - * @var array CcShowStamp[] Collection to store aggregation of CcShowStamp objects. + * @var array CcStampContents[] Collection to store aggregation of CcStampContents objects. */ - protected $collCcShowStamps; + protected $collCcStampContentss; /** * Flag to prevent endless save loop, if this object is referenced @@ -3114,7 +3114,7 @@ abstract class BaseCcFiles extends BaseObject implements Persistent $this->collCcSchedules = null; - $this->collCcShowStamps = null; + $this->collCcStampContentss = null; } // if (deep) } @@ -3307,8 +3307,8 @@ abstract class BaseCcFiles extends BaseObject implements Persistent } } - if ($this->collCcShowStamps !== null) { - foreach ($this->collCcShowStamps as $referrerFK) { + if ($this->collCcStampContentss !== null) { + foreach ($this->collCcStampContentss as $referrerFK) { if (!$referrerFK->isDeleted()) { $affectedRows += $referrerFK->save($con); } @@ -3442,8 +3442,8 @@ abstract class BaseCcFiles extends BaseObject implements Persistent } } - if ($this->collCcShowStamps !== null) { - foreach ($this->collCcShowStamps as $referrerFK) { + if ($this->collCcStampContentss !== null) { + foreach ($this->collCcStampContentss as $referrerFK) { if (!$referrerFK->validate($columns)) { $failureMap = array_merge($failureMap, $referrerFK->getValidationFailures()); } @@ -4374,9 +4374,9 @@ abstract class BaseCcFiles extends BaseObject implements Persistent } } - foreach ($this->getCcShowStamps() as $relObj) { + foreach ($this->getCcStampContentss() as $relObj) { if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves - $copyObj->addCcShowStamp($relObj->copy($deepCopy)); + $copyObj->addCcStampContents($relObj->copy($deepCopy)); } } @@ -5184,36 +5184,36 @@ abstract class BaseCcFiles extends BaseObject implements Persistent } /** - * Clears out the collCcShowStamps collection + * Clears out the collCcStampContentss collection * * This does not modify the database; however, it will remove any associated objects, causing * them to be refetched by subsequent calls to accessor method. * * @return void - * @see addCcShowStamps() + * @see addCcStampContentss() */ - public function clearCcShowStamps() + public function clearCcStampContentss() { - $this->collCcShowStamps = null; // important to set this to NULL since that means it is uninitialized + $this->collCcStampContentss = null; // important to set this to NULL since that means it is uninitialized } /** - * Initializes the collCcShowStamps collection. + * Initializes the collCcStampContentss collection. * - * By default this just sets the collCcShowStamps collection to an empty array (like clearcollCcShowStamps()); + * By default this just sets the collCcStampContentss collection to an empty array (like clearcollCcStampContentss()); * however, you may wish to override this method in your stub class to provide setting appropriate * to your application -- for example, setting the initial array to the values stored in database. * * @return void */ - public function initCcShowStamps() + public function initCcStampContentss() { - $this->collCcShowStamps = new PropelObjectCollection(); - $this->collCcShowStamps->setModel('CcShowStamp'); + $this->collCcStampContentss = new PropelObjectCollection(); + $this->collCcStampContentss->setModel('CcStampContents'); } /** - * Gets an array of CcShowStamp objects which contain a foreign key that references this object. + * Gets an array of CcStampContents 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. @@ -5223,44 +5223,44 @@ abstract class BaseCcFiles extends BaseObject implements Persistent * * @param Criteria $criteria optional Criteria object to narrow the query * @param PropelPDO $con optional connection object - * @return PropelCollection|array CcShowStamp[] List of CcShowStamp objects + * @return PropelCollection|array CcStampContents[] List of CcStampContents objects * @throws PropelException */ - public function getCcShowStamps($criteria = null, PropelPDO $con = null) + public function getCcStampContentss($criteria = null, PropelPDO $con = null) { - if(null === $this->collCcShowStamps || null !== $criteria) { - if ($this->isNew() && null === $this->collCcShowStamps) { + if(null === $this->collCcStampContentss || null !== $criteria) { + if ($this->isNew() && null === $this->collCcStampContentss) { // return empty collection - $this->initCcShowStamps(); + $this->initCcStampContentss(); } else { - $collCcShowStamps = CcShowStampQuery::create(null, $criteria) + $collCcStampContentss = CcStampContentsQuery::create(null, $criteria) ->filterByCcFiles($this) ->find($con); if (null !== $criteria) { - return $collCcShowStamps; + return $collCcStampContentss; } - $this->collCcShowStamps = $collCcShowStamps; + $this->collCcStampContentss = $collCcStampContentss; } } - return $this->collCcShowStamps; + return $this->collCcStampContentss; } /** - * Returns the number of related CcShowStamp objects. + * Returns the number of related CcStampContents objects. * * @param Criteria $criteria * @param boolean $distinct * @param PropelPDO $con - * @return int Count of related CcShowStamp objects. + * @return int Count of related CcStampContents objects. * @throws PropelException */ - public function countCcShowStamps(Criteria $criteria = null, $distinct = false, PropelPDO $con = null) + public function countCcStampContentss(Criteria $criteria = null, $distinct = false, PropelPDO $con = null) { - if(null === $this->collCcShowStamps || null !== $criteria) { - if ($this->isNew() && null === $this->collCcShowStamps) { + if(null === $this->collCcStampContentss || null !== $criteria) { + if ($this->isNew() && null === $this->collCcStampContentss) { return 0; } else { - $query = CcShowStampQuery::create(null, $criteria); + $query = CcStampContentsQuery::create(null, $criteria); if($distinct) { $query->distinct(); } @@ -5269,25 +5269,25 @@ abstract class BaseCcFiles extends BaseObject implements Persistent ->count($con); } } else { - return count($this->collCcShowStamps); + return count($this->collCcStampContentss); } } /** - * Method called to associate a CcShowStamp object to this object - * through the CcShowStamp foreign key attribute. + * Method called to associate a CcStampContents object to this object + * through the CcStampContents foreign key attribute. * - * @param CcShowStamp $l CcShowStamp + * @param CcStampContents $l CcStampContents * @return void * @throws PropelException */ - public function addCcShowStamp(CcShowStamp $l) + public function addCcStampContents(CcStampContents $l) { - if ($this->collCcShowStamps === null) { - $this->initCcShowStamps(); + if ($this->collCcStampContentss === null) { + $this->initCcStampContentss(); } - if (!$this->collCcShowStamps->contains($l)) { // only add it if the **same** object is not already associated - $this->collCcShowStamps[]= $l; + if (!$this->collCcStampContentss->contains($l)) { // only add it if the **same** object is not already associated + $this->collCcStampContentss[]= $l; $l->setCcFiles($this); } } @@ -5298,7 +5298,7 @@ abstract class BaseCcFiles extends BaseObject implements Persistent * an identical criteria, it returns the collection. * Otherwise if this CcFiles is new, it will return * an empty collection; or if this CcFiles has previously - * been saved, it will retrieve related CcShowStamps from storage. + * been saved, it will retrieve related CcStampContentss from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you @@ -5307,14 +5307,14 @@ abstract class BaseCcFiles extends BaseObject implements Persistent * @param Criteria $criteria optional Criteria object to narrow the query * @param PropelPDO $con optional connection object * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) - * @return PropelCollection|array CcShowStamp[] List of CcShowStamp objects + * @return PropelCollection|array CcStampContents[] List of CcStampContents objects */ - public function getCcShowStampsJoinCcShow($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) + public function getCcStampContentssJoinCcStamp($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { - $query = CcShowStampQuery::create(null, $criteria); - $query->joinWith('CcShow', $join_behavior); + $query = CcStampContentsQuery::create(null, $criteria); + $query->joinWith('CcStamp', $join_behavior); - return $this->getCcShowStamps($query, $con); + return $this->getCcStampContentss($query, $con); } @@ -5323,7 +5323,7 @@ abstract class BaseCcFiles extends BaseObject implements Persistent * an identical criteria, it returns the collection. * Otherwise if this CcFiles is new, it will return * an empty collection; or if this CcFiles has previously - * been saved, it will retrieve related CcShowStamps from storage. + * been saved, it will retrieve related CcStampContentss from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you @@ -5332,39 +5332,14 @@ abstract class BaseCcFiles extends BaseObject implements Persistent * @param Criteria $criteria optional Criteria object to narrow the query * @param PropelPDO $con optional connection object * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) - * @return PropelCollection|array CcShowStamp[] List of CcShowStamp objects + * @return PropelCollection|array CcStampContents[] List of CcStampContents objects */ - public function getCcShowStampsJoinCcShowInstances($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) + public function getCcStampContentssJoinCcWebstream($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { - $query = CcShowStampQuery::create(null, $criteria); - $query->joinWith('CcShowInstances', $join_behavior); - - return $this->getCcShowStamps($query, $con); - } - - - /** - * If this collection has already been initialized with - * an identical criteria, it returns the collection. - * Otherwise if this CcFiles is new, it will return - * an empty collection; or if this CcFiles has previously - * been saved, it will retrieve related CcShowStamps from storage. - * - * This method is protected by default in order to keep the public - * api reasonable. You can provide public methods for those you - * actually need in CcFiles. - * - * @param Criteria $criteria optional Criteria object to narrow the query - * @param PropelPDO $con optional connection object - * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) - * @return PropelCollection|array CcShowStamp[] List of CcShowStamp objects - */ - public function getCcShowStampsJoinCcWebstream($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) - { - $query = CcShowStampQuery::create(null, $criteria); + $query = CcStampContentsQuery::create(null, $criteria); $query->joinWith('CcWebstream', $join_behavior); - return $this->getCcShowStamps($query, $con); + return $this->getCcStampContentss($query, $con); } @@ -5373,7 +5348,7 @@ abstract class BaseCcFiles extends BaseObject implements Persistent * an identical criteria, it returns the collection. * Otherwise if this CcFiles is new, it will return * an empty collection; or if this CcFiles has previously - * been saved, it will retrieve related CcShowStamps from storage. + * been saved, it will retrieve related CcStampContentss from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you @@ -5382,14 +5357,14 @@ abstract class BaseCcFiles extends BaseObject implements Persistent * @param Criteria $criteria optional Criteria object to narrow the query * @param PropelPDO $con optional connection object * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) - * @return PropelCollection|array CcShowStamp[] List of CcShowStamp objects + * @return PropelCollection|array CcStampContents[] List of CcStampContents objects */ - public function getCcShowStampsJoinCcBlock($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) + public function getCcStampContentssJoinCcBlock($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { - $query = CcShowStampQuery::create(null, $criteria); + $query = CcStampContentsQuery::create(null, $criteria); $query->joinWith('CcBlock', $join_behavior); - return $this->getCcShowStamps($query, $con); + return $this->getCcStampContentss($query, $con); } @@ -5398,7 +5373,7 @@ abstract class BaseCcFiles extends BaseObject implements Persistent * an identical criteria, it returns the collection. * Otherwise if this CcFiles is new, it will return * an empty collection; or if this CcFiles has previously - * been saved, it will retrieve related CcShowStamps from storage. + * been saved, it will retrieve related CcStampContentss from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you @@ -5407,14 +5382,14 @@ abstract class BaseCcFiles extends BaseObject implements Persistent * @param Criteria $criteria optional Criteria object to narrow the query * @param PropelPDO $con optional connection object * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) - * @return PropelCollection|array CcShowStamp[] List of CcShowStamp objects + * @return PropelCollection|array CcStampContents[] List of CcStampContents objects */ - public function getCcShowStampsJoinCcPlaylist($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) + public function getCcStampContentssJoinCcPlaylist($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { - $query = CcShowStampQuery::create(null, $criteria); + $query = CcStampContentsQuery::create(null, $criteria); $query->joinWith('CcPlaylist', $join_behavior); - return $this->getCcShowStamps($query, $con); + return $this->getCcStampContentss($query, $con); } /** @@ -5533,8 +5508,8 @@ abstract class BaseCcFiles extends BaseObject implements Persistent $o->clearAllReferences($deep); } } - if ($this->collCcShowStamps) { - foreach ((array) $this->collCcShowStamps as $o) { + if ($this->collCcStampContentss) { + foreach ((array) $this->collCcStampContentss as $o) { $o->clearAllReferences($deep); } } @@ -5544,7 +5519,7 @@ abstract class BaseCcFiles extends BaseObject implements Persistent $this->collCcPlaylistcontentss = null; $this->collCcBlockcontentss = null; $this->collCcSchedules = null; - $this->collCcShowStamps = null; + $this->collCcStampContentss = null; $this->aFkOwner = null; $this->aCcSubjsRelatedByDbEditedby = null; $this->aCcMusicDirs = null; diff --git a/airtime_mvc/application/models/airtime/om/BaseCcFilesPeer.php b/airtime_mvc/application/models/airtime/om/BaseCcFilesPeer.php index 331dc1bfd..0f5ecc02f 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcFilesPeer.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcFilesPeer.php @@ -695,9 +695,9 @@ abstract class BaseCcFilesPeer { // Invalidate objects in CcSchedulePeer instance pool, // since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule. CcSchedulePeer::clearInstancePool(); - // Invalidate objects in CcShowStampPeer instance pool, + // Invalidate objects in CcStampContentsPeer instance pool, // since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule. - CcShowStampPeer::clearInstancePool(); + CcStampContentsPeer::clearInstancePool(); } /** diff --git a/airtime_mvc/application/models/airtime/om/BaseCcFilesQuery.php b/airtime_mvc/application/models/airtime/om/BaseCcFilesQuery.php index ae5c46c28..5a9113904 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcFilesQuery.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcFilesQuery.php @@ -180,9 +180,9 @@ * @method CcFilesQuery rightJoinCcSchedule($relationAlias = '') Adds a RIGHT JOIN clause to the query using the CcSchedule relation * @method CcFilesQuery innerJoinCcSchedule($relationAlias = '') Adds a INNER JOIN clause to the query using the CcSchedule relation * - * @method CcFilesQuery leftJoinCcShowStamp($relationAlias = '') Adds a LEFT JOIN clause to the query using the CcShowStamp relation - * @method CcFilesQuery rightJoinCcShowStamp($relationAlias = '') Adds a RIGHT JOIN clause to the query using the CcShowStamp relation - * @method CcFilesQuery innerJoinCcShowStamp($relationAlias = '') Adds a INNER JOIN clause to the query using the CcShowStamp relation + * @method CcFilesQuery leftJoinCcStampContents($relationAlias = '') Adds a LEFT JOIN clause to the query using the CcStampContents relation + * @method CcFilesQuery rightJoinCcStampContents($relationAlias = '') Adds a RIGHT JOIN clause to the query using the CcStampContents relation + * @method CcFilesQuery innerJoinCcStampContents($relationAlias = '') Adds a INNER JOIN clause to the query using the CcStampContents relation * * @method CcFiles findOne(PropelPDO $con = null) Return the first CcFiles matching the query * @method CcFiles findOneOrCreate(PropelPDO $con = null) Return the first CcFiles matching the query, or a new CcFiles object populated from the query conditions when no match is found @@ -2540,31 +2540,31 @@ abstract class BaseCcFilesQuery extends ModelCriteria } /** - * Filter the query by a related CcShowStamp object + * Filter the query by a related CcStampContents object * - * @param CcShowStamp $ccShowStamp the related object to use as filter + * @param CcStampContents $ccStampContents the related object to use as filter * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return CcFilesQuery The current query, for fluid interface */ - public function filterByCcShowStamp($ccShowStamp, $comparison = null) + public function filterByCcStampContents($ccStampContents, $comparison = null) { return $this - ->addUsingAlias(CcFilesPeer::ID, $ccShowStamp->getDbFileId(), $comparison); + ->addUsingAlias(CcFilesPeer::ID, $ccStampContents->getDbFileId(), $comparison); } /** - * Adds a JOIN clause to the query using the CcShowStamp relation + * Adds a JOIN clause to the query using the CcStampContents relation * * @param string $relationAlias optional alias for the relation * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' * * @return CcFilesQuery The current query, for fluid interface */ - public function joinCcShowStamp($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + public function joinCcStampContents($relationAlias = '', $joinType = Criteria::LEFT_JOIN) { $tableMap = $this->getTableMap(); - $relationMap = $tableMap->getRelation('CcShowStamp'); + $relationMap = $tableMap->getRelation('CcStampContents'); // create a ModelJoin object for this join $join = new ModelJoin(); @@ -2579,14 +2579,14 @@ abstract class BaseCcFilesQuery extends ModelCriteria $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); $this->addJoinObject($join, $relationAlias); } else { - $this->addJoinObject($join, 'CcShowStamp'); + $this->addJoinObject($join, 'CcStampContents'); } return $this; } /** - * Use the CcShowStamp relation CcShowStamp object + * Use the CcStampContents relation CcStampContents object * * @see useQuery() * @@ -2594,13 +2594,13 @@ abstract class BaseCcFilesQuery extends ModelCriteria * to be used as main alias in the secondary query * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' * - * @return CcShowStampQuery A secondary query class using the current class as primary query + * @return CcStampContentsQuery A secondary query class using the current class as primary query */ - public function useCcShowStampQuery($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + public function useCcStampContentsQuery($relationAlias = '', $joinType = Criteria::LEFT_JOIN) { return $this - ->joinCcShowStamp($relationAlias, $joinType) - ->useQuery($relationAlias ? $relationAlias : 'CcShowStamp', 'CcShowStampQuery'); + ->joinCcStampContents($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'CcStampContents', 'CcStampContentsQuery'); } /** diff --git a/airtime_mvc/application/models/airtime/om/BaseCcPlaylist.php b/airtime_mvc/application/models/airtime/om/BaseCcPlaylist.php index fb822e999..e41337be9 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcPlaylist.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcPlaylist.php @@ -79,9 +79,9 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent protected $collCcPlaylistcontentss; /** - * @var array CcShowStamp[] Collection to store aggregation of CcShowStamp objects. + * @var array CcStampContents[] Collection to store aggregation of CcStampContents objects. */ - protected $collCcShowStamps; + protected $collCcStampContentss; /** * Flag to prevent endless save loop, if this object is referenced @@ -560,7 +560,7 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent $this->aCcSubjs = null; $this->collCcPlaylistcontentss = null; - $this->collCcShowStamps = null; + $this->collCcStampContentss = null; } // if (deep) } @@ -715,8 +715,8 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent } } - if ($this->collCcShowStamps !== null) { - foreach ($this->collCcShowStamps as $referrerFK) { + if ($this->collCcStampContentss !== null) { + foreach ($this->collCcStampContentss as $referrerFK) { if (!$referrerFK->isDeleted()) { $affectedRows += $referrerFK->save($con); } @@ -814,8 +814,8 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent } } - if ($this->collCcShowStamps !== null) { - foreach ($this->collCcShowStamps as $referrerFK) { + if ($this->collCcStampContentss !== null) { + foreach ($this->collCcStampContentss as $referrerFK) { if (!$referrerFK->validate($columns)) { $failureMap = array_merge($failureMap, $referrerFK->getValidationFailures()); } @@ -1092,9 +1092,9 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent } } - foreach ($this->getCcShowStamps() as $relObj) { + foreach ($this->getCcStampContentss() as $relObj) { if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves - $copyObj->addCcShowStamp($relObj->copy($deepCopy)); + $copyObj->addCcStampContents($relObj->copy($deepCopy)); } } @@ -1352,36 +1352,36 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent } /** - * Clears out the collCcShowStamps collection + * Clears out the collCcStampContentss collection * * This does not modify the database; however, it will remove any associated objects, causing * them to be refetched by subsequent calls to accessor method. * * @return void - * @see addCcShowStamps() + * @see addCcStampContentss() */ - public function clearCcShowStamps() + public function clearCcStampContentss() { - $this->collCcShowStamps = null; // important to set this to NULL since that means it is uninitialized + $this->collCcStampContentss = null; // important to set this to NULL since that means it is uninitialized } /** - * Initializes the collCcShowStamps collection. + * Initializes the collCcStampContentss collection. * - * By default this just sets the collCcShowStamps collection to an empty array (like clearcollCcShowStamps()); + * By default this just sets the collCcStampContentss collection to an empty array (like clearcollCcStampContentss()); * however, you may wish to override this method in your stub class to provide setting appropriate * to your application -- for example, setting the initial array to the values stored in database. * * @return void */ - public function initCcShowStamps() + public function initCcStampContentss() { - $this->collCcShowStamps = new PropelObjectCollection(); - $this->collCcShowStamps->setModel('CcShowStamp'); + $this->collCcStampContentss = new PropelObjectCollection(); + $this->collCcStampContentss->setModel('CcStampContents'); } /** - * Gets an array of CcShowStamp objects which contain a foreign key that references this object. + * Gets an array of CcStampContents 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. @@ -1391,44 +1391,44 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent * * @param Criteria $criteria optional Criteria object to narrow the query * @param PropelPDO $con optional connection object - * @return PropelCollection|array CcShowStamp[] List of CcShowStamp objects + * @return PropelCollection|array CcStampContents[] List of CcStampContents objects * @throws PropelException */ - public function getCcShowStamps($criteria = null, PropelPDO $con = null) + public function getCcStampContentss($criteria = null, PropelPDO $con = null) { - if(null === $this->collCcShowStamps || null !== $criteria) { - if ($this->isNew() && null === $this->collCcShowStamps) { + if(null === $this->collCcStampContentss || null !== $criteria) { + if ($this->isNew() && null === $this->collCcStampContentss) { // return empty collection - $this->initCcShowStamps(); + $this->initCcStampContentss(); } else { - $collCcShowStamps = CcShowStampQuery::create(null, $criteria) + $collCcStampContentss = CcStampContentsQuery::create(null, $criteria) ->filterByCcPlaylist($this) ->find($con); if (null !== $criteria) { - return $collCcShowStamps; + return $collCcStampContentss; } - $this->collCcShowStamps = $collCcShowStamps; + $this->collCcStampContentss = $collCcStampContentss; } } - return $this->collCcShowStamps; + return $this->collCcStampContentss; } /** - * Returns the number of related CcShowStamp objects. + * Returns the number of related CcStampContents objects. * * @param Criteria $criteria * @param boolean $distinct * @param PropelPDO $con - * @return int Count of related CcShowStamp objects. + * @return int Count of related CcStampContents objects. * @throws PropelException */ - public function countCcShowStamps(Criteria $criteria = null, $distinct = false, PropelPDO $con = null) + public function countCcStampContentss(Criteria $criteria = null, $distinct = false, PropelPDO $con = null) { - if(null === $this->collCcShowStamps || null !== $criteria) { - if ($this->isNew() && null === $this->collCcShowStamps) { + if(null === $this->collCcStampContentss || null !== $criteria) { + if ($this->isNew() && null === $this->collCcStampContentss) { return 0; } else { - $query = CcShowStampQuery::create(null, $criteria); + $query = CcStampContentsQuery::create(null, $criteria); if($distinct) { $query->distinct(); } @@ -1437,25 +1437,25 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent ->count($con); } } else { - return count($this->collCcShowStamps); + return count($this->collCcStampContentss); } } /** - * Method called to associate a CcShowStamp object to this object - * through the CcShowStamp foreign key attribute. + * Method called to associate a CcStampContents object to this object + * through the CcStampContents foreign key attribute. * - * @param CcShowStamp $l CcShowStamp + * @param CcStampContents $l CcStampContents * @return void * @throws PropelException */ - public function addCcShowStamp(CcShowStamp $l) + public function addCcStampContents(CcStampContents $l) { - if ($this->collCcShowStamps === null) { - $this->initCcShowStamps(); + if ($this->collCcStampContentss === null) { + $this->initCcStampContentss(); } - if (!$this->collCcShowStamps->contains($l)) { // only add it if the **same** object is not already associated - $this->collCcShowStamps[]= $l; + if (!$this->collCcStampContentss->contains($l)) { // only add it if the **same** object is not already associated + $this->collCcStampContentss[]= $l; $l->setCcPlaylist($this); } } @@ -1466,7 +1466,7 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent * an identical criteria, it returns the collection. * Otherwise if this CcPlaylist is new, it will return * an empty collection; or if this CcPlaylist has previously - * been saved, it will retrieve related CcShowStamps from storage. + * been saved, it will retrieve related CcStampContentss from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you @@ -1475,14 +1475,14 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent * @param Criteria $criteria optional Criteria object to narrow the query * @param PropelPDO $con optional connection object * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) - * @return PropelCollection|array CcShowStamp[] List of CcShowStamp objects + * @return PropelCollection|array CcStampContents[] List of CcStampContents objects */ - public function getCcShowStampsJoinCcShow($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) + public function getCcStampContentssJoinCcStamp($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { - $query = CcShowStampQuery::create(null, $criteria); - $query->joinWith('CcShow', $join_behavior); + $query = CcStampContentsQuery::create(null, $criteria); + $query->joinWith('CcStamp', $join_behavior); - return $this->getCcShowStamps($query, $con); + return $this->getCcStampContentss($query, $con); } @@ -1491,7 +1491,7 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent * an identical criteria, it returns the collection. * Otherwise if this CcPlaylist is new, it will return * an empty collection; or if this CcPlaylist has previously - * been saved, it will retrieve related CcShowStamps from storage. + * been saved, it will retrieve related CcStampContentss from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you @@ -1500,39 +1500,14 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent * @param Criteria $criteria optional Criteria object to narrow the query * @param PropelPDO $con optional connection object * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) - * @return PropelCollection|array CcShowStamp[] List of CcShowStamp objects + * @return PropelCollection|array CcStampContents[] List of CcStampContents objects */ - public function getCcShowStampsJoinCcShowInstances($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) + public function getCcStampContentssJoinCcFiles($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { - $query = CcShowStampQuery::create(null, $criteria); - $query->joinWith('CcShowInstances', $join_behavior); - - return $this->getCcShowStamps($query, $con); - } - - - /** - * If this collection has already been initialized with - * an identical criteria, it returns the collection. - * Otherwise if this CcPlaylist is new, it will return - * an empty collection; or if this CcPlaylist has previously - * been saved, it will retrieve related CcShowStamps from storage. - * - * This method is protected by default in order to keep the public - * api reasonable. You can provide public methods for those you - * actually need in CcPlaylist. - * - * @param Criteria $criteria optional Criteria object to narrow the query - * @param PropelPDO $con optional connection object - * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) - * @return PropelCollection|array CcShowStamp[] List of CcShowStamp objects - */ - public function getCcShowStampsJoinCcFiles($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) - { - $query = CcShowStampQuery::create(null, $criteria); + $query = CcStampContentsQuery::create(null, $criteria); $query->joinWith('CcFiles', $join_behavior); - return $this->getCcShowStamps($query, $con); + return $this->getCcStampContentss($query, $con); } @@ -1541,7 +1516,7 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent * an identical criteria, it returns the collection. * Otherwise if this CcPlaylist is new, it will return * an empty collection; or if this CcPlaylist has previously - * been saved, it will retrieve related CcShowStamps from storage. + * been saved, it will retrieve related CcStampContentss from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you @@ -1550,14 +1525,14 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent * @param Criteria $criteria optional Criteria object to narrow the query * @param PropelPDO $con optional connection object * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) - * @return PropelCollection|array CcShowStamp[] List of CcShowStamp objects + * @return PropelCollection|array CcStampContents[] List of CcStampContents objects */ - public function getCcShowStampsJoinCcWebstream($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) + public function getCcStampContentssJoinCcWebstream($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { - $query = CcShowStampQuery::create(null, $criteria); + $query = CcStampContentsQuery::create(null, $criteria); $query->joinWith('CcWebstream', $join_behavior); - return $this->getCcShowStamps($query, $con); + return $this->getCcStampContentss($query, $con); } @@ -1566,7 +1541,7 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent * an identical criteria, it returns the collection. * Otherwise if this CcPlaylist is new, it will return * an empty collection; or if this CcPlaylist has previously - * been saved, it will retrieve related CcShowStamps from storage. + * been saved, it will retrieve related CcStampContentss from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you @@ -1575,14 +1550,14 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent * @param Criteria $criteria optional Criteria object to narrow the query * @param PropelPDO $con optional connection object * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) - * @return PropelCollection|array CcShowStamp[] List of CcShowStamp objects + * @return PropelCollection|array CcStampContents[] List of CcStampContents objects */ - public function getCcShowStampsJoinCcBlock($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) + public function getCcStampContentssJoinCcBlock($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { - $query = CcShowStampQuery::create(null, $criteria); + $query = CcStampContentsQuery::create(null, $criteria); $query->joinWith('CcBlock', $join_behavior); - return $this->getCcShowStamps($query, $con); + return $this->getCcStampContentss($query, $con); } /** @@ -1623,15 +1598,15 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent $o->clearAllReferences($deep); } } - if ($this->collCcShowStamps) { - foreach ((array) $this->collCcShowStamps as $o) { + if ($this->collCcStampContentss) { + foreach ((array) $this->collCcStampContentss as $o) { $o->clearAllReferences($deep); } } } // if ($deep) $this->collCcPlaylistcontentss = null; - $this->collCcShowStamps = null; + $this->collCcStampContentss = null; $this->aCcSubjs = null; } diff --git a/airtime_mvc/application/models/airtime/om/BaseCcPlaylistPeer.php b/airtime_mvc/application/models/airtime/om/BaseCcPlaylistPeer.php index b8f2ce721..36c810648 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcPlaylistPeer.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcPlaylistPeer.php @@ -371,9 +371,9 @@ abstract class BaseCcPlaylistPeer { // Invalidate objects in CcPlaylistcontentsPeer instance pool, // since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule. CcPlaylistcontentsPeer::clearInstancePool(); - // Invalidate objects in CcShowStampPeer instance pool, + // Invalidate objects in CcStampContentsPeer instance pool, // since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule. - CcShowStampPeer::clearInstancePool(); + CcStampContentsPeer::clearInstancePool(); } /** diff --git a/airtime_mvc/application/models/airtime/om/BaseCcPlaylistQuery.php b/airtime_mvc/application/models/airtime/om/BaseCcPlaylistQuery.php index 6b365ed5a..3ca7d19a7 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcPlaylistQuery.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcPlaylistQuery.php @@ -34,9 +34,9 @@ * @method CcPlaylistQuery rightJoinCcPlaylistcontents($relationAlias = '') Adds a RIGHT JOIN clause to the query using the CcPlaylistcontents relation * @method CcPlaylistQuery innerJoinCcPlaylistcontents($relationAlias = '') Adds a INNER JOIN clause to the query using the CcPlaylistcontents relation * - * @method CcPlaylistQuery leftJoinCcShowStamp($relationAlias = '') Adds a LEFT JOIN clause to the query using the CcShowStamp relation - * @method CcPlaylistQuery rightJoinCcShowStamp($relationAlias = '') Adds a RIGHT JOIN clause to the query using the CcShowStamp relation - * @method CcPlaylistQuery innerJoinCcShowStamp($relationAlias = '') Adds a INNER JOIN clause to the query using the CcShowStamp relation + * @method CcPlaylistQuery leftJoinCcStampContents($relationAlias = '') Adds a LEFT JOIN clause to the query using the CcStampContents relation + * @method CcPlaylistQuery rightJoinCcStampContents($relationAlias = '') Adds a RIGHT JOIN clause to the query using the CcStampContents relation + * @method CcPlaylistQuery innerJoinCcStampContents($relationAlias = '') Adds a INNER JOIN clause to the query using the CcStampContents relation * * @method CcPlaylist findOne(PropelPDO $con = null) Return the first CcPlaylist matching the query * @method CcPlaylist findOneOrCreate(PropelPDO $con = null) Return the first CcPlaylist matching the query, or a new CcPlaylist object populated from the query conditions when no match is found @@ -470,31 +470,31 @@ abstract class BaseCcPlaylistQuery extends ModelCriteria } /** - * Filter the query by a related CcShowStamp object + * Filter the query by a related CcStampContents object * - * @param CcShowStamp $ccShowStamp the related object to use as filter + * @param CcStampContents $ccStampContents the related object to use as filter * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return CcPlaylistQuery The current query, for fluid interface */ - public function filterByCcShowStamp($ccShowStamp, $comparison = null) + public function filterByCcStampContents($ccStampContents, $comparison = null) { return $this - ->addUsingAlias(CcPlaylistPeer::ID, $ccShowStamp->getDbPlaylistId(), $comparison); + ->addUsingAlias(CcPlaylistPeer::ID, $ccStampContents->getDbPlaylistId(), $comparison); } /** - * Adds a JOIN clause to the query using the CcShowStamp relation + * Adds a JOIN clause to the query using the CcStampContents relation * * @param string $relationAlias optional alias for the relation * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' * * @return CcPlaylistQuery The current query, for fluid interface */ - public function joinCcShowStamp($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + public function joinCcStampContents($relationAlias = '', $joinType = Criteria::LEFT_JOIN) { $tableMap = $this->getTableMap(); - $relationMap = $tableMap->getRelation('CcShowStamp'); + $relationMap = $tableMap->getRelation('CcStampContents'); // create a ModelJoin object for this join $join = new ModelJoin(); @@ -509,14 +509,14 @@ abstract class BaseCcPlaylistQuery extends ModelCriteria $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); $this->addJoinObject($join, $relationAlias); } else { - $this->addJoinObject($join, 'CcShowStamp'); + $this->addJoinObject($join, 'CcStampContents'); } return $this; } /** - * Use the CcShowStamp relation CcShowStamp object + * Use the CcStampContents relation CcStampContents object * * @see useQuery() * @@ -524,13 +524,13 @@ abstract class BaseCcPlaylistQuery extends ModelCriteria * to be used as main alias in the secondary query * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' * - * @return CcShowStampQuery A secondary query class using the current class as primary query + * @return CcStampContentsQuery A secondary query class using the current class as primary query */ - public function useCcShowStampQuery($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + public function useCcStampContentsQuery($relationAlias = '', $joinType = Criteria::LEFT_JOIN) { return $this - ->joinCcShowStamp($relationAlias, $joinType) - ->useQuery($relationAlias ? $relationAlias : 'CcShowStamp', 'CcShowStampQuery'); + ->joinCcStampContents($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'CcStampContents', 'CcStampContentsQuery'); } /** diff --git a/airtime_mvc/application/models/airtime/om/BaseCcShow.php b/airtime_mvc/application/models/airtime/om/BaseCcShow.php index 662ce9cff..311b33969 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcShow.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcShow.php @@ -123,9 +123,9 @@ abstract class BaseCcShow extends BaseObject implements Persistent protected $collCcShowHostss; /** - * @var array CcShowStamp[] Collection to store aggregation of CcShowStamp objects. + * @var array CcStamp[] Collection to store aggregation of CcStamp objects. */ - protected $collCcShowStamps; + protected $collCcStamps; /** * Flag to prevent endless save loop, if this object is referenced @@ -673,7 +673,7 @@ abstract class BaseCcShow extends BaseObject implements Persistent $this->collCcShowHostss = null; - $this->collCcShowStamps = null; + $this->collCcStamps = null; } // if (deep) } @@ -840,8 +840,8 @@ abstract class BaseCcShow extends BaseObject implements Persistent } } - if ($this->collCcShowStamps !== null) { - foreach ($this->collCcShowStamps as $referrerFK) { + if ($this->collCcStamps !== null) { + foreach ($this->collCcStamps as $referrerFK) { if (!$referrerFK->isDeleted()) { $affectedRows += $referrerFK->save($con); } @@ -951,8 +951,8 @@ abstract class BaseCcShow extends BaseObject implements Persistent } } - if ($this->collCcShowStamps !== null) { - foreach ($this->collCcShowStamps as $referrerFK) { + if ($this->collCcStamps !== null) { + foreach ($this->collCcStamps as $referrerFK) { if (!$referrerFK->validate($columns)) { $failureMap = array_merge($failureMap, $referrerFK->getValidationFailures()); } @@ -1291,9 +1291,9 @@ abstract class BaseCcShow extends BaseObject implements Persistent } } - foreach ($this->getCcShowStamps() as $relObj) { + foreach ($this->getCcStamps() as $relObj) { if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves - $copyObj->addCcShowStamp($relObj->copy($deepCopy)); + $copyObj->addCcStamp($relObj->copy($deepCopy)); } } @@ -1854,36 +1854,36 @@ abstract class BaseCcShow extends BaseObject implements Persistent } /** - * Clears out the collCcShowStamps collection + * Clears out the collCcStamps collection * * This does not modify the database; however, it will remove any associated objects, causing * them to be refetched by subsequent calls to accessor method. * * @return void - * @see addCcShowStamps() + * @see addCcStamps() */ - public function clearCcShowStamps() + public function clearCcStamps() { - $this->collCcShowStamps = null; // important to set this to NULL since that means it is uninitialized + $this->collCcStamps = null; // important to set this to NULL since that means it is uninitialized } /** - * Initializes the collCcShowStamps collection. + * Initializes the collCcStamps collection. * - * By default this just sets the collCcShowStamps collection to an empty array (like clearcollCcShowStamps()); + * By default this just sets the collCcStamps collection to an empty array (like clearcollCcStamps()); * however, you may wish to override this method in your stub class to provide setting appropriate * to your application -- for example, setting the initial array to the values stored in database. * * @return void */ - public function initCcShowStamps() + public function initCcStamps() { - $this->collCcShowStamps = new PropelObjectCollection(); - $this->collCcShowStamps->setModel('CcShowStamp'); + $this->collCcStamps = new PropelObjectCollection(); + $this->collCcStamps->setModel('CcStamp'); } /** - * Gets an array of CcShowStamp objects which contain a foreign key that references this object. + * Gets an array of CcStamp 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. @@ -1893,44 +1893,44 @@ abstract class BaseCcShow extends BaseObject implements Persistent * * @param Criteria $criteria optional Criteria object to narrow the query * @param PropelPDO $con optional connection object - * @return PropelCollection|array CcShowStamp[] List of CcShowStamp objects + * @return PropelCollection|array CcStamp[] List of CcStamp objects * @throws PropelException */ - public function getCcShowStamps($criteria = null, PropelPDO $con = null) + public function getCcStamps($criteria = null, PropelPDO $con = null) { - if(null === $this->collCcShowStamps || null !== $criteria) { - if ($this->isNew() && null === $this->collCcShowStamps) { + if(null === $this->collCcStamps || null !== $criteria) { + if ($this->isNew() && null === $this->collCcStamps) { // return empty collection - $this->initCcShowStamps(); + $this->initCcStamps(); } else { - $collCcShowStamps = CcShowStampQuery::create(null, $criteria) + $collCcStamps = CcStampQuery::create(null, $criteria) ->filterByCcShow($this) ->find($con); if (null !== $criteria) { - return $collCcShowStamps; + return $collCcStamps; } - $this->collCcShowStamps = $collCcShowStamps; + $this->collCcStamps = $collCcStamps; } } - return $this->collCcShowStamps; + return $this->collCcStamps; } /** - * Returns the number of related CcShowStamp objects. + * Returns the number of related CcStamp objects. * * @param Criteria $criteria * @param boolean $distinct * @param PropelPDO $con - * @return int Count of related CcShowStamp objects. + * @return int Count of related CcStamp objects. * @throws PropelException */ - public function countCcShowStamps(Criteria $criteria = null, $distinct = false, PropelPDO $con = null) + public function countCcStamps(Criteria $criteria = null, $distinct = false, PropelPDO $con = null) { - if(null === $this->collCcShowStamps || null !== $criteria) { - if ($this->isNew() && null === $this->collCcShowStamps) { + if(null === $this->collCcStamps || null !== $criteria) { + if ($this->isNew() && null === $this->collCcStamps) { return 0; } else { - $query = CcShowStampQuery::create(null, $criteria); + $query = CcStampQuery::create(null, $criteria); if($distinct) { $query->distinct(); } @@ -1939,25 +1939,25 @@ abstract class BaseCcShow extends BaseObject implements Persistent ->count($con); } } else { - return count($this->collCcShowStamps); + return count($this->collCcStamps); } } /** - * Method called to associate a CcShowStamp object to this object - * through the CcShowStamp foreign key attribute. + * Method called to associate a CcStamp object to this object + * through the CcStamp foreign key attribute. * - * @param CcShowStamp $l CcShowStamp + * @param CcStamp $l CcStamp * @return void * @throws PropelException */ - public function addCcShowStamp(CcShowStamp $l) + public function addCcStamp(CcStamp $l) { - if ($this->collCcShowStamps === null) { - $this->initCcShowStamps(); + if ($this->collCcStamps === null) { + $this->initCcStamps(); } - if (!$this->collCcShowStamps->contains($l)) { // only add it if the **same** object is not already associated - $this->collCcShowStamps[]= $l; + if (!$this->collCcStamps->contains($l)) { // only add it if the **same** object is not already associated + $this->collCcStamps[]= $l; $l->setCcShow($this); } } @@ -1968,7 +1968,7 @@ abstract class BaseCcShow extends BaseObject implements Persistent * an identical criteria, it returns the collection. * Otherwise if this CcShow is new, it will return * an empty collection; or if this CcShow has previously - * been saved, it will retrieve related CcShowStamps from storage. + * been saved, it will retrieve related CcStamps from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you @@ -1977,114 +1977,14 @@ abstract class BaseCcShow extends BaseObject implements Persistent * @param Criteria $criteria optional Criteria object to narrow the query * @param PropelPDO $con optional connection object * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) - * @return PropelCollection|array CcShowStamp[] List of CcShowStamp objects + * @return PropelCollection|array CcStamp[] List of CcStamp objects */ - public function getCcShowStampsJoinCcShowInstances($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) + public function getCcStampsJoinCcShowInstances($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { - $query = CcShowStampQuery::create(null, $criteria); + $query = CcStampQuery::create(null, $criteria); $query->joinWith('CcShowInstances', $join_behavior); - return $this->getCcShowStamps($query, $con); - } - - - /** - * If this collection has already been initialized with - * an identical criteria, it returns the collection. - * Otherwise if this CcShow is new, it will return - * an empty collection; or if this CcShow has previously - * been saved, it will retrieve related CcShowStamps from storage. - * - * This method is protected by default in order to keep the public - * api reasonable. You can provide public methods for those you - * actually need in CcShow. - * - * @param Criteria $criteria optional Criteria object to narrow the query - * @param PropelPDO $con optional connection object - * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) - * @return PropelCollection|array CcShowStamp[] List of CcShowStamp objects - */ - public function getCcShowStampsJoinCcFiles($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) - { - $query = CcShowStampQuery::create(null, $criteria); - $query->joinWith('CcFiles', $join_behavior); - - return $this->getCcShowStamps($query, $con); - } - - - /** - * If this collection has already been initialized with - * an identical criteria, it returns the collection. - * Otherwise if this CcShow is new, it will return - * an empty collection; or if this CcShow has previously - * been saved, it will retrieve related CcShowStamps from storage. - * - * This method is protected by default in order to keep the public - * api reasonable. You can provide public methods for those you - * actually need in CcShow. - * - * @param Criteria $criteria optional Criteria object to narrow the query - * @param PropelPDO $con optional connection object - * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) - * @return PropelCollection|array CcShowStamp[] List of CcShowStamp objects - */ - public function getCcShowStampsJoinCcWebstream($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) - { - $query = CcShowStampQuery::create(null, $criteria); - $query->joinWith('CcWebstream', $join_behavior); - - return $this->getCcShowStamps($query, $con); - } - - - /** - * If this collection has already been initialized with - * an identical criteria, it returns the collection. - * Otherwise if this CcShow is new, it will return - * an empty collection; or if this CcShow has previously - * been saved, it will retrieve related CcShowStamps from storage. - * - * This method is protected by default in order to keep the public - * api reasonable. You can provide public methods for those you - * actually need in CcShow. - * - * @param Criteria $criteria optional Criteria object to narrow the query - * @param PropelPDO $con optional connection object - * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) - * @return PropelCollection|array CcShowStamp[] List of CcShowStamp objects - */ - public function getCcShowStampsJoinCcBlock($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) - { - $query = CcShowStampQuery::create(null, $criteria); - $query->joinWith('CcBlock', $join_behavior); - - return $this->getCcShowStamps($query, $con); - } - - - /** - * If this collection has already been initialized with - * an identical criteria, it returns the collection. - * Otherwise if this CcShow is new, it will return - * an empty collection; or if this CcShow has previously - * been saved, it will retrieve related CcShowStamps from storage. - * - * This method is protected by default in order to keep the public - * api reasonable. You can provide public methods for those you - * actually need in CcShow. - * - * @param Criteria $criteria optional Criteria object to narrow the query - * @param PropelPDO $con optional connection object - * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) - * @return PropelCollection|array CcShowStamp[] List of CcShowStamp objects - */ - public function getCcShowStampsJoinCcPlaylist($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) - { - $query = CcShowStampQuery::create(null, $criteria); - $query->joinWith('CcPlaylist', $join_behavior); - - return $this->getCcShowStamps($query, $con); + return $this->getCcStamps($query, $con); } /** @@ -2145,8 +2045,8 @@ abstract class BaseCcShow extends BaseObject implements Persistent $o->clearAllReferences($deep); } } - if ($this->collCcShowStamps) { - foreach ((array) $this->collCcShowStamps as $o) { + if ($this->collCcStamps) { + foreach ((array) $this->collCcStamps as $o) { $o->clearAllReferences($deep); } } @@ -2156,7 +2056,7 @@ abstract class BaseCcShow extends BaseObject implements Persistent $this->collCcShowDayss = null; $this->collCcShowRebroadcasts = null; $this->collCcShowHostss = null; - $this->collCcShowStamps = null; + $this->collCcStamps = null; } /** diff --git a/airtime_mvc/application/models/airtime/om/BaseCcShowInstances.php b/airtime_mvc/application/models/airtime/om/BaseCcShowInstances.php index 674929694..8ea2a9dd1 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcShowInstances.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcShowInstances.php @@ -126,9 +126,9 @@ abstract class BaseCcShowInstances extends BaseObject implements Persistent protected $collCcSchedules; /** - * @var array CcShowStamp[] Collection to store aggregation of CcShowStamp objects. + * @var array CcStamp[] Collection to store aggregation of CcStamp objects. */ - protected $collCcShowStamps; + protected $collCcStamps; /** * Flag to prevent endless save loop, if this object is referenced @@ -894,7 +894,7 @@ abstract class BaseCcShowInstances extends BaseObject implements Persistent $this->collCcSchedules = null; - $this->collCcShowStamps = null; + $this->collCcStamps = null; } // if (deep) } @@ -1071,8 +1071,8 @@ abstract class BaseCcShowInstances extends BaseObject implements Persistent } } - if ($this->collCcShowStamps !== null) { - foreach ($this->collCcShowStamps as $referrerFK) { + if ($this->collCcStamps !== null) { + foreach ($this->collCcStamps as $referrerFK) { if (!$referrerFK->isDeleted()) { $affectedRows += $referrerFK->save($con); } @@ -1190,8 +1190,8 @@ abstract class BaseCcShowInstances extends BaseObject implements Persistent } } - if ($this->collCcShowStamps !== null) { - foreach ($this->collCcShowStamps as $referrerFK) { + if ($this->collCcStamps !== null) { + foreach ($this->collCcStamps as $referrerFK) { if (!$referrerFK->validate($columns)) { $failureMap = array_merge($failureMap, $referrerFK->getValidationFailures()); } @@ -1530,9 +1530,9 @@ abstract class BaseCcShowInstances extends BaseObject implements Persistent } } - foreach ($this->getCcShowStamps() as $relObj) { + foreach ($this->getCcStamps() as $relObj) { if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves - $copyObj->addCcShowStamp($relObj->copy($deepCopy)); + $copyObj->addCcStamp($relObj->copy($deepCopy)); } } @@ -2047,36 +2047,36 @@ abstract class BaseCcShowInstances extends BaseObject implements Persistent } /** - * Clears out the collCcShowStamps collection + * Clears out the collCcStamps collection * * This does not modify the database; however, it will remove any associated objects, causing * them to be refetched by subsequent calls to accessor method. * * @return void - * @see addCcShowStamps() + * @see addCcStamps() */ - public function clearCcShowStamps() + public function clearCcStamps() { - $this->collCcShowStamps = null; // important to set this to NULL since that means it is uninitialized + $this->collCcStamps = null; // important to set this to NULL since that means it is uninitialized } /** - * Initializes the collCcShowStamps collection. + * Initializes the collCcStamps collection. * - * By default this just sets the collCcShowStamps collection to an empty array (like clearcollCcShowStamps()); + * By default this just sets the collCcStamps collection to an empty array (like clearcollCcStamps()); * however, you may wish to override this method in your stub class to provide setting appropriate * to your application -- for example, setting the initial array to the values stored in database. * * @return void */ - public function initCcShowStamps() + public function initCcStamps() { - $this->collCcShowStamps = new PropelObjectCollection(); - $this->collCcShowStamps->setModel('CcShowStamp'); + $this->collCcStamps = new PropelObjectCollection(); + $this->collCcStamps->setModel('CcStamp'); } /** - * Gets an array of CcShowStamp objects which contain a foreign key that references this object. + * Gets an array of CcStamp 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. @@ -2086,44 +2086,44 @@ abstract class BaseCcShowInstances extends BaseObject implements Persistent * * @param Criteria $criteria optional Criteria object to narrow the query * @param PropelPDO $con optional connection object - * @return PropelCollection|array CcShowStamp[] List of CcShowStamp objects + * @return PropelCollection|array CcStamp[] List of CcStamp objects * @throws PropelException */ - public function getCcShowStamps($criteria = null, PropelPDO $con = null) + public function getCcStamps($criteria = null, PropelPDO $con = null) { - if(null === $this->collCcShowStamps || null !== $criteria) { - if ($this->isNew() && null === $this->collCcShowStamps) { + if(null === $this->collCcStamps || null !== $criteria) { + if ($this->isNew() && null === $this->collCcStamps) { // return empty collection - $this->initCcShowStamps(); + $this->initCcStamps(); } else { - $collCcShowStamps = CcShowStampQuery::create(null, $criteria) + $collCcStamps = CcStampQuery::create(null, $criteria) ->filterByCcShowInstances($this) ->find($con); if (null !== $criteria) { - return $collCcShowStamps; + return $collCcStamps; } - $this->collCcShowStamps = $collCcShowStamps; + $this->collCcStamps = $collCcStamps; } } - return $this->collCcShowStamps; + return $this->collCcStamps; } /** - * Returns the number of related CcShowStamp objects. + * Returns the number of related CcStamp objects. * * @param Criteria $criteria * @param boolean $distinct * @param PropelPDO $con - * @return int Count of related CcShowStamp objects. + * @return int Count of related CcStamp objects. * @throws PropelException */ - public function countCcShowStamps(Criteria $criteria = null, $distinct = false, PropelPDO $con = null) + public function countCcStamps(Criteria $criteria = null, $distinct = false, PropelPDO $con = null) { - if(null === $this->collCcShowStamps || null !== $criteria) { - if ($this->isNew() && null === $this->collCcShowStamps) { + if(null === $this->collCcStamps || null !== $criteria) { + if ($this->isNew() && null === $this->collCcStamps) { return 0; } else { - $query = CcShowStampQuery::create(null, $criteria); + $query = CcStampQuery::create(null, $criteria); if($distinct) { $query->distinct(); } @@ -2132,25 +2132,25 @@ abstract class BaseCcShowInstances extends BaseObject implements Persistent ->count($con); } } else { - return count($this->collCcShowStamps); + return count($this->collCcStamps); } } /** - * Method called to associate a CcShowStamp object to this object - * through the CcShowStamp foreign key attribute. + * Method called to associate a CcStamp object to this object + * through the CcStamp foreign key attribute. * - * @param CcShowStamp $l CcShowStamp + * @param CcStamp $l CcStamp * @return void * @throws PropelException */ - public function addCcShowStamp(CcShowStamp $l) + public function addCcStamp(CcStamp $l) { - if ($this->collCcShowStamps === null) { - $this->initCcShowStamps(); + if ($this->collCcStamps === null) { + $this->initCcStamps(); } - if (!$this->collCcShowStamps->contains($l)) { // only add it if the **same** object is not already associated - $this->collCcShowStamps[]= $l; + if (!$this->collCcStamps->contains($l)) { // only add it if the **same** object is not already associated + $this->collCcStamps[]= $l; $l->setCcShowInstances($this); } } @@ -2161,7 +2161,7 @@ abstract class BaseCcShowInstances extends BaseObject implements Persistent * an identical criteria, it returns the collection. * Otherwise if this CcShowInstances is new, it will return * an empty collection; or if this CcShowInstances has previously - * been saved, it will retrieve related CcShowStamps from storage. + * been saved, it will retrieve related CcStamps from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you @@ -2170,114 +2170,14 @@ abstract class BaseCcShowInstances extends BaseObject implements Persistent * @param Criteria $criteria optional Criteria object to narrow the query * @param PropelPDO $con optional connection object * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) - * @return PropelCollection|array CcShowStamp[] List of CcShowStamp objects + * @return PropelCollection|array CcStamp[] List of CcStamp objects */ - public function getCcShowStampsJoinCcShow($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) + public function getCcStampsJoinCcShow($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { - $query = CcShowStampQuery::create(null, $criteria); + $query = CcStampQuery::create(null, $criteria); $query->joinWith('CcShow', $join_behavior); - return $this->getCcShowStamps($query, $con); - } - - - /** - * If this collection has already been initialized with - * an identical criteria, it returns the collection. - * Otherwise if this CcShowInstances is new, it will return - * an empty collection; or if this CcShowInstances has previously - * been saved, it will retrieve related CcShowStamps from storage. - * - * This method is protected by default in order to keep the public - * api reasonable. You can provide public methods for those you - * actually need in CcShowInstances. - * - * @param Criteria $criteria optional Criteria object to narrow the query - * @param PropelPDO $con optional connection object - * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) - * @return PropelCollection|array CcShowStamp[] List of CcShowStamp objects - */ - public function getCcShowStampsJoinCcFiles($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) - { - $query = CcShowStampQuery::create(null, $criteria); - $query->joinWith('CcFiles', $join_behavior); - - return $this->getCcShowStamps($query, $con); - } - - - /** - * If this collection has already been initialized with - * an identical criteria, it returns the collection. - * Otherwise if this CcShowInstances is new, it will return - * an empty collection; or if this CcShowInstances has previously - * been saved, it will retrieve related CcShowStamps from storage. - * - * This method is protected by default in order to keep the public - * api reasonable. You can provide public methods for those you - * actually need in CcShowInstances. - * - * @param Criteria $criteria optional Criteria object to narrow the query - * @param PropelPDO $con optional connection object - * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) - * @return PropelCollection|array CcShowStamp[] List of CcShowStamp objects - */ - public function getCcShowStampsJoinCcWebstream($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) - { - $query = CcShowStampQuery::create(null, $criteria); - $query->joinWith('CcWebstream', $join_behavior); - - return $this->getCcShowStamps($query, $con); - } - - - /** - * If this collection has already been initialized with - * an identical criteria, it returns the collection. - * Otherwise if this CcShowInstances is new, it will return - * an empty collection; or if this CcShowInstances has previously - * been saved, it will retrieve related CcShowStamps from storage. - * - * This method is protected by default in order to keep the public - * api reasonable. You can provide public methods for those you - * actually need in CcShowInstances. - * - * @param Criteria $criteria optional Criteria object to narrow the query - * @param PropelPDO $con optional connection object - * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) - * @return PropelCollection|array CcShowStamp[] List of CcShowStamp objects - */ - public function getCcShowStampsJoinCcBlock($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) - { - $query = CcShowStampQuery::create(null, $criteria); - $query->joinWith('CcBlock', $join_behavior); - - return $this->getCcShowStamps($query, $con); - } - - - /** - * If this collection has already been initialized with - * an identical criteria, it returns the collection. - * Otherwise if this CcShowInstances is new, it will return - * an empty collection; or if this CcShowInstances has previously - * been saved, it will retrieve related CcShowStamps from storage. - * - * This method is protected by default in order to keep the public - * api reasonable. You can provide public methods for those you - * actually need in CcShowInstances. - * - * @param Criteria $criteria optional Criteria object to narrow the query - * @param PropelPDO $con optional connection object - * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) - * @return PropelCollection|array CcShowStamp[] List of CcShowStamp objects - */ - public function getCcShowStampsJoinCcPlaylist($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) - { - $query = CcShowStampQuery::create(null, $criteria); - $query->joinWith('CcPlaylist', $join_behavior); - - return $this->getCcShowStamps($query, $con); + return $this->getCcStamps($query, $con); } /** @@ -2328,8 +2228,8 @@ abstract class BaseCcShowInstances extends BaseObject implements Persistent $o->clearAllReferences($deep); } } - if ($this->collCcShowStamps) { - foreach ((array) $this->collCcShowStamps as $o) { + if ($this->collCcStamps) { + foreach ((array) $this->collCcStamps as $o) { $o->clearAllReferences($deep); } } @@ -2337,7 +2237,7 @@ abstract class BaseCcShowInstances extends BaseObject implements Persistent $this->collCcShowInstancessRelatedByDbId = null; $this->collCcSchedules = null; - $this->collCcShowStamps = null; + $this->collCcStamps = null; $this->aCcShow = null; $this->aCcShowInstancesRelatedByDbOriginalShow = null; $this->aCcFiles = null; diff --git a/airtime_mvc/application/models/airtime/om/BaseCcShowInstancesPeer.php b/airtime_mvc/application/models/airtime/om/BaseCcShowInstancesPeer.php index 0223926b2..9a371d34e 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcShowInstancesPeer.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcShowInstancesPeer.php @@ -399,9 +399,9 @@ abstract class BaseCcShowInstancesPeer { // Invalidate objects in CcSchedulePeer instance pool, // since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule. CcSchedulePeer::clearInstancePool(); - // Invalidate objects in CcShowStampPeer instance pool, + // Invalidate objects in CcStampPeer instance pool, // since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule. - CcShowStampPeer::clearInstancePool(); + CcStampPeer::clearInstancePool(); } /** diff --git a/airtime_mvc/application/models/airtime/om/BaseCcShowInstancesQuery.php b/airtime_mvc/application/models/airtime/om/BaseCcShowInstancesQuery.php index 30ffdd523..b550cd2b5 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcShowInstancesQuery.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcShowInstancesQuery.php @@ -56,9 +56,9 @@ * @method CcShowInstancesQuery rightJoinCcSchedule($relationAlias = '') Adds a RIGHT JOIN clause to the query using the CcSchedule relation * @method CcShowInstancesQuery innerJoinCcSchedule($relationAlias = '') Adds a INNER JOIN clause to the query using the CcSchedule relation * - * @method CcShowInstancesQuery leftJoinCcShowStamp($relationAlias = '') Adds a LEFT JOIN clause to the query using the CcShowStamp relation - * @method CcShowInstancesQuery rightJoinCcShowStamp($relationAlias = '') Adds a RIGHT JOIN clause to the query using the CcShowStamp relation - * @method CcShowInstancesQuery innerJoinCcShowStamp($relationAlias = '') Adds a INNER JOIN clause to the query using the CcShowStamp relation + * @method CcShowInstancesQuery leftJoinCcStamp($relationAlias = '') Adds a LEFT JOIN clause to the query using the CcStamp relation + * @method CcShowInstancesQuery rightJoinCcStamp($relationAlias = '') Adds a RIGHT JOIN clause to the query using the CcStamp relation + * @method CcShowInstancesQuery innerJoinCcStamp($relationAlias = '') Adds a INNER JOIN clause to the query using the CcStamp relation * * @method CcShowInstances findOne(PropelPDO $con = null) Return the first CcShowInstances matching the query * @method CcShowInstances findOneOrCreate(PropelPDO $con = null) Return the first CcShowInstances matching the query, or a new CcShowInstances object populated from the query conditions when no match is found @@ -853,31 +853,31 @@ abstract class BaseCcShowInstancesQuery extends ModelCriteria } /** - * Filter the query by a related CcShowStamp object + * Filter the query by a related CcStamp object * - * @param CcShowStamp $ccShowStamp the related object to use as filter + * @param CcStamp $ccStamp the related object to use as filter * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return CcShowInstancesQuery The current query, for fluid interface */ - public function filterByCcShowStamp($ccShowStamp, $comparison = null) + public function filterByCcStamp($ccStamp, $comparison = null) { return $this - ->addUsingAlias(CcShowInstancesPeer::ID, $ccShowStamp->getDbInstanceId(), $comparison); + ->addUsingAlias(CcShowInstancesPeer::ID, $ccStamp->getDbInstanceId(), $comparison); } /** - * Adds a JOIN clause to the query using the CcShowStamp relation + * Adds a JOIN clause to the query using the CcStamp relation * * @param string $relationAlias optional alias for the relation * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' * * @return CcShowInstancesQuery The current query, for fluid interface */ - public function joinCcShowStamp($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + public function joinCcStamp($relationAlias = '', $joinType = Criteria::LEFT_JOIN) { $tableMap = $this->getTableMap(); - $relationMap = $tableMap->getRelation('CcShowStamp'); + $relationMap = $tableMap->getRelation('CcStamp'); // create a ModelJoin object for this join $join = new ModelJoin(); @@ -892,14 +892,14 @@ abstract class BaseCcShowInstancesQuery extends ModelCriteria $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); $this->addJoinObject($join, $relationAlias); } else { - $this->addJoinObject($join, 'CcShowStamp'); + $this->addJoinObject($join, 'CcStamp'); } return $this; } /** - * Use the CcShowStamp relation CcShowStamp object + * Use the CcStamp relation CcStamp object * * @see useQuery() * @@ -907,13 +907,13 @@ abstract class BaseCcShowInstancesQuery extends ModelCriteria * to be used as main alias in the secondary query * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' * - * @return CcShowStampQuery A secondary query class using the current class as primary query + * @return CcStampQuery A secondary query class using the current class as primary query */ - public function useCcShowStampQuery($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + public function useCcStampQuery($relationAlias = '', $joinType = Criteria::LEFT_JOIN) { return $this - ->joinCcShowStamp($relationAlias, $joinType) - ->useQuery($relationAlias ? $relationAlias : 'CcShowStamp', 'CcShowStampQuery'); + ->joinCcStamp($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'CcStamp', 'CcStampQuery'); } /** diff --git a/airtime_mvc/application/models/airtime/om/BaseCcShowPeer.php b/airtime_mvc/application/models/airtime/om/BaseCcShowPeer.php index f19fa875d..02c2800cf 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcShowPeer.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcShowPeer.php @@ -405,9 +405,9 @@ abstract class BaseCcShowPeer { // Invalidate objects in CcShowHostsPeer instance pool, // since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule. CcShowHostsPeer::clearInstancePool(); - // Invalidate objects in CcShowStampPeer instance pool, + // Invalidate objects in CcStampPeer instance pool, // since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule. - CcShowStampPeer::clearInstancePool(); + CcStampPeer::clearInstancePool(); } /** diff --git a/airtime_mvc/application/models/airtime/om/BaseCcShowQuery.php b/airtime_mvc/application/models/airtime/om/BaseCcShowQuery.php index d7a849308..c7d9c2788 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcShowQuery.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcShowQuery.php @@ -52,9 +52,9 @@ * @method CcShowQuery rightJoinCcShowHosts($relationAlias = '') Adds a RIGHT JOIN clause to the query using the CcShowHosts relation * @method CcShowQuery innerJoinCcShowHosts($relationAlias = '') Adds a INNER JOIN clause to the query using the CcShowHosts relation * - * @method CcShowQuery leftJoinCcShowStamp($relationAlias = '') Adds a LEFT JOIN clause to the query using the CcShowStamp relation - * @method CcShowQuery rightJoinCcShowStamp($relationAlias = '') Adds a RIGHT JOIN clause to the query using the CcShowStamp relation - * @method CcShowQuery innerJoinCcShowStamp($relationAlias = '') Adds a INNER JOIN clause to the query using the CcShowStamp relation + * @method CcShowQuery leftJoinCcStamp($relationAlias = '') Adds a LEFT JOIN clause to the query using the CcStamp relation + * @method CcShowQuery rightJoinCcStamp($relationAlias = '') Adds a RIGHT JOIN clause to the query using the CcStamp relation + * @method CcShowQuery innerJoinCcStamp($relationAlias = '') Adds a INNER JOIN clause to the query using the CcStamp relation * * @method CcShow findOne(PropelPDO $con = null) Return the first CcShow matching the query * @method CcShow findOneOrCreate(PropelPDO $con = null) Return the first CcShow matching the query, or a new CcShow object populated from the query conditions when no match is found @@ -694,31 +694,31 @@ abstract class BaseCcShowQuery extends ModelCriteria } /** - * Filter the query by a related CcShowStamp object + * Filter the query by a related CcStamp object * - * @param CcShowStamp $ccShowStamp the related object to use as filter + * @param CcStamp $ccStamp the related object to use as filter * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return CcShowQuery The current query, for fluid interface */ - public function filterByCcShowStamp($ccShowStamp, $comparison = null) + public function filterByCcStamp($ccStamp, $comparison = null) { return $this - ->addUsingAlias(CcShowPeer::ID, $ccShowStamp->getDbShowId(), $comparison); + ->addUsingAlias(CcShowPeer::ID, $ccStamp->getDbShowId(), $comparison); } /** - * Adds a JOIN clause to the query using the CcShowStamp relation + * Adds a JOIN clause to the query using the CcStamp relation * * @param string $relationAlias optional alias for the relation * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' * * @return CcShowQuery The current query, for fluid interface */ - public function joinCcShowStamp($relationAlias = '', $joinType = Criteria::INNER_JOIN) + public function joinCcStamp($relationAlias = '', $joinType = Criteria::INNER_JOIN) { $tableMap = $this->getTableMap(); - $relationMap = $tableMap->getRelation('CcShowStamp'); + $relationMap = $tableMap->getRelation('CcStamp'); // create a ModelJoin object for this join $join = new ModelJoin(); @@ -733,14 +733,14 @@ abstract class BaseCcShowQuery extends ModelCriteria $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); $this->addJoinObject($join, $relationAlias); } else { - $this->addJoinObject($join, 'CcShowStamp'); + $this->addJoinObject($join, 'CcStamp'); } return $this; } /** - * Use the CcShowStamp relation CcShowStamp object + * Use the CcStamp relation CcStamp object * * @see useQuery() * @@ -748,13 +748,13 @@ abstract class BaseCcShowQuery extends ModelCriteria * to be used as main alias in the secondary query * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' * - * @return CcShowStampQuery A secondary query class using the current class as primary query + * @return CcStampQuery A secondary query class using the current class as primary query */ - public function useCcShowStampQuery($relationAlias = '', $joinType = Criteria::INNER_JOIN) + public function useCcStampQuery($relationAlias = '', $joinType = Criteria::INNER_JOIN) { return $this - ->joinCcShowStamp($relationAlias, $joinType) - ->useQuery($relationAlias ? $relationAlias : 'CcShowStamp', 'CcShowStampQuery'); + ->joinCcStamp($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'CcStamp', 'CcStampQuery'); } /** diff --git a/airtime_mvc/application/models/airtime/om/BaseCcWebstream.php b/airtime_mvc/application/models/airtime/om/BaseCcWebstream.php index 2b6587984..5b6a66111 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcWebstream.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcWebstream.php @@ -91,9 +91,9 @@ abstract class BaseCcWebstream extends BaseObject implements Persistent protected $collCcSchedules; /** - * @var array CcShowStamp[] Collection to store aggregation of CcShowStamp objects. + * @var array CcStampContents[] Collection to store aggregation of CcStampContents objects. */ - protected $collCcShowStamps; + protected $collCcStampContentss; /** * Flag to prevent endless save loop, if this object is referenced @@ -704,7 +704,7 @@ abstract class BaseCcWebstream extends BaseObject implements Persistent $this->collCcSchedules = null; - $this->collCcShowStamps = null; + $this->collCcStampContentss = null; } // if (deep) } @@ -847,8 +847,8 @@ abstract class BaseCcWebstream extends BaseObject implements Persistent } } - if ($this->collCcShowStamps !== null) { - foreach ($this->collCcShowStamps as $referrerFK) { + if ($this->collCcStampContentss !== null) { + foreach ($this->collCcStampContentss as $referrerFK) { if (!$referrerFK->isDeleted()) { $affectedRows += $referrerFK->save($con); } @@ -934,8 +934,8 @@ abstract class BaseCcWebstream extends BaseObject implements Persistent } } - if ($this->collCcShowStamps !== null) { - foreach ($this->collCcShowStamps as $referrerFK) { + if ($this->collCcStampContentss !== null) { + foreach ($this->collCcStampContentss as $referrerFK) { if (!$referrerFK->validate($columns)) { $failureMap = array_merge($failureMap, $referrerFK->getValidationFailures()); } @@ -1236,9 +1236,9 @@ abstract class BaseCcWebstream extends BaseObject implements Persistent } } - foreach ($this->getCcShowStamps() as $relObj) { + foreach ($this->getCcStampContentss() as $relObj) { if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves - $copyObj->addCcShowStamp($relObj->copy($deepCopy)); + $copyObj->addCcStampContents($relObj->copy($deepCopy)); } } @@ -1447,36 +1447,36 @@ abstract class BaseCcWebstream extends BaseObject implements Persistent } /** - * Clears out the collCcShowStamps collection + * Clears out the collCcStampContentss collection * * This does not modify the database; however, it will remove any associated objects, causing * them to be refetched by subsequent calls to accessor method. * * @return void - * @see addCcShowStamps() + * @see addCcStampContentss() */ - public function clearCcShowStamps() + public function clearCcStampContentss() { - $this->collCcShowStamps = null; // important to set this to NULL since that means it is uninitialized + $this->collCcStampContentss = null; // important to set this to NULL since that means it is uninitialized } /** - * Initializes the collCcShowStamps collection. + * Initializes the collCcStampContentss collection. * - * By default this just sets the collCcShowStamps collection to an empty array (like clearcollCcShowStamps()); + * By default this just sets the collCcStampContentss collection to an empty array (like clearcollCcStampContentss()); * however, you may wish to override this method in your stub class to provide setting appropriate * to your application -- for example, setting the initial array to the values stored in database. * * @return void */ - public function initCcShowStamps() + public function initCcStampContentss() { - $this->collCcShowStamps = new PropelObjectCollection(); - $this->collCcShowStamps->setModel('CcShowStamp'); + $this->collCcStampContentss = new PropelObjectCollection(); + $this->collCcStampContentss->setModel('CcStampContents'); } /** - * Gets an array of CcShowStamp objects which contain a foreign key that references this object. + * Gets an array of CcStampContents 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. @@ -1486,44 +1486,44 @@ abstract class BaseCcWebstream extends BaseObject implements Persistent * * @param Criteria $criteria optional Criteria object to narrow the query * @param PropelPDO $con optional connection object - * @return PropelCollection|array CcShowStamp[] List of CcShowStamp objects + * @return PropelCollection|array CcStampContents[] List of CcStampContents objects * @throws PropelException */ - public function getCcShowStamps($criteria = null, PropelPDO $con = null) + public function getCcStampContentss($criteria = null, PropelPDO $con = null) { - if(null === $this->collCcShowStamps || null !== $criteria) { - if ($this->isNew() && null === $this->collCcShowStamps) { + if(null === $this->collCcStampContentss || null !== $criteria) { + if ($this->isNew() && null === $this->collCcStampContentss) { // return empty collection - $this->initCcShowStamps(); + $this->initCcStampContentss(); } else { - $collCcShowStamps = CcShowStampQuery::create(null, $criteria) + $collCcStampContentss = CcStampContentsQuery::create(null, $criteria) ->filterByCcWebstream($this) ->find($con); if (null !== $criteria) { - return $collCcShowStamps; + return $collCcStampContentss; } - $this->collCcShowStamps = $collCcShowStamps; + $this->collCcStampContentss = $collCcStampContentss; } } - return $this->collCcShowStamps; + return $this->collCcStampContentss; } /** - * Returns the number of related CcShowStamp objects. + * Returns the number of related CcStampContents objects. * * @param Criteria $criteria * @param boolean $distinct * @param PropelPDO $con - * @return int Count of related CcShowStamp objects. + * @return int Count of related CcStampContents objects. * @throws PropelException */ - public function countCcShowStamps(Criteria $criteria = null, $distinct = false, PropelPDO $con = null) + public function countCcStampContentss(Criteria $criteria = null, $distinct = false, PropelPDO $con = null) { - if(null === $this->collCcShowStamps || null !== $criteria) { - if ($this->isNew() && null === $this->collCcShowStamps) { + if(null === $this->collCcStampContentss || null !== $criteria) { + if ($this->isNew() && null === $this->collCcStampContentss) { return 0; } else { - $query = CcShowStampQuery::create(null, $criteria); + $query = CcStampContentsQuery::create(null, $criteria); if($distinct) { $query->distinct(); } @@ -1532,25 +1532,25 @@ abstract class BaseCcWebstream extends BaseObject implements Persistent ->count($con); } } else { - return count($this->collCcShowStamps); + return count($this->collCcStampContentss); } } /** - * Method called to associate a CcShowStamp object to this object - * through the CcShowStamp foreign key attribute. + * Method called to associate a CcStampContents object to this object + * through the CcStampContents foreign key attribute. * - * @param CcShowStamp $l CcShowStamp + * @param CcStampContents $l CcStampContents * @return void * @throws PropelException */ - public function addCcShowStamp(CcShowStamp $l) + public function addCcStampContents(CcStampContents $l) { - if ($this->collCcShowStamps === null) { - $this->initCcShowStamps(); + if ($this->collCcStampContentss === null) { + $this->initCcStampContentss(); } - if (!$this->collCcShowStamps->contains($l)) { // only add it if the **same** object is not already associated - $this->collCcShowStamps[]= $l; + if (!$this->collCcStampContentss->contains($l)) { // only add it if the **same** object is not already associated + $this->collCcStampContentss[]= $l; $l->setCcWebstream($this); } } @@ -1561,7 +1561,7 @@ abstract class BaseCcWebstream extends BaseObject implements Persistent * an identical criteria, it returns the collection. * Otherwise if this CcWebstream is new, it will return * an empty collection; or if this CcWebstream has previously - * been saved, it will retrieve related CcShowStamps from storage. + * been saved, it will retrieve related CcStampContentss from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you @@ -1570,14 +1570,14 @@ abstract class BaseCcWebstream extends BaseObject implements Persistent * @param Criteria $criteria optional Criteria object to narrow the query * @param PropelPDO $con optional connection object * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) - * @return PropelCollection|array CcShowStamp[] List of CcShowStamp objects + * @return PropelCollection|array CcStampContents[] List of CcStampContents objects */ - public function getCcShowStampsJoinCcShow($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) + public function getCcStampContentssJoinCcStamp($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { - $query = CcShowStampQuery::create(null, $criteria); - $query->joinWith('CcShow', $join_behavior); + $query = CcStampContentsQuery::create(null, $criteria); + $query->joinWith('CcStamp', $join_behavior); - return $this->getCcShowStamps($query, $con); + return $this->getCcStampContentss($query, $con); } @@ -1586,7 +1586,7 @@ abstract class BaseCcWebstream extends BaseObject implements Persistent * an identical criteria, it returns the collection. * Otherwise if this CcWebstream is new, it will return * an empty collection; or if this CcWebstream has previously - * been saved, it will retrieve related CcShowStamps from storage. + * been saved, it will retrieve related CcStampContentss from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you @@ -1595,39 +1595,14 @@ abstract class BaseCcWebstream extends BaseObject implements Persistent * @param Criteria $criteria optional Criteria object to narrow the query * @param PropelPDO $con optional connection object * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) - * @return PropelCollection|array CcShowStamp[] List of CcShowStamp objects + * @return PropelCollection|array CcStampContents[] List of CcStampContents objects */ - public function getCcShowStampsJoinCcShowInstances($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) + public function getCcStampContentssJoinCcFiles($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { - $query = CcShowStampQuery::create(null, $criteria); - $query->joinWith('CcShowInstances', $join_behavior); - - return $this->getCcShowStamps($query, $con); - } - - - /** - * If this collection has already been initialized with - * an identical criteria, it returns the collection. - * Otherwise if this CcWebstream is new, it will return - * an empty collection; or if this CcWebstream has previously - * been saved, it will retrieve related CcShowStamps from storage. - * - * This method is protected by default in order to keep the public - * api reasonable. You can provide public methods for those you - * actually need in CcWebstream. - * - * @param Criteria $criteria optional Criteria object to narrow the query - * @param PropelPDO $con optional connection object - * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) - * @return PropelCollection|array CcShowStamp[] List of CcShowStamp objects - */ - public function getCcShowStampsJoinCcFiles($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) - { - $query = CcShowStampQuery::create(null, $criteria); + $query = CcStampContentsQuery::create(null, $criteria); $query->joinWith('CcFiles', $join_behavior); - return $this->getCcShowStamps($query, $con); + return $this->getCcStampContentss($query, $con); } @@ -1636,7 +1611,7 @@ abstract class BaseCcWebstream extends BaseObject implements Persistent * an identical criteria, it returns the collection. * Otherwise if this CcWebstream is new, it will return * an empty collection; or if this CcWebstream has previously - * been saved, it will retrieve related CcShowStamps from storage. + * been saved, it will retrieve related CcStampContentss from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you @@ -1645,14 +1620,14 @@ abstract class BaseCcWebstream extends BaseObject implements Persistent * @param Criteria $criteria optional Criteria object to narrow the query * @param PropelPDO $con optional connection object * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) - * @return PropelCollection|array CcShowStamp[] List of CcShowStamp objects + * @return PropelCollection|array CcStampContents[] List of CcStampContents objects */ - public function getCcShowStampsJoinCcBlock($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) + public function getCcStampContentssJoinCcBlock($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { - $query = CcShowStampQuery::create(null, $criteria); + $query = CcStampContentsQuery::create(null, $criteria); $query->joinWith('CcBlock', $join_behavior); - return $this->getCcShowStamps($query, $con); + return $this->getCcStampContentss($query, $con); } @@ -1661,7 +1636,7 @@ abstract class BaseCcWebstream extends BaseObject implements Persistent * an identical criteria, it returns the collection. * Otherwise if this CcWebstream is new, it will return * an empty collection; or if this CcWebstream has previously - * been saved, it will retrieve related CcShowStamps from storage. + * been saved, it will retrieve related CcStampContentss from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you @@ -1670,14 +1645,14 @@ abstract class BaseCcWebstream extends BaseObject implements Persistent * @param Criteria $criteria optional Criteria object to narrow the query * @param PropelPDO $con optional connection object * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) - * @return PropelCollection|array CcShowStamp[] List of CcShowStamp objects + * @return PropelCollection|array CcStampContents[] List of CcStampContents objects */ - public function getCcShowStampsJoinCcPlaylist($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) + public function getCcStampContentssJoinCcPlaylist($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { - $query = CcShowStampQuery::create(null, $criteria); + $query = CcStampContentsQuery::create(null, $criteria); $query->joinWith('CcPlaylist', $join_behavior); - return $this->getCcShowStamps($query, $con); + return $this->getCcStampContentss($query, $con); } /** @@ -1721,15 +1696,15 @@ abstract class BaseCcWebstream extends BaseObject implements Persistent $o->clearAllReferences($deep); } } - if ($this->collCcShowStamps) { - foreach ((array) $this->collCcShowStamps as $o) { + if ($this->collCcStampContentss) { + foreach ((array) $this->collCcStampContentss as $o) { $o->clearAllReferences($deep); } } } // if ($deep) $this->collCcSchedules = null; - $this->collCcShowStamps = null; + $this->collCcStampContentss = null; } /** diff --git a/airtime_mvc/application/models/airtime/om/BaseCcWebstreamPeer.php b/airtime_mvc/application/models/airtime/om/BaseCcWebstreamPeer.php index 1965b1bf2..81bcb2b27 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcWebstreamPeer.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcWebstreamPeer.php @@ -386,9 +386,9 @@ abstract class BaseCcWebstreamPeer { // Invalidate objects in CcSchedulePeer instance pool, // since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule. CcSchedulePeer::clearInstancePool(); - // Invalidate objects in CcShowStampPeer instance pool, + // Invalidate objects in CcStampContentsPeer instance pool, // since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule. - CcShowStampPeer::clearInstancePool(); + CcStampContentsPeer::clearInstancePool(); } /** diff --git a/airtime_mvc/application/models/airtime/om/BaseCcWebstreamQuery.php b/airtime_mvc/application/models/airtime/om/BaseCcWebstreamQuery.php index 1f62828e7..6ad062e18 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcWebstreamQuery.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcWebstreamQuery.php @@ -36,9 +36,9 @@ * @method CcWebstreamQuery rightJoinCcSchedule($relationAlias = '') Adds a RIGHT JOIN clause to the query using the CcSchedule relation * @method CcWebstreamQuery innerJoinCcSchedule($relationAlias = '') Adds a INNER JOIN clause to the query using the CcSchedule relation * - * @method CcWebstreamQuery leftJoinCcShowStamp($relationAlias = '') Adds a LEFT JOIN clause to the query using the CcShowStamp relation - * @method CcWebstreamQuery rightJoinCcShowStamp($relationAlias = '') Adds a RIGHT JOIN clause to the query using the CcShowStamp relation - * @method CcWebstreamQuery innerJoinCcShowStamp($relationAlias = '') Adds a INNER JOIN clause to the query using the CcShowStamp relation + * @method CcWebstreamQuery leftJoinCcStampContents($relationAlias = '') Adds a LEFT JOIN clause to the query using the CcStampContents relation + * @method CcWebstreamQuery rightJoinCcStampContents($relationAlias = '') Adds a RIGHT JOIN clause to the query using the CcStampContents relation + * @method CcWebstreamQuery innerJoinCcStampContents($relationAlias = '') Adds a INNER JOIN clause to the query using the CcStampContents relation * * @method CcWebstream findOne(PropelPDO $con = null) Return the first CcWebstream matching the query * @method CcWebstream findOneOrCreate(PropelPDO $con = null) Return the first CcWebstream matching the query, or a new CcWebstream object populated from the query conditions when no match is found @@ -489,31 +489,31 @@ abstract class BaseCcWebstreamQuery extends ModelCriteria } /** - * Filter the query by a related CcShowStamp object + * Filter the query by a related CcStampContents object * - * @param CcShowStamp $ccShowStamp the related object to use as filter + * @param CcStampContents $ccStampContents the related object to use as filter * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return CcWebstreamQuery The current query, for fluid interface */ - public function filterByCcShowStamp($ccShowStamp, $comparison = null) + public function filterByCcStampContents($ccStampContents, $comparison = null) { return $this - ->addUsingAlias(CcWebstreamPeer::ID, $ccShowStamp->getDbStreamId(), $comparison); + ->addUsingAlias(CcWebstreamPeer::ID, $ccStampContents->getDbStreamId(), $comparison); } /** - * Adds a JOIN clause to the query using the CcShowStamp relation + * Adds a JOIN clause to the query using the CcStampContents relation * * @param string $relationAlias optional alias for the relation * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' * * @return CcWebstreamQuery The current query, for fluid interface */ - public function joinCcShowStamp($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + public function joinCcStampContents($relationAlias = '', $joinType = Criteria::LEFT_JOIN) { $tableMap = $this->getTableMap(); - $relationMap = $tableMap->getRelation('CcShowStamp'); + $relationMap = $tableMap->getRelation('CcStampContents'); // create a ModelJoin object for this join $join = new ModelJoin(); @@ -528,14 +528,14 @@ abstract class BaseCcWebstreamQuery extends ModelCriteria $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); $this->addJoinObject($join, $relationAlias); } else { - $this->addJoinObject($join, 'CcShowStamp'); + $this->addJoinObject($join, 'CcStampContents'); } return $this; } /** - * Use the CcShowStamp relation CcShowStamp object + * Use the CcStampContents relation CcStampContents object * * @see useQuery() * @@ -543,13 +543,13 @@ abstract class BaseCcWebstreamQuery extends ModelCriteria * to be used as main alias in the secondary query * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' * - * @return CcShowStampQuery A secondary query class using the current class as primary query + * @return CcStampContentsQuery A secondary query class using the current class as primary query */ - public function useCcShowStampQuery($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + public function useCcStampContentsQuery($relationAlias = '', $joinType = Criteria::LEFT_JOIN) { return $this - ->joinCcShowStamp($relationAlias, $joinType) - ->useQuery($relationAlias ? $relationAlias : 'CcShowStamp', 'CcShowStampQuery'); + ->joinCcStampContents($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'CcStampContents', 'CcStampContentsQuery'); } /** diff --git a/airtime_mvc/build/schema.xml b/airtime_mvc/build/schema.xml index 49ff7cffa..bbcd7f0fe 100644 --- a/airtime_mvc/build/schema.xml +++ b/airtime_mvc/build/schema.xml @@ -341,7 +341,7 @@ - @@ -477,10 +477,9 @@ - +
- - + @@ -491,23 +490,31 @@ - - + + - - - - + - + - + - +
+ + + + + + + + + + +
diff --git a/airtime_mvc/build/sql/schema.sql b/airtime_mvc/build/sql/schema.sql index 9d9040164..5e8af4018 100644 --- a/airtime_mvc/build/sql/schema.sql +++ b/airtime_mvc/build/sql/schema.sql @@ -751,17 +751,16 @@ COMMENT ON TABLE "cc_locale" IS ''; SET search_path TO public; ----------------------------------------------------------------------------- --- cc_show_stamp +-- cc_stamp_contents ----------------------------------------------------------------------------- -DROP TABLE "cc_show_stamp" CASCADE; +DROP TABLE "cc_stamp_contents" CASCADE; -CREATE TABLE "cc_show_stamp" +CREATE TABLE "cc_stamp_contents" ( "id" serial NOT NULL, - "show_id" INTEGER NOT NULL, - "instance_id" INTEGER, + "stamp_id" INTEGER NOT NULL, "file_id" INTEGER, "stream_id" INTEGER, "block_id" INTEGER, @@ -775,7 +774,26 @@ CREATE TABLE "cc_show_stamp" PRIMARY KEY ("id") ); -COMMENT ON TABLE "cc_show_stamp" IS ''; +COMMENT ON TABLE "cc_stamp_contents" IS ''; + + +SET search_path TO public; +----------------------------------------------------------------------------- +-- cc_stamp +----------------------------------------------------------------------------- + +DROP TABLE "cc_stamp" CASCADE; + + +CREATE TABLE "cc_stamp" +( + "id" serial NOT NULL, + "show_id" INTEGER NOT NULL, + "instance_id" INTEGER, + PRIMARY KEY ("id") +); + +COMMENT ON TABLE "cc_stamp" IS ''; SET search_path TO public; @@ -835,14 +853,16 @@ ALTER TABLE "cc_listener_count" ADD CONSTRAINT "cc_timestamp_inst_fkey" FOREIGN ALTER TABLE "cc_listener_count" ADD CONSTRAINT "cc_mount_name_inst_fkey" FOREIGN KEY ("mount_name_id") REFERENCES "cc_mount_name" ("id") ON DELETE CASCADE; -ALTER TABLE "cc_show_stamp" ADD CONSTRAINT "cc_show_stamp_show_id_fkey" FOREIGN KEY ("show_id") REFERENCES "cc_show" ("id") ON DELETE CASCADE; +ALTER TABLE "cc_stamp_contents" ADD CONSTRAINT "cc_stamp_contents_stamp_id_fkey" FOREIGN KEY ("stamp_id") REFERENCES "cc_stamp" ("id") ON DELETE CASCADE; -ALTER TABLE "cc_show_stamp" ADD CONSTRAINT "cc_show_stamp_instance_id_fkey" FOREIGN KEY ("instance_id") REFERENCES "cc_show_instances" ("id") ON DELETE CASCADE; +ALTER TABLE "cc_stamp_contents" ADD CONSTRAINT "cc_stamp_contents_file_id_fkey" FOREIGN KEY ("file_id") REFERENCES "cc_files" ("id") ON DELETE CASCADE; -ALTER TABLE "cc_show_stamp" ADD CONSTRAINT "cc_show_stamp_file_id_fkey" FOREIGN KEY ("file_id") REFERENCES "cc_files" ("id") ON DELETE CASCADE; +ALTER TABLE "cc_stamp_contents" ADD CONSTRAINT "cc_stamp_contents_stream_id_fkey" FOREIGN KEY ("stream_id") REFERENCES "cc_webstream" ("id") ON DELETE CASCADE; -ALTER TABLE "cc_show_stamp" ADD CONSTRAINT "cc_show_stamp_stream_id_fkey" FOREIGN KEY ("stream_id") REFERENCES "cc_webstream" ("id") ON DELETE CASCADE; +ALTER TABLE "cc_stamp_contents" ADD CONSTRAINT "cc_stamp_contents_block_id_fkey" FOREIGN KEY ("block_id") REFERENCES "cc_block" ("id") ON DELETE CASCADE; -ALTER TABLE "cc_show_stamp" ADD CONSTRAINT "cc_show_stamp_block_id_fkey" FOREIGN KEY ("block_id") REFERENCES "cc_block" ("id") ON DELETE CASCADE; +ALTER TABLE "cc_stamp_contents" ADD CONSTRAINT "cc_stamp_contents_playlist_id_fkey" FOREIGN KEY ("playlist_id") REFERENCES "cc_playlist" ("id") ON DELETE CASCADE; -ALTER TABLE "cc_show_stamp" ADD CONSTRAINT "cc_show_stamp_playlist_id_fkey" FOREIGN KEY ("playlist_id") REFERENCES "cc_playlist" ("id") ON DELETE CASCADE; +ALTER TABLE "cc_stamp" ADD CONSTRAINT "cc_stamp_show_id_fkey" FOREIGN KEY ("show_id") REFERENCES "cc_show" ("id") ON DELETE CASCADE; + +ALTER TABLE "cc_stamp" ADD CONSTRAINT "cc_stamp_instance_id_fkey" FOREIGN KEY ("instance_id") REFERENCES "cc_show_instances" ("id") ON DELETE CASCADE; From e64f6fb3fd37c63f3290b2a1625fa866a7cc62db Mon Sep 17 00:00:00 2001 From: denise Date: Mon, 8 Apr 2013 14:43:27 -0400 Subject: [PATCH 47/73] CC-4961: Show linking -modified db --- .../application/models/airtime/CcStamp.php | 18 + .../models/airtime/CcStampContents.php | 18 + .../models/airtime/CcStampContentsPeer.php | 18 + .../models/airtime/CcStampContentsQuery.php | 18 + .../models/airtime/CcStampPeer.php | 18 + .../models/airtime/CcStampQuery.php | 18 + .../airtime/map/CcStampContentsTableMap.php | 68 + .../models/airtime/map/CcStampTableMap.php | 57 + .../models/airtime/om/BaseCcStamp.php | 1188 ++++++++ .../models/airtime/om/BaseCcStampContents.php | 1656 +++++++++++ .../airtime/om/BaseCcStampContentsPeer.php | 2592 +++++++++++++++++ .../airtime/om/BaseCcStampContentsQuery.php | 845 ++++++ .../models/airtime/om/BaseCcStampPeer.php | 1368 +++++++++ .../models/airtime/om/BaseCcStampQuery.php | 439 +++ 14 files changed, 8321 insertions(+) create mode 100644 airtime_mvc/application/models/airtime/CcStamp.php create mode 100644 airtime_mvc/application/models/airtime/CcStampContents.php create mode 100644 airtime_mvc/application/models/airtime/CcStampContentsPeer.php create mode 100644 airtime_mvc/application/models/airtime/CcStampContentsQuery.php create mode 100644 airtime_mvc/application/models/airtime/CcStampPeer.php create mode 100644 airtime_mvc/application/models/airtime/CcStampQuery.php create mode 100644 airtime_mvc/application/models/airtime/map/CcStampContentsTableMap.php create mode 100644 airtime_mvc/application/models/airtime/map/CcStampTableMap.php create mode 100644 airtime_mvc/application/models/airtime/om/BaseCcStamp.php create mode 100644 airtime_mvc/application/models/airtime/om/BaseCcStampContents.php create mode 100644 airtime_mvc/application/models/airtime/om/BaseCcStampContentsPeer.php create mode 100644 airtime_mvc/application/models/airtime/om/BaseCcStampContentsQuery.php create mode 100644 airtime_mvc/application/models/airtime/om/BaseCcStampPeer.php create mode 100644 airtime_mvc/application/models/airtime/om/BaseCcStampQuery.php diff --git a/airtime_mvc/application/models/airtime/CcStamp.php b/airtime_mvc/application/models/airtime/CcStamp.php new file mode 100644 index 000000000..7881e7173 --- /dev/null +++ b/airtime_mvc/application/models/airtime/CcStamp.php @@ -0,0 +1,18 @@ +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', 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('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..6574cb410 --- /dev/null +++ b/airtime_mvc/application/models/airtime/map/CcStampTableMap.php @@ -0,0 +1,57 @@ +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); + // 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/BaseCcStamp.php b/airtime_mvc/application/models/airtime/om/BaseCcStamp.php new file mode 100644 index 000000000..dcb488d02 --- /dev/null +++ b/airtime_mvc/application/models/airtime/om/BaseCcStamp.php @@ -0,0 +1,1188 @@ +id; + } + + /** + * Get the [show_id] column value. + * + * @return int + */ + public function getDbShowId() + { + return $this->show_id; + } + + /** + * Get the [instance_id] column value. + * + * @return int + */ + public function getDbInstanceId() + { + return $this->instance_id; + } + + /** + * Set the value of [id] column. + * + * @param int $v new value + * @return CcStamp The current object (for fluent API support) + */ + public function setDbId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->id !== $v) { + $this->id = $v; + $this->modifiedColumns[] = CcStampPeer::ID; + } + + return $this; + } // setDbId() + + /** + * Set the value of [show_id] column. + * + * @param int $v new value + * @return CcStamp The current object (for fluent API support) + */ + public function setDbShowId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->show_id !== $v) { + $this->show_id = $v; + $this->modifiedColumns[] = CcStampPeer::SHOW_ID; + } + + if ($this->aCcShow !== null && $this->aCcShow->getDbId() !== $v) { + $this->aCcShow = null; + } + + return $this; + } // setDbShowId() + + /** + * Set the value of [instance_id] column. + * + * @param int $v new value + * @return CcStamp The current object (for fluent API support) + */ + public function setDbInstanceId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->instance_id !== $v) { + $this->instance_id = $v; + $this->modifiedColumns[] = CcStampPeer::INSTANCE_ID; + } + + if ($this->aCcShowInstances !== null && $this->aCcShowInstances->getDbId() !== $v) { + $this->aCcShowInstances = null; + } + + return $this; + } // setDbInstanceId() + + /** + * Indicates whether the columns in this object are only set to default values. + * + * This method can be used in conjunction with isModified() to indicate whether an object is both + * modified _and_ has some values set which are non-default. + * + * @return boolean Whether the columns in this object are only been set with default values. + */ + public function hasOnlyDefaultValues() + { + // otherwise, everything was equal, so return TRUE + return true; + } // hasOnlyDefaultValues() + + /** + * Hydrates (populates) the object variables with values from the database resultset. + * + * An offset (0-based "start column") is specified so that objects can be hydrated + * with a subset of the columns in the resultset rows. This is needed, for example, + * for results of JOIN queries where the resultset row includes columns from two or + * more tables. + * + * @param array $row The row returned by PDOStatement->fetch(PDO::FETCH_NUM) + * @param int $startcol 0-based offset column which indicates which restultset column to start with. + * @param boolean $rehydrate Whether this object is being re-hydrated from the database. + * @return int next starting column + * @throws PropelException - Any caught Exception will be rewrapped as a PropelException. + */ + public function hydrate($row, $startcol = 0, $rehydrate = false) + { + try { + + $this->id = ($row[$startcol + 0] !== null) ? (int) $row[$startcol + 0] : null; + $this->show_id = ($row[$startcol + 1] !== null) ? (int) $row[$startcol + 1] : null; + $this->instance_id = ($row[$startcol + 2] !== null) ? (int) $row[$startcol + 2] : null; + $this->resetModified(); + + $this->setNew(false); + + if ($rehydrate) { + $this->ensureConsistency(); + } + + return $startcol + 3; // 3 = CcStampPeer::NUM_COLUMNS - CcStampPeer::NUM_LAZY_LOAD_COLUMNS). + + } catch (Exception $e) { + throw new PropelException("Error populating CcStamp object", $e); + } + } + + /** + * Checks and repairs the internal consistency of the object. + * + * This method is executed after an already-instantiated object is re-hydrated + * from the database. It exists to check any foreign keys to make sure that + * the objects related to the current object are correct based on foreign key. + * + * You can override this method in the stub class, but you should always invoke + * the base method from the overridden method (i.e. parent::ensureConsistency()), + * in case your model changes. + * + * @throws PropelException + */ + public function ensureConsistency() + { + + if ($this->aCcShow !== null && $this->show_id !== $this->aCcShow->getDbId()) { + $this->aCcShow = null; + } + if ($this->aCcShowInstances !== null && $this->instance_id !== $this->aCcShowInstances->getDbId()) { + $this->aCcShowInstances = null; + } + } // ensureConsistency + + /** + * Reloads this object from datastore based on primary key and (optionally) resets all associated objects. + * + * This will only work if the object has been saved and has a valid primary key set. + * + * @param boolean $deep (optional) Whether to also de-associated any related objects. + * @param PropelPDO $con (optional) The PropelPDO connection to use. + * @return void + * @throws PropelException - if this object is deleted, unsaved or doesn't have pk match in db + */ + public function reload($deep = false, PropelPDO $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("Cannot reload a deleted object."); + } + + if ($this->isNew()) { + throw new PropelException("Cannot reload an unsaved object."); + } + + if ($con === null) { + $con = Propel::getConnection(CcStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + // We don't need to alter the object instance pool; we're just modifying this instance + // already in the pool. + + $stmt = CcStampPeer::doSelectStmt($this->buildPkeyCriteria(), $con); + $row = $stmt->fetch(PDO::FETCH_NUM); + $stmt->closeCursor(); + if (!$row) { + throw new PropelException('Cannot find matching row in the database to reload object values.'); + } + $this->hydrate($row, 0, true); // rehydrate + + if ($deep) { // also de-associate any related objects? + + $this->aCcShow = null; + $this->aCcShowInstances = null; + $this->collCcStampContentss = null; + + } // if (deep) + } + + /** + * Removes this object from datastore and sets delete attribute. + * + * @param PropelPDO $con + * @return void + * @throws PropelException + * @see BaseObject::setDeleted() + * @see BaseObject::isDeleted() + */ + public function delete(PropelPDO $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("This object has already been deleted."); + } + + if ($con === null) { + $con = Propel::getConnection(CcStampPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + } + + $con->beginTransaction(); + try { + $ret = $this->preDelete($con); + if ($ret) { + CcStampQuery::create() + ->filterByPrimaryKey($this->getPrimaryKey()) + ->delete($con); + $this->postDelete($con); + $con->commit(); + $this->setDeleted(true); + } else { + $con->commit(); + } + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Persists this object to the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All modified related objects will also be persisted in the doSave() + * method. This method wraps all precipitate database operations in a + * single transaction. + * + * @param PropelPDO $con + * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. + * @throws PropelException + * @see doSave() + */ + public function save(PropelPDO $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("You cannot save an object that has been deleted."); + } + + if ($con === null) { + $con = Propel::getConnection(CcStampPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + } + + $con->beginTransaction(); + $isInsert = $this->isNew(); + try { + $ret = $this->preSave($con); + if ($isInsert) { + $ret = $ret && $this->preInsert($con); + } else { + $ret = $ret && $this->preUpdate($con); + } + if ($ret) { + $affectedRows = $this->doSave($con); + if ($isInsert) { + $this->postInsert($con); + } else { + $this->postUpdate($con); + } + $this->postSave($con); + CcStampPeer::addInstanceToPool($this); + } else { + $affectedRows = 0; + } + $con->commit(); + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Performs the work of inserting or updating the row in the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All related objects are also updated in this method. + * + * @param PropelPDO $con + * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. + * @throws PropelException + * @see save() + */ + protected function doSave(PropelPDO $con) + { + $affectedRows = 0; // initialize var to track total num of affected rows + if (!$this->alreadyInSave) { + $this->alreadyInSave = true; + + // We call the save method on the following object(s) if they + // were passed to this object by their coresponding set + // method. This object relates to these object(s) by a + // foreign key reference. + + if ($this->aCcShow !== null) { + if ($this->aCcShow->isModified() || $this->aCcShow->isNew()) { + $affectedRows += $this->aCcShow->save($con); + } + $this->setCcShow($this->aCcShow); + } + + if ($this->aCcShowInstances !== null) { + if ($this->aCcShowInstances->isModified() || $this->aCcShowInstances->isNew()) { + $affectedRows += $this->aCcShowInstances->save($con); + } + $this->setCcShowInstances($this->aCcShowInstances); + } + + if ($this->isNew() ) { + $this->modifiedColumns[] = CcStampPeer::ID; + } + + // If this object has been modified, then save it to the database. + if ($this->isModified()) { + if ($this->isNew()) { + $criteria = $this->buildCriteria(); + if ($criteria->keyContainsValue(CcStampPeer::ID) ) { + throw new PropelException('Cannot insert a value for auto-increment primary key ('.CcStampPeer::ID.')'); + } + + $pk = BasePeer::doInsert($criteria, $con); + $affectedRows += 1; + $this->setDbId($pk); //[IMV] update autoincrement primary key + $this->setNew(false); + } else { + $affectedRows += CcStampPeer::doUpdate($this, $con); + } + + $this->resetModified(); // [HL] After being saved an object is no longer 'modified' + } + + if ($this->collCcStampContentss !== null) { + foreach ($this->collCcStampContentss as $referrerFK) { + if (!$referrerFK->isDeleted()) { + $affectedRows += $referrerFK->save($con); + } + } + } + + $this->alreadyInSave = false; + + } + return $affectedRows; + } // doSave() + + /** + * Array of ValidationFailed objects. + * @var array ValidationFailed[] + */ + protected $validationFailures = array(); + + /** + * Gets any ValidationFailed objects that resulted from last call to validate(). + * + * + * @return array ValidationFailed[] + * @see validate() + */ + public function getValidationFailures() + { + return $this->validationFailures; + } + + /** + * Validates the objects modified field values and all objects related to this table. + * + * If $columns is either a column name or an array of column names + * only those columns are validated. + * + * @param mixed $columns Column name or an array of column names. + * @return boolean Whether all columns pass validation. + * @see doValidate() + * @see getValidationFailures() + */ + public function validate($columns = null) + { + $res = $this->doValidate($columns); + if ($res === true) { + $this->validationFailures = array(); + return true; + } else { + $this->validationFailures = $res; + return false; + } + } + + /** + * This function performs the validation work for complex object models. + * + * In addition to checking the current object, all related objects will + * also be validated. If all pass then true is returned; otherwise + * an aggreagated array of ValidationFailed objects will be returned. + * + * @param array $columns Array of column names to validate. + * @return mixed true if all validations pass; array of ValidationFailed objets otherwise. + */ + protected function doValidate($columns = null) + { + if (!$this->alreadyInValidation) { + $this->alreadyInValidation = true; + $retval = null; + + $failureMap = array(); + + + // We call the validate method on the following object(s) if they + // were passed to this object by their coresponding set + // method. This object relates to these object(s) by a + // foreign key reference. + + if ($this->aCcShow !== null) { + if (!$this->aCcShow->validate($columns)) { + $failureMap = array_merge($failureMap, $this->aCcShow->getValidationFailures()); + } + } + + if ($this->aCcShowInstances !== null) { + if (!$this->aCcShowInstances->validate($columns)) { + $failureMap = array_merge($failureMap, $this->aCcShowInstances->getValidationFailures()); + } + } + + + if (($retval = CcStampPeer::doValidate($this, $columns)) !== true) { + $failureMap = array_merge($failureMap, $retval); + } + + + if ($this->collCcStampContentss !== null) { + foreach ($this->collCcStampContentss as $referrerFK) { + if (!$referrerFK->validate($columns)) { + $failureMap = array_merge($failureMap, $referrerFK->getValidationFailures()); + } + } + } + + + $this->alreadyInValidation = false; + } + + return (!empty($failureMap) ? $failureMap : true); + } + + /** + * Retrieves a field from the object by name passed in as a string. + * + * @param string $name name + * @param string $type The type of fieldname the $name is of: + * one of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME + * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM + * @return mixed Value of field. + */ + public function getByName($name, $type = BasePeer::TYPE_PHPNAME) + { + $pos = CcStampPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); + $field = $this->getByPosition($pos); + return $field; + } + + /** + * Retrieves a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @return mixed Value of field at $pos + */ + public function getByPosition($pos) + { + switch($pos) { + case 0: + return $this->getDbId(); + break; + case 1: + return $this->getDbShowId(); + break; + case 2: + return $this->getDbInstanceId(); + break; + default: + return null; + break; + } // switch() + } + + /** + * Exports the object as an array. + * + * You can specify the key type of the array by passing one of the class + * type constants. + * + * @param string $keyType (optional) One of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME, + * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. + * Defaults to BasePeer::TYPE_PHPNAME. + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy loaded columns. Defaults to TRUE. + * @param boolean $includeForeignObjects (optional) Whether to include hydrated related objects. Default to FALSE. + * + * @return array an associative array containing the field names (as keys) and field values + */ + public function toArray($keyType = BasePeer::TYPE_PHPNAME, $includeLazyLoadColumns = true, $includeForeignObjects = false) + { + $keys = CcStampPeer::getFieldNames($keyType); + $result = array( + $keys[0] => $this->getDbId(), + $keys[1] => $this->getDbShowId(), + $keys[2] => $this->getDbInstanceId(), + ); + if ($includeForeignObjects) { + if (null !== $this->aCcShow) { + $result['CcShow'] = $this->aCcShow->toArray($keyType, $includeLazyLoadColumns, true); + } + if (null !== $this->aCcShowInstances) { + $result['CcShowInstances'] = $this->aCcShowInstances->toArray($keyType, $includeLazyLoadColumns, true); + } + } + return $result; + } + + /** + * Sets a field from the object by name passed in as a string. + * + * @param string $name peer name + * @param mixed $value field value + * @param string $type The type of fieldname the $name is of: + * one of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME + * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM + * @return void + */ + public function setByName($name, $value, $type = BasePeer::TYPE_PHPNAME) + { + $pos = CcStampPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); + return $this->setByPosition($pos, $value); + } + + /** + * Sets a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @param mixed $value field value + * @return void + */ + public function setByPosition($pos, $value) + { + switch($pos) { + case 0: + $this->setDbId($value); + break; + case 1: + $this->setDbShowId($value); + break; + case 2: + $this->setDbInstanceId($value); + break; + } // switch() + } + + /** + * Populates the object using an array. + * + * This is particularly useful when populating an object from one of the + * request arrays (e.g. $_POST). This method goes through the column + * names, checking to see whether a matching key exists in populated + * array. If so the setByName() method is called for that column. + * + * You can specify the key type of the array by additionally passing one + * of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME, + * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. + * The default key type is the column's phpname (e.g. 'AuthorId') + * + * @param array $arr An array to populate the object from. + * @param string $keyType The type of keys the array uses. + * @return void + */ + public function fromArray($arr, $keyType = BasePeer::TYPE_PHPNAME) + { + $keys = CcStampPeer::getFieldNames($keyType); + + if (array_key_exists($keys[0], $arr)) $this->setDbId($arr[$keys[0]]); + if (array_key_exists($keys[1], $arr)) $this->setDbShowId($arr[$keys[1]]); + if (array_key_exists($keys[2], $arr)) $this->setDbInstanceId($arr[$keys[2]]); + } + + /** + * Build a Criteria object containing the values of all modified columns in this object. + * + * @return Criteria The Criteria object containing all modified values. + */ + public function buildCriteria() + { + $criteria = new Criteria(CcStampPeer::DATABASE_NAME); + + if ($this->isColumnModified(CcStampPeer::ID)) $criteria->add(CcStampPeer::ID, $this->id); + if ($this->isColumnModified(CcStampPeer::SHOW_ID)) $criteria->add(CcStampPeer::SHOW_ID, $this->show_id); + if ($this->isColumnModified(CcStampPeer::INSTANCE_ID)) $criteria->add(CcStampPeer::INSTANCE_ID, $this->instance_id); + + return $criteria; + } + + /** + * Builds a Criteria object containing the primary key for this object. + * + * Unlike buildCriteria() this method includes the primary key values regardless + * of whether or not they have been modified. + * + * @return Criteria The Criteria object containing value(s) for primary key(s). + */ + public function buildPkeyCriteria() + { + $criteria = new Criteria(CcStampPeer::DATABASE_NAME); + $criteria->add(CcStampPeer::ID, $this->id); + + return $criteria; + } + + /** + * Returns the primary key for this object (row). + * @return int + */ + public function getPrimaryKey() + { + return $this->getDbId(); + } + + /** + * Generic method to set the primary key (id column). + * + * @param int $key Primary key. + * @return void + */ + public function setPrimaryKey($key) + { + $this->setDbId($key); + } + + /** + * Returns true if the primary key for this object is null. + * @return boolean + */ + public function isPrimaryKeyNull() + { + return null === $this->getDbId(); + } + + /** + * Sets contents of passed object to values from current object. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param object $copyObj An object of CcStamp (or compatible) type. + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @throws PropelException + */ + public function copyInto($copyObj, $deepCopy = false) + { + $copyObj->setDbShowId($this->show_id); + $copyObj->setDbInstanceId($this->instance_id); + + if ($deepCopy) { + // important: temporarily setNew(false) because this affects the behavior of + // the getter/setter methods for fkey referrer objects. + $copyObj->setNew(false); + + foreach ($this->getCcStampContentss() as $relObj) { + if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves + $copyObj->addCcStampContents($relObj->copy($deepCopy)); + } + } + + } // if ($deepCopy) + + + $copyObj->setNew(true); + $copyObj->setDbId(NULL); // this is a auto-increment column, so set to default value + } + + /** + * Makes a copy of this object that will be inserted as a new row in table when saved. + * It creates a new object filling in the simple attributes, but skipping any primary + * keys that are defined for the table. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @return CcStamp Clone of current object. + * @throws PropelException + */ + public function copy($deepCopy = false) + { + // we use get_class(), because this might be a subclass + $clazz = get_class($this); + $copyObj = new $clazz(); + $this->copyInto($copyObj, $deepCopy); + return $copyObj; + } + + /** + * Returns a peer instance associated with this om. + * + * Since Peer classes are not to have any instance attributes, this method returns the + * same instance for all member of this class. The method could therefore + * be static, but this would prevent one from overriding the behavior. + * + * @return CcStampPeer + */ + public function getPeer() + { + if (self::$peer === null) { + self::$peer = new CcStampPeer(); + } + return self::$peer; + } + + /** + * Declares an association between this object and a CcShow object. + * + * @param CcShow $v + * @return CcStamp The current object (for fluent API support) + * @throws PropelException + */ + public function setCcShow(CcShow $v = null) + { + if ($v === null) { + $this->setDbShowId(NULL); + } else { + $this->setDbShowId($v->getDbId()); + } + + $this->aCcShow = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the CcShow object, it will not be re-added. + if ($v !== null) { + $v->addCcStamp($this); + } + + return $this; + } + + + /** + * Get the associated CcShow object + * + * @param PropelPDO Optional Connection object. + * @return CcShow The associated CcShow object. + * @throws PropelException + */ + public function getCcShow(PropelPDO $con = null) + { + if ($this->aCcShow === null && ($this->show_id !== null)) { + $this->aCcShow = CcShowQuery::create()->findPk($this->show_id, $con); + /* The following can be used additionally to + guarantee the related object contains a reference + to this object. This level of coupling may, however, be + undesirable since it could result in an only partially populated collection + in the referenced object. + $this->aCcShow->addCcStamps($this); + */ + } + return $this->aCcShow; + } + + /** + * Declares an association between this object and a CcShowInstances object. + * + * @param CcShowInstances $v + * @return CcStamp The current object (for fluent API support) + * @throws PropelException + */ + public function setCcShowInstances(CcShowInstances $v = null) + { + if ($v === null) { + $this->setDbInstanceId(NULL); + } else { + $this->setDbInstanceId($v->getDbId()); + } + + $this->aCcShowInstances = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the CcShowInstances object, it will not be re-added. + if ($v !== null) { + $v->addCcStamp($this); + } + + return $this; + } + + + /** + * Get the associated CcShowInstances object + * + * @param PropelPDO Optional Connection object. + * @return CcShowInstances The associated CcShowInstances object. + * @throws PropelException + */ + public function getCcShowInstances(PropelPDO $con = null) + { + if ($this->aCcShowInstances === null && ($this->instance_id !== null)) { + $this->aCcShowInstances = CcShowInstancesQuery::create()->findPk($this->instance_id, $con); + /* The following can be used additionally to + guarantee the related object contains a reference + to this object. This level of coupling may, however, be + undesirable since it could result in an only partially populated collection + in the referenced object. + $this->aCcShowInstances->addCcStamps($this); + */ + } + return $this->aCcShowInstances; + } + + /** + * Clears out the collCcStampContentss collection + * + * This does not modify the database; however, it will remove any associated objects, causing + * them to be refetched by subsequent calls to accessor method. + * + * @return void + * @see addCcStampContentss() + */ + public function clearCcStampContentss() + { + $this->collCcStampContentss = null; // important to set this to NULL since that means it is uninitialized + } + + /** + * Initializes the collCcStampContentss collection. + * + * By default this just sets the collCcStampContentss collection to an empty array (like clearcollCcStampContentss()); + * however, you may wish to override this method in your stub class to provide setting appropriate + * to your application -- for example, setting the initial array to the values stored in database. + * + * @return void + */ + public function initCcStampContentss() + { + $this->collCcStampContentss = new PropelObjectCollection(); + $this->collCcStampContentss->setModel('CcStampContents'); + } + + /** + * Gets an array of CcStampContents 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 CcStamp 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 CcStampContents[] List of CcStampContents objects + * @throws PropelException + */ + public function getCcStampContentss($criteria = null, PropelPDO $con = null) + { + if(null === $this->collCcStampContentss || null !== $criteria) { + if ($this->isNew() && null === $this->collCcStampContentss) { + // return empty collection + $this->initCcStampContentss(); + } else { + $collCcStampContentss = CcStampContentsQuery::create(null, $criteria) + ->filterByCcStamp($this) + ->find($con); + if (null !== $criteria) { + return $collCcStampContentss; + } + $this->collCcStampContentss = $collCcStampContentss; + } + } + return $this->collCcStampContentss; + } + + /** + * Returns the number of related CcStampContents objects. + * + * @param Criteria $criteria + * @param boolean $distinct + * @param PropelPDO $con + * @return int Count of related CcStampContents objects. + * @throws PropelException + */ + public function countCcStampContentss(Criteria $criteria = null, $distinct = false, PropelPDO $con = null) + { + if(null === $this->collCcStampContentss || null !== $criteria) { + if ($this->isNew() && null === $this->collCcStampContentss) { + return 0; + } else { + $query = CcStampContentsQuery::create(null, $criteria); + if($distinct) { + $query->distinct(); + } + return $query + ->filterByCcStamp($this) + ->count($con); + } + } else { + return count($this->collCcStampContentss); + } + } + + /** + * Method called to associate a CcStampContents object to this object + * through the CcStampContents foreign key attribute. + * + * @param CcStampContents $l CcStampContents + * @return void + * @throws PropelException + */ + public function addCcStampContents(CcStampContents $l) + { + if ($this->collCcStampContentss === null) { + $this->initCcStampContentss(); + } + if (!$this->collCcStampContentss->contains($l)) { // only add it if the **same** object is not already associated + $this->collCcStampContentss[]= $l; + $l->setCcStamp($this); + } + } + + + /** + * If this collection has already been initialized with + * an identical criteria, it returns the collection. + * Otherwise if this CcStamp is new, it will return + * an empty collection; or if this CcStamp has previously + * been saved, it will retrieve related CcStampContentss from storage. + * + * This method is protected by default in order to keep the public + * api reasonable. You can provide public methods for those you + * actually need in CcStamp. + * + * @param Criteria $criteria optional Criteria object to narrow the query + * @param PropelPDO $con optional connection object + * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) + * @return PropelCollection|array CcStampContents[] List of CcStampContents objects + */ + public function getCcStampContentssJoinCcFiles($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $query = CcStampContentsQuery::create(null, $criteria); + $query->joinWith('CcFiles', $join_behavior); + + return $this->getCcStampContentss($query, $con); + } + + + /** + * If this collection has already been initialized with + * an identical criteria, it returns the collection. + * Otherwise if this CcStamp is new, it will return + * an empty collection; or if this CcStamp has previously + * been saved, it will retrieve related CcStampContentss from storage. + * + * This method is protected by default in order to keep the public + * api reasonable. You can provide public methods for those you + * actually need in CcStamp. + * + * @param Criteria $criteria optional Criteria object to narrow the query + * @param PropelPDO $con optional connection object + * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) + * @return PropelCollection|array CcStampContents[] List of CcStampContents objects + */ + public function getCcStampContentssJoinCcWebstream($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $query = CcStampContentsQuery::create(null, $criteria); + $query->joinWith('CcWebstream', $join_behavior); + + return $this->getCcStampContentss($query, $con); + } + + + /** + * If this collection has already been initialized with + * an identical criteria, it returns the collection. + * Otherwise if this CcStamp is new, it will return + * an empty collection; or if this CcStamp has previously + * been saved, it will retrieve related CcStampContentss from storage. + * + * This method is protected by default in order to keep the public + * api reasonable. You can provide public methods for those you + * actually need in CcStamp. + * + * @param Criteria $criteria optional Criteria object to narrow the query + * @param PropelPDO $con optional connection object + * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) + * @return PropelCollection|array CcStampContents[] List of CcStampContents objects + */ + public function getCcStampContentssJoinCcBlock($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $query = CcStampContentsQuery::create(null, $criteria); + $query->joinWith('CcBlock', $join_behavior); + + return $this->getCcStampContentss($query, $con); + } + + + /** + * If this collection has already been initialized with + * an identical criteria, it returns the collection. + * Otherwise if this CcStamp is new, it will return + * an empty collection; or if this CcStamp has previously + * been saved, it will retrieve related CcStampContentss from storage. + * + * This method is protected by default in order to keep the public + * api reasonable. You can provide public methods for those you + * actually need in CcStamp. + * + * @param Criteria $criteria optional Criteria object to narrow the query + * @param PropelPDO $con optional connection object + * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) + * @return PropelCollection|array CcStampContents[] List of CcStampContents objects + */ + public function getCcStampContentssJoinCcPlaylist($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $query = CcStampContentsQuery::create(null, $criteria); + $query->joinWith('CcPlaylist', $join_behavior); + + return $this->getCcStampContentss($query, $con); + } + + /** + * Clears the current object and sets all attributes to their default values + */ + public function clear() + { + $this->id = null; + $this->show_id = null; + $this->instance_id = null; + $this->alreadyInSave = false; + $this->alreadyInValidation = false; + $this->clearAllReferences(); + $this->resetModified(); + $this->setNew(true); + $this->setDeleted(false); + } + + /** + * Resets all collections of referencing foreign keys. + * + * This method is a user-space workaround for PHP's inability to garbage collect objects + * with circular references. This is currently necessary when using Propel in certain + * daemon or large-volumne/high-memory operations. + * + * @param boolean $deep Whether to also clear the references on all associated objects. + */ + public function clearAllReferences($deep = false) + { + if ($deep) { + if ($this->collCcStampContentss) { + foreach ((array) $this->collCcStampContentss as $o) { + $o->clearAllReferences($deep); + } + } + } // if ($deep) + + $this->collCcStampContentss = null; + $this->aCcShow = null; + $this->aCcShowInstances = null; + } + + /** + * Catches calls to virtual methods + */ + public function __call($name, $params) + { + if (preg_match('/get(\w+)/', $name, $matches)) { + $virtualColumn = $matches[1]; + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + // no lcfirst in php<5.3... + $virtualColumn[0] = strtolower($virtualColumn[0]); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + } + throw new PropelException('Call to undefined method: ' . $name); + } + +} // BaseCcStamp diff --git a/airtime_mvc/application/models/airtime/om/BaseCcStampContents.php b/airtime_mvc/application/models/airtime/om/BaseCcStampContents.php new file mode 100644 index 000000000..10442dbe1 --- /dev/null +++ b/airtime_mvc/application/models/airtime/om/BaseCcStampContents.php @@ -0,0 +1,1656 @@ +clip_length = '00:00:00'; + $this->cue_in = '00:00:00'; + $this->cue_out = '00:00:00'; + $this->fade_in = '00:00:00'; + $this->fade_out = '00:00:00'; + } + + /** + * Initializes internal state of BaseCcStampContents object. + * @see applyDefaults() + */ + public function __construct() + { + parent::__construct(); + $this->applyDefaultValues(); + } + + /** + * Get the [id] column value. + * + * @return int + */ + public function getDbId() + { + return $this->id; + } + + /** + * Get the [stamp_id] column value. + * + * @return int + */ + public function getDbStampId() + { + return $this->stamp_id; + } + + /** + * Get the [file_id] column value. + * + * @return int + */ + public function getDbFileId() + { + return $this->file_id; + } + + /** + * Get the [stream_id] column value. + * + * @return int + */ + public function getDbStreamId() + { + return $this->stream_id; + } + + /** + * Get the [block_id] column value. + * + * @return int + */ + public function getDbBlockId() + { + return $this->block_id; + } + + /** + * Get the [playlist_id] column value. + * + * @return int + */ + public function getDbPlaylistId() + { + return $this->playlist_id; + } + + /** + * Get the [position] column value. + * + * @return int + */ + public function getDbPosition() + { + return $this->position; + } + + /** + * Get the [clip_length] column value. + * + * @return string + */ + public function getDbClipLength() + { + return $this->clip_length; + } + + /** + * Get the [cue_in] column value. + * + * @return string + */ + public function getDbCueIn() + { + return $this->cue_in; + } + + /** + * Get the [cue_out] column value. + * + * @return string + */ + public function getDbCueOut() + { + return $this->cue_out; + } + + /** + * Get the [fade_in] column value. + * + * @return string + */ + public function getDbFadeIn() + { + return $this->fade_in; + } + + /** + * Get the [fade_out] column value. + * + * @return string + */ + public function getDbFadeOut() + { + return $this->fade_out; + } + + /** + * Set the value of [id] column. + * + * @param int $v new value + * @return CcStampContents The current object (for fluent API support) + */ + public function setDbId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->id !== $v) { + $this->id = $v; + $this->modifiedColumns[] = CcStampContentsPeer::ID; + } + + return $this; + } // setDbId() + + /** + * Set the value of [stamp_id] column. + * + * @param int $v new value + * @return CcStampContents The current object (for fluent API support) + */ + public function setDbStampId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->stamp_id !== $v) { + $this->stamp_id = $v; + $this->modifiedColumns[] = CcStampContentsPeer::STAMP_ID; + } + + if ($this->aCcStamp !== null && $this->aCcStamp->getDbId() !== $v) { + $this->aCcStamp = null; + } + + return $this; + } // setDbStampId() + + /** + * Set the value of [file_id] column. + * + * @param int $v new value + * @return CcStampContents The current object (for fluent API support) + */ + public function setDbFileId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->file_id !== $v) { + $this->file_id = $v; + $this->modifiedColumns[] = CcStampContentsPeer::FILE_ID; + } + + if ($this->aCcFiles !== null && $this->aCcFiles->getDbId() !== $v) { + $this->aCcFiles = null; + } + + return $this; + } // setDbFileId() + + /** + * Set the value of [stream_id] column. + * + * @param int $v new value + * @return CcStampContents The current object (for fluent API support) + */ + public function setDbStreamId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->stream_id !== $v) { + $this->stream_id = $v; + $this->modifiedColumns[] = CcStampContentsPeer::STREAM_ID; + } + + if ($this->aCcWebstream !== null && $this->aCcWebstream->getDbId() !== $v) { + $this->aCcWebstream = null; + } + + return $this; + } // setDbStreamId() + + /** + * Set the value of [block_id] column. + * + * @param int $v new value + * @return CcStampContents The current object (for fluent API support) + */ + public function setDbBlockId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->block_id !== $v) { + $this->block_id = $v; + $this->modifiedColumns[] = CcStampContentsPeer::BLOCK_ID; + } + + if ($this->aCcBlock !== null && $this->aCcBlock->getDbId() !== $v) { + $this->aCcBlock = null; + } + + return $this; + } // setDbBlockId() + + /** + * Set the value of [playlist_id] column. + * + * @param int $v new value + * @return CcStampContents The current object (for fluent API support) + */ + public function setDbPlaylistId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->playlist_id !== $v) { + $this->playlist_id = $v; + $this->modifiedColumns[] = CcStampContentsPeer::PLAYLIST_ID; + } + + if ($this->aCcPlaylist !== null && $this->aCcPlaylist->getDbId() !== $v) { + $this->aCcPlaylist = null; + } + + return $this; + } // setDbPlaylistId() + + /** + * Set the value of [position] column. + * + * @param int $v new value + * @return CcStampContents The current object (for fluent API support) + */ + public function setDbPosition($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->position !== $v) { + $this->position = $v; + $this->modifiedColumns[] = CcStampContentsPeer::POSITION; + } + + return $this; + } // setDbPosition() + + /** + * Set the value of [clip_length] column. + * + * @param string $v new value + * @return CcStampContents The current object (for fluent API support) + */ + public function setDbClipLength($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->clip_length !== $v || $this->isNew()) { + $this->clip_length = $v; + $this->modifiedColumns[] = CcStampContentsPeer::CLIP_LENGTH; + } + + return $this; + } // setDbClipLength() + + /** + * Set the value of [cue_in] column. + * + * @param string $v new value + * @return CcStampContents The current object (for fluent API support) + */ + public function setDbCueIn($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->cue_in !== $v || $this->isNew()) { + $this->cue_in = $v; + $this->modifiedColumns[] = CcStampContentsPeer::CUE_IN; + } + + return $this; + } // setDbCueIn() + + /** + * Set the value of [cue_out] column. + * + * @param string $v new value + * @return CcStampContents The current object (for fluent API support) + */ + public function setDbCueOut($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->cue_out !== $v || $this->isNew()) { + $this->cue_out = $v; + $this->modifiedColumns[] = CcStampContentsPeer::CUE_OUT; + } + + return $this; + } // setDbCueOut() + + /** + * Set the value of [fade_in] column. + * + * @param string $v new value + * @return CcStampContents The current object (for fluent API support) + */ + public function setDbFadeIn($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->fade_in !== $v || $this->isNew()) { + $this->fade_in = $v; + $this->modifiedColumns[] = CcStampContentsPeer::FADE_IN; + } + + return $this; + } // setDbFadeIn() + + /** + * Set the value of [fade_out] column. + * + * @param string $v new value + * @return CcStampContents The current object (for fluent API support) + */ + public function setDbFadeOut($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->fade_out !== $v || $this->isNew()) { + $this->fade_out = $v; + $this->modifiedColumns[] = CcStampContentsPeer::FADE_OUT; + } + + return $this; + } // setDbFadeOut() + + /** + * Indicates whether the columns in this object are only set to default values. + * + * This method can be used in conjunction with isModified() to indicate whether an object is both + * modified _and_ has some values set which are non-default. + * + * @return boolean Whether the columns in this object are only been set with default values. + */ + public function hasOnlyDefaultValues() + { + if ($this->clip_length !== '00:00:00') { + return false; + } + + if ($this->cue_in !== '00:00:00') { + return false; + } + + if ($this->cue_out !== '00:00:00') { + return false; + } + + if ($this->fade_in !== '00:00:00') { + return false; + } + + if ($this->fade_out !== '00:00:00') { + return false; + } + + // otherwise, everything was equal, so return TRUE + return true; + } // hasOnlyDefaultValues() + + /** + * Hydrates (populates) the object variables with values from the database resultset. + * + * An offset (0-based "start column") is specified so that objects can be hydrated + * with a subset of the columns in the resultset rows. This is needed, for example, + * for results of JOIN queries where the resultset row includes columns from two or + * more tables. + * + * @param array $row The row returned by PDOStatement->fetch(PDO::FETCH_NUM) + * @param int $startcol 0-based offset column which indicates which restultset column to start with. + * @param boolean $rehydrate Whether this object is being re-hydrated from the database. + * @return int next starting column + * @throws PropelException - Any caught Exception will be rewrapped as a PropelException. + */ + public function hydrate($row, $startcol = 0, $rehydrate = false) + { + try { + + $this->id = ($row[$startcol + 0] !== null) ? (int) $row[$startcol + 0] : null; + $this->stamp_id = ($row[$startcol + 1] !== null) ? (int) $row[$startcol + 1] : null; + $this->file_id = ($row[$startcol + 2] !== null) ? (int) $row[$startcol + 2] : null; + $this->stream_id = ($row[$startcol + 3] !== null) ? (int) $row[$startcol + 3] : null; + $this->block_id = ($row[$startcol + 4] !== null) ? (int) $row[$startcol + 4] : null; + $this->playlist_id = ($row[$startcol + 5] !== null) ? (int) $row[$startcol + 5] : null; + $this->position = ($row[$startcol + 6] !== null) ? (int) $row[$startcol + 6] : null; + $this->clip_length = ($row[$startcol + 7] !== null) ? (string) $row[$startcol + 7] : null; + $this->cue_in = ($row[$startcol + 8] !== null) ? (string) $row[$startcol + 8] : null; + $this->cue_out = ($row[$startcol + 9] !== null) ? (string) $row[$startcol + 9] : null; + $this->fade_in = ($row[$startcol + 10] !== null) ? (string) $row[$startcol + 10] : null; + $this->fade_out = ($row[$startcol + 11] !== null) ? (string) $row[$startcol + 11] : null; + $this->resetModified(); + + $this->setNew(false); + + if ($rehydrate) { + $this->ensureConsistency(); + } + + return $startcol + 12; // 12 = CcStampContentsPeer::NUM_COLUMNS - CcStampContentsPeer::NUM_LAZY_LOAD_COLUMNS). + + } catch (Exception $e) { + throw new PropelException("Error populating CcStampContents object", $e); + } + } + + /** + * Checks and repairs the internal consistency of the object. + * + * This method is executed after an already-instantiated object is re-hydrated + * from the database. It exists to check any foreign keys to make sure that + * the objects related to the current object are correct based on foreign key. + * + * You can override this method in the stub class, but you should always invoke + * the base method from the overridden method (i.e. parent::ensureConsistency()), + * in case your model changes. + * + * @throws PropelException + */ + public function ensureConsistency() + { + + if ($this->aCcStamp !== null && $this->stamp_id !== $this->aCcStamp->getDbId()) { + $this->aCcStamp = null; + } + if ($this->aCcFiles !== null && $this->file_id !== $this->aCcFiles->getDbId()) { + $this->aCcFiles = null; + } + if ($this->aCcWebstream !== null && $this->stream_id !== $this->aCcWebstream->getDbId()) { + $this->aCcWebstream = null; + } + if ($this->aCcBlock !== null && $this->block_id !== $this->aCcBlock->getDbId()) { + $this->aCcBlock = null; + } + if ($this->aCcPlaylist !== null && $this->playlist_id !== $this->aCcPlaylist->getDbId()) { + $this->aCcPlaylist = null; + } + } // ensureConsistency + + /** + * Reloads this object from datastore based on primary key and (optionally) resets all associated objects. + * + * This will only work if the object has been saved and has a valid primary key set. + * + * @param boolean $deep (optional) Whether to also de-associated any related objects. + * @param PropelPDO $con (optional) The PropelPDO connection to use. + * @return void + * @throws PropelException - if this object is deleted, unsaved or doesn't have pk match in db + */ + public function reload($deep = false, PropelPDO $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("Cannot reload a deleted object."); + } + + if ($this->isNew()) { + throw new PropelException("Cannot reload an unsaved object."); + } + + if ($con === null) { + $con = Propel::getConnection(CcStampContentsPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + // We don't need to alter the object instance pool; we're just modifying this instance + // already in the pool. + + $stmt = CcStampContentsPeer::doSelectStmt($this->buildPkeyCriteria(), $con); + $row = $stmt->fetch(PDO::FETCH_NUM); + $stmt->closeCursor(); + if (!$row) { + throw new PropelException('Cannot find matching row in the database to reload object values.'); + } + $this->hydrate($row, 0, true); // rehydrate + + if ($deep) { // also de-associate any related objects? + + $this->aCcStamp = null; + $this->aCcFiles = null; + $this->aCcWebstream = null; + $this->aCcBlock = null; + $this->aCcPlaylist = null; + } // if (deep) + } + + /** + * Removes this object from datastore and sets delete attribute. + * + * @param PropelPDO $con + * @return void + * @throws PropelException + * @see BaseObject::setDeleted() + * @see BaseObject::isDeleted() + */ + public function delete(PropelPDO $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("This object has already been deleted."); + } + + if ($con === null) { + $con = Propel::getConnection(CcStampContentsPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + } + + $con->beginTransaction(); + try { + $ret = $this->preDelete($con); + if ($ret) { + CcStampContentsQuery::create() + ->filterByPrimaryKey($this->getPrimaryKey()) + ->delete($con); + $this->postDelete($con); + $con->commit(); + $this->setDeleted(true); + } else { + $con->commit(); + } + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Persists this object to the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All modified related objects will also be persisted in the doSave() + * method. This method wraps all precipitate database operations in a + * single transaction. + * + * @param PropelPDO $con + * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. + * @throws PropelException + * @see doSave() + */ + public function save(PropelPDO $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("You cannot save an object that has been deleted."); + } + + if ($con === null) { + $con = Propel::getConnection(CcStampContentsPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + } + + $con->beginTransaction(); + $isInsert = $this->isNew(); + try { + $ret = $this->preSave($con); + if ($isInsert) { + $ret = $ret && $this->preInsert($con); + } else { + $ret = $ret && $this->preUpdate($con); + } + if ($ret) { + $affectedRows = $this->doSave($con); + if ($isInsert) { + $this->postInsert($con); + } else { + $this->postUpdate($con); + } + $this->postSave($con); + CcStampContentsPeer::addInstanceToPool($this); + } else { + $affectedRows = 0; + } + $con->commit(); + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Performs the work of inserting or updating the row in the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All related objects are also updated in this method. + * + * @param PropelPDO $con + * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. + * @throws PropelException + * @see save() + */ + protected function doSave(PropelPDO $con) + { + $affectedRows = 0; // initialize var to track total num of affected rows + if (!$this->alreadyInSave) { + $this->alreadyInSave = true; + + // We call the save method on the following object(s) if they + // were passed to this object by their coresponding set + // method. This object relates to these object(s) by a + // foreign key reference. + + if ($this->aCcStamp !== null) { + if ($this->aCcStamp->isModified() || $this->aCcStamp->isNew()) { + $affectedRows += $this->aCcStamp->save($con); + } + $this->setCcStamp($this->aCcStamp); + } + + if ($this->aCcFiles !== null) { + if ($this->aCcFiles->isModified() || $this->aCcFiles->isNew()) { + $affectedRows += $this->aCcFiles->save($con); + } + $this->setCcFiles($this->aCcFiles); + } + + if ($this->aCcWebstream !== null) { + if ($this->aCcWebstream->isModified() || $this->aCcWebstream->isNew()) { + $affectedRows += $this->aCcWebstream->save($con); + } + $this->setCcWebstream($this->aCcWebstream); + } + + if ($this->aCcBlock !== null) { + if ($this->aCcBlock->isModified() || $this->aCcBlock->isNew()) { + $affectedRows += $this->aCcBlock->save($con); + } + $this->setCcBlock($this->aCcBlock); + } + + if ($this->aCcPlaylist !== null) { + if ($this->aCcPlaylist->isModified() || $this->aCcPlaylist->isNew()) { + $affectedRows += $this->aCcPlaylist->save($con); + } + $this->setCcPlaylist($this->aCcPlaylist); + } + + if ($this->isNew() ) { + $this->modifiedColumns[] = CcStampContentsPeer::ID; + } + + // If this object has been modified, then save it to the database. + if ($this->isModified()) { + if ($this->isNew()) { + $criteria = $this->buildCriteria(); + if ($criteria->keyContainsValue(CcStampContentsPeer::ID) ) { + throw new PropelException('Cannot insert a value for auto-increment primary key ('.CcStampContentsPeer::ID.')'); + } + + $pk = BasePeer::doInsert($criteria, $con); + $affectedRows += 1; + $this->setDbId($pk); //[IMV] update autoincrement primary key + $this->setNew(false); + } else { + $affectedRows += CcStampContentsPeer::doUpdate($this, $con); + } + + $this->resetModified(); // [HL] After being saved an object is no longer 'modified' + } + + $this->alreadyInSave = false; + + } + return $affectedRows; + } // doSave() + + /** + * Array of ValidationFailed objects. + * @var array ValidationFailed[] + */ + protected $validationFailures = array(); + + /** + * Gets any ValidationFailed objects that resulted from last call to validate(). + * + * + * @return array ValidationFailed[] + * @see validate() + */ + public function getValidationFailures() + { + return $this->validationFailures; + } + + /** + * Validates the objects modified field values and all objects related to this table. + * + * If $columns is either a column name or an array of column names + * only those columns are validated. + * + * @param mixed $columns Column name or an array of column names. + * @return boolean Whether all columns pass validation. + * @see doValidate() + * @see getValidationFailures() + */ + public function validate($columns = null) + { + $res = $this->doValidate($columns); + if ($res === true) { + $this->validationFailures = array(); + return true; + } else { + $this->validationFailures = $res; + return false; + } + } + + /** + * This function performs the validation work for complex object models. + * + * In addition to checking the current object, all related objects will + * also be validated. If all pass then true is returned; otherwise + * an aggreagated array of ValidationFailed objects will be returned. + * + * @param array $columns Array of column names to validate. + * @return mixed true if all validations pass; array of ValidationFailed objets otherwise. + */ + protected function doValidate($columns = null) + { + if (!$this->alreadyInValidation) { + $this->alreadyInValidation = true; + $retval = null; + + $failureMap = array(); + + + // We call the validate method on the following object(s) if they + // were passed to this object by their coresponding set + // method. This object relates to these object(s) by a + // foreign key reference. + + if ($this->aCcStamp !== null) { + if (!$this->aCcStamp->validate($columns)) { + $failureMap = array_merge($failureMap, $this->aCcStamp->getValidationFailures()); + } + } + + if ($this->aCcFiles !== null) { + if (!$this->aCcFiles->validate($columns)) { + $failureMap = array_merge($failureMap, $this->aCcFiles->getValidationFailures()); + } + } + + if ($this->aCcWebstream !== null) { + if (!$this->aCcWebstream->validate($columns)) { + $failureMap = array_merge($failureMap, $this->aCcWebstream->getValidationFailures()); + } + } + + if ($this->aCcBlock !== null) { + if (!$this->aCcBlock->validate($columns)) { + $failureMap = array_merge($failureMap, $this->aCcBlock->getValidationFailures()); + } + } + + if ($this->aCcPlaylist !== null) { + if (!$this->aCcPlaylist->validate($columns)) { + $failureMap = array_merge($failureMap, $this->aCcPlaylist->getValidationFailures()); + } + } + + + if (($retval = CcStampContentsPeer::doValidate($this, $columns)) !== true) { + $failureMap = array_merge($failureMap, $retval); + } + + + + $this->alreadyInValidation = false; + } + + return (!empty($failureMap) ? $failureMap : true); + } + + /** + * Retrieves a field from the object by name passed in as a string. + * + * @param string $name name + * @param string $type The type of fieldname the $name is of: + * one of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME + * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM + * @return mixed Value of field. + */ + public function getByName($name, $type = BasePeer::TYPE_PHPNAME) + { + $pos = CcStampContentsPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); + $field = $this->getByPosition($pos); + return $field; + } + + /** + * Retrieves a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @return mixed Value of field at $pos + */ + public function getByPosition($pos) + { + switch($pos) { + case 0: + return $this->getDbId(); + break; + case 1: + return $this->getDbStampId(); + break; + case 2: + return $this->getDbFileId(); + break; + case 3: + return $this->getDbStreamId(); + break; + case 4: + return $this->getDbBlockId(); + break; + case 5: + return $this->getDbPlaylistId(); + break; + case 6: + return $this->getDbPosition(); + break; + case 7: + return $this->getDbClipLength(); + break; + case 8: + return $this->getDbCueIn(); + break; + case 9: + return $this->getDbCueOut(); + break; + case 10: + return $this->getDbFadeIn(); + break; + case 11: + return $this->getDbFadeOut(); + break; + default: + return null; + break; + } // switch() + } + + /** + * Exports the object as an array. + * + * You can specify the key type of the array by passing one of the class + * type constants. + * + * @param string $keyType (optional) One of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME, + * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. + * Defaults to BasePeer::TYPE_PHPNAME. + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy loaded columns. Defaults to TRUE. + * @param boolean $includeForeignObjects (optional) Whether to include hydrated related objects. Default to FALSE. + * + * @return array an associative array containing the field names (as keys) and field values + */ + public function toArray($keyType = BasePeer::TYPE_PHPNAME, $includeLazyLoadColumns = true, $includeForeignObjects = false) + { + $keys = CcStampContentsPeer::getFieldNames($keyType); + $result = array( + $keys[0] => $this->getDbId(), + $keys[1] => $this->getDbStampId(), + $keys[2] => $this->getDbFileId(), + $keys[3] => $this->getDbStreamId(), + $keys[4] => $this->getDbBlockId(), + $keys[5] => $this->getDbPlaylistId(), + $keys[6] => $this->getDbPosition(), + $keys[7] => $this->getDbClipLength(), + $keys[8] => $this->getDbCueIn(), + $keys[9] => $this->getDbCueOut(), + $keys[10] => $this->getDbFadeIn(), + $keys[11] => $this->getDbFadeOut(), + ); + if ($includeForeignObjects) { + if (null !== $this->aCcStamp) { + $result['CcStamp'] = $this->aCcStamp->toArray($keyType, $includeLazyLoadColumns, true); + } + if (null !== $this->aCcFiles) { + $result['CcFiles'] = $this->aCcFiles->toArray($keyType, $includeLazyLoadColumns, true); + } + if (null !== $this->aCcWebstream) { + $result['CcWebstream'] = $this->aCcWebstream->toArray($keyType, $includeLazyLoadColumns, true); + } + if (null !== $this->aCcBlock) { + $result['CcBlock'] = $this->aCcBlock->toArray($keyType, $includeLazyLoadColumns, true); + } + if (null !== $this->aCcPlaylist) { + $result['CcPlaylist'] = $this->aCcPlaylist->toArray($keyType, $includeLazyLoadColumns, true); + } + } + return $result; + } + + /** + * Sets a field from the object by name passed in as a string. + * + * @param string $name peer name + * @param mixed $value field value + * @param string $type The type of fieldname the $name is of: + * one of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME + * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM + * @return void + */ + public function setByName($name, $value, $type = BasePeer::TYPE_PHPNAME) + { + $pos = CcStampContentsPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); + return $this->setByPosition($pos, $value); + } + + /** + * Sets a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @param mixed $value field value + * @return void + */ + public function setByPosition($pos, $value) + { + switch($pos) { + case 0: + $this->setDbId($value); + break; + case 1: + $this->setDbStampId($value); + break; + case 2: + $this->setDbFileId($value); + break; + case 3: + $this->setDbStreamId($value); + break; + case 4: + $this->setDbBlockId($value); + break; + case 5: + $this->setDbPlaylistId($value); + break; + case 6: + $this->setDbPosition($value); + break; + case 7: + $this->setDbClipLength($value); + break; + case 8: + $this->setDbCueIn($value); + break; + case 9: + $this->setDbCueOut($value); + break; + case 10: + $this->setDbFadeIn($value); + break; + case 11: + $this->setDbFadeOut($value); + break; + } // switch() + } + + /** + * Populates the object using an array. + * + * This is particularly useful when populating an object from one of the + * request arrays (e.g. $_POST). This method goes through the column + * names, checking to see whether a matching key exists in populated + * array. If so the setByName() method is called for that column. + * + * You can specify the key type of the array by additionally passing one + * of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME, + * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. + * The default key type is the column's phpname (e.g. 'AuthorId') + * + * @param array $arr An array to populate the object from. + * @param string $keyType The type of keys the array uses. + * @return void + */ + public function fromArray($arr, $keyType = BasePeer::TYPE_PHPNAME) + { + $keys = CcStampContentsPeer::getFieldNames($keyType); + + if (array_key_exists($keys[0], $arr)) $this->setDbId($arr[$keys[0]]); + if (array_key_exists($keys[1], $arr)) $this->setDbStampId($arr[$keys[1]]); + if (array_key_exists($keys[2], $arr)) $this->setDbFileId($arr[$keys[2]]); + if (array_key_exists($keys[3], $arr)) $this->setDbStreamId($arr[$keys[3]]); + if (array_key_exists($keys[4], $arr)) $this->setDbBlockId($arr[$keys[4]]); + if (array_key_exists($keys[5], $arr)) $this->setDbPlaylistId($arr[$keys[5]]); + if (array_key_exists($keys[6], $arr)) $this->setDbPosition($arr[$keys[6]]); + if (array_key_exists($keys[7], $arr)) $this->setDbClipLength($arr[$keys[7]]); + if (array_key_exists($keys[8], $arr)) $this->setDbCueIn($arr[$keys[8]]); + if (array_key_exists($keys[9], $arr)) $this->setDbCueOut($arr[$keys[9]]); + if (array_key_exists($keys[10], $arr)) $this->setDbFadeIn($arr[$keys[10]]); + if (array_key_exists($keys[11], $arr)) $this->setDbFadeOut($arr[$keys[11]]); + } + + /** + * Build a Criteria object containing the values of all modified columns in this object. + * + * @return Criteria The Criteria object containing all modified values. + */ + public function buildCriteria() + { + $criteria = new Criteria(CcStampContentsPeer::DATABASE_NAME); + + if ($this->isColumnModified(CcStampContentsPeer::ID)) $criteria->add(CcStampContentsPeer::ID, $this->id); + if ($this->isColumnModified(CcStampContentsPeer::STAMP_ID)) $criteria->add(CcStampContentsPeer::STAMP_ID, $this->stamp_id); + if ($this->isColumnModified(CcStampContentsPeer::FILE_ID)) $criteria->add(CcStampContentsPeer::FILE_ID, $this->file_id); + if ($this->isColumnModified(CcStampContentsPeer::STREAM_ID)) $criteria->add(CcStampContentsPeer::STREAM_ID, $this->stream_id); + if ($this->isColumnModified(CcStampContentsPeer::BLOCK_ID)) $criteria->add(CcStampContentsPeer::BLOCK_ID, $this->block_id); + if ($this->isColumnModified(CcStampContentsPeer::PLAYLIST_ID)) $criteria->add(CcStampContentsPeer::PLAYLIST_ID, $this->playlist_id); + if ($this->isColumnModified(CcStampContentsPeer::POSITION)) $criteria->add(CcStampContentsPeer::POSITION, $this->position); + if ($this->isColumnModified(CcStampContentsPeer::CLIP_LENGTH)) $criteria->add(CcStampContentsPeer::CLIP_LENGTH, $this->clip_length); + if ($this->isColumnModified(CcStampContentsPeer::CUE_IN)) $criteria->add(CcStampContentsPeer::CUE_IN, $this->cue_in); + if ($this->isColumnModified(CcStampContentsPeer::CUE_OUT)) $criteria->add(CcStampContentsPeer::CUE_OUT, $this->cue_out); + if ($this->isColumnModified(CcStampContentsPeer::FADE_IN)) $criteria->add(CcStampContentsPeer::FADE_IN, $this->fade_in); + if ($this->isColumnModified(CcStampContentsPeer::FADE_OUT)) $criteria->add(CcStampContentsPeer::FADE_OUT, $this->fade_out); + + return $criteria; + } + + /** + * Builds a Criteria object containing the primary key for this object. + * + * Unlike buildCriteria() this method includes the primary key values regardless + * of whether or not they have been modified. + * + * @return Criteria The Criteria object containing value(s) for primary key(s). + */ + public function buildPkeyCriteria() + { + $criteria = new Criteria(CcStampContentsPeer::DATABASE_NAME); + $criteria->add(CcStampContentsPeer::ID, $this->id); + + return $criteria; + } + + /** + * Returns the primary key for this object (row). + * @return int + */ + public function getPrimaryKey() + { + return $this->getDbId(); + } + + /** + * Generic method to set the primary key (id column). + * + * @param int $key Primary key. + * @return void + */ + public function setPrimaryKey($key) + { + $this->setDbId($key); + } + + /** + * Returns true if the primary key for this object is null. + * @return boolean + */ + public function isPrimaryKeyNull() + { + return null === $this->getDbId(); + } + + /** + * Sets contents of passed object to values from current object. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param object $copyObj An object of CcStampContents (or compatible) type. + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @throws PropelException + */ + public function copyInto($copyObj, $deepCopy = false) + { + $copyObj->setDbStampId($this->stamp_id); + $copyObj->setDbFileId($this->file_id); + $copyObj->setDbStreamId($this->stream_id); + $copyObj->setDbBlockId($this->block_id); + $copyObj->setDbPlaylistId($this->playlist_id); + $copyObj->setDbPosition($this->position); + $copyObj->setDbClipLength($this->clip_length); + $copyObj->setDbCueIn($this->cue_in); + $copyObj->setDbCueOut($this->cue_out); + $copyObj->setDbFadeIn($this->fade_in); + $copyObj->setDbFadeOut($this->fade_out); + + $copyObj->setNew(true); + $copyObj->setDbId(NULL); // this is a auto-increment column, so set to default value + } + + /** + * Makes a copy of this object that will be inserted as a new row in table when saved. + * It creates a new object filling in the simple attributes, but skipping any primary + * keys that are defined for the table. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @return CcStampContents Clone of current object. + * @throws PropelException + */ + public function copy($deepCopy = false) + { + // we use get_class(), because this might be a subclass + $clazz = get_class($this); + $copyObj = new $clazz(); + $this->copyInto($copyObj, $deepCopy); + return $copyObj; + } + + /** + * Returns a peer instance associated with this om. + * + * Since Peer classes are not to have any instance attributes, this method returns the + * same instance for all member of this class. The method could therefore + * be static, but this would prevent one from overriding the behavior. + * + * @return CcStampContentsPeer + */ + public function getPeer() + { + if (self::$peer === null) { + self::$peer = new CcStampContentsPeer(); + } + return self::$peer; + } + + /** + * Declares an association between this object and a CcStamp object. + * + * @param CcStamp $v + * @return CcStampContents The current object (for fluent API support) + * @throws PropelException + */ + public function setCcStamp(CcStamp $v = null) + { + if ($v === null) { + $this->setDbStampId(NULL); + } else { + $this->setDbStampId($v->getDbId()); + } + + $this->aCcStamp = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the CcStamp object, it will not be re-added. + if ($v !== null) { + $v->addCcStampContents($this); + } + + return $this; + } + + + /** + * Get the associated CcStamp object + * + * @param PropelPDO Optional Connection object. + * @return CcStamp The associated CcStamp object. + * @throws PropelException + */ + public function getCcStamp(PropelPDO $con = null) + { + if ($this->aCcStamp === null && ($this->stamp_id !== null)) { + $this->aCcStamp = CcStampQuery::create()->findPk($this->stamp_id, $con); + /* The following can be used additionally to + guarantee the related object contains a reference + to this object. This level of coupling may, however, be + undesirable since it could result in an only partially populated collection + in the referenced object. + $this->aCcStamp->addCcStampContentss($this); + */ + } + return $this->aCcStamp; + } + + /** + * Declares an association between this object and a CcFiles object. + * + * @param CcFiles $v + * @return CcStampContents The current object (for fluent API support) + * @throws PropelException + */ + public function setCcFiles(CcFiles $v = null) + { + if ($v === null) { + $this->setDbFileId(NULL); + } else { + $this->setDbFileId($v->getDbId()); + } + + $this->aCcFiles = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the CcFiles object, it will not be re-added. + if ($v !== null) { + $v->addCcStampContents($this); + } + + return $this; + } + + + /** + * Get the associated CcFiles object + * + * @param PropelPDO Optional Connection object. + * @return CcFiles The associated CcFiles object. + * @throws PropelException + */ + public function getCcFiles(PropelPDO $con = null) + { + if ($this->aCcFiles === null && ($this->file_id !== null)) { + $this->aCcFiles = CcFilesQuery::create()->findPk($this->file_id, $con); + /* The following can be used additionally to + guarantee the related object contains a reference + to this object. This level of coupling may, however, be + undesirable since it could result in an only partially populated collection + in the referenced object. + $this->aCcFiles->addCcStampContentss($this); + */ + } + return $this->aCcFiles; + } + + /** + * Declares an association between this object and a CcWebstream object. + * + * @param CcWebstream $v + * @return CcStampContents The current object (for fluent API support) + * @throws PropelException + */ + public function setCcWebstream(CcWebstream $v = null) + { + if ($v === null) { + $this->setDbStreamId(NULL); + } else { + $this->setDbStreamId($v->getDbId()); + } + + $this->aCcWebstream = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the CcWebstream object, it will not be re-added. + if ($v !== null) { + $v->addCcStampContents($this); + } + + return $this; + } + + + /** + * Get the associated CcWebstream object + * + * @param PropelPDO Optional Connection object. + * @return CcWebstream The associated CcWebstream object. + * @throws PropelException + */ + public function getCcWebstream(PropelPDO $con = null) + { + if ($this->aCcWebstream === null && ($this->stream_id !== null)) { + $this->aCcWebstream = CcWebstreamQuery::create()->findPk($this->stream_id, $con); + /* The following can be used additionally to + guarantee the related object contains a reference + to this object. This level of coupling may, however, be + undesirable since it could result in an only partially populated collection + in the referenced object. + $this->aCcWebstream->addCcStampContentss($this); + */ + } + return $this->aCcWebstream; + } + + /** + * Declares an association between this object and a CcBlock object. + * + * @param CcBlock $v + * @return CcStampContents The current object (for fluent API support) + * @throws PropelException + */ + public function setCcBlock(CcBlock $v = null) + { + if ($v === null) { + $this->setDbBlockId(NULL); + } else { + $this->setDbBlockId($v->getDbId()); + } + + $this->aCcBlock = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the CcBlock object, it will not be re-added. + if ($v !== null) { + $v->addCcStampContents($this); + } + + return $this; + } + + + /** + * Get the associated CcBlock object + * + * @param PropelPDO Optional Connection object. + * @return CcBlock The associated CcBlock object. + * @throws PropelException + */ + public function getCcBlock(PropelPDO $con = null) + { + if ($this->aCcBlock === null && ($this->block_id !== null)) { + $this->aCcBlock = CcBlockQuery::create()->findPk($this->block_id, $con); + /* The following can be used additionally to + guarantee the related object contains a reference + to this object. This level of coupling may, however, be + undesirable since it could result in an only partially populated collection + in the referenced object. + $this->aCcBlock->addCcStampContentss($this); + */ + } + return $this->aCcBlock; + } + + /** + * Declares an association between this object and a CcPlaylist object. + * + * @param CcPlaylist $v + * @return CcStampContents The current object (for fluent API support) + * @throws PropelException + */ + public function setCcPlaylist(CcPlaylist $v = null) + { + if ($v === null) { + $this->setDbPlaylistId(NULL); + } else { + $this->setDbPlaylistId($v->getDbId()); + } + + $this->aCcPlaylist = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the CcPlaylist object, it will not be re-added. + if ($v !== null) { + $v->addCcStampContents($this); + } + + return $this; + } + + + /** + * Get the associated CcPlaylist object + * + * @param PropelPDO Optional Connection object. + * @return CcPlaylist The associated CcPlaylist object. + * @throws PropelException + */ + public function getCcPlaylist(PropelPDO $con = null) + { + if ($this->aCcPlaylist === null && ($this->playlist_id !== null)) { + $this->aCcPlaylist = CcPlaylistQuery::create()->findPk($this->playlist_id, $con); + /* The following can be used additionally to + guarantee the related object contains a reference + to this object. This level of coupling may, however, be + undesirable since it could result in an only partially populated collection + in the referenced object. + $this->aCcPlaylist->addCcStampContentss($this); + */ + } + return $this->aCcPlaylist; + } + + /** + * Clears the current object and sets all attributes to their default values + */ + public function clear() + { + $this->id = null; + $this->stamp_id = null; + $this->file_id = null; + $this->stream_id = null; + $this->block_id = null; + $this->playlist_id = null; + $this->position = null; + $this->clip_length = null; + $this->cue_in = null; + $this->cue_out = null; + $this->fade_in = null; + $this->fade_out = null; + $this->alreadyInSave = false; + $this->alreadyInValidation = false; + $this->clearAllReferences(); + $this->applyDefaultValues(); + $this->resetModified(); + $this->setNew(true); + $this->setDeleted(false); + } + + /** + * Resets all collections of referencing foreign keys. + * + * This method is a user-space workaround for PHP's inability to garbage collect objects + * with circular references. This is currently necessary when using Propel in certain + * daemon or large-volumne/high-memory operations. + * + * @param boolean $deep Whether to also clear the references on all associated objects. + */ + public function clearAllReferences($deep = false) + { + if ($deep) { + } // if ($deep) + + $this->aCcStamp = null; + $this->aCcFiles = null; + $this->aCcWebstream = null; + $this->aCcBlock = null; + $this->aCcPlaylist = null; + } + + /** + * Catches calls to virtual methods + */ + public function __call($name, $params) + { + if (preg_match('/get(\w+)/', $name, $matches)) { + $virtualColumn = $matches[1]; + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + // no lcfirst in php<5.3... + $virtualColumn[0] = strtolower($virtualColumn[0]); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + } + throw new PropelException('Call to undefined method: ' . $name); + } + +} // BaseCcStampContents diff --git a/airtime_mvc/application/models/airtime/om/BaseCcStampContentsPeer.php b/airtime_mvc/application/models/airtime/om/BaseCcStampContentsPeer.php new file mode 100644 index 000000000..490941207 --- /dev/null +++ b/airtime_mvc/application/models/airtime/om/BaseCcStampContentsPeer.php @@ -0,0 +1,2592 @@ + array ('DbId', 'DbStampId', 'DbFileId', 'DbStreamId', 'DbBlockId', 'DbPlaylistId', 'DbPosition', 'DbClipLength', 'DbCueIn', 'DbCueOut', 'DbFadeIn', 'DbFadeOut', ), + BasePeer::TYPE_STUDLYPHPNAME => array ('dbId', 'dbStampId', 'dbFileId', 'dbStreamId', 'dbBlockId', 'dbPlaylistId', 'dbPosition', 'dbClipLength', 'dbCueIn', 'dbCueOut', 'dbFadeIn', 'dbFadeOut', ), + BasePeer::TYPE_COLNAME => array (self::ID, self::STAMP_ID, self::FILE_ID, self::STREAM_ID, self::BLOCK_ID, self::PLAYLIST_ID, self::POSITION, self::CLIP_LENGTH, self::CUE_IN, self::CUE_OUT, self::FADE_IN, self::FADE_OUT, ), + BasePeer::TYPE_RAW_COLNAME => array ('ID', 'STAMP_ID', 'FILE_ID', 'STREAM_ID', 'BLOCK_ID', 'PLAYLIST_ID', 'POSITION', 'CLIP_LENGTH', 'CUE_IN', 'CUE_OUT', 'FADE_IN', 'FADE_OUT', ), + BasePeer::TYPE_FIELDNAME => array ('id', 'stamp_id', 'file_id', 'stream_id', 'block_id', 'playlist_id', 'position', 'clip_length', 'cue_in', 'cue_out', 'fade_in', 'fade_out', ), + BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ) + ); + + /** + * holds an array of keys for quick access to the fieldnames array + * + * first dimension keys are the type constants + * e.g. self::$fieldNames[BasePeer::TYPE_PHPNAME]['Id'] = 0 + */ + private static $fieldKeys = array ( + BasePeer::TYPE_PHPNAME => array ('DbId' => 0, 'DbStampId' => 1, 'DbFileId' => 2, 'DbStreamId' => 3, 'DbBlockId' => 4, 'DbPlaylistId' => 5, 'DbPosition' => 6, 'DbClipLength' => 7, 'DbCueIn' => 8, 'DbCueOut' => 9, 'DbFadeIn' => 10, 'DbFadeOut' => 11, ), + BasePeer::TYPE_STUDLYPHPNAME => array ('dbId' => 0, 'dbStampId' => 1, 'dbFileId' => 2, 'dbStreamId' => 3, 'dbBlockId' => 4, 'dbPlaylistId' => 5, 'dbPosition' => 6, 'dbClipLength' => 7, 'dbCueIn' => 8, 'dbCueOut' => 9, 'dbFadeIn' => 10, 'dbFadeOut' => 11, ), + BasePeer::TYPE_COLNAME => array (self::ID => 0, self::STAMP_ID => 1, self::FILE_ID => 2, self::STREAM_ID => 3, self::BLOCK_ID => 4, self::PLAYLIST_ID => 5, self::POSITION => 6, self::CLIP_LENGTH => 7, self::CUE_IN => 8, self::CUE_OUT => 9, self::FADE_IN => 10, self::FADE_OUT => 11, ), + BasePeer::TYPE_RAW_COLNAME => array ('ID' => 0, 'STAMP_ID' => 1, 'FILE_ID' => 2, 'STREAM_ID' => 3, 'BLOCK_ID' => 4, 'PLAYLIST_ID' => 5, 'POSITION' => 6, 'CLIP_LENGTH' => 7, 'CUE_IN' => 8, 'CUE_OUT' => 9, 'FADE_IN' => 10, 'FADE_OUT' => 11, ), + BasePeer::TYPE_FIELDNAME => array ('id' => 0, 'stamp_id' => 1, 'file_id' => 2, 'stream_id' => 3, 'block_id' => 4, 'playlist_id' => 5, 'position' => 6, 'clip_length' => 7, 'cue_in' => 8, 'cue_out' => 9, 'fade_in' => 10, 'fade_out' => 11, ), + BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ) + ); + + /** + * Translates a fieldname to another type + * + * @param string $name field name + * @param string $fromType One of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME + * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM + * @param string $toType One of the class type constants + * @return string translated name of the field. + * @throws PropelException - if the specified name could not be found in the fieldname mappings. + */ + static public function translateFieldName($name, $fromType, $toType) + { + $toNames = self::getFieldNames($toType); + $key = isset(self::$fieldKeys[$fromType][$name]) ? self::$fieldKeys[$fromType][$name] : null; + if ($key === null) { + throw new PropelException("'$name' could not be found in the field names of type '$fromType'. These are: " . print_r(self::$fieldKeys[$fromType], true)); + } + return $toNames[$key]; + } + + /** + * Returns an array of field names. + * + * @param string $type The type of fieldnames to return: + * One of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME + * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM + * @return array A list of field names + */ + + static public function getFieldNames($type = BasePeer::TYPE_PHPNAME) + { + if (!array_key_exists($type, self::$fieldNames)) { + throw new PropelException('Method getFieldNames() expects the parameter $type to be one of the class constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME, BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. ' . $type . ' was given.'); + } + return self::$fieldNames[$type]; + } + + /** + * Convenience method which changes table.column to alias.column. + * + * Using this method you can maintain SQL abstraction while using column aliases. + * + * $c->addAlias("alias1", TablePeer::TABLE_NAME); + * $c->addJoin(TablePeer::alias("alias1", TablePeer::PRIMARY_KEY_COLUMN), TablePeer::PRIMARY_KEY_COLUMN); + * + * @param string $alias The alias for the current table. + * @param string $column The column name for current table. (i.e. CcStampContentsPeer::COLUMN_NAME). + * @return string + */ + public static function alias($alias, $column) + { + return str_replace(CcStampContentsPeer::TABLE_NAME.'.', $alias.'.', $column); + } + + /** + * Add all the columns needed to create a new object. + * + * Note: any columns that were marked with lazyLoad="true" in the + * XML schema will not be added to the select list and only loaded + * on demand. + * + * @param Criteria $criteria object containing the columns to add. + * @param string $alias optional table alias + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function addSelectColumns(Criteria $criteria, $alias = null) + { + if (null === $alias) { + $criteria->addSelectColumn(CcStampContentsPeer::ID); + $criteria->addSelectColumn(CcStampContentsPeer::STAMP_ID); + $criteria->addSelectColumn(CcStampContentsPeer::FILE_ID); + $criteria->addSelectColumn(CcStampContentsPeer::STREAM_ID); + $criteria->addSelectColumn(CcStampContentsPeer::BLOCK_ID); + $criteria->addSelectColumn(CcStampContentsPeer::PLAYLIST_ID); + $criteria->addSelectColumn(CcStampContentsPeer::POSITION); + $criteria->addSelectColumn(CcStampContentsPeer::CLIP_LENGTH); + $criteria->addSelectColumn(CcStampContentsPeer::CUE_IN); + $criteria->addSelectColumn(CcStampContentsPeer::CUE_OUT); + $criteria->addSelectColumn(CcStampContentsPeer::FADE_IN); + $criteria->addSelectColumn(CcStampContentsPeer::FADE_OUT); + } else { + $criteria->addSelectColumn($alias . '.ID'); + $criteria->addSelectColumn($alias . '.STAMP_ID'); + $criteria->addSelectColumn($alias . '.FILE_ID'); + $criteria->addSelectColumn($alias . '.STREAM_ID'); + $criteria->addSelectColumn($alias . '.BLOCK_ID'); + $criteria->addSelectColumn($alias . '.PLAYLIST_ID'); + $criteria->addSelectColumn($alias . '.POSITION'); + $criteria->addSelectColumn($alias . '.CLIP_LENGTH'); + $criteria->addSelectColumn($alias . '.CUE_IN'); + $criteria->addSelectColumn($alias . '.CUE_OUT'); + $criteria->addSelectColumn($alias . '.FADE_IN'); + $criteria->addSelectColumn($alias . '.FADE_OUT'); + } + } + + /** + * Returns the number of rows matching criteria. + * + * @param Criteria $criteria + * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. + * @param PropelPDO $con + * @return int Number of matching rows. + */ + public static function doCount(Criteria $criteria, $distinct = false, PropelPDO $con = null) + { + // we may modify criteria, so copy it first + $criteria = clone $criteria; + + // We need to set the primary table name, since in the case that there are no WHERE columns + // it will be impossible for the BasePeer::createSelectSql() method to determine which + // tables go into the FROM clause. + $criteria->setPrimaryTableName(CcStampContentsPeer::TABLE_NAME); + + if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->setDistinct(); + } + + if (!$criteria->hasSelectClause()) { + CcStampContentsPeer::addSelectColumns($criteria); + } + + $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count + $criteria->setDbName(self::DATABASE_NAME); // Set the correct dbName + + if ($con === null) { + $con = Propel::getConnection(CcStampContentsPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + // BasePeer returns a PDOStatement + $stmt = BasePeer::doCount($criteria, $con); + + if ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $count = (int) $row[0]; + } else { + $count = 0; // no rows returned; we infer that means 0 matches. + } + $stmt->closeCursor(); + return $count; + } + /** + * Method to select one object from the DB. + * + * @param Criteria $criteria object used to create the SELECT statement. + * @param PropelPDO $con + * @return CcStampContents + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelectOne(Criteria $criteria, PropelPDO $con = null) + { + $critcopy = clone $criteria; + $critcopy->setLimit(1); + $objects = CcStampContentsPeer::doSelect($critcopy, $con); + if ($objects) { + return $objects[0]; + } + return null; + } + /** + * Method to do selects. + * + * @param Criteria $criteria The Criteria object used to build the SELECT statement. + * @param PropelPDO $con + * @return array Array of selected Objects + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelect(Criteria $criteria, PropelPDO $con = null) + { + return CcStampContentsPeer::populateObjects(CcStampContentsPeer::doSelectStmt($criteria, $con)); + } + /** + * Prepares the Criteria object and uses the parent doSelect() method to execute a PDOStatement. + * + * Use this method directly if you want to work with an executed statement durirectly (for example + * to perform your own object hydration). + * + * @param Criteria $criteria The Criteria object used to build the SELECT statement. + * @param PropelPDO $con The connection to use + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + * @return PDOStatement The executed PDOStatement object. + * @see BasePeer::doSelect() + */ + public static function doSelectStmt(Criteria $criteria, PropelPDO $con = null) + { + if ($con === null) { + $con = Propel::getConnection(CcStampContentsPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + if (!$criteria->hasSelectClause()) { + $criteria = clone $criteria; + CcStampContentsPeer::addSelectColumns($criteria); + } + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + // BasePeer returns a PDOStatement + return BasePeer::doSelect($criteria, $con); + } + /** + * Adds an object to the instance pool. + * + * Propel keeps cached copies of objects in an instance pool when they are retrieved + * from the database. In some cases -- especially when you override doSelect*() + * methods in your stub classes -- you may need to explicitly add objects + * to the cache in order to ensure that the same objects are always returned by doSelect*() + * and retrieveByPK*() calls. + * + * @param CcStampContents $value A CcStampContents object. + * @param string $key (optional) key to use for instance map (for performance boost if key was already calculated externally). + */ + public static function addInstanceToPool(CcStampContents $obj, $key = null) + { + if (Propel::isInstancePoolingEnabled()) { + if ($key === null) { + $key = (string) $obj->getDbId(); + } // if key === null + self::$instances[$key] = $obj; + } + } + + /** + * Removes an object from the instance pool. + * + * Propel keeps cached copies of objects in an instance pool when they are retrieved + * from the database. In some cases -- especially when you override doDelete + * methods in your stub classes -- you may need to explicitly remove objects + * from the cache in order to prevent returning objects that no longer exist. + * + * @param mixed $value A CcStampContents object or a primary key value. + */ + public static function removeInstanceFromPool($value) + { + if (Propel::isInstancePoolingEnabled() && $value !== null) { + if (is_object($value) && $value instanceof CcStampContents) { + $key = (string) $value->getDbId(); + } elseif (is_scalar($value)) { + // assume we've been passed a primary key + $key = (string) $value; + } else { + $e = new PropelException("Invalid value passed to removeInstanceFromPool(). Expected primary key or CcStampContents object; got " . (is_object($value) ? get_class($value) . ' object.' : var_export($value,true))); + throw $e; + } + + unset(self::$instances[$key]); + } + } // removeInstanceFromPool() + + /** + * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table. + * + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, a serialize()d version of the primary key will be returned. + * + * @param string $key The key (@see getPrimaryKeyHash()) for this instance. + * @return CcStampContents Found object or NULL if 1) no instance exists for specified key or 2) instance pooling has been disabled. + * @see getPrimaryKeyHash() + */ + public static function getInstanceFromPool($key) + { + if (Propel::isInstancePoolingEnabled()) { + if (isset(self::$instances[$key])) { + return self::$instances[$key]; + } + } + return null; // just to be explicit + } + + /** + * Clear the instance pool. + * + * @return void + */ + public static function clearInstancePool() + { + self::$instances = array(); + } + + /** + * Method to invalidate the instance pool of all tables related to cc_stamp_contents + * by a foreign key with ON DELETE CASCADE + */ + public static function clearRelatedInstancePool() + { + } + + /** + * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table. + * + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, a serialize()d version of the primary key will be returned. + * + * @param array $row PropelPDO resultset row. + * @param int $startcol The 0-based offset for reading from the resultset row. + * @return string A string version of PK or NULL if the components of primary key in result array are all null. + */ + public static function getPrimaryKeyHashFromRow($row, $startcol = 0) + { + // If the PK cannot be derived from the row, return NULL. + if ($row[$startcol] === null) { + return null; + } + return (string) $row[$startcol]; + } + + /** + * Retrieves the primary key from the DB resultset row + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, an array of the primary key columns will be returned. + * + * @param array $row PropelPDO resultset row. + * @param int $startcol The 0-based offset for reading from the resultset row. + * @return mixed The primary key of the row + */ + public static function getPrimaryKeyFromRow($row, $startcol = 0) + { + return (int) $row[$startcol]; + } + + /** + * The returned array will contain objects of the default type or + * objects that inherit from the default. + * + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function populateObjects(PDOStatement $stmt) + { + $results = array(); + + // set the class once to avoid overhead in the loop + $cls = CcStampContentsPeer::getOMClass(false); + // populate the object(s) + while ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $key = CcStampContentsPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj = CcStampContentsPeer::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, 0, true); // rehydrate + $results[] = $obj; + } else { + $obj = new $cls(); + $obj->hydrate($row); + $results[] = $obj; + CcStampContentsPeer::addInstanceToPool($obj, $key); + } // if key exists + } + $stmt->closeCursor(); + return $results; + } + /** + * Populates an object of the default type or an object that inherit from the default. + * + * @param array $row PropelPDO resultset row. + * @param int $startcol The 0-based offset for reading from the resultset row. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + * @return array (CcStampContents object, last column rank) + */ + public static function populateObject($row, $startcol = 0) + { + $key = CcStampContentsPeer::getPrimaryKeyHashFromRow($row, $startcol); + if (null !== ($obj = CcStampContentsPeer::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, $startcol, true); // rehydrate + $col = $startcol + CcStampContentsPeer::NUM_COLUMNS; + } else { + $cls = CcStampContentsPeer::OM_CLASS; + $obj = new $cls(); + $col = $obj->hydrate($row, $startcol); + CcStampContentsPeer::addInstanceToPool($obj, $key); + } + return array($obj, $col); + } + + /** + * Returns the number of rows matching criteria, joining the related CcStamp table + * + * @param Criteria $criteria + * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return int Number of matching rows. + */ + public static function doCountJoinCcStamp(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + // we're going to modify criteria, so copy it first + $criteria = clone $criteria; + + // We need to set the primary table name, since in the case that there are no WHERE columns + // it will be impossible for the BasePeer::createSelectSql() method to determine which + // tables go into the FROM clause. + $criteria->setPrimaryTableName(CcStampContentsPeer::TABLE_NAME); + + if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->setDistinct(); + } + + if (!$criteria->hasSelectClause()) { + CcStampContentsPeer::addSelectColumns($criteria); + } + + $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + if ($con === null) { + $con = Propel::getConnection(CcStampContentsPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $criteria->addJoin(CcStampContentsPeer::STAMP_ID, CcStampPeer::ID, $join_behavior); + + $stmt = BasePeer::doCount($criteria, $con); + + if ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $count = (int) $row[0]; + } else { + $count = 0; // no rows returned; we infer that means 0 matches. + } + $stmt->closeCursor(); + return $count; + } + + + /** + * Returns the number of rows matching criteria, joining the related CcFiles table + * + * @param Criteria $criteria + * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return int Number of matching rows. + */ + public static function doCountJoinCcFiles(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + // we're going to modify criteria, so copy it first + $criteria = clone $criteria; + + // We need to set the primary table name, since in the case that there are no WHERE columns + // it will be impossible for the BasePeer::createSelectSql() method to determine which + // tables go into the FROM clause. + $criteria->setPrimaryTableName(CcStampContentsPeer::TABLE_NAME); + + if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->setDistinct(); + } + + if (!$criteria->hasSelectClause()) { + CcStampContentsPeer::addSelectColumns($criteria); + } + + $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + if ($con === null) { + $con = Propel::getConnection(CcStampContentsPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $criteria->addJoin(CcStampContentsPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + + $stmt = BasePeer::doCount($criteria, $con); + + if ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $count = (int) $row[0]; + } else { + $count = 0; // no rows returned; we infer that means 0 matches. + } + $stmt->closeCursor(); + return $count; + } + + + /** + * Returns the number of rows matching criteria, joining the related CcWebstream table + * + * @param Criteria $criteria + * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return int Number of matching rows. + */ + public static function doCountJoinCcWebstream(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + // we're going to modify criteria, so copy it first + $criteria = clone $criteria; + + // We need to set the primary table name, since in the case that there are no WHERE columns + // it will be impossible for the BasePeer::createSelectSql() method to determine which + // tables go into the FROM clause. + $criteria->setPrimaryTableName(CcStampContentsPeer::TABLE_NAME); + + if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->setDistinct(); + } + + if (!$criteria->hasSelectClause()) { + CcStampContentsPeer::addSelectColumns($criteria); + } + + $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + if ($con === null) { + $con = Propel::getConnection(CcStampContentsPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $criteria->addJoin(CcStampContentsPeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); + + $stmt = BasePeer::doCount($criteria, $con); + + if ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $count = (int) $row[0]; + } else { + $count = 0; // no rows returned; we infer that means 0 matches. + } + $stmt->closeCursor(); + return $count; + } + + + /** + * Returns the number of rows matching criteria, joining the related CcBlock table + * + * @param Criteria $criteria + * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return int Number of matching rows. + */ + public static function doCountJoinCcBlock(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + // we're going to modify criteria, so copy it first + $criteria = clone $criteria; + + // We need to set the primary table name, since in the case that there are no WHERE columns + // it will be impossible for the BasePeer::createSelectSql() method to determine which + // tables go into the FROM clause. + $criteria->setPrimaryTableName(CcStampContentsPeer::TABLE_NAME); + + if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->setDistinct(); + } + + if (!$criteria->hasSelectClause()) { + CcStampContentsPeer::addSelectColumns($criteria); + } + + $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + if ($con === null) { + $con = Propel::getConnection(CcStampContentsPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $criteria->addJoin(CcStampContentsPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); + + $stmt = BasePeer::doCount($criteria, $con); + + if ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $count = (int) $row[0]; + } else { + $count = 0; // no rows returned; we infer that means 0 matches. + } + $stmt->closeCursor(); + return $count; + } + + + /** + * Returns the number of rows matching criteria, joining the related CcPlaylist table + * + * @param Criteria $criteria + * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return int Number of matching rows. + */ + public static function doCountJoinCcPlaylist(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + // we're going to modify criteria, so copy it first + $criteria = clone $criteria; + + // We need to set the primary table name, since in the case that there are no WHERE columns + // it will be impossible for the BasePeer::createSelectSql() method to determine which + // tables go into the FROM clause. + $criteria->setPrimaryTableName(CcStampContentsPeer::TABLE_NAME); + + if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->setDistinct(); + } + + if (!$criteria->hasSelectClause()) { + CcStampContentsPeer::addSelectColumns($criteria); + } + + $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + if ($con === null) { + $con = Propel::getConnection(CcStampContentsPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $criteria->addJoin(CcStampContentsPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); + + $stmt = BasePeer::doCount($criteria, $con); + + if ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $count = (int) $row[0]; + } else { + $count = 0; // no rows returned; we infer that means 0 matches. + } + $stmt->closeCursor(); + return $count; + } + + + /** + * Selects a collection of CcStampContents objects pre-filled with their CcStamp objects. + * @param Criteria $criteria + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return array Array of CcStampContents objects. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelectJoinCcStamp(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $criteria = clone $criteria; + + // Set the correct dbName if it has not been overridden + if ($criteria->getDbName() == Propel::getDefaultDB()) { + $criteria->setDbName(self::DATABASE_NAME); + } + + CcStampContentsPeer::addSelectColumns($criteria); + $startcol = (CcStampContentsPeer::NUM_COLUMNS - CcStampContentsPeer::NUM_LAZY_LOAD_COLUMNS); + CcStampPeer::addSelectColumns($criteria); + + $criteria->addJoin(CcStampContentsPeer::STAMP_ID, CcStampPeer::ID, $join_behavior); + + $stmt = BasePeer::doSelect($criteria, $con); + $results = array(); + + while ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $key1 = CcStampContentsPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcStampContentsPeer::getInstanceFromPool($key1))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj1->hydrate($row, 0, true); // rehydrate + } else { + + $cls = CcStampContentsPeer::getOMClass(false); + + $obj1 = new $cls(); + $obj1->hydrate($row); + CcStampContentsPeer::addInstanceToPool($obj1, $key1); + } // if $obj1 already loaded + + $key2 = CcStampPeer::getPrimaryKeyHashFromRow($row, $startcol); + if ($key2 !== null) { + $obj2 = CcStampPeer::getInstanceFromPool($key2); + if (!$obj2) { + + $cls = CcStampPeer::getOMClass(false); + + $obj2 = new $cls(); + $obj2->hydrate($row, $startcol); + CcStampPeer::addInstanceToPool($obj2, $key2); + } // if obj2 already loaded + + // Add the $obj1 (CcStampContents) to $obj2 (CcStamp) + $obj2->addCcStampContents($obj1); + + } // if joined row was not null + + $results[] = $obj1; + } + $stmt->closeCursor(); + return $results; + } + + + /** + * Selects a collection of CcStampContents objects pre-filled with their CcFiles objects. + * @param Criteria $criteria + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return array Array of CcStampContents objects. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelectJoinCcFiles(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $criteria = clone $criteria; + + // Set the correct dbName if it has not been overridden + if ($criteria->getDbName() == Propel::getDefaultDB()) { + $criteria->setDbName(self::DATABASE_NAME); + } + + CcStampContentsPeer::addSelectColumns($criteria); + $startcol = (CcStampContentsPeer::NUM_COLUMNS - CcStampContentsPeer::NUM_LAZY_LOAD_COLUMNS); + CcFilesPeer::addSelectColumns($criteria); + + $criteria->addJoin(CcStampContentsPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + + $stmt = BasePeer::doSelect($criteria, $con); + $results = array(); + + while ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $key1 = CcStampContentsPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcStampContentsPeer::getInstanceFromPool($key1))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj1->hydrate($row, 0, true); // rehydrate + } else { + + $cls = CcStampContentsPeer::getOMClass(false); + + $obj1 = new $cls(); + $obj1->hydrate($row); + CcStampContentsPeer::addInstanceToPool($obj1, $key1); + } // if $obj1 already loaded + + $key2 = CcFilesPeer::getPrimaryKeyHashFromRow($row, $startcol); + if ($key2 !== null) { + $obj2 = CcFilesPeer::getInstanceFromPool($key2); + if (!$obj2) { + + $cls = CcFilesPeer::getOMClass(false); + + $obj2 = new $cls(); + $obj2->hydrate($row, $startcol); + CcFilesPeer::addInstanceToPool($obj2, $key2); + } // if obj2 already loaded + + // Add the $obj1 (CcStampContents) to $obj2 (CcFiles) + $obj2->addCcStampContents($obj1); + + } // if joined row was not null + + $results[] = $obj1; + } + $stmt->closeCursor(); + return $results; + } + + + /** + * Selects a collection of CcStampContents objects pre-filled with their CcWebstream objects. + * @param Criteria $criteria + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return array Array of CcStampContents objects. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelectJoinCcWebstream(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $criteria = clone $criteria; + + // Set the correct dbName if it has not been overridden + if ($criteria->getDbName() == Propel::getDefaultDB()) { + $criteria->setDbName(self::DATABASE_NAME); + } + + CcStampContentsPeer::addSelectColumns($criteria); + $startcol = (CcStampContentsPeer::NUM_COLUMNS - CcStampContentsPeer::NUM_LAZY_LOAD_COLUMNS); + CcWebstreamPeer::addSelectColumns($criteria); + + $criteria->addJoin(CcStampContentsPeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); + + $stmt = BasePeer::doSelect($criteria, $con); + $results = array(); + + while ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $key1 = CcStampContentsPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcStampContentsPeer::getInstanceFromPool($key1))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj1->hydrate($row, 0, true); // rehydrate + } else { + + $cls = CcStampContentsPeer::getOMClass(false); + + $obj1 = new $cls(); + $obj1->hydrate($row); + CcStampContentsPeer::addInstanceToPool($obj1, $key1); + } // if $obj1 already loaded + + $key2 = CcWebstreamPeer::getPrimaryKeyHashFromRow($row, $startcol); + if ($key2 !== null) { + $obj2 = CcWebstreamPeer::getInstanceFromPool($key2); + if (!$obj2) { + + $cls = CcWebstreamPeer::getOMClass(false); + + $obj2 = new $cls(); + $obj2->hydrate($row, $startcol); + CcWebstreamPeer::addInstanceToPool($obj2, $key2); + } // if obj2 already loaded + + // Add the $obj1 (CcStampContents) to $obj2 (CcWebstream) + $obj2->addCcStampContents($obj1); + + } // if joined row was not null + + $results[] = $obj1; + } + $stmt->closeCursor(); + return $results; + } + + + /** + * Selects a collection of CcStampContents objects pre-filled with their CcBlock objects. + * @param Criteria $criteria + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return array Array of CcStampContents objects. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelectJoinCcBlock(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $criteria = clone $criteria; + + // Set the correct dbName if it has not been overridden + if ($criteria->getDbName() == Propel::getDefaultDB()) { + $criteria->setDbName(self::DATABASE_NAME); + } + + CcStampContentsPeer::addSelectColumns($criteria); + $startcol = (CcStampContentsPeer::NUM_COLUMNS - CcStampContentsPeer::NUM_LAZY_LOAD_COLUMNS); + CcBlockPeer::addSelectColumns($criteria); + + $criteria->addJoin(CcStampContentsPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); + + $stmt = BasePeer::doSelect($criteria, $con); + $results = array(); + + while ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $key1 = CcStampContentsPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcStampContentsPeer::getInstanceFromPool($key1))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj1->hydrate($row, 0, true); // rehydrate + } else { + + $cls = CcStampContentsPeer::getOMClass(false); + + $obj1 = new $cls(); + $obj1->hydrate($row); + CcStampContentsPeer::addInstanceToPool($obj1, $key1); + } // if $obj1 already loaded + + $key2 = CcBlockPeer::getPrimaryKeyHashFromRow($row, $startcol); + if ($key2 !== null) { + $obj2 = CcBlockPeer::getInstanceFromPool($key2); + if (!$obj2) { + + $cls = CcBlockPeer::getOMClass(false); + + $obj2 = new $cls(); + $obj2->hydrate($row, $startcol); + CcBlockPeer::addInstanceToPool($obj2, $key2); + } // if obj2 already loaded + + // Add the $obj1 (CcStampContents) to $obj2 (CcBlock) + $obj2->addCcStampContents($obj1); + + } // if joined row was not null + + $results[] = $obj1; + } + $stmt->closeCursor(); + return $results; + } + + + /** + * Selects a collection of CcStampContents objects pre-filled with their CcPlaylist objects. + * @param Criteria $criteria + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return array Array of CcStampContents objects. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelectJoinCcPlaylist(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $criteria = clone $criteria; + + // Set the correct dbName if it has not been overridden + if ($criteria->getDbName() == Propel::getDefaultDB()) { + $criteria->setDbName(self::DATABASE_NAME); + } + + CcStampContentsPeer::addSelectColumns($criteria); + $startcol = (CcStampContentsPeer::NUM_COLUMNS - CcStampContentsPeer::NUM_LAZY_LOAD_COLUMNS); + CcPlaylistPeer::addSelectColumns($criteria); + + $criteria->addJoin(CcStampContentsPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); + + $stmt = BasePeer::doSelect($criteria, $con); + $results = array(); + + while ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $key1 = CcStampContentsPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcStampContentsPeer::getInstanceFromPool($key1))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj1->hydrate($row, 0, true); // rehydrate + } else { + + $cls = CcStampContentsPeer::getOMClass(false); + + $obj1 = new $cls(); + $obj1->hydrate($row); + CcStampContentsPeer::addInstanceToPool($obj1, $key1); + } // if $obj1 already loaded + + $key2 = CcPlaylistPeer::getPrimaryKeyHashFromRow($row, $startcol); + if ($key2 !== null) { + $obj2 = CcPlaylistPeer::getInstanceFromPool($key2); + if (!$obj2) { + + $cls = CcPlaylistPeer::getOMClass(false); + + $obj2 = new $cls(); + $obj2->hydrate($row, $startcol); + CcPlaylistPeer::addInstanceToPool($obj2, $key2); + } // if obj2 already loaded + + // Add the $obj1 (CcStampContents) to $obj2 (CcPlaylist) + $obj2->addCcStampContents($obj1); + + } // if joined row was not null + + $results[] = $obj1; + } + $stmt->closeCursor(); + return $results; + } + + + /** + * Returns the number of rows matching criteria, joining all related tables + * + * @param Criteria $criteria + * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return int Number of matching rows. + */ + public static function doCountJoinAll(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + // we're going to modify criteria, so copy it first + $criteria = clone $criteria; + + // We need to set the primary table name, since in the case that there are no WHERE columns + // it will be impossible for the BasePeer::createSelectSql() method to determine which + // tables go into the FROM clause. + $criteria->setPrimaryTableName(CcStampContentsPeer::TABLE_NAME); + + if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->setDistinct(); + } + + if (!$criteria->hasSelectClause()) { + CcStampContentsPeer::addSelectColumns($criteria); + } + + $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + if ($con === null) { + $con = Propel::getConnection(CcStampContentsPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $criteria->addJoin(CcStampContentsPeer::STAMP_ID, CcStampPeer::ID, $join_behavior); + + $criteria->addJoin(CcStampContentsPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + + $criteria->addJoin(CcStampContentsPeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); + + $criteria->addJoin(CcStampContentsPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); + + $criteria->addJoin(CcStampContentsPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); + + $stmt = BasePeer::doCount($criteria, $con); + + if ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $count = (int) $row[0]; + } else { + $count = 0; // no rows returned; we infer that means 0 matches. + } + $stmt->closeCursor(); + return $count; + } + + /** + * Selects a collection of CcStampContents objects pre-filled with all related objects. + * + * @param Criteria $criteria + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return array Array of CcStampContents objects. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelectJoinAll(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $criteria = clone $criteria; + + // Set the correct dbName if it has not been overridden + if ($criteria->getDbName() == Propel::getDefaultDB()) { + $criteria->setDbName(self::DATABASE_NAME); + } + + CcStampContentsPeer::addSelectColumns($criteria); + $startcol2 = (CcStampContentsPeer::NUM_COLUMNS - CcStampContentsPeer::NUM_LAZY_LOAD_COLUMNS); + + CcStampPeer::addSelectColumns($criteria); + $startcol3 = $startcol2 + (CcStampPeer::NUM_COLUMNS - CcStampPeer::NUM_LAZY_LOAD_COLUMNS); + + CcFilesPeer::addSelectColumns($criteria); + $startcol4 = $startcol3 + (CcFilesPeer::NUM_COLUMNS - CcFilesPeer::NUM_LAZY_LOAD_COLUMNS); + + CcWebstreamPeer::addSelectColumns($criteria); + $startcol5 = $startcol4 + (CcWebstreamPeer::NUM_COLUMNS - CcWebstreamPeer::NUM_LAZY_LOAD_COLUMNS); + + CcBlockPeer::addSelectColumns($criteria); + $startcol6 = $startcol5 + (CcBlockPeer::NUM_COLUMNS - CcBlockPeer::NUM_LAZY_LOAD_COLUMNS); + + CcPlaylistPeer::addSelectColumns($criteria); + $startcol7 = $startcol6 + (CcPlaylistPeer::NUM_COLUMNS - CcPlaylistPeer::NUM_LAZY_LOAD_COLUMNS); + + $criteria->addJoin(CcStampContentsPeer::STAMP_ID, CcStampPeer::ID, $join_behavior); + + $criteria->addJoin(CcStampContentsPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + + $criteria->addJoin(CcStampContentsPeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); + + $criteria->addJoin(CcStampContentsPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); + + $criteria->addJoin(CcStampContentsPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); + + $stmt = BasePeer::doSelect($criteria, $con); + $results = array(); + + while ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $key1 = CcStampContentsPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcStampContentsPeer::getInstanceFromPool($key1))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj1->hydrate($row, 0, true); // rehydrate + } else { + $cls = CcStampContentsPeer::getOMClass(false); + + $obj1 = new $cls(); + $obj1->hydrate($row); + CcStampContentsPeer::addInstanceToPool($obj1, $key1); + } // if obj1 already loaded + + // Add objects for joined CcStamp rows + + $key2 = CcStampPeer::getPrimaryKeyHashFromRow($row, $startcol2); + if ($key2 !== null) { + $obj2 = CcStampPeer::getInstanceFromPool($key2); + if (!$obj2) { + + $cls = CcStampPeer::getOMClass(false); + + $obj2 = new $cls(); + $obj2->hydrate($row, $startcol2); + CcStampPeer::addInstanceToPool($obj2, $key2); + } // if obj2 loaded + + // Add the $obj1 (CcStampContents) to the collection in $obj2 (CcStamp) + $obj2->addCcStampContents($obj1); + } // if joined row not null + + // Add objects for joined CcFiles rows + + $key3 = CcFilesPeer::getPrimaryKeyHashFromRow($row, $startcol3); + if ($key3 !== null) { + $obj3 = CcFilesPeer::getInstanceFromPool($key3); + if (!$obj3) { + + $cls = CcFilesPeer::getOMClass(false); + + $obj3 = new $cls(); + $obj3->hydrate($row, $startcol3); + CcFilesPeer::addInstanceToPool($obj3, $key3); + } // if obj3 loaded + + // Add the $obj1 (CcStampContents) to the collection in $obj3 (CcFiles) + $obj3->addCcStampContents($obj1); + } // if joined row not null + + // Add objects for joined CcWebstream rows + + $key4 = CcWebstreamPeer::getPrimaryKeyHashFromRow($row, $startcol4); + if ($key4 !== null) { + $obj4 = CcWebstreamPeer::getInstanceFromPool($key4); + if (!$obj4) { + + $cls = CcWebstreamPeer::getOMClass(false); + + $obj4 = new $cls(); + $obj4->hydrate($row, $startcol4); + CcWebstreamPeer::addInstanceToPool($obj4, $key4); + } // if obj4 loaded + + // Add the $obj1 (CcStampContents) to the collection in $obj4 (CcWebstream) + $obj4->addCcStampContents($obj1); + } // if joined row not null + + // Add objects for joined CcBlock rows + + $key5 = CcBlockPeer::getPrimaryKeyHashFromRow($row, $startcol5); + if ($key5 !== null) { + $obj5 = CcBlockPeer::getInstanceFromPool($key5); + if (!$obj5) { + + $cls = CcBlockPeer::getOMClass(false); + + $obj5 = new $cls(); + $obj5->hydrate($row, $startcol5); + CcBlockPeer::addInstanceToPool($obj5, $key5); + } // if obj5 loaded + + // Add the $obj1 (CcStampContents) to the collection in $obj5 (CcBlock) + $obj5->addCcStampContents($obj1); + } // if joined row not null + + // Add objects for joined CcPlaylist rows + + $key6 = CcPlaylistPeer::getPrimaryKeyHashFromRow($row, $startcol6); + if ($key6 !== null) { + $obj6 = CcPlaylistPeer::getInstanceFromPool($key6); + if (!$obj6) { + + $cls = CcPlaylistPeer::getOMClass(false); + + $obj6 = new $cls(); + $obj6->hydrate($row, $startcol6); + CcPlaylistPeer::addInstanceToPool($obj6, $key6); + } // if obj6 loaded + + // Add the $obj1 (CcStampContents) to the collection in $obj6 (CcPlaylist) + $obj6->addCcStampContents($obj1); + } // if joined row not null + + $results[] = $obj1; + } + $stmt->closeCursor(); + return $results; + } + + + /** + * Returns the number of rows matching criteria, joining the related CcStamp table + * + * @param Criteria $criteria + * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return int Number of matching rows. + */ + public static function doCountJoinAllExceptCcStamp(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + // we're going to modify criteria, so copy it first + $criteria = clone $criteria; + + // We need to set the primary table name, since in the case that there are no WHERE columns + // it will be impossible for the BasePeer::createSelectSql() method to determine which + // tables go into the FROM clause. + $criteria->setPrimaryTableName(CcStampContentsPeer::TABLE_NAME); + + if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->setDistinct(); + } + + if (!$criteria->hasSelectClause()) { + CcStampContentsPeer::addSelectColumns($criteria); + } + + $criteria->clearOrderByColumns(); // ORDER BY should not affect count + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + if ($con === null) { + $con = Propel::getConnection(CcStampContentsPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $criteria->addJoin(CcStampContentsPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + + $criteria->addJoin(CcStampContentsPeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); + + $criteria->addJoin(CcStampContentsPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); + + $criteria->addJoin(CcStampContentsPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); + + $stmt = BasePeer::doCount($criteria, $con); + + if ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $count = (int) $row[0]; + } else { + $count = 0; // no rows returned; we infer that means 0 matches. + } + $stmt->closeCursor(); + return $count; + } + + + /** + * Returns the number of rows matching criteria, joining the related CcFiles table + * + * @param Criteria $criteria + * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return int Number of matching rows. + */ + public static function doCountJoinAllExceptCcFiles(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + // we're going to modify criteria, so copy it first + $criteria = clone $criteria; + + // We need to set the primary table name, since in the case that there are no WHERE columns + // it will be impossible for the BasePeer::createSelectSql() method to determine which + // tables go into the FROM clause. + $criteria->setPrimaryTableName(CcStampContentsPeer::TABLE_NAME); + + if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->setDistinct(); + } + + if (!$criteria->hasSelectClause()) { + CcStampContentsPeer::addSelectColumns($criteria); + } + + $criteria->clearOrderByColumns(); // ORDER BY should not affect count + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + if ($con === null) { + $con = Propel::getConnection(CcStampContentsPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $criteria->addJoin(CcStampContentsPeer::STAMP_ID, CcStampPeer::ID, $join_behavior); + + $criteria->addJoin(CcStampContentsPeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); + + $criteria->addJoin(CcStampContentsPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); + + $criteria->addJoin(CcStampContentsPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); + + $stmt = BasePeer::doCount($criteria, $con); + + if ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $count = (int) $row[0]; + } else { + $count = 0; // no rows returned; we infer that means 0 matches. + } + $stmt->closeCursor(); + return $count; + } + + + /** + * Returns the number of rows matching criteria, joining the related CcWebstream table + * + * @param Criteria $criteria + * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return int Number of matching rows. + */ + public static function doCountJoinAllExceptCcWebstream(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + // we're going to modify criteria, so copy it first + $criteria = clone $criteria; + + // We need to set the primary table name, since in the case that there are no WHERE columns + // it will be impossible for the BasePeer::createSelectSql() method to determine which + // tables go into the FROM clause. + $criteria->setPrimaryTableName(CcStampContentsPeer::TABLE_NAME); + + if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->setDistinct(); + } + + if (!$criteria->hasSelectClause()) { + CcStampContentsPeer::addSelectColumns($criteria); + } + + $criteria->clearOrderByColumns(); // ORDER BY should not affect count + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + if ($con === null) { + $con = Propel::getConnection(CcStampContentsPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $criteria->addJoin(CcStampContentsPeer::STAMP_ID, CcStampPeer::ID, $join_behavior); + + $criteria->addJoin(CcStampContentsPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + + $criteria->addJoin(CcStampContentsPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); + + $criteria->addJoin(CcStampContentsPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); + + $stmt = BasePeer::doCount($criteria, $con); + + if ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $count = (int) $row[0]; + } else { + $count = 0; // no rows returned; we infer that means 0 matches. + } + $stmt->closeCursor(); + return $count; + } + + + /** + * Returns the number of rows matching criteria, joining the related CcBlock table + * + * @param Criteria $criteria + * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return int Number of matching rows. + */ + public static function doCountJoinAllExceptCcBlock(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + // we're going to modify criteria, so copy it first + $criteria = clone $criteria; + + // We need to set the primary table name, since in the case that there are no WHERE columns + // it will be impossible for the BasePeer::createSelectSql() method to determine which + // tables go into the FROM clause. + $criteria->setPrimaryTableName(CcStampContentsPeer::TABLE_NAME); + + if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->setDistinct(); + } + + if (!$criteria->hasSelectClause()) { + CcStampContentsPeer::addSelectColumns($criteria); + } + + $criteria->clearOrderByColumns(); // ORDER BY should not affect count + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + if ($con === null) { + $con = Propel::getConnection(CcStampContentsPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $criteria->addJoin(CcStampContentsPeer::STAMP_ID, CcStampPeer::ID, $join_behavior); + + $criteria->addJoin(CcStampContentsPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + + $criteria->addJoin(CcStampContentsPeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); + + $criteria->addJoin(CcStampContentsPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); + + $stmt = BasePeer::doCount($criteria, $con); + + if ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $count = (int) $row[0]; + } else { + $count = 0; // no rows returned; we infer that means 0 matches. + } + $stmt->closeCursor(); + return $count; + } + + + /** + * Returns the number of rows matching criteria, joining the related CcPlaylist table + * + * @param Criteria $criteria + * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return int Number of matching rows. + */ + public static function doCountJoinAllExceptCcPlaylist(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + // we're going to modify criteria, so copy it first + $criteria = clone $criteria; + + // We need to set the primary table name, since in the case that there are no WHERE columns + // it will be impossible for the BasePeer::createSelectSql() method to determine which + // tables go into the FROM clause. + $criteria->setPrimaryTableName(CcStampContentsPeer::TABLE_NAME); + + if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->setDistinct(); + } + + if (!$criteria->hasSelectClause()) { + CcStampContentsPeer::addSelectColumns($criteria); + } + + $criteria->clearOrderByColumns(); // ORDER BY should not affect count + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + if ($con === null) { + $con = Propel::getConnection(CcStampContentsPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $criteria->addJoin(CcStampContentsPeer::STAMP_ID, CcStampPeer::ID, $join_behavior); + + $criteria->addJoin(CcStampContentsPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + + $criteria->addJoin(CcStampContentsPeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); + + $criteria->addJoin(CcStampContentsPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); + + $stmt = BasePeer::doCount($criteria, $con); + + if ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $count = (int) $row[0]; + } else { + $count = 0; // no rows returned; we infer that means 0 matches. + } + $stmt->closeCursor(); + return $count; + } + + + /** + * Selects a collection of CcStampContents objects pre-filled with all related objects except CcStamp. + * + * @param Criteria $criteria + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return array Array of CcStampContents objects. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelectJoinAllExceptCcStamp(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $criteria = clone $criteria; + + // Set the correct dbName if it has not been overridden + // $criteria->getDbName() will return the same object if not set to another value + // so == check is okay and faster + if ($criteria->getDbName() == Propel::getDefaultDB()) { + $criteria->setDbName(self::DATABASE_NAME); + } + + CcStampContentsPeer::addSelectColumns($criteria); + $startcol2 = (CcStampContentsPeer::NUM_COLUMNS - CcStampContentsPeer::NUM_LAZY_LOAD_COLUMNS); + + CcFilesPeer::addSelectColumns($criteria); + $startcol3 = $startcol2 + (CcFilesPeer::NUM_COLUMNS - CcFilesPeer::NUM_LAZY_LOAD_COLUMNS); + + CcWebstreamPeer::addSelectColumns($criteria); + $startcol4 = $startcol3 + (CcWebstreamPeer::NUM_COLUMNS - CcWebstreamPeer::NUM_LAZY_LOAD_COLUMNS); + + CcBlockPeer::addSelectColumns($criteria); + $startcol5 = $startcol4 + (CcBlockPeer::NUM_COLUMNS - CcBlockPeer::NUM_LAZY_LOAD_COLUMNS); + + CcPlaylistPeer::addSelectColumns($criteria); + $startcol6 = $startcol5 + (CcPlaylistPeer::NUM_COLUMNS - CcPlaylistPeer::NUM_LAZY_LOAD_COLUMNS); + + $criteria->addJoin(CcStampContentsPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + + $criteria->addJoin(CcStampContentsPeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); + + $criteria->addJoin(CcStampContentsPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); + + $criteria->addJoin(CcStampContentsPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); + + + $stmt = BasePeer::doSelect($criteria, $con); + $results = array(); + + while ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $key1 = CcStampContentsPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcStampContentsPeer::getInstanceFromPool($key1))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj1->hydrate($row, 0, true); // rehydrate + } else { + $cls = CcStampContentsPeer::getOMClass(false); + + $obj1 = new $cls(); + $obj1->hydrate($row); + CcStampContentsPeer::addInstanceToPool($obj1, $key1); + } // if obj1 already loaded + + // Add objects for joined CcFiles rows + + $key2 = CcFilesPeer::getPrimaryKeyHashFromRow($row, $startcol2); + if ($key2 !== null) { + $obj2 = CcFilesPeer::getInstanceFromPool($key2); + if (!$obj2) { + + $cls = CcFilesPeer::getOMClass(false); + + $obj2 = new $cls(); + $obj2->hydrate($row, $startcol2); + CcFilesPeer::addInstanceToPool($obj2, $key2); + } // if $obj2 already loaded + + // Add the $obj1 (CcStampContents) to the collection in $obj2 (CcFiles) + $obj2->addCcStampContents($obj1); + + } // if joined row is not null + + // Add objects for joined CcWebstream rows + + $key3 = CcWebstreamPeer::getPrimaryKeyHashFromRow($row, $startcol3); + if ($key3 !== null) { + $obj3 = CcWebstreamPeer::getInstanceFromPool($key3); + if (!$obj3) { + + $cls = CcWebstreamPeer::getOMClass(false); + + $obj3 = new $cls(); + $obj3->hydrate($row, $startcol3); + CcWebstreamPeer::addInstanceToPool($obj3, $key3); + } // if $obj3 already loaded + + // Add the $obj1 (CcStampContents) to the collection in $obj3 (CcWebstream) + $obj3->addCcStampContents($obj1); + + } // if joined row is not null + + // Add objects for joined CcBlock rows + + $key4 = CcBlockPeer::getPrimaryKeyHashFromRow($row, $startcol4); + if ($key4 !== null) { + $obj4 = CcBlockPeer::getInstanceFromPool($key4); + if (!$obj4) { + + $cls = CcBlockPeer::getOMClass(false); + + $obj4 = new $cls(); + $obj4->hydrate($row, $startcol4); + CcBlockPeer::addInstanceToPool($obj4, $key4); + } // if $obj4 already loaded + + // Add the $obj1 (CcStampContents) to the collection in $obj4 (CcBlock) + $obj4->addCcStampContents($obj1); + + } // if joined row is not null + + // Add objects for joined CcPlaylist rows + + $key5 = CcPlaylistPeer::getPrimaryKeyHashFromRow($row, $startcol5); + if ($key5 !== null) { + $obj5 = CcPlaylistPeer::getInstanceFromPool($key5); + if (!$obj5) { + + $cls = CcPlaylistPeer::getOMClass(false); + + $obj5 = new $cls(); + $obj5->hydrate($row, $startcol5); + CcPlaylistPeer::addInstanceToPool($obj5, $key5); + } // if $obj5 already loaded + + // Add the $obj1 (CcStampContents) to the collection in $obj5 (CcPlaylist) + $obj5->addCcStampContents($obj1); + + } // if joined row is not null + + $results[] = $obj1; + } + $stmt->closeCursor(); + return $results; + } + + + /** + * Selects a collection of CcStampContents objects pre-filled with all related objects except CcFiles. + * + * @param Criteria $criteria + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return array Array of CcStampContents objects. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelectJoinAllExceptCcFiles(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $criteria = clone $criteria; + + // Set the correct dbName if it has not been overridden + // $criteria->getDbName() will return the same object if not set to another value + // so == check is okay and faster + if ($criteria->getDbName() == Propel::getDefaultDB()) { + $criteria->setDbName(self::DATABASE_NAME); + } + + CcStampContentsPeer::addSelectColumns($criteria); + $startcol2 = (CcStampContentsPeer::NUM_COLUMNS - CcStampContentsPeer::NUM_LAZY_LOAD_COLUMNS); + + CcStampPeer::addSelectColumns($criteria); + $startcol3 = $startcol2 + (CcStampPeer::NUM_COLUMNS - CcStampPeer::NUM_LAZY_LOAD_COLUMNS); + + CcWebstreamPeer::addSelectColumns($criteria); + $startcol4 = $startcol3 + (CcWebstreamPeer::NUM_COLUMNS - CcWebstreamPeer::NUM_LAZY_LOAD_COLUMNS); + + CcBlockPeer::addSelectColumns($criteria); + $startcol5 = $startcol4 + (CcBlockPeer::NUM_COLUMNS - CcBlockPeer::NUM_LAZY_LOAD_COLUMNS); + + CcPlaylistPeer::addSelectColumns($criteria); + $startcol6 = $startcol5 + (CcPlaylistPeer::NUM_COLUMNS - CcPlaylistPeer::NUM_LAZY_LOAD_COLUMNS); + + $criteria->addJoin(CcStampContentsPeer::STAMP_ID, CcStampPeer::ID, $join_behavior); + + $criteria->addJoin(CcStampContentsPeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); + + $criteria->addJoin(CcStampContentsPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); + + $criteria->addJoin(CcStampContentsPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); + + + $stmt = BasePeer::doSelect($criteria, $con); + $results = array(); + + while ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $key1 = CcStampContentsPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcStampContentsPeer::getInstanceFromPool($key1))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj1->hydrate($row, 0, true); // rehydrate + } else { + $cls = CcStampContentsPeer::getOMClass(false); + + $obj1 = new $cls(); + $obj1->hydrate($row); + CcStampContentsPeer::addInstanceToPool($obj1, $key1); + } // if obj1 already loaded + + // Add objects for joined CcStamp rows + + $key2 = CcStampPeer::getPrimaryKeyHashFromRow($row, $startcol2); + if ($key2 !== null) { + $obj2 = CcStampPeer::getInstanceFromPool($key2); + if (!$obj2) { + + $cls = CcStampPeer::getOMClass(false); + + $obj2 = new $cls(); + $obj2->hydrate($row, $startcol2); + CcStampPeer::addInstanceToPool($obj2, $key2); + } // if $obj2 already loaded + + // Add the $obj1 (CcStampContents) to the collection in $obj2 (CcStamp) + $obj2->addCcStampContents($obj1); + + } // if joined row is not null + + // Add objects for joined CcWebstream rows + + $key3 = CcWebstreamPeer::getPrimaryKeyHashFromRow($row, $startcol3); + if ($key3 !== null) { + $obj3 = CcWebstreamPeer::getInstanceFromPool($key3); + if (!$obj3) { + + $cls = CcWebstreamPeer::getOMClass(false); + + $obj3 = new $cls(); + $obj3->hydrate($row, $startcol3); + CcWebstreamPeer::addInstanceToPool($obj3, $key3); + } // if $obj3 already loaded + + // Add the $obj1 (CcStampContents) to the collection in $obj3 (CcWebstream) + $obj3->addCcStampContents($obj1); + + } // if joined row is not null + + // Add objects for joined CcBlock rows + + $key4 = CcBlockPeer::getPrimaryKeyHashFromRow($row, $startcol4); + if ($key4 !== null) { + $obj4 = CcBlockPeer::getInstanceFromPool($key4); + if (!$obj4) { + + $cls = CcBlockPeer::getOMClass(false); + + $obj4 = new $cls(); + $obj4->hydrate($row, $startcol4); + CcBlockPeer::addInstanceToPool($obj4, $key4); + } // if $obj4 already loaded + + // Add the $obj1 (CcStampContents) to the collection in $obj4 (CcBlock) + $obj4->addCcStampContents($obj1); + + } // if joined row is not null + + // Add objects for joined CcPlaylist rows + + $key5 = CcPlaylistPeer::getPrimaryKeyHashFromRow($row, $startcol5); + if ($key5 !== null) { + $obj5 = CcPlaylistPeer::getInstanceFromPool($key5); + if (!$obj5) { + + $cls = CcPlaylistPeer::getOMClass(false); + + $obj5 = new $cls(); + $obj5->hydrate($row, $startcol5); + CcPlaylistPeer::addInstanceToPool($obj5, $key5); + } // if $obj5 already loaded + + // Add the $obj1 (CcStampContents) to the collection in $obj5 (CcPlaylist) + $obj5->addCcStampContents($obj1); + + } // if joined row is not null + + $results[] = $obj1; + } + $stmt->closeCursor(); + return $results; + } + + + /** + * Selects a collection of CcStampContents objects pre-filled with all related objects except CcWebstream. + * + * @param Criteria $criteria + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return array Array of CcStampContents objects. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelectJoinAllExceptCcWebstream(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $criteria = clone $criteria; + + // Set the correct dbName if it has not been overridden + // $criteria->getDbName() will return the same object if not set to another value + // so == check is okay and faster + if ($criteria->getDbName() == Propel::getDefaultDB()) { + $criteria->setDbName(self::DATABASE_NAME); + } + + CcStampContentsPeer::addSelectColumns($criteria); + $startcol2 = (CcStampContentsPeer::NUM_COLUMNS - CcStampContentsPeer::NUM_LAZY_LOAD_COLUMNS); + + CcStampPeer::addSelectColumns($criteria); + $startcol3 = $startcol2 + (CcStampPeer::NUM_COLUMNS - CcStampPeer::NUM_LAZY_LOAD_COLUMNS); + + CcFilesPeer::addSelectColumns($criteria); + $startcol4 = $startcol3 + (CcFilesPeer::NUM_COLUMNS - CcFilesPeer::NUM_LAZY_LOAD_COLUMNS); + + CcBlockPeer::addSelectColumns($criteria); + $startcol5 = $startcol4 + (CcBlockPeer::NUM_COLUMNS - CcBlockPeer::NUM_LAZY_LOAD_COLUMNS); + + CcPlaylistPeer::addSelectColumns($criteria); + $startcol6 = $startcol5 + (CcPlaylistPeer::NUM_COLUMNS - CcPlaylistPeer::NUM_LAZY_LOAD_COLUMNS); + + $criteria->addJoin(CcStampContentsPeer::STAMP_ID, CcStampPeer::ID, $join_behavior); + + $criteria->addJoin(CcStampContentsPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + + $criteria->addJoin(CcStampContentsPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); + + $criteria->addJoin(CcStampContentsPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); + + + $stmt = BasePeer::doSelect($criteria, $con); + $results = array(); + + while ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $key1 = CcStampContentsPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcStampContentsPeer::getInstanceFromPool($key1))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj1->hydrate($row, 0, true); // rehydrate + } else { + $cls = CcStampContentsPeer::getOMClass(false); + + $obj1 = new $cls(); + $obj1->hydrate($row); + CcStampContentsPeer::addInstanceToPool($obj1, $key1); + } // if obj1 already loaded + + // Add objects for joined CcStamp rows + + $key2 = CcStampPeer::getPrimaryKeyHashFromRow($row, $startcol2); + if ($key2 !== null) { + $obj2 = CcStampPeer::getInstanceFromPool($key2); + if (!$obj2) { + + $cls = CcStampPeer::getOMClass(false); + + $obj2 = new $cls(); + $obj2->hydrate($row, $startcol2); + CcStampPeer::addInstanceToPool($obj2, $key2); + } // if $obj2 already loaded + + // Add the $obj1 (CcStampContents) to the collection in $obj2 (CcStamp) + $obj2->addCcStampContents($obj1); + + } // if joined row is not null + + // Add objects for joined CcFiles rows + + $key3 = CcFilesPeer::getPrimaryKeyHashFromRow($row, $startcol3); + if ($key3 !== null) { + $obj3 = CcFilesPeer::getInstanceFromPool($key3); + if (!$obj3) { + + $cls = CcFilesPeer::getOMClass(false); + + $obj3 = new $cls(); + $obj3->hydrate($row, $startcol3); + CcFilesPeer::addInstanceToPool($obj3, $key3); + } // if $obj3 already loaded + + // Add the $obj1 (CcStampContents) to the collection in $obj3 (CcFiles) + $obj3->addCcStampContents($obj1); + + } // if joined row is not null + + // Add objects for joined CcBlock rows + + $key4 = CcBlockPeer::getPrimaryKeyHashFromRow($row, $startcol4); + if ($key4 !== null) { + $obj4 = CcBlockPeer::getInstanceFromPool($key4); + if (!$obj4) { + + $cls = CcBlockPeer::getOMClass(false); + + $obj4 = new $cls(); + $obj4->hydrate($row, $startcol4); + CcBlockPeer::addInstanceToPool($obj4, $key4); + } // if $obj4 already loaded + + // Add the $obj1 (CcStampContents) to the collection in $obj4 (CcBlock) + $obj4->addCcStampContents($obj1); + + } // if joined row is not null + + // Add objects for joined CcPlaylist rows + + $key5 = CcPlaylistPeer::getPrimaryKeyHashFromRow($row, $startcol5); + if ($key5 !== null) { + $obj5 = CcPlaylistPeer::getInstanceFromPool($key5); + if (!$obj5) { + + $cls = CcPlaylistPeer::getOMClass(false); + + $obj5 = new $cls(); + $obj5->hydrate($row, $startcol5); + CcPlaylistPeer::addInstanceToPool($obj5, $key5); + } // if $obj5 already loaded + + // Add the $obj1 (CcStampContents) to the collection in $obj5 (CcPlaylist) + $obj5->addCcStampContents($obj1); + + } // if joined row is not null + + $results[] = $obj1; + } + $stmt->closeCursor(); + return $results; + } + + + /** + * Selects a collection of CcStampContents objects pre-filled with all related objects except CcBlock. + * + * @param Criteria $criteria + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return array Array of CcStampContents objects. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelectJoinAllExceptCcBlock(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $criteria = clone $criteria; + + // Set the correct dbName if it has not been overridden + // $criteria->getDbName() will return the same object if not set to another value + // so == check is okay and faster + if ($criteria->getDbName() == Propel::getDefaultDB()) { + $criteria->setDbName(self::DATABASE_NAME); + } + + CcStampContentsPeer::addSelectColumns($criteria); + $startcol2 = (CcStampContentsPeer::NUM_COLUMNS - CcStampContentsPeer::NUM_LAZY_LOAD_COLUMNS); + + CcStampPeer::addSelectColumns($criteria); + $startcol3 = $startcol2 + (CcStampPeer::NUM_COLUMNS - CcStampPeer::NUM_LAZY_LOAD_COLUMNS); + + CcFilesPeer::addSelectColumns($criteria); + $startcol4 = $startcol3 + (CcFilesPeer::NUM_COLUMNS - CcFilesPeer::NUM_LAZY_LOAD_COLUMNS); + + CcWebstreamPeer::addSelectColumns($criteria); + $startcol5 = $startcol4 + (CcWebstreamPeer::NUM_COLUMNS - CcWebstreamPeer::NUM_LAZY_LOAD_COLUMNS); + + CcPlaylistPeer::addSelectColumns($criteria); + $startcol6 = $startcol5 + (CcPlaylistPeer::NUM_COLUMNS - CcPlaylistPeer::NUM_LAZY_LOAD_COLUMNS); + + $criteria->addJoin(CcStampContentsPeer::STAMP_ID, CcStampPeer::ID, $join_behavior); + + $criteria->addJoin(CcStampContentsPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + + $criteria->addJoin(CcStampContentsPeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); + + $criteria->addJoin(CcStampContentsPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); + + + $stmt = BasePeer::doSelect($criteria, $con); + $results = array(); + + while ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $key1 = CcStampContentsPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcStampContentsPeer::getInstanceFromPool($key1))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj1->hydrate($row, 0, true); // rehydrate + } else { + $cls = CcStampContentsPeer::getOMClass(false); + + $obj1 = new $cls(); + $obj1->hydrate($row); + CcStampContentsPeer::addInstanceToPool($obj1, $key1); + } // if obj1 already loaded + + // Add objects for joined CcStamp rows + + $key2 = CcStampPeer::getPrimaryKeyHashFromRow($row, $startcol2); + if ($key2 !== null) { + $obj2 = CcStampPeer::getInstanceFromPool($key2); + if (!$obj2) { + + $cls = CcStampPeer::getOMClass(false); + + $obj2 = new $cls(); + $obj2->hydrate($row, $startcol2); + CcStampPeer::addInstanceToPool($obj2, $key2); + } // if $obj2 already loaded + + // Add the $obj1 (CcStampContents) to the collection in $obj2 (CcStamp) + $obj2->addCcStampContents($obj1); + + } // if joined row is not null + + // Add objects for joined CcFiles rows + + $key3 = CcFilesPeer::getPrimaryKeyHashFromRow($row, $startcol3); + if ($key3 !== null) { + $obj3 = CcFilesPeer::getInstanceFromPool($key3); + if (!$obj3) { + + $cls = CcFilesPeer::getOMClass(false); + + $obj3 = new $cls(); + $obj3->hydrate($row, $startcol3); + CcFilesPeer::addInstanceToPool($obj3, $key3); + } // if $obj3 already loaded + + // Add the $obj1 (CcStampContents) to the collection in $obj3 (CcFiles) + $obj3->addCcStampContents($obj1); + + } // if joined row is not null + + // Add objects for joined CcWebstream rows + + $key4 = CcWebstreamPeer::getPrimaryKeyHashFromRow($row, $startcol4); + if ($key4 !== null) { + $obj4 = CcWebstreamPeer::getInstanceFromPool($key4); + if (!$obj4) { + + $cls = CcWebstreamPeer::getOMClass(false); + + $obj4 = new $cls(); + $obj4->hydrate($row, $startcol4); + CcWebstreamPeer::addInstanceToPool($obj4, $key4); + } // if $obj4 already loaded + + // Add the $obj1 (CcStampContents) to the collection in $obj4 (CcWebstream) + $obj4->addCcStampContents($obj1); + + } // if joined row is not null + + // Add objects for joined CcPlaylist rows + + $key5 = CcPlaylistPeer::getPrimaryKeyHashFromRow($row, $startcol5); + if ($key5 !== null) { + $obj5 = CcPlaylistPeer::getInstanceFromPool($key5); + if (!$obj5) { + + $cls = CcPlaylistPeer::getOMClass(false); + + $obj5 = new $cls(); + $obj5->hydrate($row, $startcol5); + CcPlaylistPeer::addInstanceToPool($obj5, $key5); + } // if $obj5 already loaded + + // Add the $obj1 (CcStampContents) to the collection in $obj5 (CcPlaylist) + $obj5->addCcStampContents($obj1); + + } // if joined row is not null + + $results[] = $obj1; + } + $stmt->closeCursor(); + return $results; + } + + + /** + * Selects a collection of CcStampContents objects pre-filled with all related objects except CcPlaylist. + * + * @param Criteria $criteria + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return array Array of CcStampContents objects. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelectJoinAllExceptCcPlaylist(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $criteria = clone $criteria; + + // Set the correct dbName if it has not been overridden + // $criteria->getDbName() will return the same object if not set to another value + // so == check is okay and faster + if ($criteria->getDbName() == Propel::getDefaultDB()) { + $criteria->setDbName(self::DATABASE_NAME); + } + + CcStampContentsPeer::addSelectColumns($criteria); + $startcol2 = (CcStampContentsPeer::NUM_COLUMNS - CcStampContentsPeer::NUM_LAZY_LOAD_COLUMNS); + + CcStampPeer::addSelectColumns($criteria); + $startcol3 = $startcol2 + (CcStampPeer::NUM_COLUMNS - CcStampPeer::NUM_LAZY_LOAD_COLUMNS); + + CcFilesPeer::addSelectColumns($criteria); + $startcol4 = $startcol3 + (CcFilesPeer::NUM_COLUMNS - CcFilesPeer::NUM_LAZY_LOAD_COLUMNS); + + CcWebstreamPeer::addSelectColumns($criteria); + $startcol5 = $startcol4 + (CcWebstreamPeer::NUM_COLUMNS - CcWebstreamPeer::NUM_LAZY_LOAD_COLUMNS); + + CcBlockPeer::addSelectColumns($criteria); + $startcol6 = $startcol5 + (CcBlockPeer::NUM_COLUMNS - CcBlockPeer::NUM_LAZY_LOAD_COLUMNS); + + $criteria->addJoin(CcStampContentsPeer::STAMP_ID, CcStampPeer::ID, $join_behavior); + + $criteria->addJoin(CcStampContentsPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + + $criteria->addJoin(CcStampContentsPeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); + + $criteria->addJoin(CcStampContentsPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); + + + $stmt = BasePeer::doSelect($criteria, $con); + $results = array(); + + while ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $key1 = CcStampContentsPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcStampContentsPeer::getInstanceFromPool($key1))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj1->hydrate($row, 0, true); // rehydrate + } else { + $cls = CcStampContentsPeer::getOMClass(false); + + $obj1 = new $cls(); + $obj1->hydrate($row); + CcStampContentsPeer::addInstanceToPool($obj1, $key1); + } // if obj1 already loaded + + // Add objects for joined CcStamp rows + + $key2 = CcStampPeer::getPrimaryKeyHashFromRow($row, $startcol2); + if ($key2 !== null) { + $obj2 = CcStampPeer::getInstanceFromPool($key2); + if (!$obj2) { + + $cls = CcStampPeer::getOMClass(false); + + $obj2 = new $cls(); + $obj2->hydrate($row, $startcol2); + CcStampPeer::addInstanceToPool($obj2, $key2); + } // if $obj2 already loaded + + // Add the $obj1 (CcStampContents) to the collection in $obj2 (CcStamp) + $obj2->addCcStampContents($obj1); + + } // if joined row is not null + + // Add objects for joined CcFiles rows + + $key3 = CcFilesPeer::getPrimaryKeyHashFromRow($row, $startcol3); + if ($key3 !== null) { + $obj3 = CcFilesPeer::getInstanceFromPool($key3); + if (!$obj3) { + + $cls = CcFilesPeer::getOMClass(false); + + $obj3 = new $cls(); + $obj3->hydrate($row, $startcol3); + CcFilesPeer::addInstanceToPool($obj3, $key3); + } // if $obj3 already loaded + + // Add the $obj1 (CcStampContents) to the collection in $obj3 (CcFiles) + $obj3->addCcStampContents($obj1); + + } // if joined row is not null + + // Add objects for joined CcWebstream rows + + $key4 = CcWebstreamPeer::getPrimaryKeyHashFromRow($row, $startcol4); + if ($key4 !== null) { + $obj4 = CcWebstreamPeer::getInstanceFromPool($key4); + if (!$obj4) { + + $cls = CcWebstreamPeer::getOMClass(false); + + $obj4 = new $cls(); + $obj4->hydrate($row, $startcol4); + CcWebstreamPeer::addInstanceToPool($obj4, $key4); + } // if $obj4 already loaded + + // Add the $obj1 (CcStampContents) to the collection in $obj4 (CcWebstream) + $obj4->addCcStampContents($obj1); + + } // if joined row is not null + + // Add objects for joined CcBlock rows + + $key5 = CcBlockPeer::getPrimaryKeyHashFromRow($row, $startcol5); + if ($key5 !== null) { + $obj5 = CcBlockPeer::getInstanceFromPool($key5); + if (!$obj5) { + + $cls = CcBlockPeer::getOMClass(false); + + $obj5 = new $cls(); + $obj5->hydrate($row, $startcol5); + CcBlockPeer::addInstanceToPool($obj5, $key5); + } // if $obj5 already loaded + + // Add the $obj1 (CcStampContents) to the collection in $obj5 (CcBlock) + $obj5->addCcStampContents($obj1); + + } // if joined row is not null + + $results[] = $obj1; + } + $stmt->closeCursor(); + return $results; + } + + /** + * Returns the TableMap related to this peer. + * This method is not needed for general use but a specific application could have a need. + * @return TableMap + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function getTableMap() + { + return Propel::getDatabaseMap(self::DATABASE_NAME)->getTable(self::TABLE_NAME); + } + + /** + * Add a TableMap instance to the database for this peer class. + */ + public static function buildTableMap() + { + $dbMap = Propel::getDatabaseMap(BaseCcStampContentsPeer::DATABASE_NAME); + if (!$dbMap->hasTable(BaseCcStampContentsPeer::TABLE_NAME)) + { + $dbMap->addTableObject(new CcStampContentsTableMap()); + } + } + + /** + * The class that the Peer will make instances of. + * + * If $withPrefix is true, the returned path + * uses a dot-path notation which is tranalted into a path + * relative to a location on the PHP include_path. + * (e.g. path.to.MyClass -> 'path/to/MyClass.php') + * + * @param boolean $withPrefix Whether or not to return the path with the class name + * @return string path.to.ClassName + */ + public static function getOMClass($withPrefix = true) + { + return $withPrefix ? CcStampContentsPeer::CLASS_DEFAULT : CcStampContentsPeer::OM_CLASS; + } + + /** + * Method perform an INSERT on the database, given a CcStampContents or Criteria object. + * + * @param mixed $values Criteria or CcStampContents object containing data that is used to create the INSERT statement. + * @param PropelPDO $con the PropelPDO connection to use + * @return mixed The new primary key. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doInsert($values, PropelPDO $con = null) + { + if ($con === null) { + $con = Propel::getConnection(CcStampContentsPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + } + + if ($values instanceof Criteria) { + $criteria = clone $values; // rename for clarity + } else { + $criteria = $values->buildCriteria(); // build Criteria from CcStampContents object + } + + if ($criteria->containsKey(CcStampContentsPeer::ID) && $criteria->keyContainsValue(CcStampContentsPeer::ID) ) { + throw new PropelException('Cannot insert a value for auto-increment primary key ('.CcStampContentsPeer::ID.')'); + } + + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + try { + // use transaction because $criteria could contain info + // for more than one table (I guess, conceivably) + $con->beginTransaction(); + $pk = BasePeer::doInsert($criteria, $con); + $con->commit(); + } catch(PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $pk; + } + + /** + * Method perform an UPDATE on the database, given a CcStampContents or Criteria object. + * + * @param mixed $values Criteria or CcStampContents object containing data that is used to create the UPDATE statement. + * @param PropelPDO $con The connection to use (specify PropelPDO connection object to exert more control over transactions). + * @return int The number of affected rows (if supported by underlying database driver). + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doUpdate($values, PropelPDO $con = null) + { + if ($con === null) { + $con = Propel::getConnection(CcStampContentsPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + } + + $selectCriteria = new Criteria(self::DATABASE_NAME); + + if ($values instanceof Criteria) { + $criteria = clone $values; // rename for clarity + + $comparison = $criteria->getComparison(CcStampContentsPeer::ID); + $value = $criteria->remove(CcStampContentsPeer::ID); + if ($value) { + $selectCriteria->add(CcStampContentsPeer::ID, $value, $comparison); + } else { + $selectCriteria->setPrimaryTableName(CcStampContentsPeer::TABLE_NAME); + } + + } else { // $values is CcStampContents object + $criteria = $values->buildCriteria(); // gets full criteria + $selectCriteria = $values->buildPkeyCriteria(); // gets criteria w/ primary key(s) + } + + // set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + return BasePeer::doUpdate($selectCriteria, $criteria, $con); + } + + /** + * Method to DELETE all rows from the cc_stamp_contents table. + * + * @return int The number of affected rows (if supported by underlying database driver). + */ + public static function doDeleteAll($con = null) + { + if ($con === null) { + $con = Propel::getConnection(CcStampContentsPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + } + $affectedRows = 0; // initialize var to track total num of affected rows + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->beginTransaction(); + $affectedRows += BasePeer::doDeleteAll(CcStampContentsPeer::TABLE_NAME, $con, CcStampContentsPeer::DATABASE_NAME); + // Because this db requires some delete cascade/set null emulation, we have to + // clear the cached instance *after* the emulation has happened (since + // instances get re-added by the select statement contained therein). + CcStampContentsPeer::clearInstancePool(); + CcStampContentsPeer::clearRelatedInstancePool(); + $con->commit(); + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Method perform a DELETE on the database, given a CcStampContents or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or CcStampContents object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param PropelPDO $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows + * if supported by native driver or if emulated using Propel. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doDelete($values, PropelPDO $con = null) + { + if ($con === null) { + $con = Propel::getConnection(CcStampContentsPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + } + + if ($values instanceof Criteria) { + // invalidate the cache for all objects of this type, since we have no + // way of knowing (without running a query) what objects should be invalidated + // from the cache based on this Criteria. + CcStampContentsPeer::clearInstancePool(); + // rename for clarity + $criteria = clone $values; + } elseif ($values instanceof CcStampContents) { // it's a model object + // invalidate the cache for this single object + CcStampContentsPeer::removeInstanceFromPool($values); + // create criteria based on pk values + $criteria = $values->buildPkeyCriteria(); + } else { // it's a primary key, or an array of pks + $criteria = new Criteria(self::DATABASE_NAME); + $criteria->add(CcStampContentsPeer::ID, (array) $values, Criteria::IN); + // invalidate the cache for this object(s) + foreach ((array) $values as $singleval) { + CcStampContentsPeer::removeInstanceFromPool($singleval); + } + } + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + $affectedRows = 0; // initialize var to track total num of affected rows + + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->beginTransaction(); + + $affectedRows += BasePeer::doDelete($criteria, $con); + CcStampContentsPeer::clearRelatedInstancePool(); + $con->commit(); + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Validates all modified columns of given CcStampContents object. + * If parameter $columns is either a single column name or an array of column names + * than only those columns are validated. + * + * NOTICE: This does not apply to primary or foreign keys for now. + * + * @param CcStampContents $obj The object to validate. + * @param mixed $cols Column name or array of column names. + * + * @return mixed TRUE if all columns are valid or the error message of the first invalid column. + */ + public static function doValidate(CcStampContents $obj, $cols = null) + { + $columns = array(); + + if ($cols) { + $dbMap = Propel::getDatabaseMap(CcStampContentsPeer::DATABASE_NAME); + $tableMap = $dbMap->getTable(CcStampContentsPeer::TABLE_NAME); + + if (! is_array($cols)) { + $cols = array($cols); + } + + foreach ($cols as $colName) { + if ($tableMap->containsColumn($colName)) { + $get = 'get' . $tableMap->getColumn($colName)->getPhpName(); + $columns[$colName] = $obj->$get(); + } + } + } else { + + } + + return BasePeer::doValidate(CcStampContentsPeer::DATABASE_NAME, CcStampContentsPeer::TABLE_NAME, $columns); + } + + /** + * Retrieve a single object by pkey. + * + * @param int $pk the primary key. + * @param PropelPDO $con the connection to use + * @return CcStampContents + */ + public static function retrieveByPK($pk, PropelPDO $con = null) + { + + if (null !== ($obj = CcStampContentsPeer::getInstanceFromPool((string) $pk))) { + return $obj; + } + + if ($con === null) { + $con = Propel::getConnection(CcStampContentsPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $criteria = new Criteria(CcStampContentsPeer::DATABASE_NAME); + $criteria->add(CcStampContentsPeer::ID, $pk); + + $v = CcStampContentsPeer::doSelect($criteria, $con); + + return !empty($v) > 0 ? $v[0] : null; + } + + /** + * Retrieve multiple objects by pkey. + * + * @param array $pks List of primary keys + * @param PropelPDO $con the connection to use + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function retrieveByPKs($pks, PropelPDO $con = null) + { + if ($con === null) { + $con = Propel::getConnection(CcStampContentsPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $objs = null; + if (empty($pks)) { + $objs = array(); + } else { + $criteria = new Criteria(CcStampContentsPeer::DATABASE_NAME); + $criteria->add(CcStampContentsPeer::ID, $pks, Criteria::IN); + $objs = CcStampContentsPeer::doSelect($criteria, $con); + } + return $objs; + } + +} // BaseCcStampContentsPeer + +// This is the static code needed to register the TableMap for this table with the main Propel class. +// +BaseCcStampContentsPeer::buildTableMap(); + diff --git a/airtime_mvc/application/models/airtime/om/BaseCcStampContentsQuery.php b/airtime_mvc/application/models/airtime/om/BaseCcStampContentsQuery.php new file mode 100644 index 000000000..fbbcd3601 --- /dev/null +++ b/airtime_mvc/application/models/airtime/om/BaseCcStampContentsQuery.php @@ -0,0 +1,845 @@ +setModelAlias($modelAlias); + } + if ($criteria instanceof Criteria) { + $query->mergeWith($criteria); + } + return $query; + } + + /** + * Find object by primary key + * Use instance pooling to avoid a database query if the object exists + * + * $obj = $c->findPk(12, $con); + * + * @param mixed $key Primary key to use for the query + * @param PropelPDO $con an optional connection object + * + * @return CcStampContents|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ((null !== ($obj = CcStampContentsPeer::getInstanceFromPool((string) $key))) && $this->getFormatter()->isObjectFormatter()) { + // the object is alredy in the instance pool + return $obj; + } else { + // the object has not been requested yet, or the formatter is not an object formatter + $criteria = $this->isKeepQuery() ? clone $this : $this; + $stmt = $criteria + ->filterByPrimaryKey($key) + ->getSelectStatement($con); + return $criteria->getFormatter()->init($criteria)->formatOne($stmt); + } + } + + /** + * Find objects by primary key + * + * $objs = $c->findPks(array(12, 56, 832), $con); + * + * @param array $keys Primary keys to use for the query + * @param PropelPDO $con an optional connection object + * + * @return PropelObjectCollection|array|mixed the list of results, formatted by the current formatter + */ + public function findPks($keys, $con = null) + { + $criteria = $this->isKeepQuery() ? clone $this : $this; + return $this + ->filterByPrimaryKeys($keys) + ->find($con); + } + + /** + * Filter the query by primary key + * + * @param mixed $key Primary key to use for the query + * + * @return CcStampContentsQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + return $this->addUsingAlias(CcStampContentsPeer::ID, $key, Criteria::EQUAL); + } + + /** + * Filter the query by a list of primary keys + * + * @param array $keys The list of primary key to use for the query + * + * @return CcStampContentsQuery The current query, for fluid interface + */ + public function filterByPrimaryKeys($keys) + { + return $this->addUsingAlias(CcStampContentsPeer::ID, $keys, Criteria::IN); + } + + /** + * Filter the query on the id column + * + * @param int|array $dbId 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 CcStampContentsQuery The current query, for fluid interface + */ + public function filterByDbId($dbId = null, $comparison = null) + { + if (is_array($dbId) && null === $comparison) { + $comparison = Criteria::IN; + } + return $this->addUsingAlias(CcStampContentsPeer::ID, $dbId, $comparison); + } + + /** + * Filter the query on the stamp_id column + * + * @param int|array $dbStampId 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 CcStampContentsQuery The current query, for fluid interface + */ + public function filterByDbStampId($dbStampId = null, $comparison = null) + { + if (is_array($dbStampId)) { + $useMinMax = false; + if (isset($dbStampId['min'])) { + $this->addUsingAlias(CcStampContentsPeer::STAMP_ID, $dbStampId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbStampId['max'])) { + $this->addUsingAlias(CcStampContentsPeer::STAMP_ID, $dbStampId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcStampContentsPeer::STAMP_ID, $dbStampId, $comparison); + } + + /** + * Filter the query on the file_id column + * + * @param int|array $dbFileId 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 CcStampContentsQuery The current query, for fluid interface + */ + public function filterByDbFileId($dbFileId = null, $comparison = null) + { + if (is_array($dbFileId)) { + $useMinMax = false; + if (isset($dbFileId['min'])) { + $this->addUsingAlias(CcStampContentsPeer::FILE_ID, $dbFileId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbFileId['max'])) { + $this->addUsingAlias(CcStampContentsPeer::FILE_ID, $dbFileId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcStampContentsPeer::FILE_ID, $dbFileId, $comparison); + } + + /** + * Filter the query on the stream_id column + * + * @param int|array $dbStreamId 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 CcStampContentsQuery The current query, for fluid interface + */ + public function filterByDbStreamId($dbStreamId = null, $comparison = null) + { + if (is_array($dbStreamId)) { + $useMinMax = false; + if (isset($dbStreamId['min'])) { + $this->addUsingAlias(CcStampContentsPeer::STREAM_ID, $dbStreamId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbStreamId['max'])) { + $this->addUsingAlias(CcStampContentsPeer::STREAM_ID, $dbStreamId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcStampContentsPeer::STREAM_ID, $dbStreamId, $comparison); + } + + /** + * Filter the query on the block_id column + * + * @param int|array $dbBlockId 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 CcStampContentsQuery The current query, for fluid interface + */ + public function filterByDbBlockId($dbBlockId = null, $comparison = null) + { + if (is_array($dbBlockId)) { + $useMinMax = false; + if (isset($dbBlockId['min'])) { + $this->addUsingAlias(CcStampContentsPeer::BLOCK_ID, $dbBlockId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbBlockId['max'])) { + $this->addUsingAlias(CcStampContentsPeer::BLOCK_ID, $dbBlockId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcStampContentsPeer::BLOCK_ID, $dbBlockId, $comparison); + } + + /** + * Filter the query on the playlist_id column + * + * @param int|array $dbPlaylistId 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 CcStampContentsQuery The current query, for fluid interface + */ + public function filterByDbPlaylistId($dbPlaylistId = null, $comparison = null) + { + if (is_array($dbPlaylistId)) { + $useMinMax = false; + if (isset($dbPlaylistId['min'])) { + $this->addUsingAlias(CcStampContentsPeer::PLAYLIST_ID, $dbPlaylistId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbPlaylistId['max'])) { + $this->addUsingAlias(CcStampContentsPeer::PLAYLIST_ID, $dbPlaylistId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcStampContentsPeer::PLAYLIST_ID, $dbPlaylistId, $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 CcStampContentsQuery 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(CcStampContentsPeer::POSITION, $dbPosition['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbPosition['max'])) { + $this->addUsingAlias(CcStampContentsPeer::POSITION, $dbPosition['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcStampContentsPeer::POSITION, $dbPosition, $comparison); + } + + /** + * Filter the query on the clip_length column + * + * @param string $dbClipLength The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return CcStampContentsQuery The current query, for fluid interface + */ + public function filterByDbClipLength($dbClipLength = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($dbClipLength)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $dbClipLength)) { + $dbClipLength = str_replace('*', '%', $dbClipLength); + $comparison = Criteria::LIKE; + } + } + return $this->addUsingAlias(CcStampContentsPeer::CLIP_LENGTH, $dbClipLength, $comparison); + } + + /** + * Filter the query on the cue_in column + * + * @param string $dbCueIn The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return CcStampContentsQuery The current query, for fluid interface + */ + public function filterByDbCueIn($dbCueIn = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($dbCueIn)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $dbCueIn)) { + $dbCueIn = str_replace('*', '%', $dbCueIn); + $comparison = Criteria::LIKE; + } + } + return $this->addUsingAlias(CcStampContentsPeer::CUE_IN, $dbCueIn, $comparison); + } + + /** + * Filter the query on the cue_out column + * + * @param string $dbCueOut The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return CcStampContentsQuery The current query, for fluid interface + */ + public function filterByDbCueOut($dbCueOut = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($dbCueOut)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $dbCueOut)) { + $dbCueOut = str_replace('*', '%', $dbCueOut); + $comparison = Criteria::LIKE; + } + } + return $this->addUsingAlias(CcStampContentsPeer::CUE_OUT, $dbCueOut, $comparison); + } + + /** + * Filter the query on the fade_in column + * + * @param string $dbFadeIn The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return CcStampContentsQuery The current query, for fluid interface + */ + public function filterByDbFadeIn($dbFadeIn = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($dbFadeIn)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $dbFadeIn)) { + $dbFadeIn = str_replace('*', '%', $dbFadeIn); + $comparison = Criteria::LIKE; + } + } + return $this->addUsingAlias(CcStampContentsPeer::FADE_IN, $dbFadeIn, $comparison); + } + + /** + * Filter the query on the fade_out column + * + * @param string $dbFadeOut The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return CcStampContentsQuery The current query, for fluid interface + */ + public function filterByDbFadeOut($dbFadeOut = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($dbFadeOut)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $dbFadeOut)) { + $dbFadeOut = str_replace('*', '%', $dbFadeOut); + $comparison = Criteria::LIKE; + } + } + return $this->addUsingAlias(CcStampContentsPeer::FADE_OUT, $dbFadeOut, $comparison); + } + + /** + * Filter the query by a related CcStamp object + * + * @param CcStamp $ccStamp the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return CcStampContentsQuery The current query, for fluid interface + */ + public function filterByCcStamp($ccStamp, $comparison = null) + { + return $this + ->addUsingAlias(CcStampContentsPeer::STAMP_ID, $ccStamp->getDbId(), $comparison); + } + + /** + * Adds a JOIN clause to the query using the CcStamp relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return CcStampContentsQuery The current query, for fluid interface + */ + public function joinCcStamp($relationAlias = '', $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('CcStamp'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'CcStamp'); + } + + return $this; + } + + /** + * Use the CcStamp relation CcStamp object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return CcStampQuery A secondary query class using the current class as primary query + */ + public function useCcStampQuery($relationAlias = '', $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinCcStamp($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'CcStamp', 'CcStampQuery'); + } + + /** + * Filter the query by a related CcFiles object + * + * @param CcFiles $ccFiles the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return CcStampContentsQuery The current query, for fluid interface + */ + public function filterByCcFiles($ccFiles, $comparison = null) + { + return $this + ->addUsingAlias(CcStampContentsPeer::FILE_ID, $ccFiles->getDbId(), $comparison); + } + + /** + * Adds a JOIN clause to the query using the CcFiles relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return CcStampContentsQuery The current query, for fluid interface + */ + public function joinCcFiles($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('CcFiles'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'CcFiles'); + } + + return $this; + } + + /** + * Use the CcFiles relation CcFiles object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return CcFilesQuery A secondary query class using the current class as primary query + */ + public function useCcFilesQuery($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + { + return $this + ->joinCcFiles($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'CcFiles', 'CcFilesQuery'); + } + + /** + * Filter the query by a related CcWebstream object + * + * @param CcWebstream $ccWebstream the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return CcStampContentsQuery The current query, for fluid interface + */ + public function filterByCcWebstream($ccWebstream, $comparison = null) + { + return $this + ->addUsingAlias(CcStampContentsPeer::STREAM_ID, $ccWebstream->getDbId(), $comparison); + } + + /** + * Adds a JOIN clause to the query using the CcWebstream relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return CcStampContentsQuery The current query, for fluid interface + */ + public function joinCcWebstream($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('CcWebstream'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'CcWebstream'); + } + + return $this; + } + + /** + * Use the CcWebstream relation CcWebstream object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return CcWebstreamQuery A secondary query class using the current class as primary query + */ + public function useCcWebstreamQuery($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + { + return $this + ->joinCcWebstream($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'CcWebstream', 'CcWebstreamQuery'); + } + + /** + * Filter the query by a related CcBlock object + * + * @param CcBlock $ccBlock the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return CcStampContentsQuery The current query, for fluid interface + */ + public function filterByCcBlock($ccBlock, $comparison = null) + { + return $this + ->addUsingAlias(CcStampContentsPeer::BLOCK_ID, $ccBlock->getDbId(), $comparison); + } + + /** + * Adds a JOIN clause to the query using the CcBlock relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return CcStampContentsQuery The current query, for fluid interface + */ + public function joinCcBlock($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('CcBlock'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'CcBlock'); + } + + return $this; + } + + /** + * Use the CcBlock relation CcBlock object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return CcBlockQuery A secondary query class using the current class as primary query + */ + public function useCcBlockQuery($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + { + return $this + ->joinCcBlock($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'CcBlock', 'CcBlockQuery'); + } + + /** + * Filter the query by a related CcPlaylist object + * + * @param CcPlaylist $ccPlaylist the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return CcStampContentsQuery The current query, for fluid interface + */ + public function filterByCcPlaylist($ccPlaylist, $comparison = null) + { + return $this + ->addUsingAlias(CcStampContentsPeer::PLAYLIST_ID, $ccPlaylist->getDbId(), $comparison); + } + + /** + * Adds a JOIN clause to the query using the CcPlaylist relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return CcStampContentsQuery The current query, for fluid interface + */ + public function joinCcPlaylist($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('CcPlaylist'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'CcPlaylist'); + } + + return $this; + } + + /** + * Use the CcPlaylist relation CcPlaylist object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return CcPlaylistQuery A secondary query class using the current class as primary query + */ + public function useCcPlaylistQuery($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + { + return $this + ->joinCcPlaylist($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'CcPlaylist', 'CcPlaylistQuery'); + } + + /** + * Exclude object from result + * + * @param CcStampContents $ccStampContents Object to remove from the list of results + * + * @return CcStampContentsQuery The current query, for fluid interface + */ + public function prune($ccStampContents = null) + { + if ($ccStampContents) { + $this->addUsingAlias(CcStampContentsPeer::ID, $ccStampContents->getDbId(), Criteria::NOT_EQUAL); + } + + return $this; + } + +} // BaseCcStampContentsQuery diff --git a/airtime_mvc/application/models/airtime/om/BaseCcStampPeer.php b/airtime_mvc/application/models/airtime/om/BaseCcStampPeer.php new file mode 100644 index 000000000..d6db733c7 --- /dev/null +++ b/airtime_mvc/application/models/airtime/om/BaseCcStampPeer.php @@ -0,0 +1,1368 @@ + array ('DbId', 'DbShowId', 'DbInstanceId', ), + BasePeer::TYPE_STUDLYPHPNAME => array ('dbId', 'dbShowId', 'dbInstanceId', ), + BasePeer::TYPE_COLNAME => array (self::ID, self::SHOW_ID, self::INSTANCE_ID, ), + BasePeer::TYPE_RAW_COLNAME => array ('ID', 'SHOW_ID', 'INSTANCE_ID', ), + BasePeer::TYPE_FIELDNAME => array ('id', 'show_id', 'instance_id', ), + BasePeer::TYPE_NUM => array (0, 1, 2, ) + ); + + /** + * holds an array of keys for quick access to the fieldnames array + * + * first dimension keys are the type constants + * e.g. self::$fieldNames[BasePeer::TYPE_PHPNAME]['Id'] = 0 + */ + private static $fieldKeys = array ( + BasePeer::TYPE_PHPNAME => array ('DbId' => 0, 'DbShowId' => 1, 'DbInstanceId' => 2, ), + BasePeer::TYPE_STUDLYPHPNAME => array ('dbId' => 0, 'dbShowId' => 1, 'dbInstanceId' => 2, ), + BasePeer::TYPE_COLNAME => array (self::ID => 0, self::SHOW_ID => 1, self::INSTANCE_ID => 2, ), + BasePeer::TYPE_RAW_COLNAME => array ('ID' => 0, 'SHOW_ID' => 1, 'INSTANCE_ID' => 2, ), + BasePeer::TYPE_FIELDNAME => array ('id' => 0, 'show_id' => 1, 'instance_id' => 2, ), + BasePeer::TYPE_NUM => array (0, 1, 2, ) + ); + + /** + * Translates a fieldname to another type + * + * @param string $name field name + * @param string $fromType One of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME + * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM + * @param string $toType One of the class type constants + * @return string translated name of the field. + * @throws PropelException - if the specified name could not be found in the fieldname mappings. + */ + static public function translateFieldName($name, $fromType, $toType) + { + $toNames = self::getFieldNames($toType); + $key = isset(self::$fieldKeys[$fromType][$name]) ? self::$fieldKeys[$fromType][$name] : null; + if ($key === null) { + throw new PropelException("'$name' could not be found in the field names of type '$fromType'. These are: " . print_r(self::$fieldKeys[$fromType], true)); + } + return $toNames[$key]; + } + + /** + * Returns an array of field names. + * + * @param string $type The type of fieldnames to return: + * One of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME + * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM + * @return array A list of field names + */ + + static public function getFieldNames($type = BasePeer::TYPE_PHPNAME) + { + if (!array_key_exists($type, self::$fieldNames)) { + throw new PropelException('Method getFieldNames() expects the parameter $type to be one of the class constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME, BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. ' . $type . ' was given.'); + } + return self::$fieldNames[$type]; + } + + /** + * Convenience method which changes table.column to alias.column. + * + * Using this method you can maintain SQL abstraction while using column aliases. + * + * $c->addAlias("alias1", TablePeer::TABLE_NAME); + * $c->addJoin(TablePeer::alias("alias1", TablePeer::PRIMARY_KEY_COLUMN), TablePeer::PRIMARY_KEY_COLUMN); + * + * @param string $alias The alias for the current table. + * @param string $column The column name for current table. (i.e. CcStampPeer::COLUMN_NAME). + * @return string + */ + public static function alias($alias, $column) + { + return str_replace(CcStampPeer::TABLE_NAME.'.', $alias.'.', $column); + } + + /** + * Add all the columns needed to create a new object. + * + * Note: any columns that were marked with lazyLoad="true" in the + * XML schema will not be added to the select list and only loaded + * on demand. + * + * @param Criteria $criteria object containing the columns to add. + * @param string $alias optional table alias + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function addSelectColumns(Criteria $criteria, $alias = null) + { + if (null === $alias) { + $criteria->addSelectColumn(CcStampPeer::ID); + $criteria->addSelectColumn(CcStampPeer::SHOW_ID); + $criteria->addSelectColumn(CcStampPeer::INSTANCE_ID); + } else { + $criteria->addSelectColumn($alias . '.ID'); + $criteria->addSelectColumn($alias . '.SHOW_ID'); + $criteria->addSelectColumn($alias . '.INSTANCE_ID'); + } + } + + /** + * Returns the number of rows matching criteria. + * + * @param Criteria $criteria + * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. + * @param PropelPDO $con + * @return int Number of matching rows. + */ + public static function doCount(Criteria $criteria, $distinct = false, PropelPDO $con = null) + { + // we may modify criteria, so copy it first + $criteria = clone $criteria; + + // We need to set the primary table name, since in the case that there are no WHERE columns + // it will be impossible for the BasePeer::createSelectSql() method to determine which + // tables go into the FROM clause. + $criteria->setPrimaryTableName(CcStampPeer::TABLE_NAME); + + if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->setDistinct(); + } + + if (!$criteria->hasSelectClause()) { + CcStampPeer::addSelectColumns($criteria); + } + + $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count + $criteria->setDbName(self::DATABASE_NAME); // Set the correct dbName + + if ($con === null) { + $con = Propel::getConnection(CcStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + // BasePeer returns a PDOStatement + $stmt = BasePeer::doCount($criteria, $con); + + if ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $count = (int) $row[0]; + } else { + $count = 0; // no rows returned; we infer that means 0 matches. + } + $stmt->closeCursor(); + return $count; + } + /** + * Method to select one object from the DB. + * + * @param Criteria $criteria object used to create the SELECT statement. + * @param PropelPDO $con + * @return CcStamp + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelectOne(Criteria $criteria, PropelPDO $con = null) + { + $critcopy = clone $criteria; + $critcopy->setLimit(1); + $objects = CcStampPeer::doSelect($critcopy, $con); + if ($objects) { + return $objects[0]; + } + return null; + } + /** + * Method to do selects. + * + * @param Criteria $criteria The Criteria object used to build the SELECT statement. + * @param PropelPDO $con + * @return array Array of selected Objects + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelect(Criteria $criteria, PropelPDO $con = null) + { + return CcStampPeer::populateObjects(CcStampPeer::doSelectStmt($criteria, $con)); + } + /** + * Prepares the Criteria object and uses the parent doSelect() method to execute a PDOStatement. + * + * Use this method directly if you want to work with an executed statement durirectly (for example + * to perform your own object hydration). + * + * @param Criteria $criteria The Criteria object used to build the SELECT statement. + * @param PropelPDO $con The connection to use + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + * @return PDOStatement The executed PDOStatement object. + * @see BasePeer::doSelect() + */ + public static function doSelectStmt(Criteria $criteria, PropelPDO $con = null) + { + if ($con === null) { + $con = Propel::getConnection(CcStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + if (!$criteria->hasSelectClause()) { + $criteria = clone $criteria; + CcStampPeer::addSelectColumns($criteria); + } + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + // BasePeer returns a PDOStatement + return BasePeer::doSelect($criteria, $con); + } + /** + * Adds an object to the instance pool. + * + * Propel keeps cached copies of objects in an instance pool when they are retrieved + * from the database. In some cases -- especially when you override doSelect*() + * methods in your stub classes -- you may need to explicitly add objects + * to the cache in order to ensure that the same objects are always returned by doSelect*() + * and retrieveByPK*() calls. + * + * @param CcStamp $value A CcStamp object. + * @param string $key (optional) key to use for instance map (for performance boost if key was already calculated externally). + */ + public static function addInstanceToPool(CcStamp $obj, $key = null) + { + if (Propel::isInstancePoolingEnabled()) { + if ($key === null) { + $key = (string) $obj->getDbId(); + } // if key === null + self::$instances[$key] = $obj; + } + } + + /** + * Removes an object from the instance pool. + * + * Propel keeps cached copies of objects in an instance pool when they are retrieved + * from the database. In some cases -- especially when you override doDelete + * methods in your stub classes -- you may need to explicitly remove objects + * from the cache in order to prevent returning objects that no longer exist. + * + * @param mixed $value A CcStamp object or a primary key value. + */ + public static function removeInstanceFromPool($value) + { + if (Propel::isInstancePoolingEnabled() && $value !== null) { + if (is_object($value) && $value instanceof CcStamp) { + $key = (string) $value->getDbId(); + } elseif (is_scalar($value)) { + // assume we've been passed a primary key + $key = (string) $value; + } else { + $e = new PropelException("Invalid value passed to removeInstanceFromPool(). Expected primary key or CcStamp object; got " . (is_object($value) ? get_class($value) . ' object.' : var_export($value,true))); + throw $e; + } + + unset(self::$instances[$key]); + } + } // removeInstanceFromPool() + + /** + * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table. + * + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, a serialize()d version of the primary key will be returned. + * + * @param string $key The key (@see getPrimaryKeyHash()) for this instance. + * @return CcStamp Found object or NULL if 1) no instance exists for specified key or 2) instance pooling has been disabled. + * @see getPrimaryKeyHash() + */ + public static function getInstanceFromPool($key) + { + if (Propel::isInstancePoolingEnabled()) { + if (isset(self::$instances[$key])) { + return self::$instances[$key]; + } + } + return null; // just to be explicit + } + + /** + * Clear the instance pool. + * + * @return void + */ + public static function clearInstancePool() + { + self::$instances = array(); + } + + /** + * Method to invalidate the instance pool of all tables related to cc_stamp + * by a foreign key with ON DELETE CASCADE + */ + public static function clearRelatedInstancePool() + { + // Invalidate objects in CcStampContentsPeer instance pool, + // since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule. + CcStampContentsPeer::clearInstancePool(); + } + + /** + * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table. + * + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, a serialize()d version of the primary key will be returned. + * + * @param array $row PropelPDO resultset row. + * @param int $startcol The 0-based offset for reading from the resultset row. + * @return string A string version of PK or NULL if the components of primary key in result array are all null. + */ + public static function getPrimaryKeyHashFromRow($row, $startcol = 0) + { + // If the PK cannot be derived from the row, return NULL. + if ($row[$startcol] === null) { + return null; + } + return (string) $row[$startcol]; + } + + /** + * Retrieves the primary key from the DB resultset row + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, an array of the primary key columns will be returned. + * + * @param array $row PropelPDO resultset row. + * @param int $startcol The 0-based offset for reading from the resultset row. + * @return mixed The primary key of the row + */ + public static function getPrimaryKeyFromRow($row, $startcol = 0) + { + return (int) $row[$startcol]; + } + + /** + * The returned array will contain objects of the default type or + * objects that inherit from the default. + * + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function populateObjects(PDOStatement $stmt) + { + $results = array(); + + // set the class once to avoid overhead in the loop + $cls = CcStampPeer::getOMClass(false); + // populate the object(s) + while ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $key = CcStampPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj = CcStampPeer::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, 0, true); // rehydrate + $results[] = $obj; + } else { + $obj = new $cls(); + $obj->hydrate($row); + $results[] = $obj; + CcStampPeer::addInstanceToPool($obj, $key); + } // if key exists + } + $stmt->closeCursor(); + return $results; + } + /** + * Populates an object of the default type or an object that inherit from the default. + * + * @param array $row PropelPDO resultset row. + * @param int $startcol The 0-based offset for reading from the resultset row. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + * @return array (CcStamp object, last column rank) + */ + public static function populateObject($row, $startcol = 0) + { + $key = CcStampPeer::getPrimaryKeyHashFromRow($row, $startcol); + if (null !== ($obj = CcStampPeer::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, $startcol, true); // rehydrate + $col = $startcol + CcStampPeer::NUM_COLUMNS; + } else { + $cls = CcStampPeer::OM_CLASS; + $obj = new $cls(); + $col = $obj->hydrate($row, $startcol); + CcStampPeer::addInstanceToPool($obj, $key); + } + return array($obj, $col); + } + + /** + * Returns the number of rows matching criteria, joining the related CcShow table + * + * @param Criteria $criteria + * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return int Number of matching rows. + */ + public static function doCountJoinCcShow(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + // we're going to modify criteria, so copy it first + $criteria = clone $criteria; + + // We need to set the primary table name, since in the case that there are no WHERE columns + // it will be impossible for the BasePeer::createSelectSql() method to determine which + // tables go into the FROM clause. + $criteria->setPrimaryTableName(CcStampPeer::TABLE_NAME); + + if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->setDistinct(); + } + + if (!$criteria->hasSelectClause()) { + CcStampPeer::addSelectColumns($criteria); + } + + $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + if ($con === null) { + $con = Propel::getConnection(CcStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $criteria->addJoin(CcStampPeer::SHOW_ID, CcShowPeer::ID, $join_behavior); + + $stmt = BasePeer::doCount($criteria, $con); + + if ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $count = (int) $row[0]; + } else { + $count = 0; // no rows returned; we infer that means 0 matches. + } + $stmt->closeCursor(); + return $count; + } + + + /** + * Returns the number of rows matching criteria, joining the related CcShowInstances table + * + * @param Criteria $criteria + * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return int Number of matching rows. + */ + public static function doCountJoinCcShowInstances(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + // we're going to modify criteria, so copy it first + $criteria = clone $criteria; + + // We need to set the primary table name, since in the case that there are no WHERE columns + // it will be impossible for the BasePeer::createSelectSql() method to determine which + // tables go into the FROM clause. + $criteria->setPrimaryTableName(CcStampPeer::TABLE_NAME); + + if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->setDistinct(); + } + + if (!$criteria->hasSelectClause()) { + CcStampPeer::addSelectColumns($criteria); + } + + $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + if ($con === null) { + $con = Propel::getConnection(CcStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $criteria->addJoin(CcStampPeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); + + $stmt = BasePeer::doCount($criteria, $con); + + if ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $count = (int) $row[0]; + } else { + $count = 0; // no rows returned; we infer that means 0 matches. + } + $stmt->closeCursor(); + return $count; + } + + + /** + * Selects a collection of CcStamp objects pre-filled with their CcShow objects. + * @param Criteria $criteria + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return array Array of CcStamp objects. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelectJoinCcShow(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $criteria = clone $criteria; + + // Set the correct dbName if it has not been overridden + if ($criteria->getDbName() == Propel::getDefaultDB()) { + $criteria->setDbName(self::DATABASE_NAME); + } + + CcStampPeer::addSelectColumns($criteria); + $startcol = (CcStampPeer::NUM_COLUMNS - CcStampPeer::NUM_LAZY_LOAD_COLUMNS); + CcShowPeer::addSelectColumns($criteria); + + $criteria->addJoin(CcStampPeer::SHOW_ID, CcShowPeer::ID, $join_behavior); + + $stmt = BasePeer::doSelect($criteria, $con); + $results = array(); + + while ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $key1 = CcStampPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcStampPeer::getInstanceFromPool($key1))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj1->hydrate($row, 0, true); // rehydrate + } else { + + $cls = CcStampPeer::getOMClass(false); + + $obj1 = new $cls(); + $obj1->hydrate($row); + CcStampPeer::addInstanceToPool($obj1, $key1); + } // if $obj1 already loaded + + $key2 = CcShowPeer::getPrimaryKeyHashFromRow($row, $startcol); + if ($key2 !== null) { + $obj2 = CcShowPeer::getInstanceFromPool($key2); + if (!$obj2) { + + $cls = CcShowPeer::getOMClass(false); + + $obj2 = new $cls(); + $obj2->hydrate($row, $startcol); + CcShowPeer::addInstanceToPool($obj2, $key2); + } // if obj2 already loaded + + // Add the $obj1 (CcStamp) to $obj2 (CcShow) + $obj2->addCcStamp($obj1); + + } // if joined row was not null + + $results[] = $obj1; + } + $stmt->closeCursor(); + return $results; + } + + + /** + * Selects a collection of CcStamp objects pre-filled with their CcShowInstances objects. + * @param Criteria $criteria + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return array Array of CcStamp objects. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelectJoinCcShowInstances(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $criteria = clone $criteria; + + // Set the correct dbName if it has not been overridden + if ($criteria->getDbName() == Propel::getDefaultDB()) { + $criteria->setDbName(self::DATABASE_NAME); + } + + CcStampPeer::addSelectColumns($criteria); + $startcol = (CcStampPeer::NUM_COLUMNS - CcStampPeer::NUM_LAZY_LOAD_COLUMNS); + CcShowInstancesPeer::addSelectColumns($criteria); + + $criteria->addJoin(CcStampPeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); + + $stmt = BasePeer::doSelect($criteria, $con); + $results = array(); + + while ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $key1 = CcStampPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcStampPeer::getInstanceFromPool($key1))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj1->hydrate($row, 0, true); // rehydrate + } else { + + $cls = CcStampPeer::getOMClass(false); + + $obj1 = new $cls(); + $obj1->hydrate($row); + CcStampPeer::addInstanceToPool($obj1, $key1); + } // if $obj1 already loaded + + $key2 = CcShowInstancesPeer::getPrimaryKeyHashFromRow($row, $startcol); + if ($key2 !== null) { + $obj2 = CcShowInstancesPeer::getInstanceFromPool($key2); + if (!$obj2) { + + $cls = CcShowInstancesPeer::getOMClass(false); + + $obj2 = new $cls(); + $obj2->hydrate($row, $startcol); + CcShowInstancesPeer::addInstanceToPool($obj2, $key2); + } // if obj2 already loaded + + // Add the $obj1 (CcStamp) to $obj2 (CcShowInstances) + $obj2->addCcStamp($obj1); + + } // if joined row was not null + + $results[] = $obj1; + } + $stmt->closeCursor(); + return $results; + } + + + /** + * Returns the number of rows matching criteria, joining all related tables + * + * @param Criteria $criteria + * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return int Number of matching rows. + */ + public static function doCountJoinAll(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + // we're going to modify criteria, so copy it first + $criteria = clone $criteria; + + // We need to set the primary table name, since in the case that there are no WHERE columns + // it will be impossible for the BasePeer::createSelectSql() method to determine which + // tables go into the FROM clause. + $criteria->setPrimaryTableName(CcStampPeer::TABLE_NAME); + + if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->setDistinct(); + } + + if (!$criteria->hasSelectClause()) { + CcStampPeer::addSelectColumns($criteria); + } + + $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + if ($con === null) { + $con = Propel::getConnection(CcStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $criteria->addJoin(CcStampPeer::SHOW_ID, CcShowPeer::ID, $join_behavior); + + $criteria->addJoin(CcStampPeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); + + $stmt = BasePeer::doCount($criteria, $con); + + if ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $count = (int) $row[0]; + } else { + $count = 0; // no rows returned; we infer that means 0 matches. + } + $stmt->closeCursor(); + return $count; + } + + /** + * Selects a collection of CcStamp objects pre-filled with all related objects. + * + * @param Criteria $criteria + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return array Array of CcStamp objects. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelectJoinAll(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $criteria = clone $criteria; + + // Set the correct dbName if it has not been overridden + if ($criteria->getDbName() == Propel::getDefaultDB()) { + $criteria->setDbName(self::DATABASE_NAME); + } + + CcStampPeer::addSelectColumns($criteria); + $startcol2 = (CcStampPeer::NUM_COLUMNS - CcStampPeer::NUM_LAZY_LOAD_COLUMNS); + + CcShowPeer::addSelectColumns($criteria); + $startcol3 = $startcol2 + (CcShowPeer::NUM_COLUMNS - CcShowPeer::NUM_LAZY_LOAD_COLUMNS); + + CcShowInstancesPeer::addSelectColumns($criteria); + $startcol4 = $startcol3 + (CcShowInstancesPeer::NUM_COLUMNS - CcShowInstancesPeer::NUM_LAZY_LOAD_COLUMNS); + + $criteria->addJoin(CcStampPeer::SHOW_ID, CcShowPeer::ID, $join_behavior); + + $criteria->addJoin(CcStampPeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); + + $stmt = BasePeer::doSelect($criteria, $con); + $results = array(); + + while ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $key1 = CcStampPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcStampPeer::getInstanceFromPool($key1))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj1->hydrate($row, 0, true); // rehydrate + } else { + $cls = CcStampPeer::getOMClass(false); + + $obj1 = new $cls(); + $obj1->hydrate($row); + CcStampPeer::addInstanceToPool($obj1, $key1); + } // if obj1 already loaded + + // Add objects for joined CcShow rows + + $key2 = CcShowPeer::getPrimaryKeyHashFromRow($row, $startcol2); + if ($key2 !== null) { + $obj2 = CcShowPeer::getInstanceFromPool($key2); + if (!$obj2) { + + $cls = CcShowPeer::getOMClass(false); + + $obj2 = new $cls(); + $obj2->hydrate($row, $startcol2); + CcShowPeer::addInstanceToPool($obj2, $key2); + } // if obj2 loaded + + // Add the $obj1 (CcStamp) to the collection in $obj2 (CcShow) + $obj2->addCcStamp($obj1); + } // if joined row not null + + // Add objects for joined CcShowInstances rows + + $key3 = CcShowInstancesPeer::getPrimaryKeyHashFromRow($row, $startcol3); + if ($key3 !== null) { + $obj3 = CcShowInstancesPeer::getInstanceFromPool($key3); + if (!$obj3) { + + $cls = CcShowInstancesPeer::getOMClass(false); + + $obj3 = new $cls(); + $obj3->hydrate($row, $startcol3); + CcShowInstancesPeer::addInstanceToPool($obj3, $key3); + } // if obj3 loaded + + // Add the $obj1 (CcStamp) to the collection in $obj3 (CcShowInstances) + $obj3->addCcStamp($obj1); + } // if joined row not null + + $results[] = $obj1; + } + $stmt->closeCursor(); + return $results; + } + + + /** + * Returns the number of rows matching criteria, joining the related CcShow table + * + * @param Criteria $criteria + * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return int Number of matching rows. + */ + public static function doCountJoinAllExceptCcShow(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + // we're going to modify criteria, so copy it first + $criteria = clone $criteria; + + // We need to set the primary table name, since in the case that there are no WHERE columns + // it will be impossible for the BasePeer::createSelectSql() method to determine which + // tables go into the FROM clause. + $criteria->setPrimaryTableName(CcStampPeer::TABLE_NAME); + + if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->setDistinct(); + } + + if (!$criteria->hasSelectClause()) { + CcStampPeer::addSelectColumns($criteria); + } + + $criteria->clearOrderByColumns(); // ORDER BY should not affect count + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + if ($con === null) { + $con = Propel::getConnection(CcStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $criteria->addJoin(CcStampPeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); + + $stmt = BasePeer::doCount($criteria, $con); + + if ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $count = (int) $row[0]; + } else { + $count = 0; // no rows returned; we infer that means 0 matches. + } + $stmt->closeCursor(); + return $count; + } + + + /** + * Returns the number of rows matching criteria, joining the related CcShowInstances table + * + * @param Criteria $criteria + * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return int Number of matching rows. + */ + public static function doCountJoinAllExceptCcShowInstances(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + // we're going to modify criteria, so copy it first + $criteria = clone $criteria; + + // We need to set the primary table name, since in the case that there are no WHERE columns + // it will be impossible for the BasePeer::createSelectSql() method to determine which + // tables go into the FROM clause. + $criteria->setPrimaryTableName(CcStampPeer::TABLE_NAME); + + if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->setDistinct(); + } + + if (!$criteria->hasSelectClause()) { + CcStampPeer::addSelectColumns($criteria); + } + + $criteria->clearOrderByColumns(); // ORDER BY should not affect count + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + if ($con === null) { + $con = Propel::getConnection(CcStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $criteria->addJoin(CcStampPeer::SHOW_ID, CcShowPeer::ID, $join_behavior); + + $stmt = BasePeer::doCount($criteria, $con); + + if ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $count = (int) $row[0]; + } else { + $count = 0; // no rows returned; we infer that means 0 matches. + } + $stmt->closeCursor(); + return $count; + } + + + /** + * Selects a collection of CcStamp objects pre-filled with all related objects except CcShow. + * + * @param Criteria $criteria + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return array Array of CcStamp objects. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelectJoinAllExceptCcShow(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $criteria = clone $criteria; + + // Set the correct dbName if it has not been overridden + // $criteria->getDbName() will return the same object if not set to another value + // so == check is okay and faster + if ($criteria->getDbName() == Propel::getDefaultDB()) { + $criteria->setDbName(self::DATABASE_NAME); + } + + CcStampPeer::addSelectColumns($criteria); + $startcol2 = (CcStampPeer::NUM_COLUMNS - CcStampPeer::NUM_LAZY_LOAD_COLUMNS); + + CcShowInstancesPeer::addSelectColumns($criteria); + $startcol3 = $startcol2 + (CcShowInstancesPeer::NUM_COLUMNS - CcShowInstancesPeer::NUM_LAZY_LOAD_COLUMNS); + + $criteria->addJoin(CcStampPeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); + + + $stmt = BasePeer::doSelect($criteria, $con); + $results = array(); + + while ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $key1 = CcStampPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcStampPeer::getInstanceFromPool($key1))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj1->hydrate($row, 0, true); // rehydrate + } else { + $cls = CcStampPeer::getOMClass(false); + + $obj1 = new $cls(); + $obj1->hydrate($row); + CcStampPeer::addInstanceToPool($obj1, $key1); + } // if obj1 already loaded + + // Add objects for joined CcShowInstances rows + + $key2 = CcShowInstancesPeer::getPrimaryKeyHashFromRow($row, $startcol2); + if ($key2 !== null) { + $obj2 = CcShowInstancesPeer::getInstanceFromPool($key2); + if (!$obj2) { + + $cls = CcShowInstancesPeer::getOMClass(false); + + $obj2 = new $cls(); + $obj2->hydrate($row, $startcol2); + CcShowInstancesPeer::addInstanceToPool($obj2, $key2); + } // if $obj2 already loaded + + // Add the $obj1 (CcStamp) to the collection in $obj2 (CcShowInstances) + $obj2->addCcStamp($obj1); + + } // if joined row is not null + + $results[] = $obj1; + } + $stmt->closeCursor(); + return $results; + } + + + /** + * Selects a collection of CcStamp objects pre-filled with all related objects except CcShowInstances. + * + * @param Criteria $criteria + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return array Array of CcStamp objects. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelectJoinAllExceptCcShowInstances(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $criteria = clone $criteria; + + // Set the correct dbName if it has not been overridden + // $criteria->getDbName() will return the same object if not set to another value + // so == check is okay and faster + if ($criteria->getDbName() == Propel::getDefaultDB()) { + $criteria->setDbName(self::DATABASE_NAME); + } + + CcStampPeer::addSelectColumns($criteria); + $startcol2 = (CcStampPeer::NUM_COLUMNS - CcStampPeer::NUM_LAZY_LOAD_COLUMNS); + + CcShowPeer::addSelectColumns($criteria); + $startcol3 = $startcol2 + (CcShowPeer::NUM_COLUMNS - CcShowPeer::NUM_LAZY_LOAD_COLUMNS); + + $criteria->addJoin(CcStampPeer::SHOW_ID, CcShowPeer::ID, $join_behavior); + + + $stmt = BasePeer::doSelect($criteria, $con); + $results = array(); + + while ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $key1 = CcStampPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcStampPeer::getInstanceFromPool($key1))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj1->hydrate($row, 0, true); // rehydrate + } else { + $cls = CcStampPeer::getOMClass(false); + + $obj1 = new $cls(); + $obj1->hydrate($row); + CcStampPeer::addInstanceToPool($obj1, $key1); + } // if obj1 already loaded + + // Add objects for joined CcShow rows + + $key2 = CcShowPeer::getPrimaryKeyHashFromRow($row, $startcol2); + if ($key2 !== null) { + $obj2 = CcShowPeer::getInstanceFromPool($key2); + if (!$obj2) { + + $cls = CcShowPeer::getOMClass(false); + + $obj2 = new $cls(); + $obj2->hydrate($row, $startcol2); + CcShowPeer::addInstanceToPool($obj2, $key2); + } // if $obj2 already loaded + + // Add the $obj1 (CcStamp) to the collection in $obj2 (CcShow) + $obj2->addCcStamp($obj1); + + } // if joined row is not null + + $results[] = $obj1; + } + $stmt->closeCursor(); + return $results; + } + + /** + * Returns the TableMap related to this peer. + * This method is not needed for general use but a specific application could have a need. + * @return TableMap + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function getTableMap() + { + return Propel::getDatabaseMap(self::DATABASE_NAME)->getTable(self::TABLE_NAME); + } + + /** + * Add a TableMap instance to the database for this peer class. + */ + public static function buildTableMap() + { + $dbMap = Propel::getDatabaseMap(BaseCcStampPeer::DATABASE_NAME); + if (!$dbMap->hasTable(BaseCcStampPeer::TABLE_NAME)) + { + $dbMap->addTableObject(new CcStampTableMap()); + } + } + + /** + * The class that the Peer will make instances of. + * + * If $withPrefix is true, the returned path + * uses a dot-path notation which is tranalted into a path + * relative to a location on the PHP include_path. + * (e.g. path.to.MyClass -> 'path/to/MyClass.php') + * + * @param boolean $withPrefix Whether or not to return the path with the class name + * @return string path.to.ClassName + */ + public static function getOMClass($withPrefix = true) + { + return $withPrefix ? CcStampPeer::CLASS_DEFAULT : CcStampPeer::OM_CLASS; + } + + /** + * Method perform an INSERT on the database, given a CcStamp or Criteria object. + * + * @param mixed $values Criteria or CcStamp object containing data that is used to create the INSERT statement. + * @param PropelPDO $con the PropelPDO connection to use + * @return mixed The new primary key. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doInsert($values, PropelPDO $con = null) + { + if ($con === null) { + $con = Propel::getConnection(CcStampPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + } + + if ($values instanceof Criteria) { + $criteria = clone $values; // rename for clarity + } else { + $criteria = $values->buildCriteria(); // build Criteria from CcStamp object + } + + if ($criteria->containsKey(CcStampPeer::ID) && $criteria->keyContainsValue(CcStampPeer::ID) ) { + throw new PropelException('Cannot insert a value for auto-increment primary key ('.CcStampPeer::ID.')'); + } + + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + try { + // use transaction because $criteria could contain info + // for more than one table (I guess, conceivably) + $con->beginTransaction(); + $pk = BasePeer::doInsert($criteria, $con); + $con->commit(); + } catch(PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $pk; + } + + /** + * Method perform an UPDATE on the database, given a CcStamp or Criteria object. + * + * @param mixed $values Criteria or CcStamp object containing data that is used to create the UPDATE statement. + * @param PropelPDO $con The connection to use (specify PropelPDO connection object to exert more control over transactions). + * @return int The number of affected rows (if supported by underlying database driver). + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doUpdate($values, PropelPDO $con = null) + { + if ($con === null) { + $con = Propel::getConnection(CcStampPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + } + + $selectCriteria = new Criteria(self::DATABASE_NAME); + + if ($values instanceof Criteria) { + $criteria = clone $values; // rename for clarity + + $comparison = $criteria->getComparison(CcStampPeer::ID); + $value = $criteria->remove(CcStampPeer::ID); + if ($value) { + $selectCriteria->add(CcStampPeer::ID, $value, $comparison); + } else { + $selectCriteria->setPrimaryTableName(CcStampPeer::TABLE_NAME); + } + + } else { // $values is CcStamp object + $criteria = $values->buildCriteria(); // gets full criteria + $selectCriteria = $values->buildPkeyCriteria(); // gets criteria w/ primary key(s) + } + + // set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + return BasePeer::doUpdate($selectCriteria, $criteria, $con); + } + + /** + * Method to DELETE all rows from the cc_stamp table. + * + * @return int The number of affected rows (if supported by underlying database driver). + */ + public static function doDeleteAll($con = null) + { + if ($con === null) { + $con = Propel::getConnection(CcStampPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + } + $affectedRows = 0; // initialize var to track total num of affected rows + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->beginTransaction(); + $affectedRows += BasePeer::doDeleteAll(CcStampPeer::TABLE_NAME, $con, CcStampPeer::DATABASE_NAME); + // Because this db requires some delete cascade/set null emulation, we have to + // clear the cached instance *after* the emulation has happened (since + // instances get re-added by the select statement contained therein). + CcStampPeer::clearInstancePool(); + CcStampPeer::clearRelatedInstancePool(); + $con->commit(); + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Method perform a DELETE on the database, given a CcStamp or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or CcStamp object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param PropelPDO $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows + * if supported by native driver or if emulated using Propel. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doDelete($values, PropelPDO $con = null) + { + if ($con === null) { + $con = Propel::getConnection(CcStampPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + } + + if ($values instanceof Criteria) { + // invalidate the cache for all objects of this type, since we have no + // way of knowing (without running a query) what objects should be invalidated + // from the cache based on this Criteria. + CcStampPeer::clearInstancePool(); + // rename for clarity + $criteria = clone $values; + } elseif ($values instanceof CcStamp) { // it's a model object + // invalidate the cache for this single object + CcStampPeer::removeInstanceFromPool($values); + // create criteria based on pk values + $criteria = $values->buildPkeyCriteria(); + } else { // it's a primary key, or an array of pks + $criteria = new Criteria(self::DATABASE_NAME); + $criteria->add(CcStampPeer::ID, (array) $values, Criteria::IN); + // invalidate the cache for this object(s) + foreach ((array) $values as $singleval) { + CcStampPeer::removeInstanceFromPool($singleval); + } + } + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + $affectedRows = 0; // initialize var to track total num of affected rows + + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->beginTransaction(); + + $affectedRows += BasePeer::doDelete($criteria, $con); + CcStampPeer::clearRelatedInstancePool(); + $con->commit(); + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Validates all modified columns of given CcStamp object. + * If parameter $columns is either a single column name or an array of column names + * than only those columns are validated. + * + * NOTICE: This does not apply to primary or foreign keys for now. + * + * @param CcStamp $obj The object to validate. + * @param mixed $cols Column name or array of column names. + * + * @return mixed TRUE if all columns are valid or the error message of the first invalid column. + */ + public static function doValidate(CcStamp $obj, $cols = null) + { + $columns = array(); + + if ($cols) { + $dbMap = Propel::getDatabaseMap(CcStampPeer::DATABASE_NAME); + $tableMap = $dbMap->getTable(CcStampPeer::TABLE_NAME); + + if (! is_array($cols)) { + $cols = array($cols); + } + + foreach ($cols as $colName) { + if ($tableMap->containsColumn($colName)) { + $get = 'get' . $tableMap->getColumn($colName)->getPhpName(); + $columns[$colName] = $obj->$get(); + } + } + } else { + + } + + return BasePeer::doValidate(CcStampPeer::DATABASE_NAME, CcStampPeer::TABLE_NAME, $columns); + } + + /** + * Retrieve a single object by pkey. + * + * @param int $pk the primary key. + * @param PropelPDO $con the connection to use + * @return CcStamp + */ + public static function retrieveByPK($pk, PropelPDO $con = null) + { + + if (null !== ($obj = CcStampPeer::getInstanceFromPool((string) $pk))) { + return $obj; + } + + if ($con === null) { + $con = Propel::getConnection(CcStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $criteria = new Criteria(CcStampPeer::DATABASE_NAME); + $criteria->add(CcStampPeer::ID, $pk); + + $v = CcStampPeer::doSelect($criteria, $con); + + return !empty($v) > 0 ? $v[0] : null; + } + + /** + * Retrieve multiple objects by pkey. + * + * @param array $pks List of primary keys + * @param PropelPDO $con the connection to use + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function retrieveByPKs($pks, PropelPDO $con = null) + { + if ($con === null) { + $con = Propel::getConnection(CcStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $objs = null; + if (empty($pks)) { + $objs = array(); + } else { + $criteria = new Criteria(CcStampPeer::DATABASE_NAME); + $criteria->add(CcStampPeer::ID, $pks, Criteria::IN); + $objs = CcStampPeer::doSelect($criteria, $con); + } + return $objs; + } + +} // BaseCcStampPeer + +// This is the static code needed to register the TableMap for this table with the main Propel class. +// +BaseCcStampPeer::buildTableMap(); + diff --git a/airtime_mvc/application/models/airtime/om/BaseCcStampQuery.php b/airtime_mvc/application/models/airtime/om/BaseCcStampQuery.php new file mode 100644 index 000000000..ef2053a5a --- /dev/null +++ b/airtime_mvc/application/models/airtime/om/BaseCcStampQuery.php @@ -0,0 +1,439 @@ +setModelAlias($modelAlias); + } + if ($criteria instanceof Criteria) { + $query->mergeWith($criteria); + } + return $query; + } + + /** + * Find object by primary key + * Use instance pooling to avoid a database query if the object exists + * + * $obj = $c->findPk(12, $con); + * + * @param mixed $key Primary key to use for the query + * @param PropelPDO $con an optional connection object + * + * @return CcStamp|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ((null !== ($obj = CcStampPeer::getInstanceFromPool((string) $key))) && $this->getFormatter()->isObjectFormatter()) { + // the object is alredy in the instance pool + return $obj; + } else { + // the object has not been requested yet, or the formatter is not an object formatter + $criteria = $this->isKeepQuery() ? clone $this : $this; + $stmt = $criteria + ->filterByPrimaryKey($key) + ->getSelectStatement($con); + return $criteria->getFormatter()->init($criteria)->formatOne($stmt); + } + } + + /** + * Find objects by primary key + * + * $objs = $c->findPks(array(12, 56, 832), $con); + * + * @param array $keys Primary keys to use for the query + * @param PropelPDO $con an optional connection object + * + * @return PropelObjectCollection|array|mixed the list of results, formatted by the current formatter + */ + public function findPks($keys, $con = null) + { + $criteria = $this->isKeepQuery() ? clone $this : $this; + return $this + ->filterByPrimaryKeys($keys) + ->find($con); + } + + /** + * Filter the query by primary key + * + * @param mixed $key Primary key to use for the query + * + * @return CcStampQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + return $this->addUsingAlias(CcStampPeer::ID, $key, Criteria::EQUAL); + } + + /** + * Filter the query by a list of primary keys + * + * @param array $keys The list of primary key to use for the query + * + * @return CcStampQuery The current query, for fluid interface + */ + public function filterByPrimaryKeys($keys) + { + return $this->addUsingAlias(CcStampPeer::ID, $keys, Criteria::IN); + } + + /** + * Filter the query on the id column + * + * @param int|array $dbId 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 CcStampQuery The current query, for fluid interface + */ + public function filterByDbId($dbId = null, $comparison = null) + { + if (is_array($dbId) && null === $comparison) { + $comparison = Criteria::IN; + } + return $this->addUsingAlias(CcStampPeer::ID, $dbId, $comparison); + } + + /** + * Filter the query on the show_id column + * + * @param int|array $dbShowId 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 CcStampQuery The current query, for fluid interface + */ + public function filterByDbShowId($dbShowId = null, $comparison = null) + { + if (is_array($dbShowId)) { + $useMinMax = false; + if (isset($dbShowId['min'])) { + $this->addUsingAlias(CcStampPeer::SHOW_ID, $dbShowId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbShowId['max'])) { + $this->addUsingAlias(CcStampPeer::SHOW_ID, $dbShowId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcStampPeer::SHOW_ID, $dbShowId, $comparison); + } + + /** + * Filter the query on the instance_id column + * + * @param int|array $dbInstanceId 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 CcStampQuery The current query, for fluid interface + */ + public function filterByDbInstanceId($dbInstanceId = null, $comparison = null) + { + if (is_array($dbInstanceId)) { + $useMinMax = false; + if (isset($dbInstanceId['min'])) { + $this->addUsingAlias(CcStampPeer::INSTANCE_ID, $dbInstanceId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbInstanceId['max'])) { + $this->addUsingAlias(CcStampPeer::INSTANCE_ID, $dbInstanceId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcStampPeer::INSTANCE_ID, $dbInstanceId, $comparison); + } + + /** + * Filter the query by a related CcShow object + * + * @param CcShow $ccShow the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return CcStampQuery The current query, for fluid interface + */ + public function filterByCcShow($ccShow, $comparison = null) + { + return $this + ->addUsingAlias(CcStampPeer::SHOW_ID, $ccShow->getDbId(), $comparison); + } + + /** + * Adds a JOIN clause to the query using the CcShow relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return CcStampQuery The current query, for fluid interface + */ + public function joinCcShow($relationAlias = '', $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('CcShow'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'CcShow'); + } + + return $this; + } + + /** + * Use the CcShow relation CcShow object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return CcShowQuery A secondary query class using the current class as primary query + */ + public function useCcShowQuery($relationAlias = '', $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinCcShow($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'CcShow', 'CcShowQuery'); + } + + /** + * Filter the query by a related CcShowInstances object + * + * @param CcShowInstances $ccShowInstances the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return CcStampQuery The current query, for fluid interface + */ + public function filterByCcShowInstances($ccShowInstances, $comparison = null) + { + return $this + ->addUsingAlias(CcStampPeer::INSTANCE_ID, $ccShowInstances->getDbId(), $comparison); + } + + /** + * Adds a JOIN clause to the query using the CcShowInstances relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return CcStampQuery The current query, for fluid interface + */ + public function joinCcShowInstances($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('CcShowInstances'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'CcShowInstances'); + } + + return $this; + } + + /** + * Use the CcShowInstances relation CcShowInstances object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return CcShowInstancesQuery A secondary query class using the current class as primary query + */ + public function useCcShowInstancesQuery($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + { + return $this + ->joinCcShowInstances($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'CcShowInstances', 'CcShowInstancesQuery'); + } + + /** + * Filter the query by a related CcStampContents object + * + * @param CcStampContents $ccStampContents the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return CcStampQuery The current query, for fluid interface + */ + public function filterByCcStampContents($ccStampContents, $comparison = null) + { + return $this + ->addUsingAlias(CcStampPeer::ID, $ccStampContents->getDbStampId(), $comparison); + } + + /** + * Adds a JOIN clause to the query using the CcStampContents relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return CcStampQuery The current query, for fluid interface + */ + public function joinCcStampContents($relationAlias = '', $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('CcStampContents'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'CcStampContents'); + } + + return $this; + } + + /** + * Use the CcStampContents relation CcStampContents object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return CcStampContentsQuery A secondary query class using the current class as primary query + */ + public function useCcStampContentsQuery($relationAlias = '', $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinCcStampContents($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'CcStampContents', 'CcStampContentsQuery'); + } + + /** + * Exclude object from result + * + * @param CcStamp $ccStamp Object to remove from the list of results + * + * @return CcStampQuery The current query, for fluid interface + */ + public function prune($ccStamp = null) + { + if ($ccStamp) { + $this->addUsingAlias(CcStampPeer::ID, $ccStamp->getDbId(), Criteria::NOT_EQUAL); + } + + return $this; + } + +} // BaseCcStampQuery From 9b2fb3bece971bb6ada653a08c82f72ece5fcfb3 Mon Sep 17 00:00:00 2001 From: denise Date: Tue, 9 Apr 2013 15:55:18 -0400 Subject: [PATCH 48/73] CC-4961: Show linking --- .../application/models/airtime/CcShow.php | 5 + .../models/airtime/CcShowStamp.php | 18 - .../models/airtime/CcShowStampPeer.php | 18 - .../models/airtime/CcShowStampQuery.php | 18 - .../models/airtime/map/CcScheduleTableMap.php | 1 + .../airtime/map/CcStampContentsTableMap.php | 2 +- .../models/airtime/map/CcStampTableMap.php | 1 + .../models/airtime/om/BaseCcSchedule.php | 56 +- .../models/airtime/om/BaseCcSchedulePeer.php | 31 +- .../models/airtime/om/BaseCcScheduleQuery.php | 35 + .../models/airtime/om/BaseCcShowStamp.php | 1783 ---------- .../models/airtime/om/BaseCcShowStampPeer.php | 3095 ----------------- .../airtime/om/BaseCcShowStampQuery.php | 948 ----- .../models/airtime/om/BaseCcStamp.php | 50 +- .../models/airtime/om/BaseCcStampPeer.php | 31 +- .../models/airtime/om/BaseCcStampQuery.php | 21 + .../application/services/SchedulerService.php | 282 +- airtime_mvc/build/schema.xml | 4 +- airtime_mvc/build/sql/schema.sql | 4 +- 19 files changed, 485 insertions(+), 5918 deletions(-) delete mode 100644 airtime_mvc/application/models/airtime/CcShowStamp.php delete mode 100644 airtime_mvc/application/models/airtime/CcShowStampPeer.php delete mode 100644 airtime_mvc/application/models/airtime/CcShowStampQuery.php delete mode 100644 airtime_mvc/application/models/airtime/om/BaseCcShowStamp.php delete mode 100644 airtime_mvc/application/models/airtime/om/BaseCcShowStampPeer.php delete mode 100644 airtime_mvc/application/models/airtime/om/BaseCcShowStampQuery.php diff --git a/airtime_mvc/application/models/airtime/CcShow.php b/airtime_mvc/application/models/airtime/CcShow.php index 59db84c72..be055b374 100644 --- a/airtime_mvc/application/models/airtime/CcShow.php +++ b/airtime_mvc/application/models/airtime/CcShow.php @@ -128,4 +128,9 @@ class CcShow extends BaseCcShow { ->orderByDbStarts() ->find(); } + + public function isLinked() + { + return $this->getDbLinked(); + } } // CcShow diff --git a/airtime_mvc/application/models/airtime/CcShowStamp.php b/airtime_mvc/application/models/airtime/CcShowStamp.php deleted file mode 100644 index 19ced4a05..000000000 --- a/airtime_mvc/application/models/airtime/CcShowStamp.php +++ /dev/null @@ -1,18 +0,0 @@ -addColumn('PLAYOUT_STATUS', 'DbPlayoutStatus', 'SMALLINT', true, null, 1); $this->addColumn('BROADCASTED', 'DbBroadcasted', 'SMALLINT', true, null, 0); $this->addColumn('STAMP_ID', 'DbStampId', 'INTEGER', true, null, 0); + $this->addColumn('STAMP_CONTENT_ID', 'DbStampContentId', 'INTEGER', true, null, 0); // validators } // initialize() diff --git a/airtime_mvc/application/models/airtime/map/CcStampContentsTableMap.php b/airtime_mvc/application/models/airtime/map/CcStampContentsTableMap.php index b4d62edcf..26811c472 100644 --- a/airtime_mvc/application/models/airtime/map/CcStampContentsTableMap.php +++ b/airtime_mvc/application/models/airtime/map/CcStampContentsTableMap.php @@ -44,7 +44,7 @@ class CcStampContentsTableMap extends TableMap { $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('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'); diff --git a/airtime_mvc/application/models/airtime/map/CcStampTableMap.php b/airtime_mvc/application/models/airtime/map/CcStampTableMap.php index 6574cb410..a353134ea 100644 --- a/airtime_mvc/application/models/airtime/map/CcStampTableMap.php +++ b/airtime_mvc/application/models/airtime/map/CcStampTableMap.php @@ -41,6 +41,7 @@ class CcStampTableMap extends TableMap { $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() diff --git a/airtime_mvc/application/models/airtime/om/BaseCcSchedule.php b/airtime_mvc/application/models/airtime/om/BaseCcSchedule.php index ddb931074..49a28d79b 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcSchedule.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcSchedule.php @@ -121,6 +121,13 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent */ protected $stamp_id; + /** + * The value for the stamp_content_id field. + * Note: this column has a database default value of: 0 + * @var int + */ + protected $stamp_content_id; + /** * @var CcShowInstances */ @@ -170,6 +177,7 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent $this->playout_status = 1; $this->broadcasted = 0; $this->stamp_id = 0; + $this->stamp_content_id = 0; } /** @@ -424,6 +432,16 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent return $this->stamp_id; } + /** + * Get the [stamp_content_id] column value. + * + * @return int + */ + public function getDbStampContentId() + { + return $this->stamp_content_id; + } + /** * Set the value of [id] column. * @@ -854,6 +872,26 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent return $this; } // setDbStampId() + /** + * Set the value of [stamp_content_id] column. + * + * @param int $v new value + * @return CcSchedule The current object (for fluent API support) + */ + public function setDbStampContentId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->stamp_content_id !== $v || $this->isNew()) { + $this->stamp_content_id = $v; + $this->modifiedColumns[] = CcSchedulePeer::STAMP_CONTENT_ID; + } + + return $this; + } // setDbStampContentId() + /** * Indicates whether the columns in this object are only set to default values. * @@ -892,6 +930,10 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent return false; } + if ($this->stamp_content_id !== 0) { + return false; + } + // otherwise, everything was equal, so return TRUE return true; } // hasOnlyDefaultValues() @@ -929,6 +971,7 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent $this->playout_status = ($row[$startcol + 12] !== null) ? (int) $row[$startcol + 12] : null; $this->broadcasted = ($row[$startcol + 13] !== null) ? (int) $row[$startcol + 13] : null; $this->stamp_id = ($row[$startcol + 14] !== null) ? (int) $row[$startcol + 14] : null; + $this->stamp_content_id = ($row[$startcol + 15] !== null) ? (int) $row[$startcol + 15] : null; $this->resetModified(); $this->setNew(false); @@ -937,7 +980,7 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent $this->ensureConsistency(); } - return $startcol + 15; // 15 = CcSchedulePeer::NUM_COLUMNS - CcSchedulePeer::NUM_LAZY_LOAD_COLUMNS). + return $startcol + 16; // 16 = CcSchedulePeer::NUM_COLUMNS - CcSchedulePeer::NUM_LAZY_LOAD_COLUMNS). } catch (Exception $e) { throw new PropelException("Error populating CcSchedule object", $e); @@ -1361,6 +1404,9 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent case 14: return $this->getDbStampId(); break; + case 15: + return $this->getDbStampContentId(); + break; default: return null; break; @@ -1400,6 +1446,7 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent $keys[12] => $this->getDbPlayoutStatus(), $keys[13] => $this->getDbBroadcasted(), $keys[14] => $this->getDbStampId(), + $keys[15] => $this->getDbStampContentId(), ); if ($includeForeignObjects) { if (null !== $this->aCcShowInstances) { @@ -1487,6 +1534,9 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent case 14: $this->setDbStampId($value); break; + case 15: + $this->setDbStampContentId($value); + break; } // switch() } @@ -1526,6 +1576,7 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent 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->setDbStampId($arr[$keys[14]]); + if (array_key_exists($keys[15], $arr)) $this->setDbStampContentId($arr[$keys[15]]); } /** @@ -1552,6 +1603,7 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent 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::STAMP_ID)) $criteria->add(CcSchedulePeer::STAMP_ID, $this->stamp_id); + if ($this->isColumnModified(CcSchedulePeer::STAMP_CONTENT_ID)) $criteria->add(CcSchedulePeer::STAMP_CONTENT_ID, $this->stamp_content_id); return $criteria; } @@ -1627,6 +1679,7 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent $copyObj->setDbPlayoutStatus($this->playout_status); $copyObj->setDbBroadcasted($this->broadcasted); $copyObj->setDbStampId($this->stamp_id); + $copyObj->setDbStampContentId($this->stamp_content_id); if ($deepCopy) { // important: temporarily setNew(false) because this affects the behavior of @@ -1960,6 +2013,7 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent $this->playout_status = null; $this->broadcasted = null; $this->stamp_id = null; + $this->stamp_content_id = 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 8f4551a23..f14cc6910 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 = 15; + const NUM_COLUMNS = 16; /** The number of lazy-loaded columns. */ const NUM_LAZY_LOAD_COLUMNS = 0; @@ -76,6 +76,9 @@ abstract class BaseCcSchedulePeer { /** the column name for the STAMP_ID field */ const STAMP_ID = 'cc_schedule.STAMP_ID'; + /** the column name for the STAMP_CONTENT_ID field */ + const STAMP_CONTENT_ID = 'cc_schedule.STAMP_CONTENT_ID'; + /** * 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 @@ -92,12 +95,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', 'DbStampId', ), - BasePeer::TYPE_STUDLYPHPNAME => array ('dbId', 'dbStarts', 'dbEnds', 'dbFileId', 'dbStreamId', 'dbClipLength', 'dbFadeIn', 'dbFadeOut', 'dbCueIn', 'dbCueOut', 'dbMediaItemPlayed', 'dbInstanceId', 'dbPlayoutStatus', 'dbBroadcasted', 'dbStampId', ), - 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::STAMP_ID, ), - 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', 'STAMP_ID', ), - 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', 'stamp_id', ), - BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, ) + BasePeer::TYPE_PHPNAME => array ('DbId', 'DbStarts', 'DbEnds', 'DbFileId', 'DbStreamId', 'DbClipLength', 'DbFadeIn', 'DbFadeOut', 'DbCueIn', 'DbCueOut', 'DbMediaItemPlayed', 'DbInstanceId', 'DbPlayoutStatus', 'DbBroadcasted', 'DbStampId', 'DbStampContentId', ), + BasePeer::TYPE_STUDLYPHPNAME => array ('dbId', 'dbStarts', 'dbEnds', 'dbFileId', 'dbStreamId', 'dbClipLength', 'dbFadeIn', 'dbFadeOut', 'dbCueIn', 'dbCueOut', 'dbMediaItemPlayed', 'dbInstanceId', 'dbPlayoutStatus', 'dbBroadcasted', 'dbStampId', 'dbStampContentId', ), + 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::STAMP_ID, self::STAMP_CONTENT_ID, ), + 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', 'STAMP_ID', 'STAMP_CONTENT_ID', ), + 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', 'stamp_id', 'stamp_content_id', ), + BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, ) ); /** @@ -107,12 +110,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, 'DbStampId' => 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, 'dbStampId' => 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::STAMP_ID => 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, 'STAMP_ID' => 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, 'stamp_id' => 14, ), - BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, ) + 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, 'DbStampId' => 14, 'DbStampContentId' => 15, ), + 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, 'dbStampId' => 14, 'dbStampContentId' => 15, ), + 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::STAMP_ID => 14, self::STAMP_CONTENT_ID => 15, ), + 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, 'STAMP_ID' => 14, 'STAMP_CONTENT_ID' => 15, ), + 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, 'stamp_id' => 14, 'stamp_content_id' => 15, ), + BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, ) ); /** @@ -199,6 +202,7 @@ abstract class BaseCcSchedulePeer { $criteria->addSelectColumn(CcSchedulePeer::PLAYOUT_STATUS); $criteria->addSelectColumn(CcSchedulePeer::BROADCASTED); $criteria->addSelectColumn(CcSchedulePeer::STAMP_ID); + $criteria->addSelectColumn(CcSchedulePeer::STAMP_CONTENT_ID); } else { $criteria->addSelectColumn($alias . '.ID'); $criteria->addSelectColumn($alias . '.STARTS'); @@ -215,6 +219,7 @@ abstract class BaseCcSchedulePeer { $criteria->addSelectColumn($alias . '.PLAYOUT_STATUS'); $criteria->addSelectColumn($alias . '.BROADCASTED'); $criteria->addSelectColumn($alias . '.STAMP_ID'); + $criteria->addSelectColumn($alias . '.STAMP_CONTENT_ID'); } } diff --git a/airtime_mvc/application/models/airtime/om/BaseCcScheduleQuery.php b/airtime_mvc/application/models/airtime/om/BaseCcScheduleQuery.php index 9076adc8b..f99c36476 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcScheduleQuery.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcScheduleQuery.php @@ -21,6 +21,7 @@ * @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 orderByDbStampId($order = Criteria::ASC) Order by the stamp_id column + * @method CcScheduleQuery orderByDbStampContentId($order = Criteria::ASC) Order by the stamp_content_id column * * @method CcScheduleQuery groupByDbId() Group by the id column * @method CcScheduleQuery groupByDbStarts() Group by the starts column @@ -37,6 +38,7 @@ * @method CcScheduleQuery groupByDbPlayoutStatus() Group by the playout_status column * @method CcScheduleQuery groupByDbBroadcasted() Group by the broadcasted column * @method CcScheduleQuery groupByDbStampId() Group by the stamp_id column + * @method CcScheduleQuery groupByDbStampContentId() Group by the stamp_content_id 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 @@ -76,6 +78,7 @@ * @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 findOneByDbStampId(int $stamp_id) Return the first CcSchedule filtered by the stamp_id column + * @method CcSchedule findOneByDbStampContentId(int $stamp_content_id) Return the first CcSchedule filtered by the stamp_content_id 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 @@ -92,6 +95,7 @@ * @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 findByDbStampId(int $stamp_id) Return CcSchedule objects filtered by the stamp_id column + * @method array findByDbStampContentId(int $stamp_content_id) Return CcSchedule objects filtered by the stamp_content_id column * * @package propel.generator.airtime.om */ @@ -611,6 +615,37 @@ abstract class BaseCcScheduleQuery extends ModelCriteria return $this->addUsingAlias(CcSchedulePeer::STAMP_ID, $dbStampId, $comparison); } + /** + * Filter the query on the stamp_content_id column + * + * @param int|array $dbStampContentId 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 filterByDbStampContentId($dbStampContentId = null, $comparison = null) + { + if (is_array($dbStampContentId)) { + $useMinMax = false; + if (isset($dbStampContentId['min'])) { + $this->addUsingAlias(CcSchedulePeer::STAMP_CONTENT_ID, $dbStampContentId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbStampContentId['max'])) { + $this->addUsingAlias(CcSchedulePeer::STAMP_CONTENT_ID, $dbStampContentId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcSchedulePeer::STAMP_CONTENT_ID, $dbStampContentId, $comparison); + } + /** * Filter the query by a related CcShowInstances object * diff --git a/airtime_mvc/application/models/airtime/om/BaseCcShowStamp.php b/airtime_mvc/application/models/airtime/om/BaseCcShowStamp.php deleted file mode 100644 index c4e55cf59..000000000 --- a/airtime_mvc/application/models/airtime/om/BaseCcShowStamp.php +++ /dev/null @@ -1,1783 +0,0 @@ -clip_length = '00:00:00'; - $this->cue_in = '00:00:00'; - $this->cue_out = '00:00:00'; - $this->fade_in = '00:00:00'; - $this->fade_out = '00:00:00'; - } - - /** - * Initializes internal state of BaseCcShowStamp object. - * @see applyDefaults() - */ - public function __construct() - { - parent::__construct(); - $this->applyDefaultValues(); - } - - /** - * Get the [id] column value. - * - * @return int - */ - public function getDbId() - { - return $this->id; - } - - /** - * Get the [show_id] column value. - * - * @return int - */ - public function getDbShowId() - { - return $this->show_id; - } - - /** - * Get the [instance_id] column value. - * - * @return int - */ - public function getDbInstanceId() - { - return $this->instance_id; - } - - /** - * Get the [file_id] column value. - * - * @return int - */ - public function getDbFileId() - { - return $this->file_id; - } - - /** - * Get the [stream_id] column value. - * - * @return int - */ - public function getDbStreamId() - { - return $this->stream_id; - } - - /** - * Get the [block_id] column value. - * - * @return int - */ - public function getDbBlockId() - { - return $this->block_id; - } - - /** - * Get the [playlist_id] column value. - * - * @return int - */ - public function getDbPlaylistId() - { - return $this->playlist_id; - } - - /** - * Get the [position] column value. - * - * @return int - */ - public function getDbPosition() - { - return $this->position; - } - - /** - * Get the [clip_length] column value. - * - * @return string - */ - public function getDbClipLength() - { - return $this->clip_length; - } - - /** - * Get the [cue_in] column value. - * - * @return string - */ - public function getDbCueIn() - { - return $this->cue_in; - } - - /** - * Get the [cue_out] column value. - * - * @return string - */ - public function getDbCueOut() - { - return $this->cue_out; - } - - /** - * Get the [fade_in] column value. - * - * @return string - */ - public function getDbFadeIn() - { - return $this->fade_in; - } - - /** - * Get the [fade_out] column value. - * - * @return string - */ - public function getDbFadeOut() - { - return $this->fade_out; - } - - /** - * Set the value of [id] column. - * - * @param int $v new value - * @return CcShowStamp The current object (for fluent API support) - */ - public function setDbId($v) - { - if ($v !== null) { - $v = (int) $v; - } - - if ($this->id !== $v) { - $this->id = $v; - $this->modifiedColumns[] = CcShowStampPeer::ID; - } - - return $this; - } // setDbId() - - /** - * Set the value of [show_id] column. - * - * @param int $v new value - * @return CcShowStamp The current object (for fluent API support) - */ - public function setDbShowId($v) - { - if ($v !== null) { - $v = (int) $v; - } - - if ($this->show_id !== $v) { - $this->show_id = $v; - $this->modifiedColumns[] = CcShowStampPeer::SHOW_ID; - } - - if ($this->aCcShow !== null && $this->aCcShow->getDbId() !== $v) { - $this->aCcShow = null; - } - - return $this; - } // setDbShowId() - - /** - * Set the value of [instance_id] column. - * - * @param int $v new value - * @return CcShowStamp The current object (for fluent API support) - */ - public function setDbInstanceId($v) - { - if ($v !== null) { - $v = (int) $v; - } - - if ($this->instance_id !== $v) { - $this->instance_id = $v; - $this->modifiedColumns[] = CcShowStampPeer::INSTANCE_ID; - } - - if ($this->aCcShowInstances !== null && $this->aCcShowInstances->getDbId() !== $v) { - $this->aCcShowInstances = null; - } - - return $this; - } // setDbInstanceId() - - /** - * Set the value of [file_id] column. - * - * @param int $v new value - * @return CcShowStamp The current object (for fluent API support) - */ - public function setDbFileId($v) - { - if ($v !== null) { - $v = (int) $v; - } - - if ($this->file_id !== $v) { - $this->file_id = $v; - $this->modifiedColumns[] = CcShowStampPeer::FILE_ID; - } - - if ($this->aCcFiles !== null && $this->aCcFiles->getDbId() !== $v) { - $this->aCcFiles = null; - } - - return $this; - } // setDbFileId() - - /** - * Set the value of [stream_id] column. - * - * @param int $v new value - * @return CcShowStamp The current object (for fluent API support) - */ - public function setDbStreamId($v) - { - if ($v !== null) { - $v = (int) $v; - } - - if ($this->stream_id !== $v) { - $this->stream_id = $v; - $this->modifiedColumns[] = CcShowStampPeer::STREAM_ID; - } - - if ($this->aCcWebstream !== null && $this->aCcWebstream->getDbId() !== $v) { - $this->aCcWebstream = null; - } - - return $this; - } // setDbStreamId() - - /** - * Set the value of [block_id] column. - * - * @param int $v new value - * @return CcShowStamp The current object (for fluent API support) - */ - public function setDbBlockId($v) - { - if ($v !== null) { - $v = (int) $v; - } - - if ($this->block_id !== $v) { - $this->block_id = $v; - $this->modifiedColumns[] = CcShowStampPeer::BLOCK_ID; - } - - if ($this->aCcBlock !== null && $this->aCcBlock->getDbId() !== $v) { - $this->aCcBlock = null; - } - - return $this; - } // setDbBlockId() - - /** - * Set the value of [playlist_id] column. - * - * @param int $v new value - * @return CcShowStamp The current object (for fluent API support) - */ - public function setDbPlaylistId($v) - { - if ($v !== null) { - $v = (int) $v; - } - - if ($this->playlist_id !== $v) { - $this->playlist_id = $v; - $this->modifiedColumns[] = CcShowStampPeer::PLAYLIST_ID; - } - - if ($this->aCcPlaylist !== null && $this->aCcPlaylist->getDbId() !== $v) { - $this->aCcPlaylist = null; - } - - return $this; - } // setDbPlaylistId() - - /** - * Set the value of [position] column. - * - * @param int $v new value - * @return CcShowStamp The current object (for fluent API support) - */ - public function setDbPosition($v) - { - if ($v !== null) { - $v = (int) $v; - } - - if ($this->position !== $v) { - $this->position = $v; - $this->modifiedColumns[] = CcShowStampPeer::POSITION; - } - - return $this; - } // setDbPosition() - - /** - * Set the value of [clip_length] column. - * - * @param string $v new value - * @return CcShowStamp The current object (for fluent API support) - */ - public function setDbClipLength($v) - { - if ($v !== null) { - $v = (string) $v; - } - - if ($this->clip_length !== $v || $this->isNew()) { - $this->clip_length = $v; - $this->modifiedColumns[] = CcShowStampPeer::CLIP_LENGTH; - } - - return $this; - } // setDbClipLength() - - /** - * Set the value of [cue_in] column. - * - * @param string $v new value - * @return CcShowStamp The current object (for fluent API support) - */ - public function setDbCueIn($v) - { - if ($v !== null) { - $v = (string) $v; - } - - if ($this->cue_in !== $v || $this->isNew()) { - $this->cue_in = $v; - $this->modifiedColumns[] = CcShowStampPeer::CUE_IN; - } - - return $this; - } // setDbCueIn() - - /** - * Set the value of [cue_out] column. - * - * @param string $v new value - * @return CcShowStamp The current object (for fluent API support) - */ - public function setDbCueOut($v) - { - if ($v !== null) { - $v = (string) $v; - } - - if ($this->cue_out !== $v || $this->isNew()) { - $this->cue_out = $v; - $this->modifiedColumns[] = CcShowStampPeer::CUE_OUT; - } - - return $this; - } // setDbCueOut() - - /** - * Set the value of [fade_in] column. - * - * @param string $v new value - * @return CcShowStamp The current object (for fluent API support) - */ - public function setDbFadeIn($v) - { - if ($v !== null) { - $v = (string) $v; - } - - if ($this->fade_in !== $v || $this->isNew()) { - $this->fade_in = $v; - $this->modifiedColumns[] = CcShowStampPeer::FADE_IN; - } - - return $this; - } // setDbFadeIn() - - /** - * Set the value of [fade_out] column. - * - * @param string $v new value - * @return CcShowStamp The current object (for fluent API support) - */ - public function setDbFadeOut($v) - { - if ($v !== null) { - $v = (string) $v; - } - - if ($this->fade_out !== $v || $this->isNew()) { - $this->fade_out = $v; - $this->modifiedColumns[] = CcShowStampPeer::FADE_OUT; - } - - return $this; - } // setDbFadeOut() - - /** - * Indicates whether the columns in this object are only set to default values. - * - * This method can be used in conjunction with isModified() to indicate whether an object is both - * modified _and_ has some values set which are non-default. - * - * @return boolean Whether the columns in this object are only been set with default values. - */ - public function hasOnlyDefaultValues() - { - if ($this->clip_length !== '00:00:00') { - return false; - } - - if ($this->cue_in !== '00:00:00') { - return false; - } - - if ($this->cue_out !== '00:00:00') { - return false; - } - - if ($this->fade_in !== '00:00:00') { - return false; - } - - if ($this->fade_out !== '00:00:00') { - return false; - } - - // otherwise, everything was equal, so return TRUE - return true; - } // hasOnlyDefaultValues() - - /** - * Hydrates (populates) the object variables with values from the database resultset. - * - * An offset (0-based "start column") is specified so that objects can be hydrated - * with a subset of the columns in the resultset rows. This is needed, for example, - * for results of JOIN queries where the resultset row includes columns from two or - * more tables. - * - * @param array $row The row returned by PDOStatement->fetch(PDO::FETCH_NUM) - * @param int $startcol 0-based offset column which indicates which restultset column to start with. - * @param boolean $rehydrate Whether this object is being re-hydrated from the database. - * @return int next starting column - * @throws PropelException - Any caught Exception will be rewrapped as a PropelException. - */ - public function hydrate($row, $startcol = 0, $rehydrate = false) - { - try { - - $this->id = ($row[$startcol + 0] !== null) ? (int) $row[$startcol + 0] : null; - $this->show_id = ($row[$startcol + 1] !== null) ? (int) $row[$startcol + 1] : null; - $this->instance_id = ($row[$startcol + 2] !== null) ? (int) $row[$startcol + 2] : null; - $this->file_id = ($row[$startcol + 3] !== null) ? (int) $row[$startcol + 3] : null; - $this->stream_id = ($row[$startcol + 4] !== null) ? (int) $row[$startcol + 4] : null; - $this->block_id = ($row[$startcol + 5] !== null) ? (int) $row[$startcol + 5] : null; - $this->playlist_id = ($row[$startcol + 6] !== null) ? (int) $row[$startcol + 6] : null; - $this->position = ($row[$startcol + 7] !== null) ? (int) $row[$startcol + 7] : null; - $this->clip_length = ($row[$startcol + 8] !== null) ? (string) $row[$startcol + 8] : null; - $this->cue_in = ($row[$startcol + 9] !== null) ? (string) $row[$startcol + 9] : null; - $this->cue_out = ($row[$startcol + 10] !== null) ? (string) $row[$startcol + 10] : null; - $this->fade_in = ($row[$startcol + 11] !== null) ? (string) $row[$startcol + 11] : null; - $this->fade_out = ($row[$startcol + 12] !== null) ? (string) $row[$startcol + 12] : null; - $this->resetModified(); - - $this->setNew(false); - - if ($rehydrate) { - $this->ensureConsistency(); - } - - return $startcol + 13; // 13 = CcShowStampPeer::NUM_COLUMNS - CcShowStampPeer::NUM_LAZY_LOAD_COLUMNS). - - } catch (Exception $e) { - throw new PropelException("Error populating CcShowStamp object", $e); - } - } - - /** - * Checks and repairs the internal consistency of the object. - * - * This method is executed after an already-instantiated object is re-hydrated - * from the database. It exists to check any foreign keys to make sure that - * the objects related to the current object are correct based on foreign key. - * - * You can override this method in the stub class, but you should always invoke - * the base method from the overridden method (i.e. parent::ensureConsistency()), - * in case your model changes. - * - * @throws PropelException - */ - public function ensureConsistency() - { - - if ($this->aCcShow !== null && $this->show_id !== $this->aCcShow->getDbId()) { - $this->aCcShow = null; - } - if ($this->aCcShowInstances !== null && $this->instance_id !== $this->aCcShowInstances->getDbId()) { - $this->aCcShowInstances = null; - } - if ($this->aCcFiles !== null && $this->file_id !== $this->aCcFiles->getDbId()) { - $this->aCcFiles = null; - } - if ($this->aCcWebstream !== null && $this->stream_id !== $this->aCcWebstream->getDbId()) { - $this->aCcWebstream = null; - } - if ($this->aCcBlock !== null && $this->block_id !== $this->aCcBlock->getDbId()) { - $this->aCcBlock = null; - } - if ($this->aCcPlaylist !== null && $this->playlist_id !== $this->aCcPlaylist->getDbId()) { - $this->aCcPlaylist = null; - } - } // ensureConsistency - - /** - * Reloads this object from datastore based on primary key and (optionally) resets all associated objects. - * - * This will only work if the object has been saved and has a valid primary key set. - * - * @param boolean $deep (optional) Whether to also de-associated any related objects. - * @param PropelPDO $con (optional) The PropelPDO connection to use. - * @return void - * @throws PropelException - if this object is deleted, unsaved or doesn't have pk match in db - */ - public function reload($deep = false, PropelPDO $con = null) - { - if ($this->isDeleted()) { - throw new PropelException("Cannot reload a deleted object."); - } - - if ($this->isNew()) { - throw new PropelException("Cannot reload an unsaved object."); - } - - if ($con === null) { - $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); - } - - // We don't need to alter the object instance pool; we're just modifying this instance - // already in the pool. - - $stmt = CcShowStampPeer::doSelectStmt($this->buildPkeyCriteria(), $con); - $row = $stmt->fetch(PDO::FETCH_NUM); - $stmt->closeCursor(); - if (!$row) { - throw new PropelException('Cannot find matching row in the database to reload object values.'); - } - $this->hydrate($row, 0, true); // rehydrate - - if ($deep) { // also de-associate any related objects? - - $this->aCcShow = null; - $this->aCcShowInstances = null; - $this->aCcFiles = null; - $this->aCcWebstream = null; - $this->aCcBlock = null; - $this->aCcPlaylist = null; - } // if (deep) - } - - /** - * Removes this object from datastore and sets delete attribute. - * - * @param PropelPDO $con - * @return void - * @throws PropelException - * @see BaseObject::setDeleted() - * @see BaseObject::isDeleted() - */ - public function delete(PropelPDO $con = null) - { - if ($this->isDeleted()) { - throw new PropelException("This object has already been deleted."); - } - - if ($con === null) { - $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); - } - - $con->beginTransaction(); - try { - $ret = $this->preDelete($con); - if ($ret) { - CcShowStampQuery::create() - ->filterByPrimaryKey($this->getPrimaryKey()) - ->delete($con); - $this->postDelete($con); - $con->commit(); - $this->setDeleted(true); - } else { - $con->commit(); - } - } catch (PropelException $e) { - $con->rollBack(); - throw $e; - } - } - - /** - * Persists this object to the database. - * - * If the object is new, it inserts it; otherwise an update is performed. - * All modified related objects will also be persisted in the doSave() - * method. This method wraps all precipitate database operations in a - * single transaction. - * - * @param PropelPDO $con - * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. - * @throws PropelException - * @see doSave() - */ - public function save(PropelPDO $con = null) - { - if ($this->isDeleted()) { - throw new PropelException("You cannot save an object that has been deleted."); - } - - if ($con === null) { - $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); - } - - $con->beginTransaction(); - $isInsert = $this->isNew(); - try { - $ret = $this->preSave($con); - if ($isInsert) { - $ret = $ret && $this->preInsert($con); - } else { - $ret = $ret && $this->preUpdate($con); - } - if ($ret) { - $affectedRows = $this->doSave($con); - if ($isInsert) { - $this->postInsert($con); - } else { - $this->postUpdate($con); - } - $this->postSave($con); - CcShowStampPeer::addInstanceToPool($this); - } else { - $affectedRows = 0; - } - $con->commit(); - return $affectedRows; - } catch (PropelException $e) { - $con->rollBack(); - throw $e; - } - } - - /** - * Performs the work of inserting or updating the row in the database. - * - * If the object is new, it inserts it; otherwise an update is performed. - * All related objects are also updated in this method. - * - * @param PropelPDO $con - * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. - * @throws PropelException - * @see save() - */ - protected function doSave(PropelPDO $con) - { - $affectedRows = 0; // initialize var to track total num of affected rows - if (!$this->alreadyInSave) { - $this->alreadyInSave = true; - - // We call the save method on the following object(s) if they - // were passed to this object by their coresponding set - // method. This object relates to these object(s) by a - // foreign key reference. - - if ($this->aCcShow !== null) { - if ($this->aCcShow->isModified() || $this->aCcShow->isNew()) { - $affectedRows += $this->aCcShow->save($con); - } - $this->setCcShow($this->aCcShow); - } - - if ($this->aCcShowInstances !== null) { - if ($this->aCcShowInstances->isModified() || $this->aCcShowInstances->isNew()) { - $affectedRows += $this->aCcShowInstances->save($con); - } - $this->setCcShowInstances($this->aCcShowInstances); - } - - if ($this->aCcFiles !== null) { - if ($this->aCcFiles->isModified() || $this->aCcFiles->isNew()) { - $affectedRows += $this->aCcFiles->save($con); - } - $this->setCcFiles($this->aCcFiles); - } - - if ($this->aCcWebstream !== null) { - if ($this->aCcWebstream->isModified() || $this->aCcWebstream->isNew()) { - $affectedRows += $this->aCcWebstream->save($con); - } - $this->setCcWebstream($this->aCcWebstream); - } - - if ($this->aCcBlock !== null) { - if ($this->aCcBlock->isModified() || $this->aCcBlock->isNew()) { - $affectedRows += $this->aCcBlock->save($con); - } - $this->setCcBlock($this->aCcBlock); - } - - if ($this->aCcPlaylist !== null) { - if ($this->aCcPlaylist->isModified() || $this->aCcPlaylist->isNew()) { - $affectedRows += $this->aCcPlaylist->save($con); - } - $this->setCcPlaylist($this->aCcPlaylist); - } - - if ($this->isNew() ) { - $this->modifiedColumns[] = CcShowStampPeer::ID; - } - - // If this object has been modified, then save it to the database. - if ($this->isModified()) { - if ($this->isNew()) { - $criteria = $this->buildCriteria(); - if ($criteria->keyContainsValue(CcShowStampPeer::ID) ) { - throw new PropelException('Cannot insert a value for auto-increment primary key ('.CcShowStampPeer::ID.')'); - } - - $pk = BasePeer::doInsert($criteria, $con); - $affectedRows += 1; - $this->setDbId($pk); //[IMV] update autoincrement primary key - $this->setNew(false); - } else { - $affectedRows += CcShowStampPeer::doUpdate($this, $con); - } - - $this->resetModified(); // [HL] After being saved an object is no longer 'modified' - } - - $this->alreadyInSave = false; - - } - return $affectedRows; - } // doSave() - - /** - * Array of ValidationFailed objects. - * @var array ValidationFailed[] - */ - protected $validationFailures = array(); - - /** - * Gets any ValidationFailed objects that resulted from last call to validate(). - * - * - * @return array ValidationFailed[] - * @see validate() - */ - public function getValidationFailures() - { - return $this->validationFailures; - } - - /** - * Validates the objects modified field values and all objects related to this table. - * - * If $columns is either a column name or an array of column names - * only those columns are validated. - * - * @param mixed $columns Column name or an array of column names. - * @return boolean Whether all columns pass validation. - * @see doValidate() - * @see getValidationFailures() - */ - public function validate($columns = null) - { - $res = $this->doValidate($columns); - if ($res === true) { - $this->validationFailures = array(); - return true; - } else { - $this->validationFailures = $res; - return false; - } - } - - /** - * This function performs the validation work for complex object models. - * - * In addition to checking the current object, all related objects will - * also be validated. If all pass then true is returned; otherwise - * an aggreagated array of ValidationFailed objects will be returned. - * - * @param array $columns Array of column names to validate. - * @return mixed true if all validations pass; array of ValidationFailed objets otherwise. - */ - protected function doValidate($columns = null) - { - if (!$this->alreadyInValidation) { - $this->alreadyInValidation = true; - $retval = null; - - $failureMap = array(); - - - // We call the validate method on the following object(s) if they - // were passed to this object by their coresponding set - // method. This object relates to these object(s) by a - // foreign key reference. - - if ($this->aCcShow !== null) { - if (!$this->aCcShow->validate($columns)) { - $failureMap = array_merge($failureMap, $this->aCcShow->getValidationFailures()); - } - } - - if ($this->aCcShowInstances !== null) { - if (!$this->aCcShowInstances->validate($columns)) { - $failureMap = array_merge($failureMap, $this->aCcShowInstances->getValidationFailures()); - } - } - - if ($this->aCcFiles !== null) { - if (!$this->aCcFiles->validate($columns)) { - $failureMap = array_merge($failureMap, $this->aCcFiles->getValidationFailures()); - } - } - - if ($this->aCcWebstream !== null) { - if (!$this->aCcWebstream->validate($columns)) { - $failureMap = array_merge($failureMap, $this->aCcWebstream->getValidationFailures()); - } - } - - if ($this->aCcBlock !== null) { - if (!$this->aCcBlock->validate($columns)) { - $failureMap = array_merge($failureMap, $this->aCcBlock->getValidationFailures()); - } - } - - if ($this->aCcPlaylist !== null) { - if (!$this->aCcPlaylist->validate($columns)) { - $failureMap = array_merge($failureMap, $this->aCcPlaylist->getValidationFailures()); - } - } - - - if (($retval = CcShowStampPeer::doValidate($this, $columns)) !== true) { - $failureMap = array_merge($failureMap, $retval); - } - - - - $this->alreadyInValidation = false; - } - - return (!empty($failureMap) ? $failureMap : true); - } - - /** - * Retrieves a field from the object by name passed in as a string. - * - * @param string $name name - * @param string $type The type of fieldname the $name is of: - * one of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME - * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM - * @return mixed Value of field. - */ - public function getByName($name, $type = BasePeer::TYPE_PHPNAME) - { - $pos = CcShowStampPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); - $field = $this->getByPosition($pos); - return $field; - } - - /** - * Retrieves a field from the object by Position as specified in the xml schema. - * Zero-based. - * - * @param int $pos position in xml schema - * @return mixed Value of field at $pos - */ - public function getByPosition($pos) - { - switch($pos) { - case 0: - return $this->getDbId(); - break; - case 1: - return $this->getDbShowId(); - break; - case 2: - return $this->getDbInstanceId(); - break; - case 3: - return $this->getDbFileId(); - break; - case 4: - return $this->getDbStreamId(); - break; - case 5: - return $this->getDbBlockId(); - break; - case 6: - return $this->getDbPlaylistId(); - break; - case 7: - return $this->getDbPosition(); - break; - case 8: - return $this->getDbClipLength(); - break; - case 9: - return $this->getDbCueIn(); - break; - case 10: - return $this->getDbCueOut(); - break; - case 11: - return $this->getDbFadeIn(); - break; - case 12: - return $this->getDbFadeOut(); - break; - default: - return null; - break; - } // switch() - } - - /** - * Exports the object as an array. - * - * You can specify the key type of the array by passing one of the class - * type constants. - * - * @param string $keyType (optional) One of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME, - * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. - * Defaults to BasePeer::TYPE_PHPNAME. - * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy loaded columns. Defaults to TRUE. - * @param boolean $includeForeignObjects (optional) Whether to include hydrated related objects. Default to FALSE. - * - * @return array an associative array containing the field names (as keys) and field values - */ - public function toArray($keyType = BasePeer::TYPE_PHPNAME, $includeLazyLoadColumns = true, $includeForeignObjects = false) - { - $keys = CcShowStampPeer::getFieldNames($keyType); - $result = array( - $keys[0] => $this->getDbId(), - $keys[1] => $this->getDbShowId(), - $keys[2] => $this->getDbInstanceId(), - $keys[3] => $this->getDbFileId(), - $keys[4] => $this->getDbStreamId(), - $keys[5] => $this->getDbBlockId(), - $keys[6] => $this->getDbPlaylistId(), - $keys[7] => $this->getDbPosition(), - $keys[8] => $this->getDbClipLength(), - $keys[9] => $this->getDbCueIn(), - $keys[10] => $this->getDbCueOut(), - $keys[11] => $this->getDbFadeIn(), - $keys[12] => $this->getDbFadeOut(), - ); - if ($includeForeignObjects) { - if (null !== $this->aCcShow) { - $result['CcShow'] = $this->aCcShow->toArray($keyType, $includeLazyLoadColumns, true); - } - if (null !== $this->aCcShowInstances) { - $result['CcShowInstances'] = $this->aCcShowInstances->toArray($keyType, $includeLazyLoadColumns, true); - } - if (null !== $this->aCcFiles) { - $result['CcFiles'] = $this->aCcFiles->toArray($keyType, $includeLazyLoadColumns, true); - } - if (null !== $this->aCcWebstream) { - $result['CcWebstream'] = $this->aCcWebstream->toArray($keyType, $includeLazyLoadColumns, true); - } - if (null !== $this->aCcBlock) { - $result['CcBlock'] = $this->aCcBlock->toArray($keyType, $includeLazyLoadColumns, true); - } - if (null !== $this->aCcPlaylist) { - $result['CcPlaylist'] = $this->aCcPlaylist->toArray($keyType, $includeLazyLoadColumns, true); - } - } - return $result; - } - - /** - * Sets a field from the object by name passed in as a string. - * - * @param string $name peer name - * @param mixed $value field value - * @param string $type The type of fieldname the $name is of: - * one of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME - * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM - * @return void - */ - public function setByName($name, $value, $type = BasePeer::TYPE_PHPNAME) - { - $pos = CcShowStampPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); - return $this->setByPosition($pos, $value); - } - - /** - * Sets a field from the object by Position as specified in the xml schema. - * Zero-based. - * - * @param int $pos position in xml schema - * @param mixed $value field value - * @return void - */ - public function setByPosition($pos, $value) - { - switch($pos) { - case 0: - $this->setDbId($value); - break; - case 1: - $this->setDbShowId($value); - break; - case 2: - $this->setDbInstanceId($value); - break; - case 3: - $this->setDbFileId($value); - break; - case 4: - $this->setDbStreamId($value); - break; - case 5: - $this->setDbBlockId($value); - break; - case 6: - $this->setDbPlaylistId($value); - break; - case 7: - $this->setDbPosition($value); - break; - case 8: - $this->setDbClipLength($value); - break; - case 9: - $this->setDbCueIn($value); - break; - case 10: - $this->setDbCueOut($value); - break; - case 11: - $this->setDbFadeIn($value); - break; - case 12: - $this->setDbFadeOut($value); - break; - } // switch() - } - - /** - * Populates the object using an array. - * - * This is particularly useful when populating an object from one of the - * request arrays (e.g. $_POST). This method goes through the column - * names, checking to see whether a matching key exists in populated - * array. If so the setByName() method is called for that column. - * - * You can specify the key type of the array by additionally passing one - * of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME, - * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. - * The default key type is the column's phpname (e.g. 'AuthorId') - * - * @param array $arr An array to populate the object from. - * @param string $keyType The type of keys the array uses. - * @return void - */ - public function fromArray($arr, $keyType = BasePeer::TYPE_PHPNAME) - { - $keys = CcShowStampPeer::getFieldNames($keyType); - - if (array_key_exists($keys[0], $arr)) $this->setDbId($arr[$keys[0]]); - if (array_key_exists($keys[1], $arr)) $this->setDbShowId($arr[$keys[1]]); - if (array_key_exists($keys[2], $arr)) $this->setDbInstanceId($arr[$keys[2]]); - if (array_key_exists($keys[3], $arr)) $this->setDbFileId($arr[$keys[3]]); - if (array_key_exists($keys[4], $arr)) $this->setDbStreamId($arr[$keys[4]]); - if (array_key_exists($keys[5], $arr)) $this->setDbBlockId($arr[$keys[5]]); - if (array_key_exists($keys[6], $arr)) $this->setDbPlaylistId($arr[$keys[6]]); - if (array_key_exists($keys[7], $arr)) $this->setDbPosition($arr[$keys[7]]); - if (array_key_exists($keys[8], $arr)) $this->setDbClipLength($arr[$keys[8]]); - if (array_key_exists($keys[9], $arr)) $this->setDbCueIn($arr[$keys[9]]); - if (array_key_exists($keys[10], $arr)) $this->setDbCueOut($arr[$keys[10]]); - if (array_key_exists($keys[11], $arr)) $this->setDbFadeIn($arr[$keys[11]]); - if (array_key_exists($keys[12], $arr)) $this->setDbFadeOut($arr[$keys[12]]); - } - - /** - * Build a Criteria object containing the values of all modified columns in this object. - * - * @return Criteria The Criteria object containing all modified values. - */ - public function buildCriteria() - { - $criteria = new Criteria(CcShowStampPeer::DATABASE_NAME); - - if ($this->isColumnModified(CcShowStampPeer::ID)) $criteria->add(CcShowStampPeer::ID, $this->id); - if ($this->isColumnModified(CcShowStampPeer::SHOW_ID)) $criteria->add(CcShowStampPeer::SHOW_ID, $this->show_id); - if ($this->isColumnModified(CcShowStampPeer::INSTANCE_ID)) $criteria->add(CcShowStampPeer::INSTANCE_ID, $this->instance_id); - if ($this->isColumnModified(CcShowStampPeer::FILE_ID)) $criteria->add(CcShowStampPeer::FILE_ID, $this->file_id); - if ($this->isColumnModified(CcShowStampPeer::STREAM_ID)) $criteria->add(CcShowStampPeer::STREAM_ID, $this->stream_id); - if ($this->isColumnModified(CcShowStampPeer::BLOCK_ID)) $criteria->add(CcShowStampPeer::BLOCK_ID, $this->block_id); - if ($this->isColumnModified(CcShowStampPeer::PLAYLIST_ID)) $criteria->add(CcShowStampPeer::PLAYLIST_ID, $this->playlist_id); - if ($this->isColumnModified(CcShowStampPeer::POSITION)) $criteria->add(CcShowStampPeer::POSITION, $this->position); - if ($this->isColumnModified(CcShowStampPeer::CLIP_LENGTH)) $criteria->add(CcShowStampPeer::CLIP_LENGTH, $this->clip_length); - if ($this->isColumnModified(CcShowStampPeer::CUE_IN)) $criteria->add(CcShowStampPeer::CUE_IN, $this->cue_in); - if ($this->isColumnModified(CcShowStampPeer::CUE_OUT)) $criteria->add(CcShowStampPeer::CUE_OUT, $this->cue_out); - if ($this->isColumnModified(CcShowStampPeer::FADE_IN)) $criteria->add(CcShowStampPeer::FADE_IN, $this->fade_in); - if ($this->isColumnModified(CcShowStampPeer::FADE_OUT)) $criteria->add(CcShowStampPeer::FADE_OUT, $this->fade_out); - - return $criteria; - } - - /** - * Builds a Criteria object containing the primary key for this object. - * - * Unlike buildCriteria() this method includes the primary key values regardless - * of whether or not they have been modified. - * - * @return Criteria The Criteria object containing value(s) for primary key(s). - */ - public function buildPkeyCriteria() - { - $criteria = new Criteria(CcShowStampPeer::DATABASE_NAME); - $criteria->add(CcShowStampPeer::ID, $this->id); - - return $criteria; - } - - /** - * Returns the primary key for this object (row). - * @return int - */ - public function getPrimaryKey() - { - return $this->getDbId(); - } - - /** - * Generic method to set the primary key (id column). - * - * @param int $key Primary key. - * @return void - */ - public function setPrimaryKey($key) - { - $this->setDbId($key); - } - - /** - * Returns true if the primary key for this object is null. - * @return boolean - */ - public function isPrimaryKeyNull() - { - return null === $this->getDbId(); - } - - /** - * Sets contents of passed object to values from current object. - * - * If desired, this method can also make copies of all associated (fkey referrers) - * objects. - * - * @param object $copyObj An object of CcShowStamp (or compatible) type. - * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. - * @throws PropelException - */ - public function copyInto($copyObj, $deepCopy = false) - { - $copyObj->setDbShowId($this->show_id); - $copyObj->setDbInstanceId($this->instance_id); - $copyObj->setDbFileId($this->file_id); - $copyObj->setDbStreamId($this->stream_id); - $copyObj->setDbBlockId($this->block_id); - $copyObj->setDbPlaylistId($this->playlist_id); - $copyObj->setDbPosition($this->position); - $copyObj->setDbClipLength($this->clip_length); - $copyObj->setDbCueIn($this->cue_in); - $copyObj->setDbCueOut($this->cue_out); - $copyObj->setDbFadeIn($this->fade_in); - $copyObj->setDbFadeOut($this->fade_out); - - $copyObj->setNew(true); - $copyObj->setDbId(NULL); // this is a auto-increment column, so set to default value - } - - /** - * Makes a copy of this object that will be inserted as a new row in table when saved. - * It creates a new object filling in the simple attributes, but skipping any primary - * keys that are defined for the table. - * - * If desired, this method can also make copies of all associated (fkey referrers) - * objects. - * - * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. - * @return CcShowStamp Clone of current object. - * @throws PropelException - */ - public function copy($deepCopy = false) - { - // we use get_class(), because this might be a subclass - $clazz = get_class($this); - $copyObj = new $clazz(); - $this->copyInto($copyObj, $deepCopy); - return $copyObj; - } - - /** - * Returns a peer instance associated with this om. - * - * Since Peer classes are not to have any instance attributes, this method returns the - * same instance for all member of this class. The method could therefore - * be static, but this would prevent one from overriding the behavior. - * - * @return CcShowStampPeer - */ - public function getPeer() - { - if (self::$peer === null) { - self::$peer = new CcShowStampPeer(); - } - return self::$peer; - } - - /** - * Declares an association between this object and a CcShow object. - * - * @param CcShow $v - * @return CcShowStamp The current object (for fluent API support) - * @throws PropelException - */ - public function setCcShow(CcShow $v = null) - { - if ($v === null) { - $this->setDbShowId(NULL); - } else { - $this->setDbShowId($v->getDbId()); - } - - $this->aCcShow = $v; - - // Add binding for other direction of this n:n relationship. - // If this object has already been added to the CcShow object, it will not be re-added. - if ($v !== null) { - $v->addCcShowStamp($this); - } - - return $this; - } - - - /** - * Get the associated CcShow object - * - * @param PropelPDO Optional Connection object. - * @return CcShow The associated CcShow object. - * @throws PropelException - */ - public function getCcShow(PropelPDO $con = null) - { - if ($this->aCcShow === null && ($this->show_id !== null)) { - $this->aCcShow = CcShowQuery::create()->findPk($this->show_id, $con); - /* The following can be used additionally to - guarantee the related object contains a reference - to this object. This level of coupling may, however, be - undesirable since it could result in an only partially populated collection - in the referenced object. - $this->aCcShow->addCcShowStamps($this); - */ - } - return $this->aCcShow; - } - - /** - * Declares an association between this object and a CcShowInstances object. - * - * @param CcShowInstances $v - * @return CcShowStamp The current object (for fluent API support) - * @throws PropelException - */ - public function setCcShowInstances(CcShowInstances $v = null) - { - if ($v === null) { - $this->setDbInstanceId(NULL); - } else { - $this->setDbInstanceId($v->getDbId()); - } - - $this->aCcShowInstances = $v; - - // Add binding for other direction of this n:n relationship. - // If this object has already been added to the CcShowInstances object, it will not be re-added. - if ($v !== null) { - $v->addCcShowStamp($this); - } - - return $this; - } - - - /** - * Get the associated CcShowInstances object - * - * @param PropelPDO Optional Connection object. - * @return CcShowInstances The associated CcShowInstances object. - * @throws PropelException - */ - public function getCcShowInstances(PropelPDO $con = null) - { - if ($this->aCcShowInstances === null && ($this->instance_id !== null)) { - $this->aCcShowInstances = CcShowInstancesQuery::create()->findPk($this->instance_id, $con); - /* The following can be used additionally to - guarantee the related object contains a reference - to this object. This level of coupling may, however, be - undesirable since it could result in an only partially populated collection - in the referenced object. - $this->aCcShowInstances->addCcShowStamps($this); - */ - } - return $this->aCcShowInstances; - } - - /** - * Declares an association between this object and a CcFiles object. - * - * @param CcFiles $v - * @return CcShowStamp The current object (for fluent API support) - * @throws PropelException - */ - public function setCcFiles(CcFiles $v = null) - { - if ($v === null) { - $this->setDbFileId(NULL); - } else { - $this->setDbFileId($v->getDbId()); - } - - $this->aCcFiles = $v; - - // Add binding for other direction of this n:n relationship. - // If this object has already been added to the CcFiles object, it will not be re-added. - if ($v !== null) { - $v->addCcShowStamp($this); - } - - return $this; - } - - - /** - * Get the associated CcFiles object - * - * @param PropelPDO Optional Connection object. - * @return CcFiles The associated CcFiles object. - * @throws PropelException - */ - public function getCcFiles(PropelPDO $con = null) - { - if ($this->aCcFiles === null && ($this->file_id !== null)) { - $this->aCcFiles = CcFilesQuery::create()->findPk($this->file_id, $con); - /* The following can be used additionally to - guarantee the related object contains a reference - to this object. This level of coupling may, however, be - undesirable since it could result in an only partially populated collection - in the referenced object. - $this->aCcFiles->addCcShowStamps($this); - */ - } - return $this->aCcFiles; - } - - /** - * Declares an association between this object and a CcWebstream object. - * - * @param CcWebstream $v - * @return CcShowStamp The current object (for fluent API support) - * @throws PropelException - */ - public function setCcWebstream(CcWebstream $v = null) - { - if ($v === null) { - $this->setDbStreamId(NULL); - } else { - $this->setDbStreamId($v->getDbId()); - } - - $this->aCcWebstream = $v; - - // Add binding for other direction of this n:n relationship. - // If this object has already been added to the CcWebstream object, it will not be re-added. - if ($v !== null) { - $v->addCcShowStamp($this); - } - - return $this; - } - - - /** - * Get the associated CcWebstream object - * - * @param PropelPDO Optional Connection object. - * @return CcWebstream The associated CcWebstream object. - * @throws PropelException - */ - public function getCcWebstream(PropelPDO $con = null) - { - if ($this->aCcWebstream === null && ($this->stream_id !== null)) { - $this->aCcWebstream = CcWebstreamQuery::create()->findPk($this->stream_id, $con); - /* The following can be used additionally to - guarantee the related object contains a reference - to this object. This level of coupling may, however, be - undesirable since it could result in an only partially populated collection - in the referenced object. - $this->aCcWebstream->addCcShowStamps($this); - */ - } - return $this->aCcWebstream; - } - - /** - * Declares an association between this object and a CcBlock object. - * - * @param CcBlock $v - * @return CcShowStamp The current object (for fluent API support) - * @throws PropelException - */ - public function setCcBlock(CcBlock $v = null) - { - if ($v === null) { - $this->setDbBlockId(NULL); - } else { - $this->setDbBlockId($v->getDbId()); - } - - $this->aCcBlock = $v; - - // Add binding for other direction of this n:n relationship. - // If this object has already been added to the CcBlock object, it will not be re-added. - if ($v !== null) { - $v->addCcShowStamp($this); - } - - return $this; - } - - - /** - * Get the associated CcBlock object - * - * @param PropelPDO Optional Connection object. - * @return CcBlock The associated CcBlock object. - * @throws PropelException - */ - public function getCcBlock(PropelPDO $con = null) - { - if ($this->aCcBlock === null && ($this->block_id !== null)) { - $this->aCcBlock = CcBlockQuery::create()->findPk($this->block_id, $con); - /* The following can be used additionally to - guarantee the related object contains a reference - to this object. This level of coupling may, however, be - undesirable since it could result in an only partially populated collection - in the referenced object. - $this->aCcBlock->addCcShowStamps($this); - */ - } - return $this->aCcBlock; - } - - /** - * Declares an association between this object and a CcPlaylist object. - * - * @param CcPlaylist $v - * @return CcShowStamp The current object (for fluent API support) - * @throws PropelException - */ - public function setCcPlaylist(CcPlaylist $v = null) - { - if ($v === null) { - $this->setDbPlaylistId(NULL); - } else { - $this->setDbPlaylistId($v->getDbId()); - } - - $this->aCcPlaylist = $v; - - // Add binding for other direction of this n:n relationship. - // If this object has already been added to the CcPlaylist object, it will not be re-added. - if ($v !== null) { - $v->addCcShowStamp($this); - } - - return $this; - } - - - /** - * Get the associated CcPlaylist object - * - * @param PropelPDO Optional Connection object. - * @return CcPlaylist The associated CcPlaylist object. - * @throws PropelException - */ - public function getCcPlaylist(PropelPDO $con = null) - { - if ($this->aCcPlaylist === null && ($this->playlist_id !== null)) { - $this->aCcPlaylist = CcPlaylistQuery::create()->findPk($this->playlist_id, $con); - /* The following can be used additionally to - guarantee the related object contains a reference - to this object. This level of coupling may, however, be - undesirable since it could result in an only partially populated collection - in the referenced object. - $this->aCcPlaylist->addCcShowStamps($this); - */ - } - return $this->aCcPlaylist; - } - - /** - * Clears the current object and sets all attributes to their default values - */ - public function clear() - { - $this->id = null; - $this->show_id = null; - $this->instance_id = null; - $this->file_id = null; - $this->stream_id = null; - $this->block_id = null; - $this->playlist_id = null; - $this->position = null; - $this->clip_length = null; - $this->cue_in = null; - $this->cue_out = null; - $this->fade_in = null; - $this->fade_out = null; - $this->alreadyInSave = false; - $this->alreadyInValidation = false; - $this->clearAllReferences(); - $this->applyDefaultValues(); - $this->resetModified(); - $this->setNew(true); - $this->setDeleted(false); - } - - /** - * Resets all collections of referencing foreign keys. - * - * This method is a user-space workaround for PHP's inability to garbage collect objects - * with circular references. This is currently necessary when using Propel in certain - * daemon or large-volumne/high-memory operations. - * - * @param boolean $deep Whether to also clear the references on all associated objects. - */ - public function clearAllReferences($deep = false) - { - if ($deep) { - } // if ($deep) - - $this->aCcShow = null; - $this->aCcShowInstances = null; - $this->aCcFiles = null; - $this->aCcWebstream = null; - $this->aCcBlock = null; - $this->aCcPlaylist = null; - } - - /** - * Catches calls to virtual methods - */ - public function __call($name, $params) - { - if (preg_match('/get(\w+)/', $name, $matches)) { - $virtualColumn = $matches[1]; - if ($this->hasVirtualColumn($virtualColumn)) { - return $this->getVirtualColumn($virtualColumn); - } - // no lcfirst in php<5.3... - $virtualColumn[0] = strtolower($virtualColumn[0]); - if ($this->hasVirtualColumn($virtualColumn)) { - return $this->getVirtualColumn($virtualColumn); - } - } - throw new PropelException('Call to undefined method: ' . $name); - } - -} // BaseCcShowStamp diff --git a/airtime_mvc/application/models/airtime/om/BaseCcShowStampPeer.php b/airtime_mvc/application/models/airtime/om/BaseCcShowStampPeer.php deleted file mode 100644 index fb96eb0a7..000000000 --- a/airtime_mvc/application/models/airtime/om/BaseCcShowStampPeer.php +++ /dev/null @@ -1,3095 +0,0 @@ - array ('DbId', 'DbShowId', 'DbInstanceId', 'DbFileId', 'DbStreamId', 'DbBlockId', 'DbPlaylistId', 'DbPosition', 'DbClipLength', 'DbCueIn', 'DbCueOut', 'DbFadeIn', 'DbFadeOut', ), - BasePeer::TYPE_STUDLYPHPNAME => array ('dbId', 'dbShowId', 'dbInstanceId', 'dbFileId', 'dbStreamId', 'dbBlockId', 'dbPlaylistId', 'dbPosition', 'dbClipLength', 'dbCueIn', 'dbCueOut', 'dbFadeIn', 'dbFadeOut', ), - BasePeer::TYPE_COLNAME => array (self::ID, self::SHOW_ID, self::INSTANCE_ID, self::FILE_ID, self::STREAM_ID, self::BLOCK_ID, self::PLAYLIST_ID, self::POSITION, self::CLIP_LENGTH, self::CUE_IN, self::CUE_OUT, self::FADE_IN, self::FADE_OUT, ), - BasePeer::TYPE_RAW_COLNAME => array ('ID', 'SHOW_ID', 'INSTANCE_ID', 'FILE_ID', 'STREAM_ID', 'BLOCK_ID', 'PLAYLIST_ID', 'POSITION', 'CLIP_LENGTH', 'CUE_IN', 'CUE_OUT', 'FADE_IN', 'FADE_OUT', ), - BasePeer::TYPE_FIELDNAME => array ('id', 'show_id', 'instance_id', 'file_id', 'stream_id', 'block_id', 'playlist_id', 'position', 'clip_length', 'cue_in', 'cue_out', 'fade_in', 'fade_out', ), - BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, ) - ); - - /** - * holds an array of keys for quick access to the fieldnames array - * - * first dimension keys are the type constants - * e.g. self::$fieldNames[BasePeer::TYPE_PHPNAME]['Id'] = 0 - */ - private static $fieldKeys = array ( - BasePeer::TYPE_PHPNAME => array ('DbId' => 0, 'DbShowId' => 1, 'DbInstanceId' => 2, 'DbFileId' => 3, 'DbStreamId' => 4, 'DbBlockId' => 5, 'DbPlaylistId' => 6, 'DbPosition' => 7, 'DbClipLength' => 8, 'DbCueIn' => 9, 'DbCueOut' => 10, 'DbFadeIn' => 11, 'DbFadeOut' => 12, ), - BasePeer::TYPE_STUDLYPHPNAME => array ('dbId' => 0, 'dbShowId' => 1, 'dbInstanceId' => 2, 'dbFileId' => 3, 'dbStreamId' => 4, 'dbBlockId' => 5, 'dbPlaylistId' => 6, 'dbPosition' => 7, 'dbClipLength' => 8, 'dbCueIn' => 9, 'dbCueOut' => 10, 'dbFadeIn' => 11, 'dbFadeOut' => 12, ), - BasePeer::TYPE_COLNAME => array (self::ID => 0, self::SHOW_ID => 1, self::INSTANCE_ID => 2, self::FILE_ID => 3, self::STREAM_ID => 4, self::BLOCK_ID => 5, self::PLAYLIST_ID => 6, self::POSITION => 7, self::CLIP_LENGTH => 8, self::CUE_IN => 9, self::CUE_OUT => 10, self::FADE_IN => 11, self::FADE_OUT => 12, ), - BasePeer::TYPE_RAW_COLNAME => array ('ID' => 0, 'SHOW_ID' => 1, 'INSTANCE_ID' => 2, 'FILE_ID' => 3, 'STREAM_ID' => 4, 'BLOCK_ID' => 5, 'PLAYLIST_ID' => 6, 'POSITION' => 7, 'CLIP_LENGTH' => 8, 'CUE_IN' => 9, 'CUE_OUT' => 10, 'FADE_IN' => 11, 'FADE_OUT' => 12, ), - BasePeer::TYPE_FIELDNAME => array ('id' => 0, 'show_id' => 1, 'instance_id' => 2, 'file_id' => 3, 'stream_id' => 4, 'block_id' => 5, 'playlist_id' => 6, 'position' => 7, 'clip_length' => 8, 'cue_in' => 9, 'cue_out' => 10, 'fade_in' => 11, 'fade_out' => 12, ), - BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, ) - ); - - /** - * Translates a fieldname to another type - * - * @param string $name field name - * @param string $fromType One of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME - * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM - * @param string $toType One of the class type constants - * @return string translated name of the field. - * @throws PropelException - if the specified name could not be found in the fieldname mappings. - */ - static public function translateFieldName($name, $fromType, $toType) - { - $toNames = self::getFieldNames($toType); - $key = isset(self::$fieldKeys[$fromType][$name]) ? self::$fieldKeys[$fromType][$name] : null; - if ($key === null) { - throw new PropelException("'$name' could not be found in the field names of type '$fromType'. These are: " . print_r(self::$fieldKeys[$fromType], true)); - } - return $toNames[$key]; - } - - /** - * Returns an array of field names. - * - * @param string $type The type of fieldnames to return: - * One of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME - * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM - * @return array A list of field names - */ - - static public function getFieldNames($type = BasePeer::TYPE_PHPNAME) - { - if (!array_key_exists($type, self::$fieldNames)) { - throw new PropelException('Method getFieldNames() expects the parameter $type to be one of the class constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME, BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. ' . $type . ' was given.'); - } - return self::$fieldNames[$type]; - } - - /** - * Convenience method which changes table.column to alias.column. - * - * Using this method you can maintain SQL abstraction while using column aliases. - * - * $c->addAlias("alias1", TablePeer::TABLE_NAME); - * $c->addJoin(TablePeer::alias("alias1", TablePeer::PRIMARY_KEY_COLUMN), TablePeer::PRIMARY_KEY_COLUMN); - * - * @param string $alias The alias for the current table. - * @param string $column The column name for current table. (i.e. CcShowStampPeer::COLUMN_NAME). - * @return string - */ - public static function alias($alias, $column) - { - return str_replace(CcShowStampPeer::TABLE_NAME.'.', $alias.'.', $column); - } - - /** - * Add all the columns needed to create a new object. - * - * Note: any columns that were marked with lazyLoad="true" in the - * XML schema will not be added to the select list and only loaded - * on demand. - * - * @param Criteria $criteria object containing the columns to add. - * @param string $alias optional table alias - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - */ - public static function addSelectColumns(Criteria $criteria, $alias = null) - { - if (null === $alias) { - $criteria->addSelectColumn(CcShowStampPeer::ID); - $criteria->addSelectColumn(CcShowStampPeer::SHOW_ID); - $criteria->addSelectColumn(CcShowStampPeer::INSTANCE_ID); - $criteria->addSelectColumn(CcShowStampPeer::FILE_ID); - $criteria->addSelectColumn(CcShowStampPeer::STREAM_ID); - $criteria->addSelectColumn(CcShowStampPeer::BLOCK_ID); - $criteria->addSelectColumn(CcShowStampPeer::PLAYLIST_ID); - $criteria->addSelectColumn(CcShowStampPeer::POSITION); - $criteria->addSelectColumn(CcShowStampPeer::CLIP_LENGTH); - $criteria->addSelectColumn(CcShowStampPeer::CUE_IN); - $criteria->addSelectColumn(CcShowStampPeer::CUE_OUT); - $criteria->addSelectColumn(CcShowStampPeer::FADE_IN); - $criteria->addSelectColumn(CcShowStampPeer::FADE_OUT); - } else { - $criteria->addSelectColumn($alias . '.ID'); - $criteria->addSelectColumn($alias . '.SHOW_ID'); - $criteria->addSelectColumn($alias . '.INSTANCE_ID'); - $criteria->addSelectColumn($alias . '.FILE_ID'); - $criteria->addSelectColumn($alias . '.STREAM_ID'); - $criteria->addSelectColumn($alias . '.BLOCK_ID'); - $criteria->addSelectColumn($alias . '.PLAYLIST_ID'); - $criteria->addSelectColumn($alias . '.POSITION'); - $criteria->addSelectColumn($alias . '.CLIP_LENGTH'); - $criteria->addSelectColumn($alias . '.CUE_IN'); - $criteria->addSelectColumn($alias . '.CUE_OUT'); - $criteria->addSelectColumn($alias . '.FADE_IN'); - $criteria->addSelectColumn($alias . '.FADE_OUT'); - } - } - - /** - * Returns the number of rows matching criteria. - * - * @param Criteria $criteria - * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. - * @param PropelPDO $con - * @return int Number of matching rows. - */ - public static function doCount(Criteria $criteria, $distinct = false, PropelPDO $con = null) - { - // we may modify criteria, so copy it first - $criteria = clone $criteria; - - // We need to set the primary table name, since in the case that there are no WHERE columns - // it will be impossible for the BasePeer::createSelectSql() method to determine which - // tables go into the FROM clause. - $criteria->setPrimaryTableName(CcShowStampPeer::TABLE_NAME); - - if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { - $criteria->setDistinct(); - } - - if (!$criteria->hasSelectClause()) { - CcShowStampPeer::addSelectColumns($criteria); - } - - $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count - $criteria->setDbName(self::DATABASE_NAME); // Set the correct dbName - - if ($con === null) { - $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); - } - // BasePeer returns a PDOStatement - $stmt = BasePeer::doCount($criteria, $con); - - if ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $count = (int) $row[0]; - } else { - $count = 0; // no rows returned; we infer that means 0 matches. - } - $stmt->closeCursor(); - return $count; - } - /** - * Method to select one object from the DB. - * - * @param Criteria $criteria object used to create the SELECT statement. - * @param PropelPDO $con - * @return CcShowStamp - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - */ - public static function doSelectOne(Criteria $criteria, PropelPDO $con = null) - { - $critcopy = clone $criteria; - $critcopy->setLimit(1); - $objects = CcShowStampPeer::doSelect($critcopy, $con); - if ($objects) { - return $objects[0]; - } - return null; - } - /** - * Method to do selects. - * - * @param Criteria $criteria The Criteria object used to build the SELECT statement. - * @param PropelPDO $con - * @return array Array of selected Objects - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - */ - public static function doSelect(Criteria $criteria, PropelPDO $con = null) - { - return CcShowStampPeer::populateObjects(CcShowStampPeer::doSelectStmt($criteria, $con)); - } - /** - * Prepares the Criteria object and uses the parent doSelect() method to execute a PDOStatement. - * - * Use this method directly if you want to work with an executed statement durirectly (for example - * to perform your own object hydration). - * - * @param Criteria $criteria The Criteria object used to build the SELECT statement. - * @param PropelPDO $con The connection to use - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - * @return PDOStatement The executed PDOStatement object. - * @see BasePeer::doSelect() - */ - public static function doSelectStmt(Criteria $criteria, PropelPDO $con = null) - { - if ($con === null) { - $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); - } - - if (!$criteria->hasSelectClause()) { - $criteria = clone $criteria; - CcShowStampPeer::addSelectColumns($criteria); - } - - // Set the correct dbName - $criteria->setDbName(self::DATABASE_NAME); - - // BasePeer returns a PDOStatement - return BasePeer::doSelect($criteria, $con); - } - /** - * Adds an object to the instance pool. - * - * Propel keeps cached copies of objects in an instance pool when they are retrieved - * from the database. In some cases -- especially when you override doSelect*() - * methods in your stub classes -- you may need to explicitly add objects - * to the cache in order to ensure that the same objects are always returned by doSelect*() - * and retrieveByPK*() calls. - * - * @param CcShowStamp $value A CcShowStamp object. - * @param string $key (optional) key to use for instance map (for performance boost if key was already calculated externally). - */ - public static function addInstanceToPool(CcShowStamp $obj, $key = null) - { - if (Propel::isInstancePoolingEnabled()) { - if ($key === null) { - $key = (string) $obj->getDbId(); - } // if key === null - self::$instances[$key] = $obj; - } - } - - /** - * Removes an object from the instance pool. - * - * Propel keeps cached copies of objects in an instance pool when they are retrieved - * from the database. In some cases -- especially when you override doDelete - * methods in your stub classes -- you may need to explicitly remove objects - * from the cache in order to prevent returning objects that no longer exist. - * - * @param mixed $value A CcShowStamp object or a primary key value. - */ - public static function removeInstanceFromPool($value) - { - if (Propel::isInstancePoolingEnabled() && $value !== null) { - if (is_object($value) && $value instanceof CcShowStamp) { - $key = (string) $value->getDbId(); - } elseif (is_scalar($value)) { - // assume we've been passed a primary key - $key = (string) $value; - } else { - $e = new PropelException("Invalid value passed to removeInstanceFromPool(). Expected primary key or CcShowStamp object; got " . (is_object($value) ? get_class($value) . ' object.' : var_export($value,true))); - throw $e; - } - - unset(self::$instances[$key]); - } - } // removeInstanceFromPool() - - /** - * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table. - * - * For tables with a single-column primary key, that simple pkey value will be returned. For tables with - * a multi-column primary key, a serialize()d version of the primary key will be returned. - * - * @param string $key The key (@see getPrimaryKeyHash()) for this instance. - * @return CcShowStamp Found object or NULL if 1) no instance exists for specified key or 2) instance pooling has been disabled. - * @see getPrimaryKeyHash() - */ - public static function getInstanceFromPool($key) - { - if (Propel::isInstancePoolingEnabled()) { - if (isset(self::$instances[$key])) { - return self::$instances[$key]; - } - } - return null; // just to be explicit - } - - /** - * Clear the instance pool. - * - * @return void - */ - public static function clearInstancePool() - { - self::$instances = array(); - } - - /** - * Method to invalidate the instance pool of all tables related to cc_show_stamp - * by a foreign key with ON DELETE CASCADE - */ - public static function clearRelatedInstancePool() - { - } - - /** - * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table. - * - * For tables with a single-column primary key, that simple pkey value will be returned. For tables with - * a multi-column primary key, a serialize()d version of the primary key will be returned. - * - * @param array $row PropelPDO resultset row. - * @param int $startcol The 0-based offset for reading from the resultset row. - * @return string A string version of PK or NULL if the components of primary key in result array are all null. - */ - public static function getPrimaryKeyHashFromRow($row, $startcol = 0) - { - // If the PK cannot be derived from the row, return NULL. - if ($row[$startcol] === null) { - return null; - } - return (string) $row[$startcol]; - } - - /** - * Retrieves the primary key from the DB resultset row - * For tables with a single-column primary key, that simple pkey value will be returned. For tables with - * a multi-column primary key, an array of the primary key columns will be returned. - * - * @param array $row PropelPDO resultset row. - * @param int $startcol The 0-based offset for reading from the resultset row. - * @return mixed The primary key of the row - */ - public static function getPrimaryKeyFromRow($row, $startcol = 0) - { - return (int) $row[$startcol]; - } - - /** - * The returned array will contain objects of the default type or - * objects that inherit from the default. - * - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - */ - public static function populateObjects(PDOStatement $stmt) - { - $results = array(); - - // set the class once to avoid overhead in the loop - $cls = CcShowStampPeer::getOMClass(false); - // populate the object(s) - while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $key = CcShowStampPeer::getPrimaryKeyHashFromRow($row, 0); - if (null !== ($obj = CcShowStampPeer::getInstanceFromPool($key))) { - // We no longer rehydrate the object, since this can cause data loss. - // See http://www.propelorm.org/ticket/509 - // $obj->hydrate($row, 0, true); // rehydrate - $results[] = $obj; - } else { - $obj = new $cls(); - $obj->hydrate($row); - $results[] = $obj; - CcShowStampPeer::addInstanceToPool($obj, $key); - } // if key exists - } - $stmt->closeCursor(); - return $results; - } - /** - * Populates an object of the default type or an object that inherit from the default. - * - * @param array $row PropelPDO resultset row. - * @param int $startcol The 0-based offset for reading from the resultset row. - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - * @return array (CcShowStamp object, last column rank) - */ - public static function populateObject($row, $startcol = 0) - { - $key = CcShowStampPeer::getPrimaryKeyHashFromRow($row, $startcol); - if (null !== ($obj = CcShowStampPeer::getInstanceFromPool($key))) { - // We no longer rehydrate the object, since this can cause data loss. - // See http://www.propelorm.org/ticket/509 - // $obj->hydrate($row, $startcol, true); // rehydrate - $col = $startcol + CcShowStampPeer::NUM_COLUMNS; - } else { - $cls = CcShowStampPeer::OM_CLASS; - $obj = new $cls(); - $col = $obj->hydrate($row, $startcol); - CcShowStampPeer::addInstanceToPool($obj, $key); - } - return array($obj, $col); - } - - /** - * Returns the number of rows matching criteria, joining the related CcShow table - * - * @param Criteria $criteria - * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. - * @param PropelPDO $con - * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN - * @return int Number of matching rows. - */ - public static function doCountJoinCcShow(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) - { - // we're going to modify criteria, so copy it first - $criteria = clone $criteria; - - // We need to set the primary table name, since in the case that there are no WHERE columns - // it will be impossible for the BasePeer::createSelectSql() method to determine which - // tables go into the FROM clause. - $criteria->setPrimaryTableName(CcShowStampPeer::TABLE_NAME); - - if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { - $criteria->setDistinct(); - } - - if (!$criteria->hasSelectClause()) { - CcShowStampPeer::addSelectColumns($criteria); - } - - $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count - - // Set the correct dbName - $criteria->setDbName(self::DATABASE_NAME); - - if ($con === null) { - $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); - } - - $criteria->addJoin(CcShowStampPeer::SHOW_ID, CcShowPeer::ID, $join_behavior); - - $stmt = BasePeer::doCount($criteria, $con); - - if ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $count = (int) $row[0]; - } else { - $count = 0; // no rows returned; we infer that means 0 matches. - } - $stmt->closeCursor(); - return $count; - } - - - /** - * Returns the number of rows matching criteria, joining the related CcShowInstances table - * - * @param Criteria $criteria - * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. - * @param PropelPDO $con - * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN - * @return int Number of matching rows. - */ - public static function doCountJoinCcShowInstances(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) - { - // we're going to modify criteria, so copy it first - $criteria = clone $criteria; - - // We need to set the primary table name, since in the case that there are no WHERE columns - // it will be impossible for the BasePeer::createSelectSql() method to determine which - // tables go into the FROM clause. - $criteria->setPrimaryTableName(CcShowStampPeer::TABLE_NAME); - - if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { - $criteria->setDistinct(); - } - - if (!$criteria->hasSelectClause()) { - CcShowStampPeer::addSelectColumns($criteria); - } - - $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count - - // Set the correct dbName - $criteria->setDbName(self::DATABASE_NAME); - - if ($con === null) { - $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); - } - - $criteria->addJoin(CcShowStampPeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); - - $stmt = BasePeer::doCount($criteria, $con); - - if ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $count = (int) $row[0]; - } else { - $count = 0; // no rows returned; we infer that means 0 matches. - } - $stmt->closeCursor(); - return $count; - } - - - /** - * Returns the number of rows matching criteria, joining the related CcFiles table - * - * @param Criteria $criteria - * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. - * @param PropelPDO $con - * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN - * @return int Number of matching rows. - */ - public static function doCountJoinCcFiles(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) - { - // we're going to modify criteria, so copy it first - $criteria = clone $criteria; - - // We need to set the primary table name, since in the case that there are no WHERE columns - // it will be impossible for the BasePeer::createSelectSql() method to determine which - // tables go into the FROM clause. - $criteria->setPrimaryTableName(CcShowStampPeer::TABLE_NAME); - - if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { - $criteria->setDistinct(); - } - - if (!$criteria->hasSelectClause()) { - CcShowStampPeer::addSelectColumns($criteria); - } - - $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count - - // Set the correct dbName - $criteria->setDbName(self::DATABASE_NAME); - - if ($con === null) { - $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); - } - - $criteria->addJoin(CcShowStampPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); - - $stmt = BasePeer::doCount($criteria, $con); - - if ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $count = (int) $row[0]; - } else { - $count = 0; // no rows returned; we infer that means 0 matches. - } - $stmt->closeCursor(); - return $count; - } - - - /** - * Returns the number of rows matching criteria, joining the related CcWebstream table - * - * @param Criteria $criteria - * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. - * @param PropelPDO $con - * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN - * @return int Number of matching rows. - */ - public static function doCountJoinCcWebstream(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) - { - // we're going to modify criteria, so copy it first - $criteria = clone $criteria; - - // We need to set the primary table name, since in the case that there are no WHERE columns - // it will be impossible for the BasePeer::createSelectSql() method to determine which - // tables go into the FROM clause. - $criteria->setPrimaryTableName(CcShowStampPeer::TABLE_NAME); - - if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { - $criteria->setDistinct(); - } - - if (!$criteria->hasSelectClause()) { - CcShowStampPeer::addSelectColumns($criteria); - } - - $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count - - // Set the correct dbName - $criteria->setDbName(self::DATABASE_NAME); - - if ($con === null) { - $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); - } - - $criteria->addJoin(CcShowStampPeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); - - $stmt = BasePeer::doCount($criteria, $con); - - if ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $count = (int) $row[0]; - } else { - $count = 0; // no rows returned; we infer that means 0 matches. - } - $stmt->closeCursor(); - return $count; - } - - - /** - * Returns the number of rows matching criteria, joining the related CcBlock table - * - * @param Criteria $criteria - * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. - * @param PropelPDO $con - * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN - * @return int Number of matching rows. - */ - public static function doCountJoinCcBlock(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) - { - // we're going to modify criteria, so copy it first - $criteria = clone $criteria; - - // We need to set the primary table name, since in the case that there are no WHERE columns - // it will be impossible for the BasePeer::createSelectSql() method to determine which - // tables go into the FROM clause. - $criteria->setPrimaryTableName(CcShowStampPeer::TABLE_NAME); - - if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { - $criteria->setDistinct(); - } - - if (!$criteria->hasSelectClause()) { - CcShowStampPeer::addSelectColumns($criteria); - } - - $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count - - // Set the correct dbName - $criteria->setDbName(self::DATABASE_NAME); - - if ($con === null) { - $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); - } - - $criteria->addJoin(CcShowStampPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); - - $stmt = BasePeer::doCount($criteria, $con); - - if ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $count = (int) $row[0]; - } else { - $count = 0; // no rows returned; we infer that means 0 matches. - } - $stmt->closeCursor(); - return $count; - } - - - /** - * Returns the number of rows matching criteria, joining the related CcPlaylist table - * - * @param Criteria $criteria - * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. - * @param PropelPDO $con - * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN - * @return int Number of matching rows. - */ - public static function doCountJoinCcPlaylist(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) - { - // we're going to modify criteria, so copy it first - $criteria = clone $criteria; - - // We need to set the primary table name, since in the case that there are no WHERE columns - // it will be impossible for the BasePeer::createSelectSql() method to determine which - // tables go into the FROM clause. - $criteria->setPrimaryTableName(CcShowStampPeer::TABLE_NAME); - - if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { - $criteria->setDistinct(); - } - - if (!$criteria->hasSelectClause()) { - CcShowStampPeer::addSelectColumns($criteria); - } - - $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count - - // Set the correct dbName - $criteria->setDbName(self::DATABASE_NAME); - - if ($con === null) { - $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); - } - - $criteria->addJoin(CcShowStampPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); - - $stmt = BasePeer::doCount($criteria, $con); - - if ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $count = (int) $row[0]; - } else { - $count = 0; // no rows returned; we infer that means 0 matches. - } - $stmt->closeCursor(); - return $count; - } - - - /** - * Selects a collection of CcShowStamp objects pre-filled with their CcShow objects. - * @param Criteria $criteria - * @param PropelPDO $con - * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN - * @return array Array of CcShowStamp objects. - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - */ - public static function doSelectJoinCcShow(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) - { - $criteria = clone $criteria; - - // Set the correct dbName if it has not been overridden - if ($criteria->getDbName() == Propel::getDefaultDB()) { - $criteria->setDbName(self::DATABASE_NAME); - } - - CcShowStampPeer::addSelectColumns($criteria); - $startcol = (CcShowStampPeer::NUM_COLUMNS - CcShowStampPeer::NUM_LAZY_LOAD_COLUMNS); - CcShowPeer::addSelectColumns($criteria); - - $criteria->addJoin(CcShowStampPeer::SHOW_ID, CcShowPeer::ID, $join_behavior); - - $stmt = BasePeer::doSelect($criteria, $con); - $results = array(); - - while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $key1 = CcShowStampPeer::getPrimaryKeyHashFromRow($row, 0); - if (null !== ($obj1 = CcShowStampPeer::getInstanceFromPool($key1))) { - // We no longer rehydrate the object, since this can cause data loss. - // See http://www.propelorm.org/ticket/509 - // $obj1->hydrate($row, 0, true); // rehydrate - } else { - - $cls = CcShowStampPeer::getOMClass(false); - - $obj1 = new $cls(); - $obj1->hydrate($row); - CcShowStampPeer::addInstanceToPool($obj1, $key1); - } // if $obj1 already loaded - - $key2 = CcShowPeer::getPrimaryKeyHashFromRow($row, $startcol); - if ($key2 !== null) { - $obj2 = CcShowPeer::getInstanceFromPool($key2); - if (!$obj2) { - - $cls = CcShowPeer::getOMClass(false); - - $obj2 = new $cls(); - $obj2->hydrate($row, $startcol); - CcShowPeer::addInstanceToPool($obj2, $key2); - } // if obj2 already loaded - - // Add the $obj1 (CcShowStamp) to $obj2 (CcShow) - $obj2->addCcShowStamp($obj1); - - } // if joined row was not null - - $results[] = $obj1; - } - $stmt->closeCursor(); - return $results; - } - - - /** - * Selects a collection of CcShowStamp objects pre-filled with their CcShowInstances objects. - * @param Criteria $criteria - * @param PropelPDO $con - * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN - * @return array Array of CcShowStamp objects. - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - */ - public static function doSelectJoinCcShowInstances(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) - { - $criteria = clone $criteria; - - // Set the correct dbName if it has not been overridden - if ($criteria->getDbName() == Propel::getDefaultDB()) { - $criteria->setDbName(self::DATABASE_NAME); - } - - CcShowStampPeer::addSelectColumns($criteria); - $startcol = (CcShowStampPeer::NUM_COLUMNS - CcShowStampPeer::NUM_LAZY_LOAD_COLUMNS); - CcShowInstancesPeer::addSelectColumns($criteria); - - $criteria->addJoin(CcShowStampPeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); - - $stmt = BasePeer::doSelect($criteria, $con); - $results = array(); - - while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $key1 = CcShowStampPeer::getPrimaryKeyHashFromRow($row, 0); - if (null !== ($obj1 = CcShowStampPeer::getInstanceFromPool($key1))) { - // We no longer rehydrate the object, since this can cause data loss. - // See http://www.propelorm.org/ticket/509 - // $obj1->hydrate($row, 0, true); // rehydrate - } else { - - $cls = CcShowStampPeer::getOMClass(false); - - $obj1 = new $cls(); - $obj1->hydrate($row); - CcShowStampPeer::addInstanceToPool($obj1, $key1); - } // if $obj1 already loaded - - $key2 = CcShowInstancesPeer::getPrimaryKeyHashFromRow($row, $startcol); - if ($key2 !== null) { - $obj2 = CcShowInstancesPeer::getInstanceFromPool($key2); - if (!$obj2) { - - $cls = CcShowInstancesPeer::getOMClass(false); - - $obj2 = new $cls(); - $obj2->hydrate($row, $startcol); - CcShowInstancesPeer::addInstanceToPool($obj2, $key2); - } // if obj2 already loaded - - // Add the $obj1 (CcShowStamp) to $obj2 (CcShowInstances) - $obj2->addCcShowStamp($obj1); - - } // if joined row was not null - - $results[] = $obj1; - } - $stmt->closeCursor(); - return $results; - } - - - /** - * Selects a collection of CcShowStamp objects pre-filled with their CcFiles objects. - * @param Criteria $criteria - * @param PropelPDO $con - * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN - * @return array Array of CcShowStamp objects. - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - */ - public static function doSelectJoinCcFiles(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) - { - $criteria = clone $criteria; - - // Set the correct dbName if it has not been overridden - if ($criteria->getDbName() == Propel::getDefaultDB()) { - $criteria->setDbName(self::DATABASE_NAME); - } - - CcShowStampPeer::addSelectColumns($criteria); - $startcol = (CcShowStampPeer::NUM_COLUMNS - CcShowStampPeer::NUM_LAZY_LOAD_COLUMNS); - CcFilesPeer::addSelectColumns($criteria); - - $criteria->addJoin(CcShowStampPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); - - $stmt = BasePeer::doSelect($criteria, $con); - $results = array(); - - while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $key1 = CcShowStampPeer::getPrimaryKeyHashFromRow($row, 0); - if (null !== ($obj1 = CcShowStampPeer::getInstanceFromPool($key1))) { - // We no longer rehydrate the object, since this can cause data loss. - // See http://www.propelorm.org/ticket/509 - // $obj1->hydrate($row, 0, true); // rehydrate - } else { - - $cls = CcShowStampPeer::getOMClass(false); - - $obj1 = new $cls(); - $obj1->hydrate($row); - CcShowStampPeer::addInstanceToPool($obj1, $key1); - } // if $obj1 already loaded - - $key2 = CcFilesPeer::getPrimaryKeyHashFromRow($row, $startcol); - if ($key2 !== null) { - $obj2 = CcFilesPeer::getInstanceFromPool($key2); - if (!$obj2) { - - $cls = CcFilesPeer::getOMClass(false); - - $obj2 = new $cls(); - $obj2->hydrate($row, $startcol); - CcFilesPeer::addInstanceToPool($obj2, $key2); - } // if obj2 already loaded - - // Add the $obj1 (CcShowStamp) to $obj2 (CcFiles) - $obj2->addCcShowStamp($obj1); - - } // if joined row was not null - - $results[] = $obj1; - } - $stmt->closeCursor(); - return $results; - } - - - /** - * Selects a collection of CcShowStamp objects pre-filled with their CcWebstream objects. - * @param Criteria $criteria - * @param PropelPDO $con - * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN - * @return array Array of CcShowStamp objects. - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - */ - public static function doSelectJoinCcWebstream(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) - { - $criteria = clone $criteria; - - // Set the correct dbName if it has not been overridden - if ($criteria->getDbName() == Propel::getDefaultDB()) { - $criteria->setDbName(self::DATABASE_NAME); - } - - CcShowStampPeer::addSelectColumns($criteria); - $startcol = (CcShowStampPeer::NUM_COLUMNS - CcShowStampPeer::NUM_LAZY_LOAD_COLUMNS); - CcWebstreamPeer::addSelectColumns($criteria); - - $criteria->addJoin(CcShowStampPeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); - - $stmt = BasePeer::doSelect($criteria, $con); - $results = array(); - - while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $key1 = CcShowStampPeer::getPrimaryKeyHashFromRow($row, 0); - if (null !== ($obj1 = CcShowStampPeer::getInstanceFromPool($key1))) { - // We no longer rehydrate the object, since this can cause data loss. - // See http://www.propelorm.org/ticket/509 - // $obj1->hydrate($row, 0, true); // rehydrate - } else { - - $cls = CcShowStampPeer::getOMClass(false); - - $obj1 = new $cls(); - $obj1->hydrate($row); - CcShowStampPeer::addInstanceToPool($obj1, $key1); - } // if $obj1 already loaded - - $key2 = CcWebstreamPeer::getPrimaryKeyHashFromRow($row, $startcol); - if ($key2 !== null) { - $obj2 = CcWebstreamPeer::getInstanceFromPool($key2); - if (!$obj2) { - - $cls = CcWebstreamPeer::getOMClass(false); - - $obj2 = new $cls(); - $obj2->hydrate($row, $startcol); - CcWebstreamPeer::addInstanceToPool($obj2, $key2); - } // if obj2 already loaded - - // Add the $obj1 (CcShowStamp) to $obj2 (CcWebstream) - $obj2->addCcShowStamp($obj1); - - } // if joined row was not null - - $results[] = $obj1; - } - $stmt->closeCursor(); - return $results; - } - - - /** - * Selects a collection of CcShowStamp objects pre-filled with their CcBlock objects. - * @param Criteria $criteria - * @param PropelPDO $con - * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN - * @return array Array of CcShowStamp objects. - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - */ - public static function doSelectJoinCcBlock(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) - { - $criteria = clone $criteria; - - // Set the correct dbName if it has not been overridden - if ($criteria->getDbName() == Propel::getDefaultDB()) { - $criteria->setDbName(self::DATABASE_NAME); - } - - CcShowStampPeer::addSelectColumns($criteria); - $startcol = (CcShowStampPeer::NUM_COLUMNS - CcShowStampPeer::NUM_LAZY_LOAD_COLUMNS); - CcBlockPeer::addSelectColumns($criteria); - - $criteria->addJoin(CcShowStampPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); - - $stmt = BasePeer::doSelect($criteria, $con); - $results = array(); - - while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $key1 = CcShowStampPeer::getPrimaryKeyHashFromRow($row, 0); - if (null !== ($obj1 = CcShowStampPeer::getInstanceFromPool($key1))) { - // We no longer rehydrate the object, since this can cause data loss. - // See http://www.propelorm.org/ticket/509 - // $obj1->hydrate($row, 0, true); // rehydrate - } else { - - $cls = CcShowStampPeer::getOMClass(false); - - $obj1 = new $cls(); - $obj1->hydrate($row); - CcShowStampPeer::addInstanceToPool($obj1, $key1); - } // if $obj1 already loaded - - $key2 = CcBlockPeer::getPrimaryKeyHashFromRow($row, $startcol); - if ($key2 !== null) { - $obj2 = CcBlockPeer::getInstanceFromPool($key2); - if (!$obj2) { - - $cls = CcBlockPeer::getOMClass(false); - - $obj2 = new $cls(); - $obj2->hydrate($row, $startcol); - CcBlockPeer::addInstanceToPool($obj2, $key2); - } // if obj2 already loaded - - // Add the $obj1 (CcShowStamp) to $obj2 (CcBlock) - $obj2->addCcShowStamp($obj1); - - } // if joined row was not null - - $results[] = $obj1; - } - $stmt->closeCursor(); - return $results; - } - - - /** - * Selects a collection of CcShowStamp objects pre-filled with their CcPlaylist objects. - * @param Criteria $criteria - * @param PropelPDO $con - * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN - * @return array Array of CcShowStamp objects. - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - */ - public static function doSelectJoinCcPlaylist(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) - { - $criteria = clone $criteria; - - // Set the correct dbName if it has not been overridden - if ($criteria->getDbName() == Propel::getDefaultDB()) { - $criteria->setDbName(self::DATABASE_NAME); - } - - CcShowStampPeer::addSelectColumns($criteria); - $startcol = (CcShowStampPeer::NUM_COLUMNS - CcShowStampPeer::NUM_LAZY_LOAD_COLUMNS); - CcPlaylistPeer::addSelectColumns($criteria); - - $criteria->addJoin(CcShowStampPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); - - $stmt = BasePeer::doSelect($criteria, $con); - $results = array(); - - while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $key1 = CcShowStampPeer::getPrimaryKeyHashFromRow($row, 0); - if (null !== ($obj1 = CcShowStampPeer::getInstanceFromPool($key1))) { - // We no longer rehydrate the object, since this can cause data loss. - // See http://www.propelorm.org/ticket/509 - // $obj1->hydrate($row, 0, true); // rehydrate - } else { - - $cls = CcShowStampPeer::getOMClass(false); - - $obj1 = new $cls(); - $obj1->hydrate($row); - CcShowStampPeer::addInstanceToPool($obj1, $key1); - } // if $obj1 already loaded - - $key2 = CcPlaylistPeer::getPrimaryKeyHashFromRow($row, $startcol); - if ($key2 !== null) { - $obj2 = CcPlaylistPeer::getInstanceFromPool($key2); - if (!$obj2) { - - $cls = CcPlaylistPeer::getOMClass(false); - - $obj2 = new $cls(); - $obj2->hydrate($row, $startcol); - CcPlaylistPeer::addInstanceToPool($obj2, $key2); - } // if obj2 already loaded - - // Add the $obj1 (CcShowStamp) to $obj2 (CcPlaylist) - $obj2->addCcShowStamp($obj1); - - } // if joined row was not null - - $results[] = $obj1; - } - $stmt->closeCursor(); - return $results; - } - - - /** - * Returns the number of rows matching criteria, joining all related tables - * - * @param Criteria $criteria - * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. - * @param PropelPDO $con - * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN - * @return int Number of matching rows. - */ - public static function doCountJoinAll(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) - { - // we're going to modify criteria, so copy it first - $criteria = clone $criteria; - - // We need to set the primary table name, since in the case that there are no WHERE columns - // it will be impossible for the BasePeer::createSelectSql() method to determine which - // tables go into the FROM clause. - $criteria->setPrimaryTableName(CcShowStampPeer::TABLE_NAME); - - if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { - $criteria->setDistinct(); - } - - if (!$criteria->hasSelectClause()) { - CcShowStampPeer::addSelectColumns($criteria); - } - - $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count - - // Set the correct dbName - $criteria->setDbName(self::DATABASE_NAME); - - if ($con === null) { - $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); - } - - $criteria->addJoin(CcShowStampPeer::SHOW_ID, CcShowPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); - - $stmt = BasePeer::doCount($criteria, $con); - - if ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $count = (int) $row[0]; - } else { - $count = 0; // no rows returned; we infer that means 0 matches. - } - $stmt->closeCursor(); - return $count; - } - - /** - * Selects a collection of CcShowStamp objects pre-filled with all related objects. - * - * @param Criteria $criteria - * @param PropelPDO $con - * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN - * @return array Array of CcShowStamp objects. - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - */ - public static function doSelectJoinAll(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) - { - $criteria = clone $criteria; - - // Set the correct dbName if it has not been overridden - if ($criteria->getDbName() == Propel::getDefaultDB()) { - $criteria->setDbName(self::DATABASE_NAME); - } - - CcShowStampPeer::addSelectColumns($criteria); - $startcol2 = (CcShowStampPeer::NUM_COLUMNS - CcShowStampPeer::NUM_LAZY_LOAD_COLUMNS); - - CcShowPeer::addSelectColumns($criteria); - $startcol3 = $startcol2 + (CcShowPeer::NUM_COLUMNS - CcShowPeer::NUM_LAZY_LOAD_COLUMNS); - - CcShowInstancesPeer::addSelectColumns($criteria); - $startcol4 = $startcol3 + (CcShowInstancesPeer::NUM_COLUMNS - CcShowInstancesPeer::NUM_LAZY_LOAD_COLUMNS); - - CcFilesPeer::addSelectColumns($criteria); - $startcol5 = $startcol4 + (CcFilesPeer::NUM_COLUMNS - CcFilesPeer::NUM_LAZY_LOAD_COLUMNS); - - CcWebstreamPeer::addSelectColumns($criteria); - $startcol6 = $startcol5 + (CcWebstreamPeer::NUM_COLUMNS - CcWebstreamPeer::NUM_LAZY_LOAD_COLUMNS); - - CcBlockPeer::addSelectColumns($criteria); - $startcol7 = $startcol6 + (CcBlockPeer::NUM_COLUMNS - CcBlockPeer::NUM_LAZY_LOAD_COLUMNS); - - CcPlaylistPeer::addSelectColumns($criteria); - $startcol8 = $startcol7 + (CcPlaylistPeer::NUM_COLUMNS - CcPlaylistPeer::NUM_LAZY_LOAD_COLUMNS); - - $criteria->addJoin(CcShowStampPeer::SHOW_ID, CcShowPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); - - $stmt = BasePeer::doSelect($criteria, $con); - $results = array(); - - while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $key1 = CcShowStampPeer::getPrimaryKeyHashFromRow($row, 0); - if (null !== ($obj1 = CcShowStampPeer::getInstanceFromPool($key1))) { - // We no longer rehydrate the object, since this can cause data loss. - // See http://www.propelorm.org/ticket/509 - // $obj1->hydrate($row, 0, true); // rehydrate - } else { - $cls = CcShowStampPeer::getOMClass(false); - - $obj1 = new $cls(); - $obj1->hydrate($row); - CcShowStampPeer::addInstanceToPool($obj1, $key1); - } // if obj1 already loaded - - // Add objects for joined CcShow rows - - $key2 = CcShowPeer::getPrimaryKeyHashFromRow($row, $startcol2); - if ($key2 !== null) { - $obj2 = CcShowPeer::getInstanceFromPool($key2); - if (!$obj2) { - - $cls = CcShowPeer::getOMClass(false); - - $obj2 = new $cls(); - $obj2->hydrate($row, $startcol2); - CcShowPeer::addInstanceToPool($obj2, $key2); - } // if obj2 loaded - - // Add the $obj1 (CcShowStamp) to the collection in $obj2 (CcShow) - $obj2->addCcShowStamp($obj1); - } // if joined row not null - - // Add objects for joined CcShowInstances rows - - $key3 = CcShowInstancesPeer::getPrimaryKeyHashFromRow($row, $startcol3); - if ($key3 !== null) { - $obj3 = CcShowInstancesPeer::getInstanceFromPool($key3); - if (!$obj3) { - - $cls = CcShowInstancesPeer::getOMClass(false); - - $obj3 = new $cls(); - $obj3->hydrate($row, $startcol3); - CcShowInstancesPeer::addInstanceToPool($obj3, $key3); - } // if obj3 loaded - - // Add the $obj1 (CcShowStamp) to the collection in $obj3 (CcShowInstances) - $obj3->addCcShowStamp($obj1); - } // if joined row not null - - // Add objects for joined CcFiles rows - - $key4 = CcFilesPeer::getPrimaryKeyHashFromRow($row, $startcol4); - if ($key4 !== null) { - $obj4 = CcFilesPeer::getInstanceFromPool($key4); - if (!$obj4) { - - $cls = CcFilesPeer::getOMClass(false); - - $obj4 = new $cls(); - $obj4->hydrate($row, $startcol4); - CcFilesPeer::addInstanceToPool($obj4, $key4); - } // if obj4 loaded - - // Add the $obj1 (CcShowStamp) to the collection in $obj4 (CcFiles) - $obj4->addCcShowStamp($obj1); - } // if joined row not null - - // Add objects for joined CcWebstream rows - - $key5 = CcWebstreamPeer::getPrimaryKeyHashFromRow($row, $startcol5); - if ($key5 !== null) { - $obj5 = CcWebstreamPeer::getInstanceFromPool($key5); - if (!$obj5) { - - $cls = CcWebstreamPeer::getOMClass(false); - - $obj5 = new $cls(); - $obj5->hydrate($row, $startcol5); - CcWebstreamPeer::addInstanceToPool($obj5, $key5); - } // if obj5 loaded - - // Add the $obj1 (CcShowStamp) to the collection in $obj5 (CcWebstream) - $obj5->addCcShowStamp($obj1); - } // if joined row not null - - // Add objects for joined CcBlock rows - - $key6 = CcBlockPeer::getPrimaryKeyHashFromRow($row, $startcol6); - if ($key6 !== null) { - $obj6 = CcBlockPeer::getInstanceFromPool($key6); - if (!$obj6) { - - $cls = CcBlockPeer::getOMClass(false); - - $obj6 = new $cls(); - $obj6->hydrate($row, $startcol6); - CcBlockPeer::addInstanceToPool($obj6, $key6); - } // if obj6 loaded - - // Add the $obj1 (CcShowStamp) to the collection in $obj6 (CcBlock) - $obj6->addCcShowStamp($obj1); - } // if joined row not null - - // Add objects for joined CcPlaylist rows - - $key7 = CcPlaylistPeer::getPrimaryKeyHashFromRow($row, $startcol7); - if ($key7 !== null) { - $obj7 = CcPlaylistPeer::getInstanceFromPool($key7); - if (!$obj7) { - - $cls = CcPlaylistPeer::getOMClass(false); - - $obj7 = new $cls(); - $obj7->hydrate($row, $startcol7); - CcPlaylistPeer::addInstanceToPool($obj7, $key7); - } // if obj7 loaded - - // Add the $obj1 (CcShowStamp) to the collection in $obj7 (CcPlaylist) - $obj7->addCcShowStamp($obj1); - } // if joined row not null - - $results[] = $obj1; - } - $stmt->closeCursor(); - return $results; - } - - - /** - * Returns the number of rows matching criteria, joining the related CcShow table - * - * @param Criteria $criteria - * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. - * @param PropelPDO $con - * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN - * @return int Number of matching rows. - */ - public static function doCountJoinAllExceptCcShow(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) - { - // we're going to modify criteria, so copy it first - $criteria = clone $criteria; - - // We need to set the primary table name, since in the case that there are no WHERE columns - // it will be impossible for the BasePeer::createSelectSql() method to determine which - // tables go into the FROM clause. - $criteria->setPrimaryTableName(CcShowStampPeer::TABLE_NAME); - - if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { - $criteria->setDistinct(); - } - - if (!$criteria->hasSelectClause()) { - CcShowStampPeer::addSelectColumns($criteria); - } - - $criteria->clearOrderByColumns(); // ORDER BY should not affect count - - // Set the correct dbName - $criteria->setDbName(self::DATABASE_NAME); - - if ($con === null) { - $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); - } - - $criteria->addJoin(CcShowStampPeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); - - $stmt = BasePeer::doCount($criteria, $con); - - if ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $count = (int) $row[0]; - } else { - $count = 0; // no rows returned; we infer that means 0 matches. - } - $stmt->closeCursor(); - return $count; - } - - - /** - * Returns the number of rows matching criteria, joining the related CcShowInstances table - * - * @param Criteria $criteria - * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. - * @param PropelPDO $con - * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN - * @return int Number of matching rows. - */ - public static function doCountJoinAllExceptCcShowInstances(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) - { - // we're going to modify criteria, so copy it first - $criteria = clone $criteria; - - // We need to set the primary table name, since in the case that there are no WHERE columns - // it will be impossible for the BasePeer::createSelectSql() method to determine which - // tables go into the FROM clause. - $criteria->setPrimaryTableName(CcShowStampPeer::TABLE_NAME); - - if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { - $criteria->setDistinct(); - } - - if (!$criteria->hasSelectClause()) { - CcShowStampPeer::addSelectColumns($criteria); - } - - $criteria->clearOrderByColumns(); // ORDER BY should not affect count - - // Set the correct dbName - $criteria->setDbName(self::DATABASE_NAME); - - if ($con === null) { - $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); - } - - $criteria->addJoin(CcShowStampPeer::SHOW_ID, CcShowPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); - - $stmt = BasePeer::doCount($criteria, $con); - - if ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $count = (int) $row[0]; - } else { - $count = 0; // no rows returned; we infer that means 0 matches. - } - $stmt->closeCursor(); - return $count; - } - - - /** - * Returns the number of rows matching criteria, joining the related CcFiles table - * - * @param Criteria $criteria - * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. - * @param PropelPDO $con - * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN - * @return int Number of matching rows. - */ - public static function doCountJoinAllExceptCcFiles(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) - { - // we're going to modify criteria, so copy it first - $criteria = clone $criteria; - - // We need to set the primary table name, since in the case that there are no WHERE columns - // it will be impossible for the BasePeer::createSelectSql() method to determine which - // tables go into the FROM clause. - $criteria->setPrimaryTableName(CcShowStampPeer::TABLE_NAME); - - if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { - $criteria->setDistinct(); - } - - if (!$criteria->hasSelectClause()) { - CcShowStampPeer::addSelectColumns($criteria); - } - - $criteria->clearOrderByColumns(); // ORDER BY should not affect count - - // Set the correct dbName - $criteria->setDbName(self::DATABASE_NAME); - - if ($con === null) { - $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); - } - - $criteria->addJoin(CcShowStampPeer::SHOW_ID, CcShowPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); - - $stmt = BasePeer::doCount($criteria, $con); - - if ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $count = (int) $row[0]; - } else { - $count = 0; // no rows returned; we infer that means 0 matches. - } - $stmt->closeCursor(); - return $count; - } - - - /** - * Returns the number of rows matching criteria, joining the related CcWebstream table - * - * @param Criteria $criteria - * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. - * @param PropelPDO $con - * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN - * @return int Number of matching rows. - */ - public static function doCountJoinAllExceptCcWebstream(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) - { - // we're going to modify criteria, so copy it first - $criteria = clone $criteria; - - // We need to set the primary table name, since in the case that there are no WHERE columns - // it will be impossible for the BasePeer::createSelectSql() method to determine which - // tables go into the FROM clause. - $criteria->setPrimaryTableName(CcShowStampPeer::TABLE_NAME); - - if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { - $criteria->setDistinct(); - } - - if (!$criteria->hasSelectClause()) { - CcShowStampPeer::addSelectColumns($criteria); - } - - $criteria->clearOrderByColumns(); // ORDER BY should not affect count - - // Set the correct dbName - $criteria->setDbName(self::DATABASE_NAME); - - if ($con === null) { - $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); - } - - $criteria->addJoin(CcShowStampPeer::SHOW_ID, CcShowPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); - - $stmt = BasePeer::doCount($criteria, $con); - - if ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $count = (int) $row[0]; - } else { - $count = 0; // no rows returned; we infer that means 0 matches. - } - $stmt->closeCursor(); - return $count; - } - - - /** - * Returns the number of rows matching criteria, joining the related CcBlock table - * - * @param Criteria $criteria - * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. - * @param PropelPDO $con - * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN - * @return int Number of matching rows. - */ - public static function doCountJoinAllExceptCcBlock(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) - { - // we're going to modify criteria, so copy it first - $criteria = clone $criteria; - - // We need to set the primary table name, since in the case that there are no WHERE columns - // it will be impossible for the BasePeer::createSelectSql() method to determine which - // tables go into the FROM clause. - $criteria->setPrimaryTableName(CcShowStampPeer::TABLE_NAME); - - if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { - $criteria->setDistinct(); - } - - if (!$criteria->hasSelectClause()) { - CcShowStampPeer::addSelectColumns($criteria); - } - - $criteria->clearOrderByColumns(); // ORDER BY should not affect count - - // Set the correct dbName - $criteria->setDbName(self::DATABASE_NAME); - - if ($con === null) { - $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); - } - - $criteria->addJoin(CcShowStampPeer::SHOW_ID, CcShowPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); - - $stmt = BasePeer::doCount($criteria, $con); - - if ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $count = (int) $row[0]; - } else { - $count = 0; // no rows returned; we infer that means 0 matches. - } - $stmt->closeCursor(); - return $count; - } - - - /** - * Returns the number of rows matching criteria, joining the related CcPlaylist table - * - * @param Criteria $criteria - * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. - * @param PropelPDO $con - * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN - * @return int Number of matching rows. - */ - public static function doCountJoinAllExceptCcPlaylist(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) - { - // we're going to modify criteria, so copy it first - $criteria = clone $criteria; - - // We need to set the primary table name, since in the case that there are no WHERE columns - // it will be impossible for the BasePeer::createSelectSql() method to determine which - // tables go into the FROM clause. - $criteria->setPrimaryTableName(CcShowStampPeer::TABLE_NAME); - - if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { - $criteria->setDistinct(); - } - - if (!$criteria->hasSelectClause()) { - CcShowStampPeer::addSelectColumns($criteria); - } - - $criteria->clearOrderByColumns(); // ORDER BY should not affect count - - // Set the correct dbName - $criteria->setDbName(self::DATABASE_NAME); - - if ($con === null) { - $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); - } - - $criteria->addJoin(CcShowStampPeer::SHOW_ID, CcShowPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); - - $stmt = BasePeer::doCount($criteria, $con); - - if ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $count = (int) $row[0]; - } else { - $count = 0; // no rows returned; we infer that means 0 matches. - } - $stmt->closeCursor(); - return $count; - } - - - /** - * Selects a collection of CcShowStamp objects pre-filled with all related objects except CcShow. - * - * @param Criteria $criteria - * @param PropelPDO $con - * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN - * @return array Array of CcShowStamp objects. - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - */ - public static function doSelectJoinAllExceptCcShow(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) - { - $criteria = clone $criteria; - - // Set the correct dbName if it has not been overridden - // $criteria->getDbName() will return the same object if not set to another value - // so == check is okay and faster - if ($criteria->getDbName() == Propel::getDefaultDB()) { - $criteria->setDbName(self::DATABASE_NAME); - } - - CcShowStampPeer::addSelectColumns($criteria); - $startcol2 = (CcShowStampPeer::NUM_COLUMNS - CcShowStampPeer::NUM_LAZY_LOAD_COLUMNS); - - CcShowInstancesPeer::addSelectColumns($criteria); - $startcol3 = $startcol2 + (CcShowInstancesPeer::NUM_COLUMNS - CcShowInstancesPeer::NUM_LAZY_LOAD_COLUMNS); - - CcFilesPeer::addSelectColumns($criteria); - $startcol4 = $startcol3 + (CcFilesPeer::NUM_COLUMNS - CcFilesPeer::NUM_LAZY_LOAD_COLUMNS); - - CcWebstreamPeer::addSelectColumns($criteria); - $startcol5 = $startcol4 + (CcWebstreamPeer::NUM_COLUMNS - CcWebstreamPeer::NUM_LAZY_LOAD_COLUMNS); - - CcBlockPeer::addSelectColumns($criteria); - $startcol6 = $startcol5 + (CcBlockPeer::NUM_COLUMNS - CcBlockPeer::NUM_LAZY_LOAD_COLUMNS); - - CcPlaylistPeer::addSelectColumns($criteria); - $startcol7 = $startcol6 + (CcPlaylistPeer::NUM_COLUMNS - CcPlaylistPeer::NUM_LAZY_LOAD_COLUMNS); - - $criteria->addJoin(CcShowStampPeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); - - - $stmt = BasePeer::doSelect($criteria, $con); - $results = array(); - - while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $key1 = CcShowStampPeer::getPrimaryKeyHashFromRow($row, 0); - if (null !== ($obj1 = CcShowStampPeer::getInstanceFromPool($key1))) { - // We no longer rehydrate the object, since this can cause data loss. - // See http://www.propelorm.org/ticket/509 - // $obj1->hydrate($row, 0, true); // rehydrate - } else { - $cls = CcShowStampPeer::getOMClass(false); - - $obj1 = new $cls(); - $obj1->hydrate($row); - CcShowStampPeer::addInstanceToPool($obj1, $key1); - } // if obj1 already loaded - - // Add objects for joined CcShowInstances rows - - $key2 = CcShowInstancesPeer::getPrimaryKeyHashFromRow($row, $startcol2); - if ($key2 !== null) { - $obj2 = CcShowInstancesPeer::getInstanceFromPool($key2); - if (!$obj2) { - - $cls = CcShowInstancesPeer::getOMClass(false); - - $obj2 = new $cls(); - $obj2->hydrate($row, $startcol2); - CcShowInstancesPeer::addInstanceToPool($obj2, $key2); - } // if $obj2 already loaded - - // Add the $obj1 (CcShowStamp) to the collection in $obj2 (CcShowInstances) - $obj2->addCcShowStamp($obj1); - - } // if joined row is not null - - // Add objects for joined CcFiles rows - - $key3 = CcFilesPeer::getPrimaryKeyHashFromRow($row, $startcol3); - if ($key3 !== null) { - $obj3 = CcFilesPeer::getInstanceFromPool($key3); - if (!$obj3) { - - $cls = CcFilesPeer::getOMClass(false); - - $obj3 = new $cls(); - $obj3->hydrate($row, $startcol3); - CcFilesPeer::addInstanceToPool($obj3, $key3); - } // if $obj3 already loaded - - // Add the $obj1 (CcShowStamp) to the collection in $obj3 (CcFiles) - $obj3->addCcShowStamp($obj1); - - } // if joined row is not null - - // Add objects for joined CcWebstream rows - - $key4 = CcWebstreamPeer::getPrimaryKeyHashFromRow($row, $startcol4); - if ($key4 !== null) { - $obj4 = CcWebstreamPeer::getInstanceFromPool($key4); - if (!$obj4) { - - $cls = CcWebstreamPeer::getOMClass(false); - - $obj4 = new $cls(); - $obj4->hydrate($row, $startcol4); - CcWebstreamPeer::addInstanceToPool($obj4, $key4); - } // if $obj4 already loaded - - // Add the $obj1 (CcShowStamp) to the collection in $obj4 (CcWebstream) - $obj4->addCcShowStamp($obj1); - - } // if joined row is not null - - // Add objects for joined CcBlock rows - - $key5 = CcBlockPeer::getPrimaryKeyHashFromRow($row, $startcol5); - if ($key5 !== null) { - $obj5 = CcBlockPeer::getInstanceFromPool($key5); - if (!$obj5) { - - $cls = CcBlockPeer::getOMClass(false); - - $obj5 = new $cls(); - $obj5->hydrate($row, $startcol5); - CcBlockPeer::addInstanceToPool($obj5, $key5); - } // if $obj5 already loaded - - // Add the $obj1 (CcShowStamp) to the collection in $obj5 (CcBlock) - $obj5->addCcShowStamp($obj1); - - } // if joined row is not null - - // Add objects for joined CcPlaylist rows - - $key6 = CcPlaylistPeer::getPrimaryKeyHashFromRow($row, $startcol6); - if ($key6 !== null) { - $obj6 = CcPlaylistPeer::getInstanceFromPool($key6); - if (!$obj6) { - - $cls = CcPlaylistPeer::getOMClass(false); - - $obj6 = new $cls(); - $obj6->hydrate($row, $startcol6); - CcPlaylistPeer::addInstanceToPool($obj6, $key6); - } // if $obj6 already loaded - - // Add the $obj1 (CcShowStamp) to the collection in $obj6 (CcPlaylist) - $obj6->addCcShowStamp($obj1); - - } // if joined row is not null - - $results[] = $obj1; - } - $stmt->closeCursor(); - return $results; - } - - - /** - * Selects a collection of CcShowStamp objects pre-filled with all related objects except CcShowInstances. - * - * @param Criteria $criteria - * @param PropelPDO $con - * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN - * @return array Array of CcShowStamp objects. - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - */ - public static function doSelectJoinAllExceptCcShowInstances(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) - { - $criteria = clone $criteria; - - // Set the correct dbName if it has not been overridden - // $criteria->getDbName() will return the same object if not set to another value - // so == check is okay and faster - if ($criteria->getDbName() == Propel::getDefaultDB()) { - $criteria->setDbName(self::DATABASE_NAME); - } - - CcShowStampPeer::addSelectColumns($criteria); - $startcol2 = (CcShowStampPeer::NUM_COLUMNS - CcShowStampPeer::NUM_LAZY_LOAD_COLUMNS); - - CcShowPeer::addSelectColumns($criteria); - $startcol3 = $startcol2 + (CcShowPeer::NUM_COLUMNS - CcShowPeer::NUM_LAZY_LOAD_COLUMNS); - - CcFilesPeer::addSelectColumns($criteria); - $startcol4 = $startcol3 + (CcFilesPeer::NUM_COLUMNS - CcFilesPeer::NUM_LAZY_LOAD_COLUMNS); - - CcWebstreamPeer::addSelectColumns($criteria); - $startcol5 = $startcol4 + (CcWebstreamPeer::NUM_COLUMNS - CcWebstreamPeer::NUM_LAZY_LOAD_COLUMNS); - - CcBlockPeer::addSelectColumns($criteria); - $startcol6 = $startcol5 + (CcBlockPeer::NUM_COLUMNS - CcBlockPeer::NUM_LAZY_LOAD_COLUMNS); - - CcPlaylistPeer::addSelectColumns($criteria); - $startcol7 = $startcol6 + (CcPlaylistPeer::NUM_COLUMNS - CcPlaylistPeer::NUM_LAZY_LOAD_COLUMNS); - - $criteria->addJoin(CcShowStampPeer::SHOW_ID, CcShowPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); - - - $stmt = BasePeer::doSelect($criteria, $con); - $results = array(); - - while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $key1 = CcShowStampPeer::getPrimaryKeyHashFromRow($row, 0); - if (null !== ($obj1 = CcShowStampPeer::getInstanceFromPool($key1))) { - // We no longer rehydrate the object, since this can cause data loss. - // See http://www.propelorm.org/ticket/509 - // $obj1->hydrate($row, 0, true); // rehydrate - } else { - $cls = CcShowStampPeer::getOMClass(false); - - $obj1 = new $cls(); - $obj1->hydrate($row); - CcShowStampPeer::addInstanceToPool($obj1, $key1); - } // if obj1 already loaded - - // Add objects for joined CcShow rows - - $key2 = CcShowPeer::getPrimaryKeyHashFromRow($row, $startcol2); - if ($key2 !== null) { - $obj2 = CcShowPeer::getInstanceFromPool($key2); - if (!$obj2) { - - $cls = CcShowPeer::getOMClass(false); - - $obj2 = new $cls(); - $obj2->hydrate($row, $startcol2); - CcShowPeer::addInstanceToPool($obj2, $key2); - } // if $obj2 already loaded - - // Add the $obj1 (CcShowStamp) to the collection in $obj2 (CcShow) - $obj2->addCcShowStamp($obj1); - - } // if joined row is not null - - // Add objects for joined CcFiles rows - - $key3 = CcFilesPeer::getPrimaryKeyHashFromRow($row, $startcol3); - if ($key3 !== null) { - $obj3 = CcFilesPeer::getInstanceFromPool($key3); - if (!$obj3) { - - $cls = CcFilesPeer::getOMClass(false); - - $obj3 = new $cls(); - $obj3->hydrate($row, $startcol3); - CcFilesPeer::addInstanceToPool($obj3, $key3); - } // if $obj3 already loaded - - // Add the $obj1 (CcShowStamp) to the collection in $obj3 (CcFiles) - $obj3->addCcShowStamp($obj1); - - } // if joined row is not null - - // Add objects for joined CcWebstream rows - - $key4 = CcWebstreamPeer::getPrimaryKeyHashFromRow($row, $startcol4); - if ($key4 !== null) { - $obj4 = CcWebstreamPeer::getInstanceFromPool($key4); - if (!$obj4) { - - $cls = CcWebstreamPeer::getOMClass(false); - - $obj4 = new $cls(); - $obj4->hydrate($row, $startcol4); - CcWebstreamPeer::addInstanceToPool($obj4, $key4); - } // if $obj4 already loaded - - // Add the $obj1 (CcShowStamp) to the collection in $obj4 (CcWebstream) - $obj4->addCcShowStamp($obj1); - - } // if joined row is not null - - // Add objects for joined CcBlock rows - - $key5 = CcBlockPeer::getPrimaryKeyHashFromRow($row, $startcol5); - if ($key5 !== null) { - $obj5 = CcBlockPeer::getInstanceFromPool($key5); - if (!$obj5) { - - $cls = CcBlockPeer::getOMClass(false); - - $obj5 = new $cls(); - $obj5->hydrate($row, $startcol5); - CcBlockPeer::addInstanceToPool($obj5, $key5); - } // if $obj5 already loaded - - // Add the $obj1 (CcShowStamp) to the collection in $obj5 (CcBlock) - $obj5->addCcShowStamp($obj1); - - } // if joined row is not null - - // Add objects for joined CcPlaylist rows - - $key6 = CcPlaylistPeer::getPrimaryKeyHashFromRow($row, $startcol6); - if ($key6 !== null) { - $obj6 = CcPlaylistPeer::getInstanceFromPool($key6); - if (!$obj6) { - - $cls = CcPlaylistPeer::getOMClass(false); - - $obj6 = new $cls(); - $obj6->hydrate($row, $startcol6); - CcPlaylistPeer::addInstanceToPool($obj6, $key6); - } // if $obj6 already loaded - - // Add the $obj1 (CcShowStamp) to the collection in $obj6 (CcPlaylist) - $obj6->addCcShowStamp($obj1); - - } // if joined row is not null - - $results[] = $obj1; - } - $stmt->closeCursor(); - return $results; - } - - - /** - * Selects a collection of CcShowStamp objects pre-filled with all related objects except CcFiles. - * - * @param Criteria $criteria - * @param PropelPDO $con - * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN - * @return array Array of CcShowStamp objects. - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - */ - public static function doSelectJoinAllExceptCcFiles(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) - { - $criteria = clone $criteria; - - // Set the correct dbName if it has not been overridden - // $criteria->getDbName() will return the same object if not set to another value - // so == check is okay and faster - if ($criteria->getDbName() == Propel::getDefaultDB()) { - $criteria->setDbName(self::DATABASE_NAME); - } - - CcShowStampPeer::addSelectColumns($criteria); - $startcol2 = (CcShowStampPeer::NUM_COLUMNS - CcShowStampPeer::NUM_LAZY_LOAD_COLUMNS); - - CcShowPeer::addSelectColumns($criteria); - $startcol3 = $startcol2 + (CcShowPeer::NUM_COLUMNS - CcShowPeer::NUM_LAZY_LOAD_COLUMNS); - - CcShowInstancesPeer::addSelectColumns($criteria); - $startcol4 = $startcol3 + (CcShowInstancesPeer::NUM_COLUMNS - CcShowInstancesPeer::NUM_LAZY_LOAD_COLUMNS); - - CcWebstreamPeer::addSelectColumns($criteria); - $startcol5 = $startcol4 + (CcWebstreamPeer::NUM_COLUMNS - CcWebstreamPeer::NUM_LAZY_LOAD_COLUMNS); - - CcBlockPeer::addSelectColumns($criteria); - $startcol6 = $startcol5 + (CcBlockPeer::NUM_COLUMNS - CcBlockPeer::NUM_LAZY_LOAD_COLUMNS); - - CcPlaylistPeer::addSelectColumns($criteria); - $startcol7 = $startcol6 + (CcPlaylistPeer::NUM_COLUMNS - CcPlaylistPeer::NUM_LAZY_LOAD_COLUMNS); - - $criteria->addJoin(CcShowStampPeer::SHOW_ID, CcShowPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); - - - $stmt = BasePeer::doSelect($criteria, $con); - $results = array(); - - while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $key1 = CcShowStampPeer::getPrimaryKeyHashFromRow($row, 0); - if (null !== ($obj1 = CcShowStampPeer::getInstanceFromPool($key1))) { - // We no longer rehydrate the object, since this can cause data loss. - // See http://www.propelorm.org/ticket/509 - // $obj1->hydrate($row, 0, true); // rehydrate - } else { - $cls = CcShowStampPeer::getOMClass(false); - - $obj1 = new $cls(); - $obj1->hydrate($row); - CcShowStampPeer::addInstanceToPool($obj1, $key1); - } // if obj1 already loaded - - // Add objects for joined CcShow rows - - $key2 = CcShowPeer::getPrimaryKeyHashFromRow($row, $startcol2); - if ($key2 !== null) { - $obj2 = CcShowPeer::getInstanceFromPool($key2); - if (!$obj2) { - - $cls = CcShowPeer::getOMClass(false); - - $obj2 = new $cls(); - $obj2->hydrate($row, $startcol2); - CcShowPeer::addInstanceToPool($obj2, $key2); - } // if $obj2 already loaded - - // Add the $obj1 (CcShowStamp) to the collection in $obj2 (CcShow) - $obj2->addCcShowStamp($obj1); - - } // if joined row is not null - - // Add objects for joined CcShowInstances rows - - $key3 = CcShowInstancesPeer::getPrimaryKeyHashFromRow($row, $startcol3); - if ($key3 !== null) { - $obj3 = CcShowInstancesPeer::getInstanceFromPool($key3); - if (!$obj3) { - - $cls = CcShowInstancesPeer::getOMClass(false); - - $obj3 = new $cls(); - $obj3->hydrate($row, $startcol3); - CcShowInstancesPeer::addInstanceToPool($obj3, $key3); - } // if $obj3 already loaded - - // Add the $obj1 (CcShowStamp) to the collection in $obj3 (CcShowInstances) - $obj3->addCcShowStamp($obj1); - - } // if joined row is not null - - // Add objects for joined CcWebstream rows - - $key4 = CcWebstreamPeer::getPrimaryKeyHashFromRow($row, $startcol4); - if ($key4 !== null) { - $obj4 = CcWebstreamPeer::getInstanceFromPool($key4); - if (!$obj4) { - - $cls = CcWebstreamPeer::getOMClass(false); - - $obj4 = new $cls(); - $obj4->hydrate($row, $startcol4); - CcWebstreamPeer::addInstanceToPool($obj4, $key4); - } // if $obj4 already loaded - - // Add the $obj1 (CcShowStamp) to the collection in $obj4 (CcWebstream) - $obj4->addCcShowStamp($obj1); - - } // if joined row is not null - - // Add objects for joined CcBlock rows - - $key5 = CcBlockPeer::getPrimaryKeyHashFromRow($row, $startcol5); - if ($key5 !== null) { - $obj5 = CcBlockPeer::getInstanceFromPool($key5); - if (!$obj5) { - - $cls = CcBlockPeer::getOMClass(false); - - $obj5 = new $cls(); - $obj5->hydrate($row, $startcol5); - CcBlockPeer::addInstanceToPool($obj5, $key5); - } // if $obj5 already loaded - - // Add the $obj1 (CcShowStamp) to the collection in $obj5 (CcBlock) - $obj5->addCcShowStamp($obj1); - - } // if joined row is not null - - // Add objects for joined CcPlaylist rows - - $key6 = CcPlaylistPeer::getPrimaryKeyHashFromRow($row, $startcol6); - if ($key6 !== null) { - $obj6 = CcPlaylistPeer::getInstanceFromPool($key6); - if (!$obj6) { - - $cls = CcPlaylistPeer::getOMClass(false); - - $obj6 = new $cls(); - $obj6->hydrate($row, $startcol6); - CcPlaylistPeer::addInstanceToPool($obj6, $key6); - } // if $obj6 already loaded - - // Add the $obj1 (CcShowStamp) to the collection in $obj6 (CcPlaylist) - $obj6->addCcShowStamp($obj1); - - } // if joined row is not null - - $results[] = $obj1; - } - $stmt->closeCursor(); - return $results; - } - - - /** - * Selects a collection of CcShowStamp objects pre-filled with all related objects except CcWebstream. - * - * @param Criteria $criteria - * @param PropelPDO $con - * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN - * @return array Array of CcShowStamp objects. - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - */ - public static function doSelectJoinAllExceptCcWebstream(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) - { - $criteria = clone $criteria; - - // Set the correct dbName if it has not been overridden - // $criteria->getDbName() will return the same object if not set to another value - // so == check is okay and faster - if ($criteria->getDbName() == Propel::getDefaultDB()) { - $criteria->setDbName(self::DATABASE_NAME); - } - - CcShowStampPeer::addSelectColumns($criteria); - $startcol2 = (CcShowStampPeer::NUM_COLUMNS - CcShowStampPeer::NUM_LAZY_LOAD_COLUMNS); - - CcShowPeer::addSelectColumns($criteria); - $startcol3 = $startcol2 + (CcShowPeer::NUM_COLUMNS - CcShowPeer::NUM_LAZY_LOAD_COLUMNS); - - CcShowInstancesPeer::addSelectColumns($criteria); - $startcol4 = $startcol3 + (CcShowInstancesPeer::NUM_COLUMNS - CcShowInstancesPeer::NUM_LAZY_LOAD_COLUMNS); - - CcFilesPeer::addSelectColumns($criteria); - $startcol5 = $startcol4 + (CcFilesPeer::NUM_COLUMNS - CcFilesPeer::NUM_LAZY_LOAD_COLUMNS); - - CcBlockPeer::addSelectColumns($criteria); - $startcol6 = $startcol5 + (CcBlockPeer::NUM_COLUMNS - CcBlockPeer::NUM_LAZY_LOAD_COLUMNS); - - CcPlaylistPeer::addSelectColumns($criteria); - $startcol7 = $startcol6 + (CcPlaylistPeer::NUM_COLUMNS - CcPlaylistPeer::NUM_LAZY_LOAD_COLUMNS); - - $criteria->addJoin(CcShowStampPeer::SHOW_ID, CcShowPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); - - - $stmt = BasePeer::doSelect($criteria, $con); - $results = array(); - - while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $key1 = CcShowStampPeer::getPrimaryKeyHashFromRow($row, 0); - if (null !== ($obj1 = CcShowStampPeer::getInstanceFromPool($key1))) { - // We no longer rehydrate the object, since this can cause data loss. - // See http://www.propelorm.org/ticket/509 - // $obj1->hydrate($row, 0, true); // rehydrate - } else { - $cls = CcShowStampPeer::getOMClass(false); - - $obj1 = new $cls(); - $obj1->hydrate($row); - CcShowStampPeer::addInstanceToPool($obj1, $key1); - } // if obj1 already loaded - - // Add objects for joined CcShow rows - - $key2 = CcShowPeer::getPrimaryKeyHashFromRow($row, $startcol2); - if ($key2 !== null) { - $obj2 = CcShowPeer::getInstanceFromPool($key2); - if (!$obj2) { - - $cls = CcShowPeer::getOMClass(false); - - $obj2 = new $cls(); - $obj2->hydrate($row, $startcol2); - CcShowPeer::addInstanceToPool($obj2, $key2); - } // if $obj2 already loaded - - // Add the $obj1 (CcShowStamp) to the collection in $obj2 (CcShow) - $obj2->addCcShowStamp($obj1); - - } // if joined row is not null - - // Add objects for joined CcShowInstances rows - - $key3 = CcShowInstancesPeer::getPrimaryKeyHashFromRow($row, $startcol3); - if ($key3 !== null) { - $obj3 = CcShowInstancesPeer::getInstanceFromPool($key3); - if (!$obj3) { - - $cls = CcShowInstancesPeer::getOMClass(false); - - $obj3 = new $cls(); - $obj3->hydrate($row, $startcol3); - CcShowInstancesPeer::addInstanceToPool($obj3, $key3); - } // if $obj3 already loaded - - // Add the $obj1 (CcShowStamp) to the collection in $obj3 (CcShowInstances) - $obj3->addCcShowStamp($obj1); - - } // if joined row is not null - - // Add objects for joined CcFiles rows - - $key4 = CcFilesPeer::getPrimaryKeyHashFromRow($row, $startcol4); - if ($key4 !== null) { - $obj4 = CcFilesPeer::getInstanceFromPool($key4); - if (!$obj4) { - - $cls = CcFilesPeer::getOMClass(false); - - $obj4 = new $cls(); - $obj4->hydrate($row, $startcol4); - CcFilesPeer::addInstanceToPool($obj4, $key4); - } // if $obj4 already loaded - - // Add the $obj1 (CcShowStamp) to the collection in $obj4 (CcFiles) - $obj4->addCcShowStamp($obj1); - - } // if joined row is not null - - // Add objects for joined CcBlock rows - - $key5 = CcBlockPeer::getPrimaryKeyHashFromRow($row, $startcol5); - if ($key5 !== null) { - $obj5 = CcBlockPeer::getInstanceFromPool($key5); - if (!$obj5) { - - $cls = CcBlockPeer::getOMClass(false); - - $obj5 = new $cls(); - $obj5->hydrate($row, $startcol5); - CcBlockPeer::addInstanceToPool($obj5, $key5); - } // if $obj5 already loaded - - // Add the $obj1 (CcShowStamp) to the collection in $obj5 (CcBlock) - $obj5->addCcShowStamp($obj1); - - } // if joined row is not null - - // Add objects for joined CcPlaylist rows - - $key6 = CcPlaylistPeer::getPrimaryKeyHashFromRow($row, $startcol6); - if ($key6 !== null) { - $obj6 = CcPlaylistPeer::getInstanceFromPool($key6); - if (!$obj6) { - - $cls = CcPlaylistPeer::getOMClass(false); - - $obj6 = new $cls(); - $obj6->hydrate($row, $startcol6); - CcPlaylistPeer::addInstanceToPool($obj6, $key6); - } // if $obj6 already loaded - - // Add the $obj1 (CcShowStamp) to the collection in $obj6 (CcPlaylist) - $obj6->addCcShowStamp($obj1); - - } // if joined row is not null - - $results[] = $obj1; - } - $stmt->closeCursor(); - return $results; - } - - - /** - * Selects a collection of CcShowStamp objects pre-filled with all related objects except CcBlock. - * - * @param Criteria $criteria - * @param PropelPDO $con - * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN - * @return array Array of CcShowStamp objects. - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - */ - public static function doSelectJoinAllExceptCcBlock(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) - { - $criteria = clone $criteria; - - // Set the correct dbName if it has not been overridden - // $criteria->getDbName() will return the same object if not set to another value - // so == check is okay and faster - if ($criteria->getDbName() == Propel::getDefaultDB()) { - $criteria->setDbName(self::DATABASE_NAME); - } - - CcShowStampPeer::addSelectColumns($criteria); - $startcol2 = (CcShowStampPeer::NUM_COLUMNS - CcShowStampPeer::NUM_LAZY_LOAD_COLUMNS); - - CcShowPeer::addSelectColumns($criteria); - $startcol3 = $startcol2 + (CcShowPeer::NUM_COLUMNS - CcShowPeer::NUM_LAZY_LOAD_COLUMNS); - - CcShowInstancesPeer::addSelectColumns($criteria); - $startcol4 = $startcol3 + (CcShowInstancesPeer::NUM_COLUMNS - CcShowInstancesPeer::NUM_LAZY_LOAD_COLUMNS); - - CcFilesPeer::addSelectColumns($criteria); - $startcol5 = $startcol4 + (CcFilesPeer::NUM_COLUMNS - CcFilesPeer::NUM_LAZY_LOAD_COLUMNS); - - CcWebstreamPeer::addSelectColumns($criteria); - $startcol6 = $startcol5 + (CcWebstreamPeer::NUM_COLUMNS - CcWebstreamPeer::NUM_LAZY_LOAD_COLUMNS); - - CcPlaylistPeer::addSelectColumns($criteria); - $startcol7 = $startcol6 + (CcPlaylistPeer::NUM_COLUMNS - CcPlaylistPeer::NUM_LAZY_LOAD_COLUMNS); - - $criteria->addJoin(CcShowStampPeer::SHOW_ID, CcShowPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); - - - $stmt = BasePeer::doSelect($criteria, $con); - $results = array(); - - while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $key1 = CcShowStampPeer::getPrimaryKeyHashFromRow($row, 0); - if (null !== ($obj1 = CcShowStampPeer::getInstanceFromPool($key1))) { - // We no longer rehydrate the object, since this can cause data loss. - // See http://www.propelorm.org/ticket/509 - // $obj1->hydrate($row, 0, true); // rehydrate - } else { - $cls = CcShowStampPeer::getOMClass(false); - - $obj1 = new $cls(); - $obj1->hydrate($row); - CcShowStampPeer::addInstanceToPool($obj1, $key1); - } // if obj1 already loaded - - // Add objects for joined CcShow rows - - $key2 = CcShowPeer::getPrimaryKeyHashFromRow($row, $startcol2); - if ($key2 !== null) { - $obj2 = CcShowPeer::getInstanceFromPool($key2); - if (!$obj2) { - - $cls = CcShowPeer::getOMClass(false); - - $obj2 = new $cls(); - $obj2->hydrate($row, $startcol2); - CcShowPeer::addInstanceToPool($obj2, $key2); - } // if $obj2 already loaded - - // Add the $obj1 (CcShowStamp) to the collection in $obj2 (CcShow) - $obj2->addCcShowStamp($obj1); - - } // if joined row is not null - - // Add objects for joined CcShowInstances rows - - $key3 = CcShowInstancesPeer::getPrimaryKeyHashFromRow($row, $startcol3); - if ($key3 !== null) { - $obj3 = CcShowInstancesPeer::getInstanceFromPool($key3); - if (!$obj3) { - - $cls = CcShowInstancesPeer::getOMClass(false); - - $obj3 = new $cls(); - $obj3->hydrate($row, $startcol3); - CcShowInstancesPeer::addInstanceToPool($obj3, $key3); - } // if $obj3 already loaded - - // Add the $obj1 (CcShowStamp) to the collection in $obj3 (CcShowInstances) - $obj3->addCcShowStamp($obj1); - - } // if joined row is not null - - // Add objects for joined CcFiles rows - - $key4 = CcFilesPeer::getPrimaryKeyHashFromRow($row, $startcol4); - if ($key4 !== null) { - $obj4 = CcFilesPeer::getInstanceFromPool($key4); - if (!$obj4) { - - $cls = CcFilesPeer::getOMClass(false); - - $obj4 = new $cls(); - $obj4->hydrate($row, $startcol4); - CcFilesPeer::addInstanceToPool($obj4, $key4); - } // if $obj4 already loaded - - // Add the $obj1 (CcShowStamp) to the collection in $obj4 (CcFiles) - $obj4->addCcShowStamp($obj1); - - } // if joined row is not null - - // Add objects for joined CcWebstream rows - - $key5 = CcWebstreamPeer::getPrimaryKeyHashFromRow($row, $startcol5); - if ($key5 !== null) { - $obj5 = CcWebstreamPeer::getInstanceFromPool($key5); - if (!$obj5) { - - $cls = CcWebstreamPeer::getOMClass(false); - - $obj5 = new $cls(); - $obj5->hydrate($row, $startcol5); - CcWebstreamPeer::addInstanceToPool($obj5, $key5); - } // if $obj5 already loaded - - // Add the $obj1 (CcShowStamp) to the collection in $obj5 (CcWebstream) - $obj5->addCcShowStamp($obj1); - - } // if joined row is not null - - // Add objects for joined CcPlaylist rows - - $key6 = CcPlaylistPeer::getPrimaryKeyHashFromRow($row, $startcol6); - if ($key6 !== null) { - $obj6 = CcPlaylistPeer::getInstanceFromPool($key6); - if (!$obj6) { - - $cls = CcPlaylistPeer::getOMClass(false); - - $obj6 = new $cls(); - $obj6->hydrate($row, $startcol6); - CcPlaylistPeer::addInstanceToPool($obj6, $key6); - } // if $obj6 already loaded - - // Add the $obj1 (CcShowStamp) to the collection in $obj6 (CcPlaylist) - $obj6->addCcShowStamp($obj1); - - } // if joined row is not null - - $results[] = $obj1; - } - $stmt->closeCursor(); - return $results; - } - - - /** - * Selects a collection of CcShowStamp objects pre-filled with all related objects except CcPlaylist. - * - * @param Criteria $criteria - * @param PropelPDO $con - * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN - * @return array Array of CcShowStamp objects. - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - */ - public static function doSelectJoinAllExceptCcPlaylist(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) - { - $criteria = clone $criteria; - - // Set the correct dbName if it has not been overridden - // $criteria->getDbName() will return the same object if not set to another value - // so == check is okay and faster - if ($criteria->getDbName() == Propel::getDefaultDB()) { - $criteria->setDbName(self::DATABASE_NAME); - } - - CcShowStampPeer::addSelectColumns($criteria); - $startcol2 = (CcShowStampPeer::NUM_COLUMNS - CcShowStampPeer::NUM_LAZY_LOAD_COLUMNS); - - CcShowPeer::addSelectColumns($criteria); - $startcol3 = $startcol2 + (CcShowPeer::NUM_COLUMNS - CcShowPeer::NUM_LAZY_LOAD_COLUMNS); - - CcShowInstancesPeer::addSelectColumns($criteria); - $startcol4 = $startcol3 + (CcShowInstancesPeer::NUM_COLUMNS - CcShowInstancesPeer::NUM_LAZY_LOAD_COLUMNS); - - CcFilesPeer::addSelectColumns($criteria); - $startcol5 = $startcol4 + (CcFilesPeer::NUM_COLUMNS - CcFilesPeer::NUM_LAZY_LOAD_COLUMNS); - - CcWebstreamPeer::addSelectColumns($criteria); - $startcol6 = $startcol5 + (CcWebstreamPeer::NUM_COLUMNS - CcWebstreamPeer::NUM_LAZY_LOAD_COLUMNS); - - CcBlockPeer::addSelectColumns($criteria); - $startcol7 = $startcol6 + (CcBlockPeer::NUM_COLUMNS - CcBlockPeer::NUM_LAZY_LOAD_COLUMNS); - - $criteria->addJoin(CcShowStampPeer::SHOW_ID, CcShowPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); - - $criteria->addJoin(CcShowStampPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); - - - $stmt = BasePeer::doSelect($criteria, $con); - $results = array(); - - while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $key1 = CcShowStampPeer::getPrimaryKeyHashFromRow($row, 0); - if (null !== ($obj1 = CcShowStampPeer::getInstanceFromPool($key1))) { - // We no longer rehydrate the object, since this can cause data loss. - // See http://www.propelorm.org/ticket/509 - // $obj1->hydrate($row, 0, true); // rehydrate - } else { - $cls = CcShowStampPeer::getOMClass(false); - - $obj1 = new $cls(); - $obj1->hydrate($row); - CcShowStampPeer::addInstanceToPool($obj1, $key1); - } // if obj1 already loaded - - // Add objects for joined CcShow rows - - $key2 = CcShowPeer::getPrimaryKeyHashFromRow($row, $startcol2); - if ($key2 !== null) { - $obj2 = CcShowPeer::getInstanceFromPool($key2); - if (!$obj2) { - - $cls = CcShowPeer::getOMClass(false); - - $obj2 = new $cls(); - $obj2->hydrate($row, $startcol2); - CcShowPeer::addInstanceToPool($obj2, $key2); - } // if $obj2 already loaded - - // Add the $obj1 (CcShowStamp) to the collection in $obj2 (CcShow) - $obj2->addCcShowStamp($obj1); - - } // if joined row is not null - - // Add objects for joined CcShowInstances rows - - $key3 = CcShowInstancesPeer::getPrimaryKeyHashFromRow($row, $startcol3); - if ($key3 !== null) { - $obj3 = CcShowInstancesPeer::getInstanceFromPool($key3); - if (!$obj3) { - - $cls = CcShowInstancesPeer::getOMClass(false); - - $obj3 = new $cls(); - $obj3->hydrate($row, $startcol3); - CcShowInstancesPeer::addInstanceToPool($obj3, $key3); - } // if $obj3 already loaded - - // Add the $obj1 (CcShowStamp) to the collection in $obj3 (CcShowInstances) - $obj3->addCcShowStamp($obj1); - - } // if joined row is not null - - // Add objects for joined CcFiles rows - - $key4 = CcFilesPeer::getPrimaryKeyHashFromRow($row, $startcol4); - if ($key4 !== null) { - $obj4 = CcFilesPeer::getInstanceFromPool($key4); - if (!$obj4) { - - $cls = CcFilesPeer::getOMClass(false); - - $obj4 = new $cls(); - $obj4->hydrate($row, $startcol4); - CcFilesPeer::addInstanceToPool($obj4, $key4); - } // if $obj4 already loaded - - // Add the $obj1 (CcShowStamp) to the collection in $obj4 (CcFiles) - $obj4->addCcShowStamp($obj1); - - } // if joined row is not null - - // Add objects for joined CcWebstream rows - - $key5 = CcWebstreamPeer::getPrimaryKeyHashFromRow($row, $startcol5); - if ($key5 !== null) { - $obj5 = CcWebstreamPeer::getInstanceFromPool($key5); - if (!$obj5) { - - $cls = CcWebstreamPeer::getOMClass(false); - - $obj5 = new $cls(); - $obj5->hydrate($row, $startcol5); - CcWebstreamPeer::addInstanceToPool($obj5, $key5); - } // if $obj5 already loaded - - // Add the $obj1 (CcShowStamp) to the collection in $obj5 (CcWebstream) - $obj5->addCcShowStamp($obj1); - - } // if joined row is not null - - // Add objects for joined CcBlock rows - - $key6 = CcBlockPeer::getPrimaryKeyHashFromRow($row, $startcol6); - if ($key6 !== null) { - $obj6 = CcBlockPeer::getInstanceFromPool($key6); - if (!$obj6) { - - $cls = CcBlockPeer::getOMClass(false); - - $obj6 = new $cls(); - $obj6->hydrate($row, $startcol6); - CcBlockPeer::addInstanceToPool($obj6, $key6); - } // if $obj6 already loaded - - // Add the $obj1 (CcShowStamp) to the collection in $obj6 (CcBlock) - $obj6->addCcShowStamp($obj1); - - } // if joined row is not null - - $results[] = $obj1; - } - $stmt->closeCursor(); - return $results; - } - - /** - * Returns the TableMap related to this peer. - * This method is not needed for general use but a specific application could have a need. - * @return TableMap - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - */ - public static function getTableMap() - { - return Propel::getDatabaseMap(self::DATABASE_NAME)->getTable(self::TABLE_NAME); - } - - /** - * Add a TableMap instance to the database for this peer class. - */ - public static function buildTableMap() - { - $dbMap = Propel::getDatabaseMap(BaseCcShowStampPeer::DATABASE_NAME); - if (!$dbMap->hasTable(BaseCcShowStampPeer::TABLE_NAME)) - { - $dbMap->addTableObject(new CcShowStampTableMap()); - } - } - - /** - * The class that the Peer will make instances of. - * - * If $withPrefix is true, the returned path - * uses a dot-path notation which is tranalted into a path - * relative to a location on the PHP include_path. - * (e.g. path.to.MyClass -> 'path/to/MyClass.php') - * - * @param boolean $withPrefix Whether or not to return the path with the class name - * @return string path.to.ClassName - */ - public static function getOMClass($withPrefix = true) - { - return $withPrefix ? CcShowStampPeer::CLASS_DEFAULT : CcShowStampPeer::OM_CLASS; - } - - /** - * Method perform an INSERT on the database, given a CcShowStamp or Criteria object. - * - * @param mixed $values Criteria or CcShowStamp object containing data that is used to create the INSERT statement. - * @param PropelPDO $con the PropelPDO connection to use - * @return mixed The new primary key. - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - */ - public static function doInsert($values, PropelPDO $con = null) - { - if ($con === null) { - $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); - } - - if ($values instanceof Criteria) { - $criteria = clone $values; // rename for clarity - } else { - $criteria = $values->buildCriteria(); // build Criteria from CcShowStamp object - } - - if ($criteria->containsKey(CcShowStampPeer::ID) && $criteria->keyContainsValue(CcShowStampPeer::ID) ) { - throw new PropelException('Cannot insert a value for auto-increment primary key ('.CcShowStampPeer::ID.')'); - } - - - // Set the correct dbName - $criteria->setDbName(self::DATABASE_NAME); - - try { - // use transaction because $criteria could contain info - // for more than one table (I guess, conceivably) - $con->beginTransaction(); - $pk = BasePeer::doInsert($criteria, $con); - $con->commit(); - } catch(PropelException $e) { - $con->rollBack(); - throw $e; - } - - return $pk; - } - - /** - * Method perform an UPDATE on the database, given a CcShowStamp or Criteria object. - * - * @param mixed $values Criteria or CcShowStamp object containing data that is used to create the UPDATE statement. - * @param PropelPDO $con The connection to use (specify PropelPDO connection object to exert more control over transactions). - * @return int The number of affected rows (if supported by underlying database driver). - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - */ - public static function doUpdate($values, PropelPDO $con = null) - { - if ($con === null) { - $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); - } - - $selectCriteria = new Criteria(self::DATABASE_NAME); - - if ($values instanceof Criteria) { - $criteria = clone $values; // rename for clarity - - $comparison = $criteria->getComparison(CcShowStampPeer::ID); - $value = $criteria->remove(CcShowStampPeer::ID); - if ($value) { - $selectCriteria->add(CcShowStampPeer::ID, $value, $comparison); - } else { - $selectCriteria->setPrimaryTableName(CcShowStampPeer::TABLE_NAME); - } - - } else { // $values is CcShowStamp object - $criteria = $values->buildCriteria(); // gets full criteria - $selectCriteria = $values->buildPkeyCriteria(); // gets criteria w/ primary key(s) - } - - // set the correct dbName - $criteria->setDbName(self::DATABASE_NAME); - - return BasePeer::doUpdate($selectCriteria, $criteria, $con); - } - - /** - * Method to DELETE all rows from the cc_show_stamp table. - * - * @return int The number of affected rows (if supported by underlying database driver). - */ - public static function doDeleteAll($con = null) - { - if ($con === null) { - $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); - } - $affectedRows = 0; // initialize var to track total num of affected rows - try { - // use transaction because $criteria could contain info - // for more than one table or we could emulating ON DELETE CASCADE, etc. - $con->beginTransaction(); - $affectedRows += BasePeer::doDeleteAll(CcShowStampPeer::TABLE_NAME, $con, CcShowStampPeer::DATABASE_NAME); - // Because this db requires some delete cascade/set null emulation, we have to - // clear the cached instance *after* the emulation has happened (since - // instances get re-added by the select statement contained therein). - CcShowStampPeer::clearInstancePool(); - CcShowStampPeer::clearRelatedInstancePool(); - $con->commit(); - return $affectedRows; - } catch (PropelException $e) { - $con->rollBack(); - throw $e; - } - } - - /** - * Method perform a DELETE on the database, given a CcShowStamp or Criteria object OR a primary key value. - * - * @param mixed $values Criteria or CcShowStamp object or primary key or array of primary keys - * which is used to create the DELETE statement - * @param PropelPDO $con the connection to use - * @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows - * if supported by native driver or if emulated using Propel. - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - */ - public static function doDelete($values, PropelPDO $con = null) - { - if ($con === null) { - $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); - } - - if ($values instanceof Criteria) { - // invalidate the cache for all objects of this type, since we have no - // way of knowing (without running a query) what objects should be invalidated - // from the cache based on this Criteria. - CcShowStampPeer::clearInstancePool(); - // rename for clarity - $criteria = clone $values; - } elseif ($values instanceof CcShowStamp) { // it's a model object - // invalidate the cache for this single object - CcShowStampPeer::removeInstanceFromPool($values); - // create criteria based on pk values - $criteria = $values->buildPkeyCriteria(); - } else { // it's a primary key, or an array of pks - $criteria = new Criteria(self::DATABASE_NAME); - $criteria->add(CcShowStampPeer::ID, (array) $values, Criteria::IN); - // invalidate the cache for this object(s) - foreach ((array) $values as $singleval) { - CcShowStampPeer::removeInstanceFromPool($singleval); - } - } - - // Set the correct dbName - $criteria->setDbName(self::DATABASE_NAME); - - $affectedRows = 0; // initialize var to track total num of affected rows - - try { - // use transaction because $criteria could contain info - // for more than one table or we could emulating ON DELETE CASCADE, etc. - $con->beginTransaction(); - - $affectedRows += BasePeer::doDelete($criteria, $con); - CcShowStampPeer::clearRelatedInstancePool(); - $con->commit(); - return $affectedRows; - } catch (PropelException $e) { - $con->rollBack(); - throw $e; - } - } - - /** - * Validates all modified columns of given CcShowStamp object. - * If parameter $columns is either a single column name or an array of column names - * than only those columns are validated. - * - * NOTICE: This does not apply to primary or foreign keys for now. - * - * @param CcShowStamp $obj The object to validate. - * @param mixed $cols Column name or array of column names. - * - * @return mixed TRUE if all columns are valid or the error message of the first invalid column. - */ - public static function doValidate(CcShowStamp $obj, $cols = null) - { - $columns = array(); - - if ($cols) { - $dbMap = Propel::getDatabaseMap(CcShowStampPeer::DATABASE_NAME); - $tableMap = $dbMap->getTable(CcShowStampPeer::TABLE_NAME); - - if (! is_array($cols)) { - $cols = array($cols); - } - - foreach ($cols as $colName) { - if ($tableMap->containsColumn($colName)) { - $get = 'get' . $tableMap->getColumn($colName)->getPhpName(); - $columns[$colName] = $obj->$get(); - } - } - } else { - - } - - return BasePeer::doValidate(CcShowStampPeer::DATABASE_NAME, CcShowStampPeer::TABLE_NAME, $columns); - } - - /** - * Retrieve a single object by pkey. - * - * @param int $pk the primary key. - * @param PropelPDO $con the connection to use - * @return CcShowStamp - */ - public static function retrieveByPK($pk, PropelPDO $con = null) - { - - if (null !== ($obj = CcShowStampPeer::getInstanceFromPool((string) $pk))) { - return $obj; - } - - if ($con === null) { - $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); - } - - $criteria = new Criteria(CcShowStampPeer::DATABASE_NAME); - $criteria->add(CcShowStampPeer::ID, $pk); - - $v = CcShowStampPeer::doSelect($criteria, $con); - - return !empty($v) > 0 ? $v[0] : null; - } - - /** - * Retrieve multiple objects by pkey. - * - * @param array $pks List of primary keys - * @param PropelPDO $con the connection to use - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - */ - public static function retrieveByPKs($pks, PropelPDO $con = null) - { - if ($con === null) { - $con = Propel::getConnection(CcShowStampPeer::DATABASE_NAME, Propel::CONNECTION_READ); - } - - $objs = null; - if (empty($pks)) { - $objs = array(); - } else { - $criteria = new Criteria(CcShowStampPeer::DATABASE_NAME); - $criteria->add(CcShowStampPeer::ID, $pks, Criteria::IN); - $objs = CcShowStampPeer::doSelect($criteria, $con); - } - return $objs; - } - -} // BaseCcShowStampPeer - -// This is the static code needed to register the TableMap for this table with the main Propel class. -// -BaseCcShowStampPeer::buildTableMap(); - diff --git a/airtime_mvc/application/models/airtime/om/BaseCcShowStampQuery.php b/airtime_mvc/application/models/airtime/om/BaseCcShowStampQuery.php deleted file mode 100644 index dacdcbffa..000000000 --- a/airtime_mvc/application/models/airtime/om/BaseCcShowStampQuery.php +++ /dev/null @@ -1,948 +0,0 @@ -setModelAlias($modelAlias); - } - if ($criteria instanceof Criteria) { - $query->mergeWith($criteria); - } - return $query; - } - - /** - * Find object by primary key - * Use instance pooling to avoid a database query if the object exists - * - * $obj = $c->findPk(12, $con); - * - * @param mixed $key Primary key to use for the query - * @param PropelPDO $con an optional connection object - * - * @return CcShowStamp|array|mixed the result, formatted by the current formatter - */ - public function findPk($key, $con = null) - { - if ((null !== ($obj = CcShowStampPeer::getInstanceFromPool((string) $key))) && $this->getFormatter()->isObjectFormatter()) { - // the object is alredy in the instance pool - return $obj; - } else { - // the object has not been requested yet, or the formatter is not an object formatter - $criteria = $this->isKeepQuery() ? clone $this : $this; - $stmt = $criteria - ->filterByPrimaryKey($key) - ->getSelectStatement($con); - return $criteria->getFormatter()->init($criteria)->formatOne($stmt); - } - } - - /** - * Find objects by primary key - * - * $objs = $c->findPks(array(12, 56, 832), $con); - * - * @param array $keys Primary keys to use for the query - * @param PropelPDO $con an optional connection object - * - * @return PropelObjectCollection|array|mixed the list of results, formatted by the current formatter - */ - public function findPks($keys, $con = null) - { - $criteria = $this->isKeepQuery() ? clone $this : $this; - return $this - ->filterByPrimaryKeys($keys) - ->find($con); - } - - /** - * Filter the query by primary key - * - * @param mixed $key Primary key to use for the query - * - * @return CcShowStampQuery The current query, for fluid interface - */ - public function filterByPrimaryKey($key) - { - return $this->addUsingAlias(CcShowStampPeer::ID, $key, Criteria::EQUAL); - } - - /** - * Filter the query by a list of primary keys - * - * @param array $keys The list of primary key to use for the query - * - * @return CcShowStampQuery The current query, for fluid interface - */ - public function filterByPrimaryKeys($keys) - { - return $this->addUsingAlias(CcShowStampPeer::ID, $keys, Criteria::IN); - } - - /** - * Filter the query on the id column - * - * @param int|array $dbId 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 CcShowStampQuery The current query, for fluid interface - */ - public function filterByDbId($dbId = null, $comparison = null) - { - if (is_array($dbId) && null === $comparison) { - $comparison = Criteria::IN; - } - return $this->addUsingAlias(CcShowStampPeer::ID, $dbId, $comparison); - } - - /** - * Filter the query on the show_id column - * - * @param int|array $dbShowId 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 CcShowStampQuery The current query, for fluid interface - */ - public function filterByDbShowId($dbShowId = null, $comparison = null) - { - if (is_array($dbShowId)) { - $useMinMax = false; - if (isset($dbShowId['min'])) { - $this->addUsingAlias(CcShowStampPeer::SHOW_ID, $dbShowId['min'], Criteria::GREATER_EQUAL); - $useMinMax = true; - } - if (isset($dbShowId['max'])) { - $this->addUsingAlias(CcShowStampPeer::SHOW_ID, $dbShowId['max'], Criteria::LESS_EQUAL); - $useMinMax = true; - } - if ($useMinMax) { - return $this; - } - if (null === $comparison) { - $comparison = Criteria::IN; - } - } - return $this->addUsingAlias(CcShowStampPeer::SHOW_ID, $dbShowId, $comparison); - } - - /** - * Filter the query on the instance_id column - * - * @param int|array $dbInstanceId 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 CcShowStampQuery The current query, for fluid interface - */ - public function filterByDbInstanceId($dbInstanceId = null, $comparison = null) - { - if (is_array($dbInstanceId)) { - $useMinMax = false; - if (isset($dbInstanceId['min'])) { - $this->addUsingAlias(CcShowStampPeer::INSTANCE_ID, $dbInstanceId['min'], Criteria::GREATER_EQUAL); - $useMinMax = true; - } - if (isset($dbInstanceId['max'])) { - $this->addUsingAlias(CcShowStampPeer::INSTANCE_ID, $dbInstanceId['max'], Criteria::LESS_EQUAL); - $useMinMax = true; - } - if ($useMinMax) { - return $this; - } - if (null === $comparison) { - $comparison = Criteria::IN; - } - } - return $this->addUsingAlias(CcShowStampPeer::INSTANCE_ID, $dbInstanceId, $comparison); - } - - /** - * Filter the query on the file_id column - * - * @param int|array $dbFileId 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 CcShowStampQuery The current query, for fluid interface - */ - public function filterByDbFileId($dbFileId = null, $comparison = null) - { - if (is_array($dbFileId)) { - $useMinMax = false; - if (isset($dbFileId['min'])) { - $this->addUsingAlias(CcShowStampPeer::FILE_ID, $dbFileId['min'], Criteria::GREATER_EQUAL); - $useMinMax = true; - } - if (isset($dbFileId['max'])) { - $this->addUsingAlias(CcShowStampPeer::FILE_ID, $dbFileId['max'], Criteria::LESS_EQUAL); - $useMinMax = true; - } - if ($useMinMax) { - return $this; - } - if (null === $comparison) { - $comparison = Criteria::IN; - } - } - return $this->addUsingAlias(CcShowStampPeer::FILE_ID, $dbFileId, $comparison); - } - - /** - * Filter the query on the stream_id column - * - * @param int|array $dbStreamId 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 CcShowStampQuery The current query, for fluid interface - */ - public function filterByDbStreamId($dbStreamId = null, $comparison = null) - { - if (is_array($dbStreamId)) { - $useMinMax = false; - if (isset($dbStreamId['min'])) { - $this->addUsingAlias(CcShowStampPeer::STREAM_ID, $dbStreamId['min'], Criteria::GREATER_EQUAL); - $useMinMax = true; - } - if (isset($dbStreamId['max'])) { - $this->addUsingAlias(CcShowStampPeer::STREAM_ID, $dbStreamId['max'], Criteria::LESS_EQUAL); - $useMinMax = true; - } - if ($useMinMax) { - return $this; - } - if (null === $comparison) { - $comparison = Criteria::IN; - } - } - return $this->addUsingAlias(CcShowStampPeer::STREAM_ID, $dbStreamId, $comparison); - } - - /** - * Filter the query on the block_id column - * - * @param int|array $dbBlockId 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 CcShowStampQuery The current query, for fluid interface - */ - public function filterByDbBlockId($dbBlockId = null, $comparison = null) - { - if (is_array($dbBlockId)) { - $useMinMax = false; - if (isset($dbBlockId['min'])) { - $this->addUsingAlias(CcShowStampPeer::BLOCK_ID, $dbBlockId['min'], Criteria::GREATER_EQUAL); - $useMinMax = true; - } - if (isset($dbBlockId['max'])) { - $this->addUsingAlias(CcShowStampPeer::BLOCK_ID, $dbBlockId['max'], Criteria::LESS_EQUAL); - $useMinMax = true; - } - if ($useMinMax) { - return $this; - } - if (null === $comparison) { - $comparison = Criteria::IN; - } - } - return $this->addUsingAlias(CcShowStampPeer::BLOCK_ID, $dbBlockId, $comparison); - } - - /** - * Filter the query on the playlist_id column - * - * @param int|array $dbPlaylistId 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 CcShowStampQuery The current query, for fluid interface - */ - public function filterByDbPlaylistId($dbPlaylistId = null, $comparison = null) - { - if (is_array($dbPlaylistId)) { - $useMinMax = false; - if (isset($dbPlaylistId['min'])) { - $this->addUsingAlias(CcShowStampPeer::PLAYLIST_ID, $dbPlaylistId['min'], Criteria::GREATER_EQUAL); - $useMinMax = true; - } - if (isset($dbPlaylistId['max'])) { - $this->addUsingAlias(CcShowStampPeer::PLAYLIST_ID, $dbPlaylistId['max'], Criteria::LESS_EQUAL); - $useMinMax = true; - } - if ($useMinMax) { - return $this; - } - if (null === $comparison) { - $comparison = Criteria::IN; - } - } - return $this->addUsingAlias(CcShowStampPeer::PLAYLIST_ID, $dbPlaylistId, $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 CcShowStampQuery 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(CcShowStampPeer::POSITION, $dbPosition['min'], Criteria::GREATER_EQUAL); - $useMinMax = true; - } - if (isset($dbPosition['max'])) { - $this->addUsingAlias(CcShowStampPeer::POSITION, $dbPosition['max'], Criteria::LESS_EQUAL); - $useMinMax = true; - } - if ($useMinMax) { - return $this; - } - if (null === $comparison) { - $comparison = Criteria::IN; - } - } - return $this->addUsingAlias(CcShowStampPeer::POSITION, $dbPosition, $comparison); - } - - /** - * Filter the query on the clip_length column - * - * @param string $dbClipLength The value to use as filter. - * Accepts wildcards (* and % trigger a LIKE) - * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL - * - * @return CcShowStampQuery The current query, for fluid interface - */ - public function filterByDbClipLength($dbClipLength = null, $comparison = null) - { - if (null === $comparison) { - if (is_array($dbClipLength)) { - $comparison = Criteria::IN; - } elseif (preg_match('/[\%\*]/', $dbClipLength)) { - $dbClipLength = str_replace('*', '%', $dbClipLength); - $comparison = Criteria::LIKE; - } - } - return $this->addUsingAlias(CcShowStampPeer::CLIP_LENGTH, $dbClipLength, $comparison); - } - - /** - * Filter the query on the cue_in column - * - * @param string $dbCueIn The value to use as filter. - * Accepts wildcards (* and % trigger a LIKE) - * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL - * - * @return CcShowStampQuery The current query, for fluid interface - */ - public function filterByDbCueIn($dbCueIn = null, $comparison = null) - { - if (null === $comparison) { - if (is_array($dbCueIn)) { - $comparison = Criteria::IN; - } elseif (preg_match('/[\%\*]/', $dbCueIn)) { - $dbCueIn = str_replace('*', '%', $dbCueIn); - $comparison = Criteria::LIKE; - } - } - return $this->addUsingAlias(CcShowStampPeer::CUE_IN, $dbCueIn, $comparison); - } - - /** - * Filter the query on the cue_out column - * - * @param string $dbCueOut The value to use as filter. - * Accepts wildcards (* and % trigger a LIKE) - * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL - * - * @return CcShowStampQuery The current query, for fluid interface - */ - public function filterByDbCueOut($dbCueOut = null, $comparison = null) - { - if (null === $comparison) { - if (is_array($dbCueOut)) { - $comparison = Criteria::IN; - } elseif (preg_match('/[\%\*]/', $dbCueOut)) { - $dbCueOut = str_replace('*', '%', $dbCueOut); - $comparison = Criteria::LIKE; - } - } - return $this->addUsingAlias(CcShowStampPeer::CUE_OUT, $dbCueOut, $comparison); - } - - /** - * Filter the query on the fade_in column - * - * @param string $dbFadeIn The value to use as filter. - * Accepts wildcards (* and % trigger a LIKE) - * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL - * - * @return CcShowStampQuery The current query, for fluid interface - */ - public function filterByDbFadeIn($dbFadeIn = null, $comparison = null) - { - if (null === $comparison) { - if (is_array($dbFadeIn)) { - $comparison = Criteria::IN; - } elseif (preg_match('/[\%\*]/', $dbFadeIn)) { - $dbFadeIn = str_replace('*', '%', $dbFadeIn); - $comparison = Criteria::LIKE; - } - } - return $this->addUsingAlias(CcShowStampPeer::FADE_IN, $dbFadeIn, $comparison); - } - - /** - * Filter the query on the fade_out column - * - * @param string $dbFadeOut The value to use as filter. - * Accepts wildcards (* and % trigger a LIKE) - * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL - * - * @return CcShowStampQuery The current query, for fluid interface - */ - public function filterByDbFadeOut($dbFadeOut = null, $comparison = null) - { - if (null === $comparison) { - if (is_array($dbFadeOut)) { - $comparison = Criteria::IN; - } elseif (preg_match('/[\%\*]/', $dbFadeOut)) { - $dbFadeOut = str_replace('*', '%', $dbFadeOut); - $comparison = Criteria::LIKE; - } - } - return $this->addUsingAlias(CcShowStampPeer::FADE_OUT, $dbFadeOut, $comparison); - } - - /** - * Filter the query by a related CcShow object - * - * @param CcShow $ccShow the related object to use as filter - * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL - * - * @return CcShowStampQuery The current query, for fluid interface - */ - public function filterByCcShow($ccShow, $comparison = null) - { - return $this - ->addUsingAlias(CcShowStampPeer::SHOW_ID, $ccShow->getDbId(), $comparison); - } - - /** - * Adds a JOIN clause to the query using the CcShow relation - * - * @param string $relationAlias optional alias for the relation - * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' - * - * @return CcShowStampQuery The current query, for fluid interface - */ - public function joinCcShow($relationAlias = '', $joinType = Criteria::INNER_JOIN) - { - $tableMap = $this->getTableMap(); - $relationMap = $tableMap->getRelation('CcShow'); - - // create a ModelJoin object for this join - $join = new ModelJoin(); - $join->setJoinType($joinType); - $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); - if ($previousJoin = $this->getPreviousJoin()) { - $join->setPreviousJoin($previousJoin); - } - - // add the ModelJoin to the current object - if($relationAlias) { - $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); - $this->addJoinObject($join, $relationAlias); - } else { - $this->addJoinObject($join, 'CcShow'); - } - - return $this; - } - - /** - * Use the CcShow relation CcShow object - * - * @see useQuery() - * - * @param string $relationAlias optional alias for the relation, - * to be used as main alias in the secondary query - * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' - * - * @return CcShowQuery A secondary query class using the current class as primary query - */ - public function useCcShowQuery($relationAlias = '', $joinType = Criteria::INNER_JOIN) - { - return $this - ->joinCcShow($relationAlias, $joinType) - ->useQuery($relationAlias ? $relationAlias : 'CcShow', 'CcShowQuery'); - } - - /** - * Filter the query by a related CcShowInstances object - * - * @param CcShowInstances $ccShowInstances the related object to use as filter - * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL - * - * @return CcShowStampQuery The current query, for fluid interface - */ - public function filterByCcShowInstances($ccShowInstances, $comparison = null) - { - return $this - ->addUsingAlias(CcShowStampPeer::INSTANCE_ID, $ccShowInstances->getDbId(), $comparison); - } - - /** - * Adds a JOIN clause to the query using the CcShowInstances relation - * - * @param string $relationAlias optional alias for the relation - * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' - * - * @return CcShowStampQuery The current query, for fluid interface - */ - public function joinCcShowInstances($relationAlias = '', $joinType = Criteria::LEFT_JOIN) - { - $tableMap = $this->getTableMap(); - $relationMap = $tableMap->getRelation('CcShowInstances'); - - // create a ModelJoin object for this join - $join = new ModelJoin(); - $join->setJoinType($joinType); - $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); - if ($previousJoin = $this->getPreviousJoin()) { - $join->setPreviousJoin($previousJoin); - } - - // add the ModelJoin to the current object - if($relationAlias) { - $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); - $this->addJoinObject($join, $relationAlias); - } else { - $this->addJoinObject($join, 'CcShowInstances'); - } - - return $this; - } - - /** - * Use the CcShowInstances relation CcShowInstances object - * - * @see useQuery() - * - * @param string $relationAlias optional alias for the relation, - * to be used as main alias in the secondary query - * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' - * - * @return CcShowInstancesQuery A secondary query class using the current class as primary query - */ - public function useCcShowInstancesQuery($relationAlias = '', $joinType = Criteria::LEFT_JOIN) - { - return $this - ->joinCcShowInstances($relationAlias, $joinType) - ->useQuery($relationAlias ? $relationAlias : 'CcShowInstances', 'CcShowInstancesQuery'); - } - - /** - * Filter the query by a related CcFiles object - * - * @param CcFiles $ccFiles the related object to use as filter - * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL - * - * @return CcShowStampQuery The current query, for fluid interface - */ - public function filterByCcFiles($ccFiles, $comparison = null) - { - return $this - ->addUsingAlias(CcShowStampPeer::FILE_ID, $ccFiles->getDbId(), $comparison); - } - - /** - * Adds a JOIN clause to the query using the CcFiles relation - * - * @param string $relationAlias optional alias for the relation - * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' - * - * @return CcShowStampQuery The current query, for fluid interface - */ - public function joinCcFiles($relationAlias = '', $joinType = Criteria::LEFT_JOIN) - { - $tableMap = $this->getTableMap(); - $relationMap = $tableMap->getRelation('CcFiles'); - - // create a ModelJoin object for this join - $join = new ModelJoin(); - $join->setJoinType($joinType); - $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); - if ($previousJoin = $this->getPreviousJoin()) { - $join->setPreviousJoin($previousJoin); - } - - // add the ModelJoin to the current object - if($relationAlias) { - $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); - $this->addJoinObject($join, $relationAlias); - } else { - $this->addJoinObject($join, 'CcFiles'); - } - - return $this; - } - - /** - * Use the CcFiles relation CcFiles object - * - * @see useQuery() - * - * @param string $relationAlias optional alias for the relation, - * to be used as main alias in the secondary query - * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' - * - * @return CcFilesQuery A secondary query class using the current class as primary query - */ - public function useCcFilesQuery($relationAlias = '', $joinType = Criteria::LEFT_JOIN) - { - return $this - ->joinCcFiles($relationAlias, $joinType) - ->useQuery($relationAlias ? $relationAlias : 'CcFiles', 'CcFilesQuery'); - } - - /** - * Filter the query by a related CcWebstream object - * - * @param CcWebstream $ccWebstream the related object to use as filter - * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL - * - * @return CcShowStampQuery The current query, for fluid interface - */ - public function filterByCcWebstream($ccWebstream, $comparison = null) - { - return $this - ->addUsingAlias(CcShowStampPeer::STREAM_ID, $ccWebstream->getDbId(), $comparison); - } - - /** - * Adds a JOIN clause to the query using the CcWebstream relation - * - * @param string $relationAlias optional alias for the relation - * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' - * - * @return CcShowStampQuery The current query, for fluid interface - */ - public function joinCcWebstream($relationAlias = '', $joinType = Criteria::LEFT_JOIN) - { - $tableMap = $this->getTableMap(); - $relationMap = $tableMap->getRelation('CcWebstream'); - - // create a ModelJoin object for this join - $join = new ModelJoin(); - $join->setJoinType($joinType); - $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); - if ($previousJoin = $this->getPreviousJoin()) { - $join->setPreviousJoin($previousJoin); - } - - // add the ModelJoin to the current object - if($relationAlias) { - $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); - $this->addJoinObject($join, $relationAlias); - } else { - $this->addJoinObject($join, 'CcWebstream'); - } - - return $this; - } - - /** - * Use the CcWebstream relation CcWebstream object - * - * @see useQuery() - * - * @param string $relationAlias optional alias for the relation, - * to be used as main alias in the secondary query - * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' - * - * @return CcWebstreamQuery A secondary query class using the current class as primary query - */ - public function useCcWebstreamQuery($relationAlias = '', $joinType = Criteria::LEFT_JOIN) - { - return $this - ->joinCcWebstream($relationAlias, $joinType) - ->useQuery($relationAlias ? $relationAlias : 'CcWebstream', 'CcWebstreamQuery'); - } - - /** - * Filter the query by a related CcBlock object - * - * @param CcBlock $ccBlock the related object to use as filter - * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL - * - * @return CcShowStampQuery The current query, for fluid interface - */ - public function filterByCcBlock($ccBlock, $comparison = null) - { - return $this - ->addUsingAlias(CcShowStampPeer::BLOCK_ID, $ccBlock->getDbId(), $comparison); - } - - /** - * Adds a JOIN clause to the query using the CcBlock relation - * - * @param string $relationAlias optional alias for the relation - * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' - * - * @return CcShowStampQuery The current query, for fluid interface - */ - public function joinCcBlock($relationAlias = '', $joinType = Criteria::LEFT_JOIN) - { - $tableMap = $this->getTableMap(); - $relationMap = $tableMap->getRelation('CcBlock'); - - // create a ModelJoin object for this join - $join = new ModelJoin(); - $join->setJoinType($joinType); - $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); - if ($previousJoin = $this->getPreviousJoin()) { - $join->setPreviousJoin($previousJoin); - } - - // add the ModelJoin to the current object - if($relationAlias) { - $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); - $this->addJoinObject($join, $relationAlias); - } else { - $this->addJoinObject($join, 'CcBlock'); - } - - return $this; - } - - /** - * Use the CcBlock relation CcBlock object - * - * @see useQuery() - * - * @param string $relationAlias optional alias for the relation, - * to be used as main alias in the secondary query - * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' - * - * @return CcBlockQuery A secondary query class using the current class as primary query - */ - public function useCcBlockQuery($relationAlias = '', $joinType = Criteria::LEFT_JOIN) - { - return $this - ->joinCcBlock($relationAlias, $joinType) - ->useQuery($relationAlias ? $relationAlias : 'CcBlock', 'CcBlockQuery'); - } - - /** - * Filter the query by a related CcPlaylist object - * - * @param CcPlaylist $ccPlaylist the related object to use as filter - * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL - * - * @return CcShowStampQuery The current query, for fluid interface - */ - public function filterByCcPlaylist($ccPlaylist, $comparison = null) - { - return $this - ->addUsingAlias(CcShowStampPeer::PLAYLIST_ID, $ccPlaylist->getDbId(), $comparison); - } - - /** - * Adds a JOIN clause to the query using the CcPlaylist relation - * - * @param string $relationAlias optional alias for the relation - * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' - * - * @return CcShowStampQuery The current query, for fluid interface - */ - public function joinCcPlaylist($relationAlias = '', $joinType = Criteria::LEFT_JOIN) - { - $tableMap = $this->getTableMap(); - $relationMap = $tableMap->getRelation('CcPlaylist'); - - // create a ModelJoin object for this join - $join = new ModelJoin(); - $join->setJoinType($joinType); - $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); - if ($previousJoin = $this->getPreviousJoin()) { - $join->setPreviousJoin($previousJoin); - } - - // add the ModelJoin to the current object - if($relationAlias) { - $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); - $this->addJoinObject($join, $relationAlias); - } else { - $this->addJoinObject($join, 'CcPlaylist'); - } - - return $this; - } - - /** - * Use the CcPlaylist relation CcPlaylist object - * - * @see useQuery() - * - * @param string $relationAlias optional alias for the relation, - * to be used as main alias in the secondary query - * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' - * - * @return CcPlaylistQuery A secondary query class using the current class as primary query - */ - public function useCcPlaylistQuery($relationAlias = '', $joinType = Criteria::LEFT_JOIN) - { - return $this - ->joinCcPlaylist($relationAlias, $joinType) - ->useQuery($relationAlias ? $relationAlias : 'CcPlaylist', 'CcPlaylistQuery'); - } - - /** - * Exclude object from result - * - * @param CcShowStamp $ccShowStamp Object to remove from the list of results - * - * @return CcShowStampQuery The current query, for fluid interface - */ - public function prune($ccShowStamp = null) - { - if ($ccShowStamp) { - $this->addUsingAlias(CcShowStampPeer::ID, $ccShowStamp->getDbId(), Criteria::NOT_EQUAL); - } - - return $this; - } - -} // BaseCcShowStampQuery diff --git a/airtime_mvc/application/models/airtime/om/BaseCcStamp.php b/airtime_mvc/application/models/airtime/om/BaseCcStamp.php index dcb488d02..629e28b3a 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcStamp.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcStamp.php @@ -42,6 +42,12 @@ abstract class BaseCcStamp extends BaseObject implements Persistent */ protected $instance_id; + /** + * The value for the linked field. + * @var boolean + */ + protected $linked; + /** * @var CcShow */ @@ -101,6 +107,16 @@ abstract class BaseCcStamp extends BaseObject implements Persistent return $this->instance_id; } + /** + * Get the [linked] column value. + * + * @return boolean + */ + public function getDbLinked() + { + return $this->linked; + } + /** * Set the value of [id] column. * @@ -169,6 +185,26 @@ abstract class BaseCcStamp extends BaseObject implements Persistent return $this; } // setDbInstanceId() + /** + * Set the value of [linked] column. + * + * @param boolean $v new value + * @return CcStamp The current object (for fluent API support) + */ + public function setDbLinked($v) + { + if ($v !== null) { + $v = (boolean) $v; + } + + if ($this->linked !== $v) { + $this->linked = $v; + $this->modifiedColumns[] = CcStampPeer::LINKED; + } + + return $this; + } // setDbLinked() + /** * Indicates whether the columns in this object are only set to default values. * @@ -204,6 +240,7 @@ abstract class BaseCcStamp extends BaseObject implements Persistent $this->id = ($row[$startcol + 0] !== null) ? (int) $row[$startcol + 0] : null; $this->show_id = ($row[$startcol + 1] !== null) ? (int) $row[$startcol + 1] : null; $this->instance_id = ($row[$startcol + 2] !== null) ? (int) $row[$startcol + 2] : null; + $this->linked = ($row[$startcol + 3] !== null) ? (boolean) $row[$startcol + 3] : null; $this->resetModified(); $this->setNew(false); @@ -212,7 +249,7 @@ abstract class BaseCcStamp extends BaseObject implements Persistent $this->ensureConsistency(); } - return $startcol + 3; // 3 = CcStampPeer::NUM_COLUMNS - CcStampPeer::NUM_LAZY_LOAD_COLUMNS). + return $startcol + 4; // 4 = CcStampPeer::NUM_COLUMNS - CcStampPeer::NUM_LAZY_LOAD_COLUMNS). } catch (Exception $e) { throw new PropelException("Error populating CcStamp object", $e); @@ -583,6 +620,9 @@ abstract class BaseCcStamp extends BaseObject implements Persistent case 2: return $this->getDbInstanceId(); break; + case 3: + return $this->getDbLinked(); + break; default: return null; break; @@ -610,6 +650,7 @@ abstract class BaseCcStamp extends BaseObject implements Persistent $keys[0] => $this->getDbId(), $keys[1] => $this->getDbShowId(), $keys[2] => $this->getDbInstanceId(), + $keys[3] => $this->getDbLinked(), ); if ($includeForeignObjects) { if (null !== $this->aCcShow) { @@ -658,6 +699,9 @@ abstract class BaseCcStamp extends BaseObject implements Persistent case 2: $this->setDbInstanceId($value); break; + case 3: + $this->setDbLinked($value); + break; } // switch() } @@ -685,6 +729,7 @@ abstract class BaseCcStamp extends BaseObject implements Persistent if (array_key_exists($keys[0], $arr)) $this->setDbId($arr[$keys[0]]); if (array_key_exists($keys[1], $arr)) $this->setDbShowId($arr[$keys[1]]); if (array_key_exists($keys[2], $arr)) $this->setDbInstanceId($arr[$keys[2]]); + if (array_key_exists($keys[3], $arr)) $this->setDbLinked($arr[$keys[3]]); } /** @@ -699,6 +744,7 @@ abstract class BaseCcStamp extends BaseObject implements Persistent if ($this->isColumnModified(CcStampPeer::ID)) $criteria->add(CcStampPeer::ID, $this->id); if ($this->isColumnModified(CcStampPeer::SHOW_ID)) $criteria->add(CcStampPeer::SHOW_ID, $this->show_id); if ($this->isColumnModified(CcStampPeer::INSTANCE_ID)) $criteria->add(CcStampPeer::INSTANCE_ID, $this->instance_id); + if ($this->isColumnModified(CcStampPeer::LINKED)) $criteria->add(CcStampPeer::LINKED, $this->linked); return $criteria; } @@ -762,6 +808,7 @@ abstract class BaseCcStamp extends BaseObject implements Persistent { $copyObj->setDbShowId($this->show_id); $copyObj->setDbInstanceId($this->instance_id); + $copyObj->setDbLinked($this->linked); if ($deepCopy) { // important: temporarily setNew(false) because this affects the behavior of @@ -1134,6 +1181,7 @@ abstract class BaseCcStamp extends BaseObject implements Persistent $this->id = null; $this->show_id = null; $this->instance_id = null; + $this->linked = null; $this->alreadyInSave = false; $this->alreadyInValidation = false; $this->clearAllReferences(); diff --git a/airtime_mvc/application/models/airtime/om/BaseCcStampPeer.php b/airtime_mvc/application/models/airtime/om/BaseCcStampPeer.php index d6db733c7..920862c89 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcStampPeer.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcStampPeer.php @@ -26,7 +26,7 @@ abstract class BaseCcStampPeer { const TM_CLASS = 'CcStampTableMap'; /** The total number of columns. */ - const NUM_COLUMNS = 3; + const NUM_COLUMNS = 4; /** The number of lazy-loaded columns. */ const NUM_LAZY_LOAD_COLUMNS = 0; @@ -40,6 +40,9 @@ abstract class BaseCcStampPeer { /** the column name for the INSTANCE_ID field */ const INSTANCE_ID = 'cc_stamp.INSTANCE_ID'; + /** the column name for the LINKED field */ + const LINKED = 'cc_stamp.LINKED'; + /** * An identiy map to hold any loaded instances of CcStamp objects. * This must be public so that other peer classes can access this when hydrating from JOIN @@ -56,12 +59,12 @@ abstract class BaseCcStampPeer { * e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id' */ private static $fieldNames = array ( - BasePeer::TYPE_PHPNAME => array ('DbId', 'DbShowId', 'DbInstanceId', ), - BasePeer::TYPE_STUDLYPHPNAME => array ('dbId', 'dbShowId', 'dbInstanceId', ), - BasePeer::TYPE_COLNAME => array (self::ID, self::SHOW_ID, self::INSTANCE_ID, ), - BasePeer::TYPE_RAW_COLNAME => array ('ID', 'SHOW_ID', 'INSTANCE_ID', ), - BasePeer::TYPE_FIELDNAME => array ('id', 'show_id', 'instance_id', ), - BasePeer::TYPE_NUM => array (0, 1, 2, ) + BasePeer::TYPE_PHPNAME => array ('DbId', 'DbShowId', 'DbInstanceId', 'DbLinked', ), + BasePeer::TYPE_STUDLYPHPNAME => array ('dbId', 'dbShowId', 'dbInstanceId', 'dbLinked', ), + BasePeer::TYPE_COLNAME => array (self::ID, self::SHOW_ID, self::INSTANCE_ID, self::LINKED, ), + BasePeer::TYPE_RAW_COLNAME => array ('ID', 'SHOW_ID', 'INSTANCE_ID', 'LINKED', ), + BasePeer::TYPE_FIELDNAME => array ('id', 'show_id', 'instance_id', 'linked', ), + BasePeer::TYPE_NUM => array (0, 1, 2, 3, ) ); /** @@ -71,12 +74,12 @@ abstract class BaseCcStampPeer { * e.g. self::$fieldNames[BasePeer::TYPE_PHPNAME]['Id'] = 0 */ private static $fieldKeys = array ( - BasePeer::TYPE_PHPNAME => array ('DbId' => 0, 'DbShowId' => 1, 'DbInstanceId' => 2, ), - BasePeer::TYPE_STUDLYPHPNAME => array ('dbId' => 0, 'dbShowId' => 1, 'dbInstanceId' => 2, ), - BasePeer::TYPE_COLNAME => array (self::ID => 0, self::SHOW_ID => 1, self::INSTANCE_ID => 2, ), - BasePeer::TYPE_RAW_COLNAME => array ('ID' => 0, 'SHOW_ID' => 1, 'INSTANCE_ID' => 2, ), - BasePeer::TYPE_FIELDNAME => array ('id' => 0, 'show_id' => 1, 'instance_id' => 2, ), - BasePeer::TYPE_NUM => array (0, 1, 2, ) + BasePeer::TYPE_PHPNAME => array ('DbId' => 0, 'DbShowId' => 1, 'DbInstanceId' => 2, 'DbLinked' => 3, ), + BasePeer::TYPE_STUDLYPHPNAME => array ('dbId' => 0, 'dbShowId' => 1, 'dbInstanceId' => 2, 'dbLinked' => 3, ), + BasePeer::TYPE_COLNAME => array (self::ID => 0, self::SHOW_ID => 1, self::INSTANCE_ID => 2, self::LINKED => 3, ), + BasePeer::TYPE_RAW_COLNAME => array ('ID' => 0, 'SHOW_ID' => 1, 'INSTANCE_ID' => 2, 'LINKED' => 3, ), + BasePeer::TYPE_FIELDNAME => array ('id' => 0, 'show_id' => 1, 'instance_id' => 2, 'linked' => 3, ), + BasePeer::TYPE_NUM => array (0, 1, 2, 3, ) ); /** @@ -151,10 +154,12 @@ abstract class BaseCcStampPeer { $criteria->addSelectColumn(CcStampPeer::ID); $criteria->addSelectColumn(CcStampPeer::SHOW_ID); $criteria->addSelectColumn(CcStampPeer::INSTANCE_ID); + $criteria->addSelectColumn(CcStampPeer::LINKED); } else { $criteria->addSelectColumn($alias . '.ID'); $criteria->addSelectColumn($alias . '.SHOW_ID'); $criteria->addSelectColumn($alias . '.INSTANCE_ID'); + $criteria->addSelectColumn($alias . '.LINKED'); } } diff --git a/airtime_mvc/application/models/airtime/om/BaseCcStampQuery.php b/airtime_mvc/application/models/airtime/om/BaseCcStampQuery.php index ef2053a5a..e055e8078 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcStampQuery.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcStampQuery.php @@ -9,10 +9,12 @@ * @method CcStampQuery orderByDbId($order = Criteria::ASC) Order by the id column * @method CcStampQuery orderByDbShowId($order = Criteria::ASC) Order by the show_id column * @method CcStampQuery orderByDbInstanceId($order = Criteria::ASC) Order by the instance_id column + * @method CcStampQuery orderByDbLinked($order = Criteria::ASC) Order by the linked column * * @method CcStampQuery groupByDbId() Group by the id column * @method CcStampQuery groupByDbShowId() Group by the show_id column * @method CcStampQuery groupByDbInstanceId() Group by the instance_id column + * @method CcStampQuery groupByDbLinked() Group by the linked column * * @method CcStampQuery leftJoin($relation) Adds a LEFT JOIN clause to the query * @method CcStampQuery rightJoin($relation) Adds a RIGHT JOIN clause to the query @@ -36,10 +38,12 @@ * @method CcStamp findOneByDbId(int $id) Return the first CcStamp filtered by the id column * @method CcStamp findOneByDbShowId(int $show_id) Return the first CcStamp filtered by the show_id column * @method CcStamp findOneByDbInstanceId(int $instance_id) Return the first CcStamp filtered by the instance_id column + * @method CcStamp findOneByDbLinked(boolean $linked) Return the first CcStamp filtered by the linked column * * @method array findByDbId(int $id) Return CcStamp objects filtered by the id column * @method array findByDbShowId(int $show_id) Return CcStamp objects filtered by the show_id column * @method array findByDbInstanceId(int $instance_id) Return CcStamp objects filtered by the instance_id column + * @method array findByDbLinked(boolean $linked) Return CcStamp objects filtered by the linked column * * @package propel.generator.airtime.om */ @@ -228,6 +232,23 @@ abstract class BaseCcStampQuery extends ModelCriteria return $this->addUsingAlias(CcStampPeer::INSTANCE_ID, $dbInstanceId, $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 CcStampQuery 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(CcStampPeer::LINKED, $dbLinked, $comparison); + } + /** * Filter the query by a related CcShow object * diff --git a/airtime_mvc/application/services/SchedulerService.php b/airtime_mvc/application/services/SchedulerService.php index 635569f55..a5d152680 100644 --- a/airtime_mvc/application/services/SchedulerService.php +++ b/airtime_mvc/application/services/SchedulerService.php @@ -15,7 +15,7 @@ class Application_Service_SchedulerService private $epochNow; private $nowDT; - private $user; + private $currentUser; private $checkUserPermissions = true; public function __construct() @@ -36,7 +36,7 @@ class Application_Service_SchedulerService } $user_service = new Application_Service_UserService(); - $this->user = $user_service->getCurrentUser(); + $this->currentUser = $user_service->getCurrentUser(); } /** @@ -63,12 +63,16 @@ class Application_Service_SchedulerService $diff = $showStartsEpoch - $scheduleStartsEpoch; } + } - $sql = "UPDATE cc_schedule " - ."SET starts = starts + INTERVAL '$diff sec', " - ."ends = ends + INTERVAL '$diff sec' " - ."WHERE instance_id IN ($showIdList)"; - $con->exec($sql); + $ccSchedules = CcScheduleQuery::create() + ->filterByDbInstanceId($instanceIds, Criteria::IN) + ->find(); + foreach ($ccSchedules as $ccSchedule) { + $ccSchedule + ->setDbStarts($ccSchedule->getDbStarts() + $diff) + ->setDbEnds($ccSchedule->getDbEnds() + $diff) + ->save(); } } } @@ -131,4 +135,268 @@ class Application_Service_SchedulerService return $dt; } + + /** + * + * Enter description here ... + * @param array $scheduleItems (schedule_id and instance_id it belongs to) + * @param array $mediaItems (file|block|playlist|webstream) + * @param $adjustSched + */ + public function scheduleAdd($scheduleItems, $mediaItems, $adjustSched=true) + { + $this->con->beginTransaction(); + + $filesToInsert = array(); + + try { + $this->validateRequest($scheduleItems); + + /* + * 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) + */ + foreach ($mediaItems as $media) { + $filesToInsert = array_merge($filesToInsert, $this->retrieveMediaFiles($media["id"], $media["type"])); + } + + //$this->insertAfter($scheduleItems, $filesToInsert, $adjustSched); + $ccStamp = $this->prepareStamp($scheduleItems, $mediaItems, $adjustSched); + + $this->insertStamp($ccStamp); + + //keep track of which shows had their schedule change + //dont forget about the linked shows + + $this->con->commit(); + + Application_Model_RabbitMq::PushSchedule(); + } catch (Exception $e) { + $this->con->rollback(); + throw $e; + } + } + + private function setCcStamp($ccStamp, $instanceId) + { + $ccShowInstance = CcShowInstancesQuery::create()->findPk($instanceId); + $ccShow = $ccShowInstance->getCcShow(); + if ($ccShow->isLinked()) { + $ccStamp + ->setDbLinked(true) + ->setDbShowId($ccShow->getDbId()) + ->save(); + } else { + $ccStamp + ->setDbLinked(false) + ->setDbInstanceId($ccShowInstance->getDbId()) + ->save(); + } + } + + /** + * + * 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 prepareStamp($scheduleItems, $itemsToInsert, $adjustSched = true) + { + try { + + foreach ($scheduleItems as $schedule) { + $id = intval($schedule["id"]); + + if ($id == 0) { + //if we get here, we know the show is empty and therefore + //need to create a new stamp + $pos = 0; + $ccStamp = new CcStamp(); + $this->setCcStamp($ccStamp, $schedule["instance"]); + } else { + $ccStamp = $this->getStamp($id); + //get the cc_stamp_contents item of the scheduleItem($schedule) + //this is where we are inserting after so we have to start the + //position counter after it + $ccStampContent = $this->getCurrentStampItem($id); + $pos = $ccStampContent->getDbPosition() + 1; + + //clear the positions of stamp items after the current + //item so we know we have to reassign their positions + //after inserting the new items + CcStampContentsQuery::create() + ->filterByDbStampId($ccStamp->getDbId()) + ->filterByDbPosition($pos, Criteria::GREATER_EQUAL) + ->setDbPosition(null) + ->save(); + } + + $stampId = $ccStamp->getDbId(); + foreach ($itemsToInsert as $item) { + $ccStampContent = new CcStampContents(); + $ccStampContent + ->setDbStampId($stampId) + ->setDbPosition($pos) + ->save(); + switch ($item["type"]) { + case "playlist": + $ccStampContent->setDbPlaylistId($item["id"])->save(); + break; + case "audioclip": + $ccStampContent->setDbFileId($item["id"])->save(); + + //update is_scheduled flag in cc_files + $ccFile = CcFilesQuery::create()->findPk($item['id']); + $ccFile->setDbIsScheduled(true)->save(); + break; + case "block": + $ccStampContent->setDbBlockId($item["id"])->save(); + break; + case "stream": + $ccStampContent->setDbStreamId($item["id"])->save(); + break; + } + $pos++; + } + + //reassign positions + $ccStampContents = CcStampContentsQuery::create() + ->filterByDbStampId($stampId) + ->filterByDbPosition(null) + ->find(); + foreach ($ccStampContents as $ccStampContent) { + $ccStampContent->setDbPosition($pos)->save(); + $pos++; + } + + return $ccStamp; + } + } catch (Exception $e) { + Logging::debug($e->getMessage()); + throw $e; + } + } + + private function insertStamp($ccStamp) + { + //delete cc_schedule entries + //CcScheduleQuery::create()->filterByDbStampId($ccStamp->getDbId())->delete(); + } + + private function getStamp($scheduleId) + { + $ccSchedule = CcScheduleQuery::create()->findPk($scheduleId); + return CcStamp::create()->findPk($ccSchedule->getDbStampId()); + } + + private function getCurrentStampItem($scheduleId) + { + $ccSchedule = CcScheduleQuery::create()->findPk($scheduleId); + return CcStampContents::create()->findPk($ccSchedule->getDbStampContentsId()); + } + + /** + * + * Enter description here ... + * @param array $items (schedule_id and instance_id it belongs to) + */ + private function validateRequest($items) + { + $nowEpoch = floatval($this->nowDT->format("U.u")); + + for ($i = 0; $i < count($items); $i++) { + $id = $items[$i]["id"]; + + //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"]; + } + + //what is timestamp for? + //format is instance_id => timestamp + $instanceInfo[$items[$i]["instance"]] = $items[$i]["timestamp"]; + } + + if (count($instanceInfo) === 0) { + throw new Exception("Invalid Request."); + } + + $schedIds = array(); + if (isset($schedInfo)) { + $schedIds = array_keys($schedInfo); + } + $schedItems = CcScheduleQuery::create()->findPKs($schedIds, $this->con); + $instanceIds = array_keys($instanceInfo); + $showInstances = CcShowInstancesQuery::create()->findPKs($instanceIds, $this->con); + + //an item has been deleted + if (count($schedIds) !== count($schedItems)) { + throw new OutDatedScheduleException(_("The schedule you're viewing is out of date! (sched mismatch)")); + } + + //a show has been deleted + if (count($instanceIds) !== count($showInstances)) { + throw new OutDatedScheduleException(_("The schedule you're viewing is out of date! (instance mismatch)")); + } + + foreach ($schedItems as $schedItem) { + $id = $schedItem->getDbId(); + $instance = $schedItem->getCcShowInstances($this->con); + + if (intval($schedInfo[$id]) !== $instance->getDbId()) { + throw new OutDatedScheduleException(_("The schedule you're viewing is out of date!")); + } + } + + foreach ($showInstances as $instance) { + + $id = $instance->getDbId(); + $show = $instance->getCcShow($this->con); + + 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.")); + } + + $showEndEpoch = floatval($instance->getDbEnds("U.u")); + + if ($showEndEpoch < $nowEpoch) { + throw new OutDatedScheduleException(sprintf(_("The show %s is over and cannot be scheduled."), $show->getDbName())); + } + + $ts = intval($instanceInfo[$id]); + $lastSchedTs = intval($instance->getDbLastScheduled("U")) ? : 0; + if ($ts < $lastSchedTs) { + Logging::info("ts {$ts} last sched {$lastSchedTs}"); + throw new OutDatedScheduleException(sprintf(_("The show %s has been previously updated!"), $show->getDbName())); + } + } + } } \ No newline at end of file diff --git a/airtime_mvc/build/schema.xml b/airtime_mvc/build/schema.xml index bbcd7f0fe..94ae2b5a1 100644 --- a/airtime_mvc/build/schema.xml +++ b/airtime_mvc/build/schema.xml @@ -328,6 +328,7 @@ broadcasted = 1) --> + - - + @@ -478,45 +474,4 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - -
diff --git a/airtime_mvc/build/sql/schema.sql b/airtime_mvc/build/sql/schema.sql index a6dda42e3..8ae6d5cd5 100644 --- a/airtime_mvc/build/sql/schema.sql +++ b/airtime_mvc/build/sql/schema.sql @@ -427,8 +427,7 @@ CREATE TABLE "cc_schedule" "instance_id" INTEGER NOT NULL, "playout_status" INT2 default 1 NOT NULL, "broadcasted" INT2 default 0 NOT NULL, - "stamp_id" INTEGER default 0 NOT NULL, - "stamp_content_id" INTEGER default 0 NOT NULL, + "position" INTEGER default 0 NOT NULL, PRIMARY KEY ("id") ); @@ -750,54 +749,6 @@ CREATE TABLE "cc_locale" COMMENT ON TABLE "cc_locale" IS ''; -SET search_path TO public; ------------------------------------------------------------------------------ --- cc_stamp_contents ------------------------------------------------------------------------------ - -DROP TABLE "cc_stamp_contents" CASCADE; - - -CREATE TABLE "cc_stamp_contents" -( - "id" serial NOT NULL, - "stamp_id" INTEGER NOT NULL, - "file_id" INTEGER, - "stream_id" INTEGER, - "block_id" INTEGER, - "playlist_id" INTEGER, - "position" INTEGER, - "clip_length" interval default '00:00:00', - "cue_in" interval default '00:00:00', - "cue_out" interval default '00:00:00', - "fade_in" interval default '00:00:00', - "fade_out" interval default '00:00:00', - PRIMARY KEY ("id") -); - -COMMENT ON TABLE "cc_stamp_contents" IS ''; - - -SET search_path TO public; ------------------------------------------------------------------------------ --- cc_stamp ------------------------------------------------------------------------------ - -DROP TABLE "cc_stamp" CASCADE; - - -CREATE TABLE "cc_stamp" -( - "id" serial NOT NULL, - "show_id" INTEGER NOT NULL, - "instance_id" INTEGER, - "linked" BOOLEAN NOT NULL, - PRIMARY KEY ("id") -); - -COMMENT ON TABLE "cc_stamp" IS ''; - - SET search_path TO public; ALTER TABLE "cc_files" ADD CONSTRAINT "cc_files_owner_fkey" FOREIGN KEY ("owner_id") REFERENCES "cc_subjs" ("id"); @@ -854,17 +805,3 @@ ALTER TABLE "cc_webstream_metadata" ADD CONSTRAINT "cc_schedule_inst_fkey" FOREI ALTER TABLE "cc_listener_count" ADD CONSTRAINT "cc_timestamp_inst_fkey" FOREIGN KEY ("timestamp_id") REFERENCES "cc_timestamp" ("id") ON DELETE CASCADE; ALTER TABLE "cc_listener_count" ADD CONSTRAINT "cc_mount_name_inst_fkey" FOREIGN KEY ("mount_name_id") REFERENCES "cc_mount_name" ("id") ON DELETE CASCADE; - -ALTER TABLE "cc_stamp_contents" ADD CONSTRAINT "cc_stamp_contents_stamp_id_fkey" FOREIGN KEY ("stamp_id") REFERENCES "cc_stamp" ("id") ON DELETE CASCADE; - -ALTER TABLE "cc_stamp_contents" ADD CONSTRAINT "cc_stamp_contents_file_id_fkey" FOREIGN KEY ("file_id") REFERENCES "cc_files" ("id") ON DELETE CASCADE; - -ALTER TABLE "cc_stamp_contents" ADD CONSTRAINT "cc_stamp_contents_stream_id_fkey" FOREIGN KEY ("stream_id") REFERENCES "cc_webstream" ("id") ON DELETE CASCADE; - -ALTER TABLE "cc_stamp_contents" ADD CONSTRAINT "cc_stamp_contents_block_id_fkey" FOREIGN KEY ("block_id") REFERENCES "cc_block" ("id") ON DELETE CASCADE; - -ALTER TABLE "cc_stamp_contents" ADD CONSTRAINT "cc_stamp_contents_playlist_id_fkey" FOREIGN KEY ("playlist_id") REFERENCES "cc_playlist" ("id") ON DELETE CASCADE; - -ALTER TABLE "cc_stamp" ADD CONSTRAINT "cc_stamp_show_id_fkey" FOREIGN KEY ("show_id") REFERENCES "cc_show" ("id") ON DELETE CASCADE; - -ALTER TABLE "cc_stamp" ADD CONSTRAINT "cc_stamp_instance_id_fkey" FOREIGN KEY ("instance_id") REFERENCES "cc_show_instances" ("id") ON DELETE CASCADE; From 1a2a05c3cf8a8c69265f8cbc26dd4bf3e646b5d6 Mon Sep 17 00:00:00 2001 From: denise Date: Fri, 12 Apr 2013 16:34:36 -0400 Subject: [PATCH 50/73] CC-4961: Show linking --- airtime_mvc/application/models/Scheduler.php | 126 +++++++++++++++++-- 1 file changed, 119 insertions(+), 7 deletions(-) diff --git a/airtime_mvc/application/models/Scheduler.php b/airtime_mvc/application/models/Scheduler.php index 5068149ad..685fa6222 100644 --- a/airtime_mvc/application/models/Scheduler.php +++ b/airtime_mvc/application/models/Scheduler.php @@ -45,6 +45,21 @@ class Application_Model_Scheduler $this->checkUserPermissions = $value; } + private function validateItemMove($itemsToMove, $afterItem) + { + $afterInstanceId = $afterItem["instance"]; + + foreach ($itemsToMove as $itemToMove) { + $ccShowInstance = CcShowInstancesQuery::create() + ->findPk($itemToMove["instance"]); + $linked = $ccShowInstance->getCcShow()->isLinked(); + + if ($linked && $itemToMove["instance"] != $afterInstanceId) { + throw new Exception(_("Linked items can only be moved within its own show")); + } + } + } + /* * make sure any incoming requests for scheduling are ligit. * @@ -394,6 +409,9 @@ class Application_Model_Scheduler */ private function insertAfter($scheduleItems, $filesToInsert, $adjustSched = true) { + Logging::info($scheduleItems); + //Logging::info($filesToInsert); + try { $affectedShowInstances = array(); @@ -408,23 +426,71 @@ class Application_Model_Scheduler $startProfile = microtime(true); + /* + * We need to prevent items getting added to linked shows more + * than once. This can happen if a cursor is selected in the same + * position on 2 or more linked shows + */ + $temp = array(); + $instance = null; + $pos = 0; + foreach ($scheduleItems as $schedule) { $id = intval($schedule["id"]); + 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; + } + } + } + + $instances = $this->getInstances($schedule["instance"]); + foreach($instances as $instance) { + + Logging::info($instance->getDbId()); if ($id !== 0) { $schedItem = CcScheduleQuery::create()->findPK($id, $this->con); - $instance = $schedItem->getCcShowInstances($this->con); + $pos = $schedItem->getDbPosition(); - $schedItemEndDT = $schedItem->getDbEnds(null); + $ccSchedule = CcScheduleQuery::create() + ->filterByDbInstanceId($instance->getDbId()) + ->filterByDbPosition($pos) + ->findOne(); + + //$schedItemEndDT = $schedItem->getDbEnds(null); + $schedItemEndDT = $ccSchedule->getDbEnds(null); $nextStartDT = $this->findNextStartTime($schedItemEndDT, $instance); + + $pos++; } //selected empty row to add after else { - $instance = CcShowInstancesQuery::create()->findPK($schedule["instance"], $this->con); + //$instance = CcShowInstancesQuery::create()->findPK($schedule["instance"], $this->con); $showStartDT = $instance->getDbStarts(null); $nextStartDT = $this->findNextStartTime($showStartDT, $instance); + //show is empty so start position counter at 0 + $pos = 0; } if (!in_array($instance->getDbId(), $affectedShowInstances)) { @@ -452,6 +518,7 @@ class Application_Model_Scheduler } foreach ($filesToInsert as $file) { + Logging::info("INSERTING FILE ----- ".$instance->getDbId()); $endTimeDT = $this->findEndTime($nextStartDT, $file['cliplength']); //item existed previously and is being moved. @@ -466,7 +533,7 @@ class Application_Model_Scheduler // 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']) @@ -474,6 +541,7 @@ class Application_Model_Scheduler ->setDbFadeIn($file['fadein']) ->setDbFadeOut($file['fadeout']) ->setDbClipLength($file['cliplength']) + ->setDbPosition($pos) ->setDbInstanceId($instance->getDbId()); switch ($file["type"]) { @@ -489,6 +557,7 @@ class Application_Model_Scheduler $sched->save($this->con); $nextStartDT = $endTimeDT; + $pos++; }//all files have been inserted/moved if ($adjustSched === true) { @@ -497,20 +566,23 @@ class Application_Model_Scheduler //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."); @@ -554,6 +626,17 @@ 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 (schedule_id and instance_id it belongs to) * @param array $mediaItems (file|block|playlist|webstream) @@ -611,6 +694,9 @@ class Application_Model_Scheduler */ public function moveItem($selectedItems, $afterItems, $adjustSched = true) { + //Logging::info($selectedItems); + //Logging::info($afterItems); + $startProfile = microtime(true); $this->con->beginTransaction(); @@ -618,6 +704,7 @@ class Application_Model_Scheduler try { + $this->validateItemMove($selectedItems, $afterItems[0]); $this->validateRequest($selectedItems); $this->validateRequest($afterItems); @@ -657,7 +744,7 @@ class Application_Model_Scheduler $modifiedMap[$showInstanceId] = array($schedId); } } - +Logging::info($movedData); //calculate times excluding the to be moved items. foreach ($modifiedMap as $instance => $schedIds) { $startProfile = microtime(true); @@ -716,6 +803,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 ($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)) { From a9b5d00d87386c2c10ae11eb8e911a9e61e9401b Mon Sep 17 00:00:00 2001 From: denise Date: Thu, 18 Apr 2013 16:12:26 -0400 Subject: [PATCH 51/73] CC-4961: Show linking --- airtime_mvc/application/models/Schedule.php | 1 + airtime_mvc/application/models/Scheduler.php | 309 +++++++++++------- .../application/models/ShowBuilder.php | 18 +- .../application/models/airtime/CcShow.php | 35 ++ .../public/js/airtime/showbuilder/builder.js | 6 +- 5 files changed, 240 insertions(+), 129 deletions(-) diff --git a/airtime_mvc/application/models/Schedule.php b/airtime_mvc/application/models/Schedule.php index 0796740f3..d9a17d919 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, diff --git a/airtime_mvc/application/models/Scheduler.php b/airtime_mvc/application/models/Scheduler.php index 685fa6222..3834499cc 100644 --- a/airtime_mvc/application/models/Scheduler.php +++ b/airtime_mvc/application/models/Scheduler.php @@ -52,6 +52,8 @@ class Application_Model_Scheduler foreach ($itemsToMove as $itemToMove) { $ccShowInstance = CcShowInstancesQuery::create() ->findPk($itemToMove["instance"]); + + //does the item being moved belong to a linked show $linked = $ccShowInstance->getCcShow()->isLinked(); if ($linked && $itemToMove["instance"] != $afterInstanceId) { @@ -65,8 +67,10 @@ class Application_Model_Scheduler * * @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++) { @@ -78,7 +82,6 @@ class Application_Model_Scheduler $schedInfo[$id] = $items[$i]["instance"]; } - //what is timestamp for? //format is instance_id => timestamp $instanceInfo[$items[$i]["instance"]] = $items[$i]["timestamp"]; } @@ -122,7 +125,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.")); } @@ -139,6 +142,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")); + } + } + } + } } } @@ -409,35 +434,37 @@ class Application_Model_Scheduler */ private function insertAfter($scheduleItems, $filesToInsert, $adjustSched = true) { - Logging::info($scheduleItems); - //Logging::info($filesToInsert); - try { $affectedShowInstances = array(); //dont want to recalculate times for moved items //only moved items have a sched_id $excludeIds = array(); - foreach ($filesToInsert as $file) { + /*foreach ($filesToInsert as $file) { if (isset($file["sched_id"])) { $excludeIds[] = intval($file["sched_id"]); } - } + }*/ $startProfile = microtime(true); - /* - * We need to prevent items getting added to linked shows more - * than once. This can happen if a cursor is selected in the same - * position on 2 or more linked shows - */ $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"]); + /* 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()); @@ -463,124 +490,158 @@ class Application_Model_Scheduler } } + /* 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) { - Logging::info($instance->getDbId()); - if ($id !== 0) { - $schedItem = CcScheduleQuery::create()->findPK($id, $this->con); - $pos = $schedItem->getDbPosition(); + 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(); - $ccSchedule = CcScheduleQuery::create() - ->filterByDbInstanceId($instance->getDbId()) - ->filterByDbPosition($pos) - ->findOne(); + $ccSchedule = CcScheduleQuery::create() + ->filterByDbInstanceId($instance->getDbId()) + ->filterByDbPosition($pos) + ->findOne(); - //$schedItemEndDT = $schedItem->getDbEnds(null); - $schedItemEndDT = $ccSchedule->getDbEnds(null); - $nextStartDT = $this->findNextStartTime($schedItemEndDT, $instance); + //$schedItemEndDT = $schedItem->getDbEnds(null); + $schedItemEndDT = $ccSchedule->getDbEnds(null); + $nextStartDT = $this->findNextStartTime($schedItemEndDT, $instance); - $pos++; - } - //selected empty row to add after - else { - - //$instance = CcShowInstancesQuery::create()->findPK($schedule["instance"], $this->con); - - $showStartDT = $instance->getDbStarts(null); - $nextStartDT = $this->findNextStartTime($showStartDT, $instance); - //show is empty so start position counter at 0 - $pos = 0; - } - - if (!in_array($instance->getDbId(), $affectedShowInstances)) { - $affectedShowInstances[] = $instance->getDbId(); - } - - /* - * $adjustSched is true if there are schedule items - * following the item just inserted, per show 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 ($filesToInsert as $file) { - Logging::info("INSERTING FILE ----- ".$instance->getDbId()); - $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(); - } - - // 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()); - - switch ($file["type"]) { - case 0: - $sched->setDbFileId($file['id']); - break; - case 1: - $sched->setDbStreamId($file['id']); - break; - default: break; - } - - $sched->save($this->con); - - $nextStartDT = $endTimeDT; - $pos++; - }//all files have been inserted/moved - - if ($adjustSched === true) { - - $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++; } + //selected empty row to add after + else { - $pend = microtime(true); - Logging::debug("adjusting all following items."); - Logging::debug(floatval($pend) - floatval($pstart)); - } - }//for each instance + //$instance = CcShowInstancesQuery::create()->findPK($schedule["instance"], $this->con); + + $showStartDT = $instance->getDbStarts(null); + $nextStartDT = $this->findNextStartTime($showStartDT, $instance); + + //show is empty so start position counter at 0 + $pos = 0; + } + + if (!in_array($instance->getDbId(), $affectedShowInstances)) { + $affectedShowInstances[] = $instance->getDbId(); + } + + /* + * $adjustSched is true if there are schedule items + * following the item just inserted, per show instance + */ + if ($adjustSched === true) { + + $pstart = microtime(true); + + $initalStartDT = clone $nextStartDT; + /*$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 ($filesToInsert as $file) { + Logging::info("INSERTING AT POSITION --- ".$pos); + //$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); + $sched = CcScheduleQuery::create() + ->filterByDbInstanceId($instance->getDbId()) + ->filterByDbFileId($file["id"]) + ->findOne(); + + $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()); + + switch ($file["type"]) { + case 0: + $sched->setDbFileId($file['id']); + break; + case 1: + $sched->setDbStreamId($file['id']); + break; + default: break; + } + + $sched->save($this->con); + + $nextStartDT = $endTimeDT; + $pos++; + }//all files have been inserted/moved + + /* 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 @@ -648,7 +709,7 @@ class Application_Model_Scheduler $filesToInsert = array(); try { - $this->validateRequest($scheduleItems); + $this->validateRequest($scheduleItems, true); /* * create array of arrays @@ -744,7 +805,7 @@ class Application_Model_Scheduler $modifiedMap[$showInstanceId] = array($schedId); } } -Logging::info($movedData); +//Logging::info($movedData); //calculate times excluding the to be moved items. foreach ($modifiedMap as $instance => $schedIds) { $startProfile = microtime(true); diff --git a/airtime_mvc/application/models/ShowBuilder.php b/airtime_mvc/application/models/ShowBuilder.php index fd85487db..01341ce5b 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); @@ -218,6 +232,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/airtime/CcShow.php b/airtime_mvc/application/models/airtime/CcShow.php index be055b374..fa231be12 100644 --- a/airtime_mvc/application/models/airtime/CcShow.php +++ b/airtime_mvc/application/models/airtime/CcShow.php @@ -133,4 +133,39 @@ class CcShow extends BaseCcShow { { return $this->getDbLinked(); } + + /** + * 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) + ->orderByDbId() + ->find($con); + if (null !== $criteria) { + return $collCcShowInstancess; + } + $this->collCcShowInstancess = $collCcShowInstancess; + } + } + return $this->collCcShowInstancess; + } } // CcShow diff --git a/airtime_mvc/public/js/airtime/showbuilder/builder.js b/airtime_mvc/public/js/airtime/showbuilder/builder.js index 9bbc4db92..3ce57f780 100644 --- a/airtime_mvc/public/js/airtime/showbuilder/builder.js +++ b/airtime_mvc/public/js/airtime/showbuilder/builder.js @@ -170,7 +170,6 @@ var AIRTIME = (function(AIRTIME){ }; mod.checkToolBarIcons = function() { - AIRTIME.library.checkAddButton(); mod.checkSelectButton(); mod.checkTrimButton(); @@ -297,7 +296,6 @@ var AIRTIME = (function(AIRTIME){ }; mod.fnAdd = function(aMediaIds, aSchedIds) { - mod.disableUI(); $.post(baseUrl+"showbuilder/schedule-add", @@ -644,7 +642,7 @@ var AIRTIME = (function(AIRTIME){ //save some info for reordering purposes. $nRow.data({"aData": aData}); - + if (aData.scheduled === 1) { $nRow.addClass(NOW_PLAYING_CLASS); } @@ -655,7 +653,7 @@ var AIRTIME = (function(AIRTIME){ $nRow.addClass("sb-future"); } - if (aData.allowed !== true) { + if (aData.allowed !== true || aData.linked_allowed === false) { $nRow.addClass("sb-not-allowed"); } else { From 0f1383d5419d6a321c8343298851331409f55d09 Mon Sep 17 00:00:00 2001 From: denise Date: Thu, 25 Apr 2013 09:00:37 -0400 Subject: [PATCH 52/73] CC-4961: Show linking --- .../controllers/ScheduleController.php | 11 +- airtime_mvc/application/models/Scheduler.php | 50 ++- airtime_mvc/application/models/Show.php | 2 +- .../application/models/ShowInstance.php | 8 +- .../application/models/airtime/CcShow.php | 8 + .../application/services/SchedulerService.php | 306 ++++-------------- .../application/services/ShowService.php | 116 ++++--- 7 files changed, 169 insertions(+), 332 deletions(-) diff --git a/airtime_mvc/application/controllers/ScheduleController.php b/airtime_mvc/application/controllers/ScheduleController.php index e9a97b788..e86170863 100644 --- a/airtime_mvc/application/controllers/ScheduleController.php +++ b/airtime_mvc/application/controllers/ScheduleController.php @@ -439,7 +439,7 @@ class ScheduleController extends Zend_Controller_Action $service_showForm = new Application_Service_ShowFormService( $data["add_show_id"], $data["add_show_instance_id"]); - $service_show = new Application_Service_ShowService(); + $service_show = new Application_Service_ShowService(null, $data); $forms = $this->createShowFormAction(); @@ -479,7 +479,7 @@ class ScheduleController extends Zend_Controller_Action $service_showForm = new Application_Service_ShowFormService( $data["add_show_id"]); - $service_show = new Application_Service_ShowService(); + $service_show = new Application_Service_ShowService(null, $data, true); //TODO: move this to js $data['add_show_hosts'] = $this->_getParam('hosts'); @@ -497,8 +497,7 @@ class ScheduleController extends Zend_Controller_Action if ($service_showForm->validateShowForms($forms, $data, $validateStartDate, $originalShowStartDateTime, true, $data["add_show_instance_id"])) { - //pass in true to indicate we are updating a show - $service_show->addUpdateShow($data, true); + $service_show->addUpdateShow($data); $this->view->addNewShow = true; $this->view->newForm = $this->view->render('schedule/add-show-form.phtml'); @@ -519,7 +518,7 @@ class ScheduleController extends Zend_Controller_Action public function addShowAction() { $service_showForm = new Application_Service_ShowFormService(null); - $service_show = new Application_Service_ShowService(); + //$service_show = new Application_Service_ShowService(); $js = $this->_getParam('data'); $data = array(); @@ -529,6 +528,8 @@ 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'); diff --git a/airtime_mvc/application/models/Scheduler.php b/airtime_mvc/application/models/Scheduler.php index 3834499cc..63b1c5219 100644 --- a/airtime_mvc/application/models/Scheduler.php +++ b/airtime_mvc/application/models/Scheduler.php @@ -432,7 +432,7 @@ class Application_Model_Scheduler * array of schedule item info, what gets inserted into cc_schedule * @param $adjustSched */ - private function insertAfter($scheduleItems, $filesToInsert, $adjustSched = true) + private function insertAfter($scheduleItems, $mediaItems, $filesToInsert=null, $adjustSched=true) { try { $affectedShowInstances = array(); @@ -440,11 +440,6 @@ class Application_Model_Scheduler //dont want to recalculate times for moved items //only moved items have a sched_id $excludeIds = array(); - /*foreach ($filesToInsert as $file) { - if (isset($file["sched_id"])) { - $excludeIds[] = intval($file["sched_id"]); - } - }*/ $startProfile = microtime(true); @@ -517,9 +512,6 @@ class Application_Model_Scheduler } //selected empty row to add after else { - - //$instance = CcShowInstancesQuery::create()->findPK($schedule["instance"], $this->con); - $showStartDT = $instance->getDbStarts(null); $nextStartDT = $this->findNextStartTime($showStartDT, $instance); @@ -552,15 +544,17 @@ class Application_Model_Scheduler Logging::debug(floatval($pend) - floatval($pstart)); } + if (is_null($filesToInsert)) { + $filesToInsert = array(); + foreach ($mediaItems as $media) { + $filesToInsert = array_merge($filesToInsert, $this->retrieveMediaFiles($media["id"], $media["type"])); + } + } foreach ($filesToInsert as $file) { - Logging::info("INSERTING AT POSITION --- ".$pos); - //$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); $sched = CcScheduleQuery::create() ->filterByDbInstanceId($instance->getDbId()) ->filterByDbFileId($file["id"]) @@ -607,8 +601,20 @@ class Application_Model_Scheduler $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 + */ + $filesToInsert = null; + /* 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 @@ -661,11 +667,11 @@ class Application_Model_Scheduler } // update is_scheduled flag for each cc_file - foreach ($filesToInsert as $file) { + /*foreach ($filesToInsert 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."); @@ -706,8 +712,6 @@ class Application_Model_Scheduler { $this->con->beginTransaction(); - $filesToInsert = array(); - try { $this->validateRequest($scheduleItems, true); @@ -735,10 +739,7 @@ class Application_Model_Scheduler * sched_id => , * type => 0) */ - foreach ($mediaItems as $media) { - $filesToInsert = array_merge($filesToInsert, $this->retrieveMediaFiles($media["id"], $media["type"])); - } - $this->insertAfter($scheduleItems, $filesToInsert, $adjustSched); + $this->insertAfter($scheduleItems, $mediaItems, null, $adjustSched); $this->con->commit(); @@ -755,9 +756,6 @@ class Application_Model_Scheduler */ public function moveItem($selectedItems, $afterItems, $adjustSched = true) { - //Logging::info($selectedItems); - //Logging::info($afterItems); - $startProfile = microtime(true); $this->con->beginTransaction(); @@ -805,7 +803,7 @@ class Application_Model_Scheduler $modifiedMap[$showInstanceId] = array($schedId); } } -//Logging::info($movedData); + //calculate times excluding the to be moved items. foreach ($modifiedMap as $instance => $schedIds) { $startProfile = microtime(true); @@ -819,7 +817,7 @@ class Application_Model_Scheduler $startProfile = microtime(true); - $this->insertAfter($afterItems, $movedData, $adjustSched); + $this->insertAfter($afterItems, null, $movedData, $adjustSched); $endProfile = microtime(true); Logging::debug("inserting after removing gaps."); diff --git a/airtime_mvc/application/models/Show.php b/airtime_mvc/application/models/Show.php index 5cd0d727d..121e0a3e1 100644 --- a/airtime_mvc/application/models/Show.php +++ b/airtime_mvc/application/models/Show.php @@ -1666,7 +1666,7 @@ SQL; if (is_null($showsPopUntil) || $showsPopUntil->getTimestamp() < $end_timestamp->getTimestamp()) { //Application_Model_Show::populateAllShowsInRange($showsPopUntil, $end_timestamp); $service_show = new Application_Service_ShowService(); - $service_show->delegateInstanceCreation(null, false, null, $end_timestamp); + $ccShow = $service_show->delegateInstanceCreation(null, $end_timestamp, true); Application_Model_Preference::SetShowsPopulatedUntil($end_timestamp); } diff --git a/airtime_mvc/application/models/ShowInstance.php b/airtime_mvc/application/models/ShowInstance.php index e1892d4c2..ec2a5ca01 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/airtime/CcShow.php b/airtime_mvc/application/models/airtime/CcShow.php index fa231be12..75489fee8 100644 --- a/airtime_mvc/application/models/airtime/CcShow.php +++ b/airtime_mvc/application/models/airtime/CcShow.php @@ -168,4 +168,12 @@ class CcShow extends BaseCcShow { } 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/services/SchedulerService.php b/airtime_mvc/application/services/SchedulerService.php index a5d152680..718f402ba 100644 --- a/airtime_mvc/application/services/SchedulerService.php +++ b/airtime_mvc/application/services/SchedulerService.php @@ -117,7 +117,7 @@ class Application_Service_SchedulerService * @param DateTime $instanceStart * @param string $clipLength */ - private function findEndTime($instanceStart, $clipLength) + private static function findEndTime($instanceStart, $clipLength) { $startEpoch = $instanceStart->format("U.u"); $durationSeconds = Application_Common_DateHelper::playlistTimeToSeconds($clipLength); @@ -139,264 +139,68 @@ class Application_Service_SchedulerService /** * * Enter description here ... - * @param array $scheduleItems (schedule_id and instance_id it belongs to) - * @param array $mediaItems (file|block|playlist|webstream) - * @param $adjustSched + * @param $nextStartDT + * @param $showStamp array of ccSchedule objects */ - public function scheduleAdd($scheduleItems, $mediaItems, $adjustSched=true) + private static function insertItems($showStamp, $ccShow) { - $this->con->beginTransaction(); - - $filesToInsert = array(); - - try { - $this->validateRequest($scheduleItems); - - /* - * 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) - */ - foreach ($mediaItems as $media) { - $filesToInsert = array_merge($filesToInsert, $this->retrieveMediaFiles($media["id"], $media["type"])); - } - - //$this->insertAfter($scheduleItems, $filesToInsert, $adjustSched); - $ccStamp = $this->prepareStamp($scheduleItems, $mediaItems, $adjustSched); - - $this->insertStamp($ccStamp); - - //keep track of which shows had their schedule change - //dont forget about the linked shows - - $this->con->commit(); - - Application_Model_RabbitMq::PushSchedule(); - } catch (Exception $e) { - $this->con->rollback(); - throw $e; - } + } - private function setCcStamp($ccStamp, $instanceId) + public static function fillLinkedShows($ccShow) { - $ccShowInstance = CcShowInstancesQuery::create()->findPk($instanceId); - $ccShow = $ccShowInstance->getCcShow(); if ($ccShow->isLinked()) { - $ccStamp - ->setDbLinked(true) - ->setDbShowId($ccShow->getDbId()) - ->save(); - } else { - $ccStamp - ->setDbLinked(false) - ->setDbInstanceId($ccShowInstance->getDbId()) - ->save(); - } - } - - /** - * - * 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 prepareStamp($scheduleItems, $itemsToInsert, $adjustSched = true) - { - try { - - foreach ($scheduleItems as $schedule) { - $id = intval($schedule["id"]); - - if ($id == 0) { - //if we get here, we know the show is empty and therefore - //need to create a new stamp - $pos = 0; - $ccStamp = new CcStamp(); - $this->setCcStamp($ccStamp, $schedule["instance"]); - } else { - $ccStamp = $this->getStamp($id); - //get the cc_stamp_contents item of the scheduleItem($schedule) - //this is where we are inserting after so we have to start the - //position counter after it - $ccStampContent = $this->getCurrentStampItem($id); - $pos = $ccStampContent->getDbPosition() + 1; - - //clear the positions of stamp items after the current - //item so we know we have to reassign their positions - //after inserting the new items - CcStampContentsQuery::create() - ->filterByDbStampId($ccStamp->getDbId()) - ->filterByDbPosition($pos, Criteria::GREATER_EQUAL) - ->setDbPosition(null) - ->save(); - } - - $stampId = $ccStamp->getDbId(); - foreach ($itemsToInsert as $item) { - $ccStampContent = new CcStampContents(); - $ccStampContent - ->setDbStampId($stampId) - ->setDbPosition($pos) - ->save(); - switch ($item["type"]) { - case "playlist": - $ccStampContent->setDbPlaylistId($item["id"])->save(); - break; - case "audioclip": - $ccStampContent->setDbFileId($item["id"])->save(); - - //update is_scheduled flag in cc_files - $ccFile = CcFilesQuery::create()->findPk($item['id']); - $ccFile->setDbIsScheduled(true)->save(); - break; - case "block": - $ccStampContent->setDbBlockId($item["id"])->save(); - break; - case "stream": - $ccStampContent->setDbStreamId($item["id"])->save(); - break; - } - $pos++; - } - - //reassign positions - $ccStampContents = CcStampContentsQuery::create() - ->filterByDbStampId($stampId) - ->filterByDbPosition(null) + /* 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(); - foreach ($ccStampContents as $ccStampContent) { - $ccStampContent->setDbPosition($pos)->save(); - $pos++; + } else { + break; + } + + //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 } - - return $ccStamp; - } - } catch (Exception $e) { - Logging::debug($e->getMessage()); - throw $e; - } - } - - private function insertStamp($ccStamp) - { - //delete cc_schedule entries - //CcScheduleQuery::create()->filterByDbStampId($ccStamp->getDbId())->delete(); - } - - private function getStamp($scheduleId) - { - $ccSchedule = CcScheduleQuery::create()->findPk($scheduleId); - return CcStamp::create()->findPk($ccSchedule->getDbStampId()); - } - - private function getCurrentStampItem($scheduleId) - { - $ccSchedule = CcScheduleQuery::create()->findPk($scheduleId); - return CcStampContents::create()->findPk($ccSchedule->getDbStampContentsId()); - } - - /** - * - * Enter description here ... - * @param array $items (schedule_id and instance_id it belongs to) - */ - private function validateRequest($items) - { - $nowEpoch = floatval($this->nowDT->format("U.u")); - - for ($i = 0; $i < count($items); $i++) { - $id = $items[$i]["id"]; - - //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"]; - } - - //what is timestamp for? - //format is instance_id => timestamp - $instanceInfo[$items[$i]["instance"]] = $items[$i]["timestamp"]; - } - - if (count($instanceInfo) === 0) { - throw new Exception("Invalid Request."); - } - - $schedIds = array(); - if (isset($schedInfo)) { - $schedIds = array_keys($schedInfo); - } - $schedItems = CcScheduleQuery::create()->findPKs($schedIds, $this->con); - $instanceIds = array_keys($instanceInfo); - $showInstances = CcShowInstancesQuery::create()->findPKs($instanceIds, $this->con); - - //an item has been deleted - if (count($schedIds) !== count($schedItems)) { - throw new OutDatedScheduleException(_("The schedule you're viewing is out of date! (sched mismatch)")); - } - - //a show has been deleted - if (count($instanceIds) !== count($showInstances)) { - throw new OutDatedScheduleException(_("The schedule you're viewing is out of date! (instance mismatch)")); - } - - foreach ($schedItems as $schedItem) { - $id = $schedItem->getDbId(); - $instance = $schedItem->getCcShowInstances($this->con); - - if (intval($schedInfo[$id]) !== $instance->getDbId()) { - throw new OutDatedScheduleException(_("The schedule you're viewing is out of date!")); - } - } - - foreach ($showInstances as $instance) { - - $id = $instance->getDbId(); - $show = $instance->getCcShow($this->con); - - 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.")); - } - - $showEndEpoch = floatval($instance->getDbEnds("U.u")); - - if ($showEndEpoch < $nowEpoch) { - throw new OutDatedScheduleException(sprintf(_("The show %s is over and cannot be scheduled."), $show->getDbName())); - } - - $ts = intval($instanceInfo[$id]); - $lastSchedTs = intval($instance->getDbLastScheduled("U")) ? : 0; - if ($ts < $lastSchedTs) { - Logging::info("ts {$ts} last sched {$lastSchedTs}"); - throw new OutDatedScheduleException(sprintf(_("The show %s has been previously updated!"), $show->getDbName())); - } + } //foreach linked instance } } } \ No newline at end of file diff --git a/airtime_mvc/application/services/ShowService.php b/airtime_mvc/application/services/ShowService.php index 146848aa4..82c74f031 100644 --- a/airtime_mvc/application/services/ShowService.php +++ b/airtime_mvc/application/services/ShowService.php @@ -9,12 +9,28 @@ define("REPEAT_MONTHLY_WEEKLY", 3); class Application_Service_ShowService { private $ccShow; + private $isRecorded; + private $isRebroadcast; + private $repeatType; + private $isUpdate; - public function __construct($showId=null) + public function __construct($showId=null, $showData=null, $isUpdate=false) { if (!is_null($showId)) { $this->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) { @@ -87,12 +103,12 @@ class Application_Service_ShowService } } - public function addUpdateShow($showData, $isUpdate=false) + public function addUpdateShow($showData) { $service_user = new Application_Service_UserService(); $currentUser = $service_user->getCurrentUser(); - if ($showData["add_show_repeats"]) { + /*if ($showData["add_show_repeats"]) { $repeatType = $showData["add_show_repeat_type"]; if ($showData["add_show_repeat_type"] == 2) { $repeatType = $showData["add_show_monthly_repeat_type"]; @@ -101,7 +117,7 @@ class Application_Service_ShowService $repeatType = -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; + $isRebroadcast = (isset($showData['add_show_rebroadcast']) && $showData['add_show_rebroadcast']) ? 1 : 0;*/ $showData["add_show_duration"] = $this->formatShowDuration( $showData["add_show_duration"]); @@ -113,36 +129,36 @@ class Application_Service_ShowService throw new Exception("Permission denied"); } //update ccShow - $this->setCcShow($showData, $isUpdate); + $this->setCcShow($showData); $daysAdded = array(); - if ($isUpdate) { - $daysAdded = $this->delegateInstanceCleanup($showData, $isRecorded, $repeatType); + 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 ($isRebroadcast) { + if ($this->isRebroadcast) { //delete entry in cc_show_rebroadcast $this->deleteCcShowRebroadcasts(); } } //update ccShowDays - $this->setCcShowDays($showData, $repeatType, $isRecorded); + $this->setCcShowDays($showData); //update ccShowRebroadcasts - $this->setCcShowRebroadcasts($showData, $repeatType, $isRecorded); + $this->setCcShowRebroadcasts($showData); //update ccShowHosts $this->setCcShowHosts($showData); //create new ccShowInstances - $this->delegateInstanceCreation($isRebroadcast, $isUpdate, $daysAdded); + $this->delegateInstanceCreation($daysAdded); - if ($isUpdate) { + if ($this->isUpdate) { $service_scheduler = new Application_Service_SchedulerService(); $service_scheduler->removeGaps($this->ccShow->getDbId()); } @@ -151,7 +167,7 @@ class Application_Service_ShowService Application_Model_RabbitMq::PushSchedule(); } catch (Exception $e) { $con->rollback(); - $isUpdate ? $action = "update" : $action = "creation"; + $this->isUpdate ? $action = "update" : $action = "creation"; Logging::info("EXCEPTION: Show ".$action." failed."); Logging::info($e->getMessage()); } @@ -162,7 +178,7 @@ class Application_Service_ShowService * Receives a cc_show id and determines whether to create a * single show instance or repeating show instances */ - public function delegateInstanceCreation($isRebroadcast=null, $isUpdate=false, $daysAdded=null, $end=null) + public function delegateInstanceCreation($daysAdded=null, $end=null, $fillInstances=false) { $populateUntil = $this->getPopulateShowUntilDateTIme(); @@ -179,25 +195,27 @@ class Application_Service_ShowService foreach ($ccShowDays as $day) { switch ($day->getDbRepeatType()) { case NO_REPEAT: - $this->createNonRepeatingInstance($day, $populateUntil, $isRebroadcast, $isUpdate); + $this->createNonRepeatingInstance($day, $populateUntil); break; case REPEAT_WEEKLY: $this->createRepeatingInstances($day, $populateUntil, REPEAT_WEEKLY, - new DateInterval("P7D"), $isRebroadcast, $isUpdate, $daysAdded); + new DateInterval("P7D"), $daysAdded, $fillInstances); break; case REPEAT_BI_WEEKLY: $this->createRepeatingInstances($day, $populateUntil, REPEAT_BI_WEEKLY, - new DateInterval("P14D"), $isRebroadcast, $isUpdate, $daysAdded); + new DateInterval("P14D"), $daysAdded, $fillInstances); break; case REPEAT_MONTHLY_MONTHLY: - $this->createMonthlyMonthlyRepeatInstances($day, $populateUntil, $isRebroadcast, $isUpdate); + $this->createMonthlyMonthlyRepeatInstances($day, $populateUntil, $fillInstances); break; case REPEAT_MONTHLY_WEEKLY: $this->createRepeatingInstances($day, $populateUntil, REPEAT_MONTHLY_WEEKLY, - null, $isRebroadcast, $isUpdate); + null, $fillInstances); break; } } + + return $this->ccShow; } private function getShowDaysInRange($start, $end) @@ -273,7 +291,7 @@ SQL; * @param $isRecorded value computed from the edit show form * @param $repeatType value computed from the edit show form */ - private function delegateInstanceCleanup($showData, $isRecorded, $repeatType) + private function delegateInstanceCleanup($showData) { $showId = $this->ccShow->getDbId(); @@ -310,7 +328,7 @@ SQL; $deleteRepeatTypes = array(REPEAT_BI_WEEKLY, REPEAT_MONTHLY_MONTHLY, REPEAT_MONTHLY_WEEKLY); - if (in_array($repeatType, $deleteRepeatTypes) && + 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. @@ -322,7 +340,7 @@ SQL; $currentRepeatType = $currentShowDay->getDbRepeatType(); //only delete instances if the show being edited was already repeating //and the repeat type changed - if ($currentRepeatType != -1 && $repeatType != $currentRepeatType) { + 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 @@ -759,7 +777,7 @@ SQL; * @param $showDay * @param $populateUntil */ - private function createNonRepeatingInstance($showDay, $populateUntil, $isRebroadcast, $isUpdate) + private function createNonRepeatingInstance($showDay, $populateUntil) { //DateTime object $start = $showDay->getLocalStartDateAndTime(); @@ -769,7 +787,7 @@ SQL; if ($utcStartDateTime->getTimestamp() < $populateUntil->getTimestamp()) { $ccShowInstance = new CcShowInstances(); - if ($isUpdate) { + if ($this->isUpdate) { $ccShowInstance = $this->getInstance($utcStartDateTime); } $ccShowInstance->setDbShowId($this->ccShow->getDbId()); @@ -778,12 +796,12 @@ SQL; $ccShowInstance->setDbRecord($showDay->getDbRecord()); $ccShowInstance->save(); - if ($isUpdate) { + if ($this->isUpdate) { $con = Propel::getConnection(CcSchedulePeer::DATABASE_NAME); $ccShowInstance->updateScheduleStatus($con); } - if ($isRebroadcast) { + if ($this->isRebroadcast) { $this->createRebroadcastInstances($showDay, $start, $ccShowInstance->getDbId()); } } @@ -798,7 +816,7 @@ SQL; * @param unknown_type $isRebroadcast */ private function createRepeatingInstances($showDay, $populateUntil, - $repeatType, $repeatInterval, $isRebroadcast, $isUpdate, $daysAdded=null) + $repeatType, $repeatInterval, $daysAdded=null, $fillInstances) { $show_id = $showDay->getDbShowId(); $first_show = $showDay->getDbFirstShow(); //non-UTC @@ -822,7 +840,6 @@ SQL; $utcLastShowDateTime = $last_show ? Application_Common_DateHelper::ConvertToUtcDateTime($last_show, $timezone) : null; - $utcEndDateTime = null; foreach ($datePeriod as $date) { list($utcStartDateTime, $utcEndDateTime) = $this->createUTCStartEndDateTime( $date, $duration); @@ -838,7 +855,7 @@ SQL; * This will be the case when we are adding a new show day to * a repeating show */ - if ($isUpdate) { + if ($this->isUpdate) { if ($this->hasInstance($utcStartDateTime)) { $ccShowInstance = $this->getInstance($utcStartDateTime); $newInstance = false; @@ -874,17 +891,26 @@ SQL; } } - if ($isRebroadcast) { + if ($this->isRebroadcast) { $this->createRebroadcastInstances($showDay, $date, $ccShowInstance->getDbId()); } } } - $nextDate = $utcEndDateTime->add($repeatInterval); + + /* 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, - $isRebroadcast, $isUpdate) + private function createMonthlyMonthlyRepeatInstances($showDay, $populateUntil) { $show_id = $showDay->getDbShowId(); $first_show = $showDay->getDbFirstShow(); //non-UTC @@ -920,7 +946,7 @@ SQL; * This will be the case when we are adding a new show day to * a repeating show */ - if ($isUpdate && $this->hasInstance($utcStartDateTime)) { + if ($this->isUpdate && $this->hasInstance($utcStartDateTime)) { $ccShowInstance = $this->getInstance($utcStartDateTime); $newInstance = false; $updateScheduleStatus = true; @@ -946,7 +972,7 @@ SQL; } } - if ($isRebroadcast) { + if ($this->isRebroadcast) { $this->createRebroadcastInstances($showDay, $date, $ccShowInstance->getDbId()); } } @@ -1105,9 +1131,9 @@ SQL; * @param $ccShow * @param $showData */ - private function setCcShow($showData, $isUpdate=false) + private function setCcShow($showData) { - if (!$isUpdate) { + if (!$this->isUpdate) { $ccShow = new CcShow(); } else { $ccShow = CcShowQuery::create()->findPk($showData["add_show_id"]); @@ -1139,7 +1165,7 @@ SQL; * @param $isRecorded * @param $showDay ccShowDay object we are setting values on */ - private function setCcShowDays($showData, $repeatType=-1, $isRecorded=0) + private function setCcShowDays($showData) { $showId = $this->ccShow->getDbId(); @@ -1172,9 +1198,9 @@ SQL; $showDay->setDbStartTime($startDateTime->format("H:i:s")); $showDay->setDbTimezone(Application_Model_Preference::GetTimezone()); $showDay->setDbDuration($showData['add_show_duration']); - $showDay->setDbRepeatType($repeatType); + $showDay->setDbRepeatType($this->repeatType); $showDay->setDbShowId($showId); - $showDay->setDbRecord($isRecorded); + $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")); @@ -1199,9 +1225,9 @@ SQL; $showDay->setDbTimezone(Application_Model_Preference::GetTimezone()); $showDay->setDbDuration($showData['add_show_duration']); $showDay->setDbDay($day); - $showDay->setDbRepeatType($repeatType); + $showDay->setDbRepeatType($this->repeatType); $showDay->setDbShowId($showId); - $showDay->setDbRecord($isRecorded); + $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")); @@ -1230,11 +1256,11 @@ SQL; * @param $repeatType * @param $isRecorded */ - private function setCcShowRebroadcasts($showData, $repeatType, $isRecorded) + private function setCcShowRebroadcasts($showData) { $showId = $this->ccShow->getDbId(); - if (($isRecorded && $showData['add_show_rebroadcast']) && ($repeatType != -1)) { + 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(); @@ -1244,7 +1270,7 @@ SQL; $showRebroad->save(); } } - } elseif ($isRecorded && $showData['add_show_rebroadcast'] && ($repeatType == -1)) { + } 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"]); From 628e0758289d1129e8272a20d9c7609b30588ad0 Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Fri, 26 Apr 2013 11:35:52 -0400 Subject: [PATCH 53/73] pypo syntax error --- python_apps/pypo/pypofetch.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python_apps/pypo/pypofetch.py b/python_apps/pypo/pypofetch.py index b3d03fdb8..edb6f7d37 100644 --- a/python_apps/pypo/pypofetch.py +++ b/python_apps/pypo/pypofetch.py @@ -281,7 +281,7 @@ class PypoFetch(Thread): line = line.strip() - if not len(line) or line[0] == "#" + if not len(line) or line[0] == "#": continue try: From 655c1eb5a986c41ac971455943b0ad4fc4d0c7d0 Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Fri, 26 Apr 2013 11:37:46 -0400 Subject: [PATCH 54/73] CC-5043: Invalid literal for float error from mutagen --- python_apps/media-monitor2/media/metadata/process.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/python_apps/media-monitor2/media/metadata/process.py b/python_apps/media-monitor2/media/metadata/process.py index e4ef90423..be6b81e20 100644 --- a/python_apps/media-monitor2/media/metadata/process.py +++ b/python_apps/media-monitor2/media/metadata/process.py @@ -148,7 +148,8 @@ class MetadataElement(Loggable): if self.__max_length != -1: r = truncate_to_length(r, self.__max_length) if self.__max_value != -1: - r = truncate_to_value(r, self.__max_value) + try: r = truncate_to_value(r, self.__max_value) + except ValueError, e: r = '' return r def normalize_mutagen(path): From c99207b47eae9056908802bfeb11fc7cd4a6639d Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Fri, 26 Apr 2013 12:22:18 -0400 Subject: [PATCH 55/73] CC-4417: Opus codec support --- install_full/ubuntu/airtime-full-install | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/install_full/ubuntu/airtime-full-install b/install_full/ubuntu/airtime-full-install index d574b9adb..942a19a2f 100755 --- a/install_full/ubuntu/airtime-full-install +++ b/install_full/ubuntu/airtime-full-install @@ -59,7 +59,7 @@ libtaglib-ocaml libao-ocaml libmad-ocaml ecasound \ libesd0 libportaudio2 libsamplerate0 rabbitmq-server patch \ php5-curl mpg123 monit python-virtualenv multitail libcamomile-ocaml-data \ libpulse0 vorbis-tools lsb-release lsof sudo mp3gain vorbisgain flac vorbis-tools \ -pwgen libfaad2 +pwgen libfaad2 libopus0 #install packages with --force-yes option (this is useful in the case From 09fec4b42bb66f323613c689f4df1d3986ba21e0 Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Fri, 26 Apr 2013 12:26:01 -0400 Subject: [PATCH 56/73] CC-4417: Opus codec support --- install_full/ubuntu/airtime-full-install | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/install_full/ubuntu/airtime-full-install b/install_full/ubuntu/airtime-full-install index 942a19a2f..d574b9adb 100755 --- a/install_full/ubuntu/airtime-full-install +++ b/install_full/ubuntu/airtime-full-install @@ -59,7 +59,7 @@ libtaglib-ocaml libao-ocaml libmad-ocaml ecasound \ libesd0 libportaudio2 libsamplerate0 rabbitmq-server patch \ php5-curl mpg123 monit python-virtualenv multitail libcamomile-ocaml-data \ libpulse0 vorbis-tools lsb-release lsof sudo mp3gain vorbisgain flac vorbis-tools \ -pwgen libfaad2 libopus0 +pwgen libfaad2 #install packages with --force-yes option (this is useful in the case From 91e15ea0927289ccb739adc9576cfb84a9d17fc2 Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Fri, 26 Apr 2013 12:26:13 -0400 Subject: [PATCH 57/73] CC-4417: Opus codec support --- install_full/ubuntu/airtime-full-install | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/install_full/ubuntu/airtime-full-install b/install_full/ubuntu/airtime-full-install index d574b9adb..e2ede9a18 100755 --- a/install_full/ubuntu/airtime-full-install +++ b/install_full/ubuntu/airtime-full-install @@ -82,10 +82,11 @@ else apt-get -y --force-yes install coreutils fi -#Install Sourcefabric's custom Liquidsoap debian package +#Install packages back-ported by Sourcefabric apt-get -y --force-yes install sourcefabric-keyring apt-get -y --force-yes install liquidsoap apt-get -y --force-yes install silan +apt-get -y --force-yes install libopus0 if [ "$server" = "nginx" ]; then apt-get -y --force-yes install nginx php5-fpm From 52655ab3755ccb1ec692345c8ff250a7ff207bd3 Mon Sep 17 00:00:00 2001 From: denise Date: Fri, 26 Apr 2013 13:43:30 -0400 Subject: [PATCH 58/73] CC-4961: Show linking --- airtime_mvc/application/models/Scheduler.php | 8 +- .../application/models/airtime/CcShow.php | 5 ++ .../models/airtime/map/CcShowTableMap.php | 1 + .../models/airtime/om/BaseCcShow.php | 56 ++++++++++++- .../models/airtime/om/BaseCcShowPeer.php | 31 ++++---- .../models/airtime/om/BaseCcShowQuery.php | 21 +++++ .../application/services/SchedulerService.php | 78 +++++++++---------- .../application/services/ShowFormService.php | 6 +- .../application/services/ShowService.php | 29 ++++--- airtime_mvc/build/schema.xml | 3 + airtime_mvc/build/sql/schema.sql | 1 + 11 files changed, 164 insertions(+), 75 deletions(-) diff --git a/airtime_mvc/application/models/Scheduler.php b/airtime_mvc/application/models/Scheduler.php index 63b1c5219..9e2c432ae 100644 --- a/airtime_mvc/application/models/Scheduler.php +++ b/airtime_mvc/application/models/Scheduler.php @@ -432,7 +432,7 @@ class Application_Model_Scheduler * array of schedule item info, what gets inserted into cc_schedule * @param $adjustSched */ - private function insertAfter($scheduleItems, $mediaItems, $filesToInsert=null, $adjustSched=true) + private function insertAfter($scheduleItems, $mediaItems, $filesToInsert=null, $adjustSched=true, $moveAction=false) { try { $affectedShowInstances = array(); @@ -613,7 +613,9 @@ class Application_Model_Scheduler /* 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 */ - $filesToInsert = null; + if (!$moveAction) { + $filesToInsert = null; + } /* If we are adjusting start and end times for items * after the insert location, we need to exclude the @@ -817,7 +819,7 @@ class Application_Model_Scheduler $startProfile = microtime(true); - $this->insertAfter($afterItems, null, $movedData, $adjustSched); + $this->insertAfter($afterItems, null, $movedData, $adjustSched, true); $endProfile = microtime(true); Logging::debug("inserting after removing gaps."); diff --git a/airtime_mvc/application/models/airtime/CcShow.php b/airtime_mvc/application/models/airtime/CcShow.php index 75489fee8..12139a3ff 100644 --- a/airtime_mvc/application/models/airtime/CcShow.php +++ b/airtime_mvc/application/models/airtime/CcShow.php @@ -134,6 +134,11 @@ class CcShow extends BaseCcShow { return $this->getDbLinked(); } + public function isLinkable() + { + return $this->getDbIsLinkable(); + } + /** * Gets an array of CcShowInstances objects which contain a foreign key that references this object. * diff --git a/airtime_mvc/application/models/airtime/map/CcShowTableMap.php b/airtime_mvc/application/models/airtime/map/CcShowTableMap.php index 4ba58b7d2..8a2686670 100644 --- a/airtime_mvc/application/models/airtime/map/CcShowTableMap.php +++ b/airtime_mvc/application/models/airtime/map/CcShowTableMap.php @@ -50,6 +50,7 @@ class CcShowTableMap extends TableMap { $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/om/BaseCcShow.php b/airtime_mvc/application/models/airtime/om/BaseCcShow.php index 3c8e770a8..3cf4dab1f 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcShow.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcShow.php @@ -102,6 +102,13 @@ abstract class BaseCcShow extends BaseObject implements Persistent */ 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. */ @@ -150,6 +157,7 @@ abstract class BaseCcShow extends BaseObject implements Persistent $this->live_stream_using_airtime_auth = false; $this->live_stream_using_custom_auth = false; $this->linked = false; + $this->is_linkable = true; } /** @@ -282,6 +290,16 @@ abstract class BaseCcShow extends BaseObject implements Persistent return $this->linked; } + /** + * Get the [is_linkable] column value. + * + * @return boolean + */ + public function getDbIsLinkable() + { + return $this->is_linkable; + } + /** * Set the value of [id] column. * @@ -522,6 +540,26 @@ abstract class BaseCcShow extends BaseObject implements Persistent 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. * @@ -556,6 +594,10 @@ abstract class BaseCcShow extends BaseObject implements Persistent return false; } + if ($this->is_linkable !== true) { + return false; + } + // otherwise, everything was equal, so return TRUE return true; } // hasOnlyDefaultValues() @@ -590,6 +632,7 @@ abstract class BaseCcShow extends BaseObject implements Persistent $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); @@ -598,7 +641,7 @@ abstract class BaseCcShow extends BaseObject implements Persistent $this->ensureConsistency(); } - return $startcol + 12; // 12 = 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); @@ -1005,6 +1048,9 @@ abstract class BaseCcShow extends BaseObject implements Persistent case 11: return $this->getDbLinked(); break; + case 12: + return $this->getDbIsLinkable(); + break; default: return null; break; @@ -1040,6 +1086,7 @@ abstract class BaseCcShow extends BaseObject implements Persistent $keys[9] => $this->getDbLiveStreamUser(), $keys[10] => $this->getDbLiveStreamPass(), $keys[11] => $this->getDbLinked(), + $keys[12] => $this->getDbIsLinkable(), ); return $result; } @@ -1107,6 +1154,9 @@ abstract class BaseCcShow extends BaseObject implements Persistent case 11: $this->setDbLinked($value); break; + case 12: + $this->setDbIsLinkable($value); + break; } // switch() } @@ -1143,6 +1193,7 @@ abstract class BaseCcShow extends BaseObject implements Persistent 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]]); } /** @@ -1166,6 +1217,7 @@ abstract class BaseCcShow extends BaseObject implements Persistent 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; } @@ -1238,6 +1290,7 @@ abstract class BaseCcShow extends BaseObject implements Persistent $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 @@ -1841,6 +1894,7 @@ abstract class BaseCcShow extends BaseObject implements Persistent $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 235a8da9e..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 = 12; + const NUM_COLUMNS = 13; /** The number of lazy-loaded columns. */ const NUM_LAZY_LOAD_COLUMNS = 0; @@ -67,6 +67,9 @@ abstract class BaseCcShowPeer { /** 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 @@ -83,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', 'DbLinked', ), - BasePeer::TYPE_STUDLYPHPNAME => array ('dbId', 'dbName', 'dbUrl', 'dbGenre', 'dbDescription', 'dbColor', 'dbBackgroundColor', 'dbLiveStreamUsingAirtimeAuth', 'dbLiveStreamUsingCustomAuth', 'dbLiveStreamUser', 'dbLiveStreamPass', 'dbLinked', ), - 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, ), - 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', ), - 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', ), - BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ) + 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, ) ); /** @@ -98,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, 'DbLinked' => 11, ), - 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, ), - 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, ), - 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, ), - 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, ), - BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ) + 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, ) ); /** @@ -187,6 +190,7 @@ abstract class BaseCcShowPeer { $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'); @@ -200,6 +204,7 @@ abstract class BaseCcShowPeer { $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 25206f8e7..687335e03 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcShowQuery.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcShowQuery.php @@ -18,6 +18,7 @@ * @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 @@ -31,6 +32,7 @@ * @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 @@ -67,6 +69,7 @@ * @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 @@ -80,6 +83,7 @@ * @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 */ @@ -433,6 +437,23 @@ abstract class BaseCcShowQuery extends ModelCriteria 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/SchedulerService.php b/airtime_mvc/application/services/SchedulerService.php index 718f402ba..99f2ae609 100644 --- a/airtime_mvc/application/services/SchedulerService.php +++ b/airtime_mvc/application/services/SchedulerService.php @@ -136,17 +136,6 @@ class Application_Service_SchedulerService return $dt; } - /** - * - * Enter description here ... - * @param $nextStartDT - * @param $showStamp array of ccSchedule objects - */ - private static function insertItems($showStamp, $ccShow) - { - - } - public static function fillLinkedShows($ccShow) { if ($ccShow->isLinked()) { @@ -167,40 +156,47 @@ class Application_Service_SchedulerService ->filterByDbInstanceId($ccSchedule->getDbInstanceId()) ->orderByDbStarts() ->find(); - } else { - break; - } - //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); + //get time_filled so we can update cc_show_instances + $timeFilled = $ccSchedule->getCcShowInstances()->getDbTimeFilled(); - foreach ($showStamp as $item) { - $endTimeDT = self::findEndTime($nextStartDT, $item->getDbClipLength()); + //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); - $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()) + 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(); - - $nextStartDT = $endTimeDT; - } //foreach show item - } - } //foreach linked instance + } + } //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 index 47ec2425b..2494b9c0d 100644 --- a/airtime_mvc/application/services/ShowFormService.php +++ b/airtime_mvc/application/services/ShowFormService.php @@ -215,6 +215,10 @@ class Application_Service_ShowFormService '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) @@ -337,7 +341,7 @@ class Application_Service_ShowFormService * Returns 2 DateTime objects, in the user's local time, * of the next future repeat show instance start and end time */ - private function getNextFutureRepeatShowTime() + public function getNextFutureRepeatShowTime() { $sql = <<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) { @@ -108,17 +115,6 @@ class Application_Service_ShowService $service_user = new Application_Service_UserService(); $currentUser = $service_user->getCurrentUser(); - /*if ($showData["add_show_repeats"]) { - $repeatType = $showData["add_show_repeat_type"]; - if ($showData["add_show_repeat_type"] == 2) { - $repeatType = $showData["add_show_monthly_repeat_type"]; - } - } else { - $repeatType = -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"]); @@ -860,14 +856,10 @@ SQL; $ccShowInstance = $this->getInstance($utcStartDateTime); $newInstance = false; $updateScheduleStatus = true; - } elseif (in_array($day, $daysAdded)) { + } else { $newInstance = true; $ccShowInstance = new CcShowInstances(); $updateScheduleStatus = false; - } else { - //if we get here, an instance was edited on it's own and - //thus became it's own show so there is nothing to update - break 1; } } else { $newInstance = true; @@ -1149,6 +1141,11 @@ SQL; $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(); diff --git a/airtime_mvc/build/schema.xml b/airtime_mvc/build/schema.xml index 8141562d0..c0ec104dd 100644 --- a/airtime_mvc/build/schema.xml +++ b/airtime_mvc/build/schema.xml @@ -133,6 +133,9 @@ + + diff --git a/airtime_mvc/build/sql/schema.sql b/airtime_mvc/build/sql/schema.sql index 8ae6d5cd5..ecd63a8f2 100644 --- a/airtime_mvc/build/sql/schema.sql +++ b/airtime_mvc/build/sql/schema.sql @@ -157,6 +157,7 @@ CREATE TABLE "cc_show" "live_stream_user" VARCHAR(255), "live_stream_pass" VARCHAR(255), "linked" BOOLEAN default 'f' NOT NULL, + "is_linkable" BOOLEAN default 't' NOT NULL, PRIMARY KEY ("id") ); From 6cc366b1000347df8b1667f97a90e5e9d5931ea5 Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Fri, 26 Apr 2013 13:43:40 -0400 Subject: [PATCH 59/73] CC-5069: Airtime 2.4 upgrade scripts -initial commit --- airtime_mvc/build/sql/defaultdata.sql | 2 +- install_minimal/include/airtime-constants.php | 2 +- install_minimal/include/airtime-upgrade.php | 4 ++++ install_minimal/upgrades/airtime-2.4.0/airtime-upgrade.php | 0 install_minimal/upgrades/airtime-2.4.0/data/upgrade.sql | 5 +++++ python_apps/api_clients/api_client.py | 2 +- 6 files changed, 12 insertions(+), 3 deletions(-) create mode 100644 install_minimal/upgrades/airtime-2.4.0/airtime-upgrade.php create mode 100644 install_minimal/upgrades/airtime-2.4.0/data/upgrade.sql diff --git a/airtime_mvc/build/sql/defaultdata.sql b/airtime_mvc/build/sql/defaultdata.sql index 0af91c7fd..ff4fe2d6b 100644 --- a/airtime_mvc/build/sql/defaultdata.sql +++ b/airtime_mvc/build/sql/defaultdata.sql @@ -11,7 +11,7 @@ INSERT INTO cc_live_log("state", "start_time") VALUES('S', now() at time zone 'U -- end of added in 2.1 -- added in 2.0.0 -INSERT INTO cc_pref("keystr", "valstr") VALUES('stream_type', 'ogg, mp3'); +INSERT INTO cc_pref("keystr", "valstr") VALUES('stream_type', 'ogg, mp3, opus'); INSERT INTO cc_pref("keystr", "valstr") VALUES('stream_bitrate', '24, 32, 48, 64, 96, 128, 160, 192, 224, 256, 320'); INSERT INTO cc_pref("keystr", "valstr") VALUES('num_of_streams', '3'); INSERT INTO cc_pref("keystr", "valstr") VALUES('max_bitrate', '320'); diff --git a/install_minimal/include/airtime-constants.php b/install_minimal/include/airtime-constants.php index 10c620da9..c3f6aaaaa 100644 --- a/install_minimal/include/airtime-constants.php +++ b/install_minimal/include/airtime-constants.php @@ -1,3 +1,3 @@ Date: Fri, 26 Apr 2013 13:48:15 -0400 Subject: [PATCH 60/73] cleanup of unecessary code -we shouldn't be loading config file multiple times. --- python_apps/pypo/pypocli.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python_apps/pypo/pypocli.py b/python_apps/pypo/pypocli.py index b0cdd1b59..88ed2d023 100644 --- a/python_apps/pypo/pypocli.py +++ b/python_apps/pypo/pypocli.py @@ -245,7 +245,7 @@ if __name__ == '__main__': pf.daemon = True pf.start() - pp = PypoPush(pypoPush_q, telnet_lock, pypo_liquidsoap) + pp = PypoPush(pypoPush_q, telnet_lock, pypo_liquidsoap, config) pp.daemon = True pp.start() From 49d1755b52623e900d5b5ce2494f0aa5ef5959c4 Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Fri, 26 Apr 2013 13:58:44 -0400 Subject: [PATCH 61/73] fix incorrect merge --- python_apps/pypo/pypopush.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/python_apps/pypo/pypopush.py b/python_apps/pypo/pypopush.py index be2ff523a..d032ac3c6 100644 --- a/python_apps/pypo/pypopush.py +++ b/python_apps/pypo/pypopush.py @@ -57,8 +57,7 @@ class PypoPush(Thread): self.queue_id = 0 self.future_scheduled_queue = Queue() - self.pypo_liquidsoap = PypoLiquidsoap(self.logger, telnet_lock,\ - config['ls_host'], config['ls_port']) + self.pypo_liquidsoap = pypo_liquidsoap self.plq = PypoLiqQueue(self.future_scheduled_queue, \ self.pypo_liquidsoap, \ From 21bed916787c4450cbffb1823b67a4ae525f4513 Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Fri, 26 Apr 2013 15:56:48 -0400 Subject: [PATCH 62/73] add brackets to force operator precedence --- python_apps/pypo/telnetliquidsoap.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python_apps/pypo/telnetliquidsoap.py b/python_apps/pypo/telnetliquidsoap.py index f9d63bec6..7ce2fceb3 100644 --- a/python_apps/pypo/telnetliquidsoap.py +++ b/python_apps/pypo/telnetliquidsoap.py @@ -2,9 +2,9 @@ import telnetlib def create_liquidsoap_annotation(media): # We need liq_start_next value in the annotate. That is the value that controls overlap duration of crossfade. - return 'annotate:media_id="%s",liq_start_next="0",liq_fade_in="%s",' + \ + return ('annotate:media_id="%s",liq_start_next="0",liq_fade_in="%s",' + \ 'liq_fade_out="%s",liq_cue_in="%s",liq_cue_out="%s",' + \ - 'schedule_table_id="%s",replay_gain="%s dB":%s' % \ + 'schedule_table_id="%s",replay_gain="%s dB":%s') % \ (media['id'], float(media['fade_in']) / 1000, float(media['fade_out']) / 1000, From a5264aac1e80686fa39a995e3170a437cc74cd02 Mon Sep 17 00:00:00 2001 From: denise Date: Fri, 26 Apr 2013 16:10:01 -0400 Subject: [PATCH 63/73] CC-4961: Show linking --- airtime_mvc/application/models/Scheduler.php | 22 +++++++++++++------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/airtime_mvc/application/models/Scheduler.php b/airtime_mvc/application/models/Scheduler.php index 9e2c432ae..dd05c19c7 100644 --- a/airtime_mvc/application/models/Scheduler.php +++ b/airtime_mvc/application/models/Scheduler.php @@ -45,20 +45,25 @@ class Application_Model_Scheduler $this->checkUserPermissions = $value; } - private function validateItemMove($itemsToMove, $afterItem) + private function validateItemMove($itemsToMove, $destination) { - $afterInstanceId = $afterItem["instance"]; + $destinationInstanceId = $destination["instance"]; + $destinationCcShowInstance = CcShowInstancesQuery::create() + ->findPk($destinationInstanceId); + $isDestinationLinked = $destinationCcShowInstance->getCcShow()->isLinked(); foreach ($itemsToMove as $itemToMove) { $ccShowInstance = CcShowInstancesQuery::create() ->findPk($itemToMove["instance"]); //does the item being moved belong to a linked show - $linked = $ccShowInstance->getCcShow()->isLinked(); + $isSourceLinked = $ccShowInstance->getCcShow()->isLinked(); - if ($linked && $itemToMove["instance"] != $afterInstanceId) { + if ($isSourceLinked && $itemToMove["instance"] != $destinationInstanceId) { throw new Exception(_("Linked items can only be moved within its own show")); - } + } /*elseif ($isDestinationLinked && $isSourceLinked) { + throw new Exception(_("Items can only be moved to and from unlinked shows")); + }*/ } } @@ -555,11 +560,12 @@ class Application_Model_Scheduler //need to keep same id for resources if we want REST. if (isset($file['sched_id'])) { - $sched = CcScheduleQuery::create() + /*$sched = CcScheduleQuery::create() ->filterByDbInstanceId($instance->getDbId()) ->filterByDbFileId($file["id"]) - ->findOne(); - + ->findOne();*/ + $sched = CcScheduleQuery::create()->findPk($file["sched_id"]); + $excludeIds[] = intval($sched->getDbId()); $file["cliplength"] = $sched->getDbClipLength(); From 3a931f27bfb3f65702b537d520713b136824b400 Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Fri, 26 Apr 2013 17:54:29 -0400 Subject: [PATCH 64/73] CC-4417: Opus codec support --- .../controllers/PreferenceController.php | 17 +++++++++++++---- airtime_mvc/build/sql/defaultdata.sql | 2 +- .../upgrades/airtime-2.4.0/data/upgrade.sql | 2 +- 3 files changed, 15 insertions(+), 6 deletions(-) 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/build/sql/defaultdata.sql b/airtime_mvc/build/sql/defaultdata.sql index ff4fe2d6b..ce1620f46 100644 --- a/airtime_mvc/build/sql/defaultdata.sql +++ b/airtime_mvc/build/sql/defaultdata.sql @@ -11,7 +11,7 @@ INSERT INTO cc_live_log("state", "start_time") VALUES('S', now() at time zone 'U -- end of added in 2.1 -- added in 2.0.0 -INSERT INTO cc_pref("keystr", "valstr") VALUES('stream_type', 'ogg, mp3, opus'); +INSERT INTO cc_pref("keystr", "valstr") VALUES('stream_type', 'ogg, mp3, opus, aac'); INSERT INTO cc_pref("keystr", "valstr") VALUES('stream_bitrate', '24, 32, 48, 64, 96, 128, 160, 192, 224, 256, 320'); INSERT INTO cc_pref("keystr", "valstr") VALUES('num_of_streams', '3'); INSERT INTO cc_pref("keystr", "valstr") VALUES('max_bitrate', '320'); diff --git a/install_minimal/upgrades/airtime-2.4.0/data/upgrade.sql b/install_minimal/upgrades/airtime-2.4.0/data/upgrade.sql index aad478aa0..4b091c618 100644 --- a/install_minimal/upgrades/airtime-2.4.0/data/upgrade.sql +++ b/install_minimal/upgrades/airtime-2.4.0/data/upgrade.sql @@ -2,4 +2,4 @@ DELETE FROM cc_pref WHERE keystr = 'system_version'; INSERT INTO cc_pref (keystr, valstr) VALUES ('system_version', '2.4.0'); DELETE FROM cc_pref WHERE keystr = 'stream_type'; -INSERT INTO cc_pref (keystr, valstr) VALUES ('stream_type', 'ogg, mp3, opus'); +INSERT INTO cc_pref (keystr, valstr) VALUES ('stream_type', 'ogg, mp3, opus, aac'); From 21b84c153a7da3fcf9962ca23ddb65ab0f864187 Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Fri, 26 Apr 2013 17:54:52 -0400 Subject: [PATCH 65/73] better logging for return values --- python_apps/api_clients/api_client.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/python_apps/api_clients/api_client.py b/python_apps/api_clients/api_client.py index 89167acdc..a7d88fdb9 100644 --- a/python_apps/api_clients/api_client.py +++ b/python_apps/api_clients/api_client.py @@ -140,7 +140,9 @@ class ApiRequest(object): # Ghetto hack for now because we don't the content type we are getting # (Pointless to look at mime since it's not being set correctly always) try: - return json.loads(response) + data = json.loads(response) + self.logger.debug(data) + return data except Exception: self.logger.error(response) raise From acfc72f422f1379efa8eb7893d71f09d226e5bdb Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Fri, 26 Apr 2013 18:06:07 -0400 Subject: [PATCH 66/73] use sendJson, instead of manually disabling layouts + encoding data --- .../application/controllers/ApiController.php | 68 +++---------------- 1 file changed, 11 insertions(+), 57 deletions(-) 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); } } - } From 623a67d6aa77d592720382c4b7c2930abd2c0375 Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Fri, 26 Apr 2013 18:27:40 -0400 Subject: [PATCH 67/73] CC-5072: Ensure all api requests are returning valid JSON -fixed --- python_apps/api_clients/api_client.py | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/python_apps/api_clients/api_client.py b/python_apps/api_clients/api_client.py index a7d88fdb9..cdedab130 100644 --- a/python_apps/api_clients/api_client.py +++ b/python_apps/api_clients/api_client.py @@ -127,24 +127,31 @@ class ApiRequest(object): self.__req = None if logger is None: self.logger = logging else: self.logger = logger + def __call__(self,_post_data=None, **kwargs): final_url = self.url.params(**kwargs).url() if _post_data is not None: _post_data = urllib.urlencode(_post_data) + self.logger.debug(final_url) try: req = urllib2.Request(final_url, _post_data) - response = urllib2.urlopen(req).read() + f = urllib2.urlopen(req) + content_type = f.info().getheader('Content-Type') + response = f.read() except Exception, e: self.logger.error('Exception: %s', e) self.logger.error("traceback: %s", traceback.format_exc()) raise - # Ghetto hack for now because we don't the content type we are getting - # (Pointless to look at mime since it's not being set correctly always) + try: - data = json.loads(response) - self.logger.debug(data) - return data + if content_type == 'application/json': + data = json.loads(response) + self.logger.debug(data) + return data + else: + raise InvalidContentType() except Exception: self.logger.error(response) + self.logger.error("traceback: %s", traceback.format_exc()) raise def req(self, *args, **kwargs): @@ -510,3 +517,7 @@ class AirtimeApiClient(object): except Exception, e: #TODO self.logger.error(str(e)) + + +class InvalidContentType(Exception): + pass From 2552a5224864f23181d646a01be96d77bcf334b7 Mon Sep 17 00:00:00 2001 From: "cliff.wang" Date: Mon, 29 Apr 2013 11:46:38 -0400 Subject: [PATCH 68/73] Scripts: to compile liquidsoap with chroot env. --- .../liquidsoap_compile/liquidsoap_compile.sh | 71 ++++++++ dev_tools/liquidsoap_compile/run.sh | 170 ++++++++++++++++++ 2 files changed, 241 insertions(+) create mode 100755 dev_tools/liquidsoap_compile/liquidsoap_compile.sh create mode 100755 dev_tools/liquidsoap_compile/run.sh diff --git a/dev_tools/liquidsoap_compile/liquidsoap_compile.sh b/dev_tools/liquidsoap_compile/liquidsoap_compile.sh new file mode 100755 index 000000000..58dad41d4 --- /dev/null +++ b/dev_tools/liquidsoap_compile/liquidsoap_compile.sh @@ -0,0 +1,71 @@ +#!/bin/bash -e +apt-get install -y --force-yes lsb-release sudo +dist=`lsb_release -is` +code=`lsb_release -cs` +cpu=`getconf LONG_BIT` +cpuvalue= + +if [ "$dist" = "Ubuntu" ]; then + set +e + grep -E "deb http://ca.archive.ubuntu.com/ubuntu/ $code multiverse" /etc/apt/sources.list + returncode=$? + set -e + if [ "$returncode" -ne "0" ]; then + echo "deb http://ca.archive.ubuntu.com/ubuntu/ $code multiverse" >> /etc/apt/sources.list + echo "deb http://ca.archive.ubuntu.com/ubuntu/ $code universe" >> /etc/apt/sources.list + fi +fi + +#enable squeeze backports to get lame packages +if [ "$dist" = "Debian" -a "$code" = "squeeze" ]; then + set +e + grep -E "deb http://backports.debian.org/debian-backports squeeze-backports main" /etc/apt/sources.list + returncode=$? + set -e + if [ "$returncode" -ne "0" ]; then + echo "deb http://backports.debian.org/debian-backports squeeze-backports main" >> /etc/apt/sources.list + fi +fi + +echo "System is $cpu bit..." +if [ "$cpu" = "64" ]; then + cpuvalue="amd64" +else + cpuvalue="i386" +fi + +apt-get update +apt-get -o Dpkg::Options::="--force-confold" upgrade +apt-get install wget +wget http://apt.sourcefabric.org/misc/libopus_1.0.1/libopus-dbg_1.0.1~$code~sfo-1_$cpuvalue.deb +wget http://apt.sourcefabric.org/misc/libopus_1.0.1/libopus-dev_1.0.1~$code~sfo-1_$cpuvalue.deb +wget http://apt.sourcefabric.org/misc/libopus_1.0.1/libopus0_1.0.1~$code~sfo-1_$cpuvalue.deb + +apt-get -y --force-yes install git-core ocaml-findlib libao-ocaml-dev \ +libportaudio-ocaml-dev libmad-ocaml-dev libtaglib-ocaml-dev libalsa-ocaml-dev \ +libvorbis-ocaml-dev libladspa-ocaml-dev libxmlplaylist-ocaml-dev libflac-dev \ +libxml-dom-perl libxml-dom-xpath-perl patch autoconf libmp3lame-dev \ +libcamomile-ocaml-dev libcamlimages-ocaml-dev libtool libpulse-dev camlidl \ +libfaad-dev libpcre-ocaml-dev + +dpkg -i libopus-dbg_1.0.1~$code~sfo-1_$cpuvalue.deb libopus-dev_1.0.1~$code~sfo-1_$cpuvalue.deb libopus0_1.0.1~$code~sfo-1_$cpuvalue.deb +rm -rf liquidsoap-full +git clone https://github.com/savonet/liquidsoap-full +chmod -R 777 liquidsoap-full +cd liquidsoap-full +sudo -u tmp make init +sudo -u tmp make update + +sudo -u tmp cp PACKAGES.minimal PACKAGES + +sed -i "s/#ocaml-portaudio/ocaml-portaudio/g" PACKAGES +sed -i "s/#ocaml-alsa/ocaml-alsa/g" PACKAGES +sed -i "s/#ocaml-pulseaudio/ocaml-pulseaudio/g" PACKAGES +sed -i "s/#ocaml-faad/ocaml-faad/g" PACKAGES +sed -i "s/#ocaml-opus/ocaml-opus/g" PACKAGES +#sed -i "s/#ocaml-shine/ocaml-shine/g" PACKAGES + +sudo -u tmp ./bootstrap +sudo -u tmp ./configure +sudo -u tmp make +cp /liquidsoap-full/liquidsoap/src/liquidsoap / diff --git a/dev_tools/liquidsoap_compile/run.sh b/dev_tools/liquidsoap_compile/run.sh new file mode 100755 index 000000000..89dbef1cb --- /dev/null +++ b/dev_tools/liquidsoap_compile/run.sh @@ -0,0 +1,170 @@ +#!/bin/bash + +exec 2>&1 + +ROOT_UID="0" + +#Check if run as root +if [ "$UID" -ne "$ROOT_UID" ] ; then + echo "You must have 'sudo' right to do that!" + exit 1 +fi + +rm -rf ./liquidsoap_compile_logs +mkdir -p ./liquidsoap_compile_logs + +showhelp () { + echo "Usage: run.sh [options] [parameters] +-c all|ubuntu_lucid_32 Compile liquidsoap on all platforms or specified platform. +-b all|ubuntu_lucid_32 Build shroot environments for all platforms or specified platform. +-u username Local username will be used as sudo user of chroot env. Must be assigned before -b options" + exit 0 +} + +build_env () { + if [ $sudo_user = "-1" ];then + echo "Please use -u to assign sudo username before build environments." + exit 1 + fi + + echo "build_env $1" + #exec > >(tee ./liquidsoap_compile_logs/build_env_$1.log) + os=`echo $1 | awk '/(debian)/'` + cpu=`echo $1 | awk '/(64)/'` + dist=`echo $1 | awk -F "_" '{print $2}'` + + rm -f /etc/schroot/chroot.d/$1.conf + if cat /etc/passwd | awk -F:'{print $1}' | grep "tmp" >/dev/null 2>&1;then + echo "User tmp exists." + else + useradd tmp + echo "User tmp is created." + fi + + apt-get update + apt-get --force-yes -y install debootstrap dchroot + echo [$1] > /etc/schroot/chroot.d/$1.conf + echo description=$1 >> /etc/schroot/chroot.d/$1.conf + echo directory=/srv/chroot/$1 >> /etc/schroot/chroot.d/$1.conf + echo type=directory >> /etc/schroot/chroot.d/$1.conf + echo users=$sudo_user,tmp >> /etc/schroot/chroot.d/$1.conf + echo root-users=$sudo_user >> /etc/schroot/chroot.d/$1.conf + rm -rf /srv/chroot/$1 + mkdir -p /srv/chroot/$1 + + #cp liquidsoap_compile.sh /srv/chroot/$1/ + if [ "$os" = "" ];then + if [ "$cpu" = "" ];then + echo "debootstrap --variant=buildd --arch=i386 $dist /srv/chroot/$1 http://archive.ubuntu.com/ubuntu/" + debootstrap --variant=buildd --arch=i386 $dist /srv/chroot/$1 http://archive.ubuntu.com/ubuntu/ + else + echo "debootstrap --variant=buildd --arch=amd64 $dist /srv/chroot/$1 http://archive.ubuntu.com/ubuntu/" + debootstrap --variant=buildd --arch=amd64 $dist /srv/chroot/$1 http://archive.ubuntu.com/ubuntu/ + fi + else + if [ "$cpu" = "" ];then + echo "debootstrap --variant=buildd --arch=i386 $dist /srv/chroot/$1 http://ftp.debian.com/debian/" + debootstrap --variant=buildd --arch=i386 $dist /srv/chroot/$1 http://ftp.debian.com/debian/ + else + echo "debootstrap --variant=buildd --arch=amd64 $dist /srv/chroot/$1 http://ftp.debian.com/debian/" + debootstrap --variant=buildd --arch=amd64 $dist /srv/chroot/$1 http://ftp.debian.com/debian/ + fi + fi + +} + +compile_liq () { + echo "complie_liq $1" + #exec > >(tee ./liquidsoap_compile_logs/compile_liq_$1.log) + binfilename=`echo $1 | sed -e 's/ubuntu/liquidsoap/g' -e 's/debian/liquidsoap/g' -e 's/32/i386/g' -e 's/64/amd64/g'` + rm -f /srv/chroot/$1/liquidsoap_compile.sh + rm -f /srv/chroot/$1/liquidsoap + cp liquidsoap_compile.sh /srv/chroot/$1/ + schroot -c $1 -u root -d / -- /liquidsoap_compile.sh + cp /srv/chroot/$1/liquidsoap ./$binfilename + if [ $? -ne 0 ];then + echo "$binfilename is generated successfully" + else + mv ./liquidsoap_compile_logs/compile_liq_$1.log ./liquidsoap_compile_logs/fail_to_compile_liq_$1.log + fi +} + +os_versions=("ubuntu_lucid_32" "ubuntu_lucid_64" "ubuntu_oneiric_32" "ubuntu_oneiric_64" "ubuntu_precise_32" "ubuntu_precise_64" "ubuntu_quantal_32" "ubuntu_quantal_64" "debian_squeeze_32" "debian_squeeze_64" "debian_wheezy_32" "debian_wheezy_64") + +num=${#os_versions[@]} +flag= +os= +sudo_user="-1" + +if [ x$1 = x ];then + showhelp +fi + +while getopts b:c:u: arg +do + case $arg in + b) + if [ "$OPTARG" = "all" ];then + echo "Building all platforms on server..." + for i in $(seq 0 $(($num -1))) + do + build_env ${os_versions[$i]} | tee ./liquidsoap_compile_logs/build_env_${os_versions[$i]}.log + done + else + flag=1 + for i in $(seq 0 $(($num -1))); + do + if [ "$OPTARG" = ${os_versions[$i]} ];then + echo "Building platform: $OPTARG ..." + build_env ${os_versions[$i]} | tee ./liquidsoap_compile_logs/build_env_${os_versions[$i]}.log + flag=0 + fi + done + if [ $flag = 1 ];then + echo "Unsupported Platform from:" + for j in "${os_versions[@]}" + do + echo $j + done + exit 1 + fi + fi + ;; + c) + if [ "$OPTARG" = "all" ];then + echo "Compiling liquidsoap for all platforms on server..." + for i in $(seq 0 $(($num -1))) + do + compile_liq ${os_versions[$i]} | tee ./liquidsoap_compile_logs/compile_liq_${os_versions[$i]}.log + done + + else + flag=1 + for i in $(seq 0 $(($num -1))); + do + if [ "$OPTARG" = ${os_versions[$i]} ];then + echo "Compiling liquidsoap for platform: $OPTARG ..." + compile_liq ${os_versions[$i]} | tee ./liquidsoap_compile_logs/compile_liq_${os_versions[$i]}.log + flag=0 + fi + done + if [ $flag = 1 ];then + echo "Unsupported Platform from:" + for k in "${os_versions[@]}" + do + echo $k + done + exit 1 + fi + fi + ;; + u) + sudo_user="$OPTARG" + echo "sudo_user is set as $sudo_user." + ;; + ?) + showhelp + ;; + esac +done + From de8f7b0ff7952cc5538c39648d21466e2eea8417 Mon Sep 17 00:00:00 2001 From: denise Date: Mon, 29 Apr 2013 15:27:14 -0400 Subject: [PATCH 69/73] CC-4961: Show linking --- .../controllers/_old_ScheduleController.php | 1002 -------- airtime_mvc/application/models/Scheduler.php | 50 +- airtime_mvc/application/models/Show.php | 1 - .../application/models/_old_Schedule.php | 1329 ---------- airtime_mvc/application/models/_old_Show.php | 2241 ----------------- .../application/models/airtime/CcShow.php | 1 + .../application/services/ShowService.php | 3 + 7 files changed, 24 insertions(+), 4603 deletions(-) delete mode 100644 airtime_mvc/application/controllers/_old_ScheduleController.php delete mode 100644 airtime_mvc/application/models/_old_Schedule.php delete mode 100644 airtime_mvc/application/models/_old_Show.php diff --git a/airtime_mvc/application/controllers/_old_ScheduleController.php b/airtime_mvc/application/controllers/_old_ScheduleController.php deleted file mode 100644 index 08fde37dc..000000000 --- a/airtime_mvc/application/controllers/_old_ScheduleController.php +++ /dev/null @@ -1,1002 +0,0 @@ -_helper->getHelper('AjaxContext'); - $ajaxContext->addActionContext('event-feed', 'json') - ->addActionContext('event-feed-preload', 'json') - ->addActionContext('make-context-menu', 'json') - ->addActionContext('add-show-dialog', 'json') - ->addActionContext('add-show', 'json') - ->addActionContext('edit-show', 'json') - ->addActionContext('move-show', 'json') - ->addActionContext('resize-show', 'json') - ->addActionContext('delete-show', '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('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('dj-edit-show', 'json') - ->addActionContext('calculate-duration', 'json') - ->addActionContext('get-current-show', 'json') - ->addActionContext('update-future-is-scheduled', 'json') - ->initContext(); - - $this->sched_sess = new Zend_Session_Namespace("schedule"); - } - - public function indexAction() - { - $CC_CONFIG = Config::getConfig(); - - $baseUrl = Application_Common_OsPath::getBaseDir(); - - $this->view->headScript()->appendFile($baseUrl.'js/contextmenu/jquery.contextMenu.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); - - //full-calendar-functions.js requires this variable, so that datePicker widget can be offset to server time instead of client time - $this->view->headScript()->appendScript("var timezoneOffset = ".date("Z")."; //in seconds"); - $this->view->headScript()->appendFile($baseUrl.'js/airtime/schedule/full-calendar-functions.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); - - $this->view->headScript()->appendFile($baseUrl.'js/fullcalendar/fullcalendar.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); - $this->view->headScript()->appendFile($baseUrl.'js/timepicker/jquery.ui.timepicker.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); - $this->view->headScript()->appendFile($baseUrl.'js/colorpicker/js/colorpicker.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); - - $this->view->headScript()->appendFile($baseUrl.'js/airtime/schedule/add-show.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); - $this->view->headScript()->appendFile($baseUrl.'js/airtime/schedule/schedule.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); - $this->view->headScript()->appendFile($baseUrl.'js/blockui/jquery.blockUI.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); - - $this->view->headLink()->appendStylesheet($baseUrl.'css/jquery.ui.timepicker.css?'.$CC_CONFIG['airtime_version']); - $this->view->headLink()->appendStylesheet($baseUrl.'css/fullcalendar.css?'.$CC_CONFIG['airtime_version']); - $this->view->headLink()->appendStylesheet($baseUrl.'css/colorpicker/css/colorpicker.css?'.$CC_CONFIG['airtime_version']); - $this->view->headLink()->appendStylesheet($baseUrl.'css/add-show.css?'.$CC_CONFIG['airtime_version']); - $this->view->headLink()->appendStylesheet($baseUrl.'css/jquery.contextMenu.css?'.$CC_CONFIG['airtime_version']); - - //Start Show builder JS/CSS requirements - $this->view->headScript()->appendFile($baseUrl.'js/contextmenu/jquery.contextMenu.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); - $this->view->headScript()->appendFile($baseUrl.'js/datatables/js/jquery.dataTables.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); - $this->view->headScript()->appendFile($baseUrl.'js/datatables/plugin/dataTables.pluginAPI.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); - $this->view->headScript()->appendFile($baseUrl.'js/datatables/plugin/dataTables.fnSetFilteringDelay.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); - $this->view->headScript()->appendFile($baseUrl.'js/datatables/plugin/dataTables.ColVis.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); - $this->view->headScript()->appendFile($baseUrl.'js/datatables/plugin/dataTables.ColReorder.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); - $this->view->headScript()->appendFile($baseUrl.'js/datatables/plugin/dataTables.FixedColumns.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); - $this->view->headScript()->appendFile($baseUrl.'js/datatables/plugin/dataTables.TableTools.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); - $this->view->headScript()->appendFile($baseUrl.'js/datatables/plugin/dataTables.columnFilter.js?'.$CC_CONFIG['airtime_version'], 'text/javascript'); - - $this->view->headScript()->appendFile($baseUrl.'js/airtime/buttons/buttons.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); - $this->view->headScript()->appendFile($baseUrl.'js/airtime/library/events/library_showbuilder.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); - $this->view->headScript()->appendFile($baseUrl.'js/airtime/library/library.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); - $this->view->headScript()->appendFile($baseUrl.'js/airtime/showbuilder/builder.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); - - $this->view->headLink()->appendStylesheet($baseUrl.'css/media_library.css?'.$CC_CONFIG['airtime_version']); - $this->view->headLink()->appendStylesheet($baseUrl.'css/jquery.contextMenu.css?'.$CC_CONFIG['airtime_version']); - $this->view->headLink()->appendStylesheet($baseUrl.'css/datatables/css/ColVis.css?'.$CC_CONFIG['airtime_version']); - $this->view->headLink()->appendStylesheet($baseUrl.'css/datatables/css/ColReorder.css?'.$CC_CONFIG['airtime_version']); - $this->view->headLink()->appendStylesheet($baseUrl.'css/TableTools.css?'.$CC_CONFIG['airtime_version']); - $this->view->headLink()->appendStylesheet($baseUrl.'css/showbuilder.css?'.$CC_CONFIG['airtime_version']); - //End Show builder JS/CSS requirements - - - 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->headScript()->appendScript( - "var calendarPref = {};\n". - "calendarPref.weekStart = ".Application_Model_Preference::GetWeekStartDay().";\n". - "calendarPref.timestamp = ".time().";\n". - "calendarPref.timezoneOffset = ".date("Z").";\n". - "calendarPref.timeScale = '".Application_Model_Preference::GetCalendarTimeScale()."';\n". - "calendarPref.timeInterval = ".Application_Model_Preference::GetCalendarTimeInterval().";\n". - "calendarPref.weekStartDay = ".Application_Model_Preference::GetWeekStartDay().";\n". - "var calendarEvents = null;" - ); - } - - public function eventFeedAction() - { - $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, $editable); - $this->view->events = $events; - } - - public function eventFeedPreloadAction() - { - $userInfo = Zend_Auth::getInstance()->getStorage()->read(); - $user = new Application_Model_User($userInfo->id); - $editable = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER)); - - $calendar_interval = Application_Model_Preference::GetCalendarTimeScale(); - Logging::info($calendar_interval); - if ($calendar_interval == "agendaDay") { - list($start, $end) = Application_Model_Show::getStartEndCurrentDayView(); - } else if ($calendar_interval == "agendaWeek") { - list($start, $end) = Application_Model_Show::getStartEndCurrentWeekView(); - } else if ($calendar_interval == "month") { - list($start, $end) = Application_Model_Show::getStartEndCurrentMonthView(); - } else { - Logging::error("Invalid Calendar Interval '$calendar_interval'"); - } - - $events = &Application_Model_Show::getFullCalendarEvents($start, $end, $editable); - $this->view->events = $events; - } - - public function getCurrentShowAction() - { - $currentShow = Application_Model_Show::getCurrentShow(); - if (!empty($currentShow)) { - $this->view->si_id = $currentShow[0]["instance_id"]; - $this->view->current_show = true; - } else { - $this->view->current_show = false; - } - } - - public function moveShowAction() - { - $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); - } - - if (isset($error)) { - $this->view->error = $error; - } - } - - public function resizeShowAction() - { - $deltaDay = $this->_getParam('day'); - $deltaMin = $this->_getParam('min'); - $showId = $this->_getParam('showId'); - - $userInfo = Zend_Auth::getInstance()->getStorage()->read(); - $user = new Application_Model_User($userInfo->id); - - if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) { - try { - $show = new Application_Model_Show($showId); - } catch (Exception $e) { - $this->view->show_error = true; - - return false; - } - $error = $show->resizeShow($deltaDay, $deltaMin); - } - - if (isset($error)) { - $this->view->error = $error; - } - } - - public function deleteShowAction() - { - $showInstanceId = $this->_getParam('id'); - - $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) { - Logging::info($e->getMessage()); - $this->view->show_error = true; - - return false; - } - - $showInstance->delete(); - - $this->view->show_id = $showInstance->getShowId(); - } - } - - public function uploadToSoundCloudAction() - { - $show_instance = $this->_getParam('id'); - try { - $show_inst = new Application_Model_ShowInstance($show_instance); - } catch (Exception $e) { - $this->view->show_error = true; - - return false; - } - - $file = $show_inst->getRecordedFile(); - $id = $file->getId(); - Application_Model_Soundcloud::uploadSoundcloud($id); - // we should die with ui info - $this->_helper->json->sendJson(null); - } - - public function makeContextMenuAction() - { - $id = $this->_getParam('id'); - $menu = array(); - $epochNow = time(); - $baseUrl = Application_Common_OsPath::getBaseDir(); - - $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; - - 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; - } - - public function clearShowAction() - { - $showInstanceId = $this->_getParam('id'); - $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->clearShow(); - } - - public function getCurrentPlaylistAction() - { - $range = Application_Model_Schedule::GetPlayOrderRange(); - $show = Application_Model_Show::getCurrentShow(); - - /* Convert all UTC times to localtime before sending back to user. */ - if (isset($range["previous"])) { - $range["previous"]["starts"] = Application_Common_DateHelper::ConvertToLocalDateTimeString($range["previous"]["starts"]); - $range["previous"]["ends"] = Application_Common_DateHelper::ConvertToLocalDateTimeString($range["previous"]["ends"]); - } - if (isset($range["current"])) { - $range["current"]["starts"] = Application_Common_DateHelper::ConvertToLocalDateTimeString($range["current"]["starts"]); - $range["current"]["ends"] = Application_Common_DateHelper::ConvertToLocalDateTimeString($range["current"]["ends"]); - } - if (isset($range["next"])) { - $range["next"]["starts"] = Application_Common_DateHelper::ConvertToLocalDateTimeString($range["next"]["starts"]); - $range["next"]["ends"] = Application_Common_DateHelper::ConvertToLocalDateTimeString($range["next"]["ends"]); - } - - Application_Model_Show::convertToLocalTimeZone($range["currentShow"], array("starts", "ends", "start_timestamp", "end_timestamp")); - Application_Model_Show::convertToLocalTimeZone($range["nextShow"], array("starts", "ends", "start_timestamp", "end_timestamp")); - - $source_status = array(); - $switch_status = array(); - $live_dj = Application_Model_Preference::GetSourceStatus("live_dj"); - $master_dj = Application_Model_Preference::GetSourceStatus("master_dj"); - - $scheduled_play_switch = Application_Model_Preference::GetSourceSwitchStatus("scheduled_play"); - $live_dj_switch = Application_Model_Preference::GetSourceSwitchStatus("live_dj"); - $master_dj_switch = Application_Model_Preference::GetSourceSwitchStatus("master_dj"); - - //might not be the correct place to implement this but for now let's just do it here - $source_status['live_dj_source'] = $live_dj; - $source_status['master_dj_source'] = $master_dj; - $this->view->source_status = $source_status; - - $switch_status['live_dj_source'] = $live_dj_switch; - $switch_status['master_dj_source'] = $master_dj_switch; - $switch_status['scheduled_play'] = $scheduled_play_switch; - $this->view->switch_status = $switch_status; - - $this->view->entries = $range; - $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'); - try { - $show = new Application_Model_ShowInstance($showInstanceId); - } catch (Exception $e) { - $this->view->show_error = true; - - return false; - } - - $originalShowId = $show->isRebroadcast(); - if (!is_null($originalShowId)) { - try { - $originalShow = new Application_Model_ShowInstance($originalShowId); - } catch (Exception $e) { - $this->view->show_error = true; - - return false; - } - $originalShowName = $originalShow->getName(); - $originalShowStart = $originalShow->getShowInstanceStart(); - - //convert from UTC to user's timezone for display. - $originalDateTime = new DateTime($originalShowStart, new DateTimeZone("UTC")); - $originalDateTime->setTimezone(new DateTimeZone(date_default_timezone_get())); - //$timestamp = Application_Common_DateHelper::ConvertToLocalDateTimeString($originalDateTime->format("Y-m-d H:i:s")); - $this->view->additionalShowInfo = - sprintf(_("Rebroadcast of show %s from %s at %s"), - $originalShowName, - $originalDateTime->format("l, F jS"), - $originalDateTime->format("G:i")); - } - $this->view->showLength = $show->getShowLength(); - $this->view->timeFilled = $show->getTimeScheduled(); - $this->view->percentFilled = $show->getPercentScheduled(); - $this->view->showContent = $show->getShowListContent(); - $this->view->dialog = $this->view->render('schedule/show-content-dialog.phtml'); - $this->view->showTitle = htmlspecialchars($show->getName()); - 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(); - - $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; - - $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->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); - - $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; - } - - // 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) { - $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(); - - $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(); - } - - if (!$isAdminOrPM) { - $formWhat->disable(); - $formWho->disable(); - $formWhen->disable(); - $formRepeats->disable(); - $formStyle->disable(); - } - - $this->view->newForm = $this->view->render('schedule/add-show-form.phtml'); - $this->view->entries = 5; - } - - public function getFormAction() - { - $user = Application_Model_User::getCurrentUser(); - - if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) { - Application_Model_Schedule::createNewFormSections($this->view); - $this->view->form = $this->view->render('schedule/add-show-form.phtml'); - } - } - - public function djEditShowAction() - { - $js = $this->_getParam('data'); - $data = array(); - - //need to convert from serialized jQuery array. - foreach ($js as $j) { - $data[$j["name"]] = $j["value"]; - } - - //update cc_show - $show = new Application_Model_Show($data["add_show_id"]); - $show->setAirtimeAuthFlag($data["cb_airtime_auth"]); - $show->setCustomAuthFlag($data["cb_custom_auth"]); - $show->setCustomUsername($data["custom_username"]); - $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 - $js = $this->_getParam('data'); - $data = array(); - - //need to convert from serialized jQuery array. - foreach ($js as $j) { - $data[$j["name"]] = $j["value"]; - } - - $data['add_show_hosts'] = $this->_getParam('hosts'); - $data['add_show_day_check'] = $this->_getParam('days'); - - if ($data['add_show_day_check'] == "") { - $data['add_show_day_check'] = null; - } - - $show = new Application_Model_Show($data['add_show_id']); - - $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"); - - 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 ($show->isRepeating()) { - $nextFutureRepeatShow = $show->getNextFutureRepeatShowTime(); - $originalShowStartDateTime = $nextFutureRepeatShow["starts"]; - } else { - $originalShowStartDateTime = Application_Common_DateHelper::ConvertToLocalDateTime( - $show->getStartDateAndTime()); - } - - $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 { - 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 addShowAction() - { - $js = $this->_getParam('data'); - $data = array(); - - //need to convert from serialized jQuery array. - foreach ($js as $j) { - $data[$j["name"]] = $j["value"]; - } - - $data['add_show_hosts'] = $this->_getParam('hosts'); - $data['add_show_day_check'] = $this->_getParam('days'); - - if ($data['add_show_day_check'] == "") { - $data['add_show_day_check'] = null; - } - - $validateStartDate = true; - $success = Application_Model_Schedule::addUpdateShow($data, $this, - $validateStartDate); - - 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'); - Logging::debug("Show creation failed"); - } - } - - public function cancelShowAction() - { - $user = Application_Model_User::getCurrentUser(); - - if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) { - $showInstanceId = $this->_getParam('id'); - - 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(); - } - } - - public function cancelCurrentShowAction() - { - $user = Application_Model_User::getCurrentUser(); - - if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) { - $id = $this->_getParam('id'); - - try { - $scheduler = new Application_Model_Scheduler(); - $scheduler->cancelShow($id); - Application_Model_StoredFile::updatePastFilesIsScheduled(); - // send kick out source stream signal to pypo - $data = array("sourcename"=>"live_dj"); - Application_Model_RabbitMq::SendMessageToPypo("disconnect_source", $data); - } catch (Exception $e) { - $this->view->error = $e->getMessage(); - Logging::info($e->getMessage()); - } - } - } - - public function contentContextMenuAction() - { - $id = $this->_getParam('id'); - - $params = '/format/json/id/#id#/'; - - $paramsPop = str_replace('#id#', $id, $params); - - // added for downlaod - $id = $this->_getParam('id'); - - $file_id = $this->_getParam('id', null); - $file = Application_Model_StoredFile::Recall($file_id); - - $baseUrl = $this->getRequest()->getBaseUrl(); - $url = $file->getRelativeFileUrl($baseUrl).'download/true'; - $menu[] = array('action' => array('type' => 'gourl', 'url' => $url), - 'title' => _('Download')); - - //returns format jjmenu is looking for. - $this->_helper->json->sendJson($menu); - } - - /** - * Sets the user specific preference for which time scale to use in Calendar. - * This is only being used by schedule.js at the moment. - */ - public function setTimeScaleAction() - { - Application_Model_Preference::SetCalendarTimeScale($this->_getParam('timeScale')); - } - -/** - * Sets the user specific preference for which time interval to use in Calendar. - * This is only being used by schedule.js at the moment. - */ - public function setTimeIntervalAction() - { - Application_Model_Preference::SetCalendarTimeInterval($this->_getParam('timeInterval')); - } - - 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"; - } - - echo Zend_Json::encode($result); - exit(); - } - - public function updateFutureIsScheduledAction() - { - $schedId = $this->_getParam('schedId'); - $redrawLibTable = Application_Model_StoredFile::setIsScheduled($schedId, false); - $this->_helper->json->sendJson(array("redrawLibTable" => $redrawLibTable)); - } -} diff --git a/airtime_mvc/application/models/Scheduler.php b/airtime_mvc/application/models/Scheduler.php index dd05c19c7..a6aece8c8 100644 --- a/airtime_mvc/application/models/Scheduler.php +++ b/airtime_mvc/application/models/Scheduler.php @@ -53,17 +53,20 @@ class Application_Model_Scheduler $isDestinationLinked = $destinationCcShowInstance->getCcShow()->isLinked(); foreach ($itemsToMove as $itemToMove) { + $sourceInstanceId = $itemToMove["instance"]; $ccShowInstance = CcShowInstancesQuery::create() - ->findPk($itemToMove["instance"]); + ->findPk($sourceInstanceId); //does the item being moved belong to a linked show $isSourceLinked = $ccShowInstance->getCcShow()->isLinked(); - if ($isSourceLinked && $itemToMove["instance"] != $destinationInstanceId) { - throw new Exception(_("Linked items can only be moved within its own show")); - } /*elseif ($isDestinationLinked && $isSourceLinked) { - throw new Exception(_("Items can only be moved to and from unlinked shows")); - }*/ + 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")); + } } } @@ -496,7 +499,6 @@ class Application_Model_Scheduler */ $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 @@ -537,12 +539,6 @@ class Application_Model_Scheduler $pstart = microtime(true); $initalStartDT = clone $nextStartDT; - /*$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."); @@ -559,11 +555,6 @@ class Application_Model_Scheduler //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() - ->filterByDbInstanceId($instance->getDbId()) - ->filterByDbFileId($file["id"]) - ->findOne();*/ $sched = CcScheduleQuery::create()->findPk($file["sched_id"]); $excludeIds[] = intval($sched->getDbId()); @@ -590,8 +581,11 @@ class Application_Model_Scheduler ->setDbFadeIn($file['fadein']) ->setDbFadeOut($file['fadeout']) ->setDbClipLength($file['cliplength']) - ->setDbPosition($pos) - ->setDbInstanceId($instance->getDbId()); + ->setDbPosition($pos); + //->setDbInstanceId($instance->getDbId()); + if (!$moveAction) { + $sched->setDbInstanceId($instance->getDbId()); + } switch ($file["type"]) { case 0: @@ -640,7 +634,10 @@ class Application_Model_Scheduler $pstart = microtime(true); //recalculate the start/end times after the inserted items. + Logging::info($excludeIds); + Logging::info($initalStartDT); foreach ($followingSchedItems as $item) { + Logging::info($item); $endTimeDT = $this->findEndTime($nextStartDT, $item->getDbClipLength()); $item->setDbStarts($nextStartDT); @@ -674,13 +671,6 @@ class Application_Model_Scheduler $instance->updateScheduleStatus($this->con); } - // 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); - }*/ - $endProfile = microtime(true); Logging::debug("updating show instances status."); Logging::debug(floatval($endProfile) - floatval($startProfile)); @@ -849,7 +839,7 @@ class Application_Model_Scheduler } } - public function removeItems($scheduledItems, $adjustSched = true) + public function removeItems($scheduledItems, $adjustSched = true, $cancelShow=false) { $showInstances = array(); $this->con->beginTransaction(); @@ -872,7 +862,7 @@ class Application_Model_Scheduler //check if instance is linked and if so get the schedule items //for all linked instances so we can delete them too - if ($instance->getCcShow()->isLinked()) { + if (!$cancelShow && $instance->getCcShow()->isLinked()) { //returns all linked instances if linked $ccShowInstances = $this->getInstances($instance->getDbId()); $instanceIds = array(); @@ -998,7 +988,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 121e0a3e1..186603f97 100644 --- a/airtime_mvc/application/models/Show.php +++ b/airtime_mvc/application/models/Show.php @@ -1664,7 +1664,6 @@ 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/_old_Schedule.php b/airtime_mvc/application/models/_old_Schedule.php deleted file mode 100644 index 1aac2566e..000000000 --- a/airtime_mvc/application/models/_old_Schedule.php +++ /dev/null @@ -1,1329 +0,0 @@ - NOW() AT TIME ZONE 'UTC' -SQL; - $count = Application_Common_Database::prepareAndExecute( $sql, array( - ':file_id'=>$p_fileId), 'column'); - return (is_numeric($count) && ($count != '0')); - } - - public static function getAllFutureScheduledFiles() - { - $con = Propel::getConnection(); - $sql = << now() AT TIME ZONE 'UTC' -AND file_id is not null -SQL; - $files = $con->query($sql)->fetchAll(); - $real_files = array(); - foreach ($files as $f) { - $real_files[] = $f['file_id']; - } - - return $real_files; - } - - public static function getAllFutureScheduledWebstreams() - { - $con = Propel::getConnection(); - $sql = << now() AT TIME ZONE 'UTC' -AND stream_id is not null -SQL; - $streams = $con->query($sql)->fetchAll(); - $real_streams = array(); - foreach ($streams as $s) { - $real_streams[] = $s['stream_id']; - } - - return $real_streams; - } - /** - * Returns data related to the scheduled items. - * - * @param int $p_prev - * @param int $p_next - * @return date - */ - public static function GetPlayOrderRange($p_prev = 1, $p_next = 1) - { - if (!is_int($p_prev) || !is_int($p_next)) { - //must enter integers to specify ranges - Logging::info("Invalid range parameters: $p_prev or $p_next"); - - return array(); - } - - $date = new Application_Common_DateHelper; - $timeNow = $date->getTimestamp(); - $utcTimeNow = $date->getUtcTimestamp(); - - $shows = Application_Model_Show::getPrevCurrentNext($utcTimeNow); - $previousShowID = count($shows['previousShow'])>0?$shows['previousShow'][0]['instance_id']:null; - $currentShowID = count($shows['currentShow'])>0?$shows['currentShow'][0]['instance_id']:null; - $nextShowID = count($shows['nextShow'])>0?$shows['nextShow'][0]['instance_id']:null; - $results = self::GetPrevCurrentNext($previousShowID, $currentShowID, $nextShowID, $utcTimeNow); - - $range = array("env"=>APPLICATION_ENV, - "schedulerTime"=>$timeNow, - "previous"=>$results['previous'] !=null?$results['previous']:(count($shows['previousShow'])>0?$shows['previousShow'][0]:null), - "current"=>$results['current'] !=null?$results['current']:((count($shows['currentShow'])>0 && $shows['currentShow'][0]['record'] == 1)?$shows['currentShow'][0]:null), - "next"=> $results['next'] !=null?$results['next']:(count($shows['nextShow'])>0?$shows['nextShow'][0]:null), - "currentShow"=>$shows['currentShow'], - "nextShow"=>$shows['nextShow'], - "timezone"=> date("T"), - "timezoneOffset"=> date("Z") - ); - - return $range; - } - - /** - * Queries the database for the set of schedules one hour before - * and after the given time. If a show starts and ends within that - * time that is considered the current show. Then the scheduled item - * before it is the previous show, and the scheduled item after it - * is the next show. This way the dashboard getCurrentPlaylist is - * very fast. But if any one of the three show types are not found - * through this mechanism a call is made to the old way of querying - * the database to find the track info. - **/ - public static function GetPrevCurrentNext($p_previousShowID, $p_currentShowID, $p_nextShowID, $p_timeNow) - { - if ($p_previousShowID == null && $p_currentShowID == null && $p_nextShowID == null) { - return; - } - - $sql = "SELECT %%columns%% st.starts as starts, st.ends as ends, - st.media_item_played as media_item_played, si.ends as show_ends - %%tables%% WHERE "; - - $fileColumns = "ft.artist_name, ft.track_title, "; - $fileJoin = "FROM cc_schedule st JOIN cc_files ft ON st.file_id = ft.id - LEFT JOIN cc_show_instances si ON st.instance_id = si.id"; - - $streamColumns = "ws.name AS artist_name, wm.liquidsoap_data AS track_title, "; - $streamJoin = << $rows[$i]["show_ends"]) { - $rows[$i]['ends'] = $rows[$i]["show_ends"]; - } - - if ((strtotime($rows[$i]['starts']) <= $timeNowAsMillis) && (strtotime($rows[$i]['ends']) >= $timeNowAsMillis)) { - if ($i - 1 >= 0) { - $results['previous'] = array("name"=>$rows[$i-1]["artist_name"]." - ".$rows[$i-1]["track_title"], - "starts"=>$rows[$i-1]["starts"], - "ends"=>$rows[$i-1]["ends"], - "type"=>'track'); - } - $results['current'] = array("name"=>$rows[$i]["artist_name"]." - ".$rows[$i]["track_title"], - "starts"=>$rows[$i]["starts"], - "ends"=> (($rows[$i]["ends"] > $rows[$i]["show_ends"]) ? $rows[$i]["show_ends"]: $rows[$i]["ends"]), - "media_item_played"=>$rows[$i]["media_item_played"], - "record"=>0, - "type"=>'track'); - if (isset($rows[$i+1])) { - $results['next'] = array("name"=>$rows[$i+1]["artist_name"]." - ".$rows[$i+1]["track_title"], - "starts"=>$rows[$i+1]["starts"], - "ends"=>$rows[$i+1]["ends"], - "type"=>'track'); - } - break; - } - if (strtotime($rows[$i]['ends']) < $timeNowAsMillis ) { - $previousIndex = $i; - } - if (strtotime($rows[$i]['starts']) > $timeNowAsMillis) { - $results['next'] = array("name"=>$rows[$i]["artist_name"]." - ".$rows[$i]["track_title"], - "starts"=>$rows[$i]["starts"], - "ends"=>$rows[$i]["ends"], - "type"=>'track'); - break; - } - } - //If we didn't find a a current show because the time didn't fit we may still have - //found a previous show so use it. - if ($results['previous'] === null && isset($previousIndex)) { - $results['previous'] = array("name"=>$rows[$previousIndex]["artist_name"]." - ".$rows[$previousIndex]["track_title"], - "starts"=>$rows[$previousIndex]["starts"], - "ends"=>$rows[$previousIndex]["ends"]);; - } - - return $results; - } - - public static function GetLastScheduleItem($p_timeNow) - { - $sql = <<= sit.starts - AND st.starts < sit.ends -ORDER BY st.ends DESC LIMIT 1; -SQL; - $row = Application_Common_Database::prepareAndExecute($sql, array(':timeNow'=>$p_timeNow)); - - return $row; - } - - public static function GetCurrentScheduleItem($p_timeNow, $p_instanceId) - { - /* Note that usually there will be one result returned. In some - * rare cases two songs are returned. This happens when a track - * that was overbooked from a previous show appears as if it - * hasnt ended yet (track end time hasn't been reached yet). For - * this reason, we need to get the track that starts later, as - * this is the *real* track that is currently playing. So this - * is why we are ordering by track start time. */ - $sql = "SELECT *" - ." FROM cc_schedule st" - ." LEFT JOIN cc_files ft" - ." ON st.file_id = ft.id" - ." WHERE st.starts <= TIMESTAMP :timeNow1" - ." AND st.instance_id = :instanceId" - ." AND st.ends > TIMESTAMP :timeNow2" - ." ORDER BY st.starts DESC" - ." LIMIT 1"; - - $row = Application_Common_Database::prepareAndExecute($sql, array(':timeNow1'=>$p_timeNow, ':instanceId'=>$p_instanceId, ':timeNow2'=>$p_timeNow,)); - - return $row; - } - - public static function GetNextScheduleItem($p_timeNow) - { - $sql = "SELECT" - ." ft.artist_name, ft.track_title," - ." st.starts as starts, st.ends as ends" - ." FROM cc_schedule st" - ." LEFT JOIN cc_files ft" - ." ON st.file_id = ft.id" - ." LEFT JOIN cc_show_instances sit" - ." ON st.instance_id = sit.id" - ." WHERE st.starts > TIMESTAMP :timeNow" - ." AND st.starts >= sit.starts" //this and the next line are necessary since we can overbook shows. - ." AND st.starts < sit.ends" - ." ORDER BY st.starts" - ." LIMIT 1"; - - $row = Application_Common_Database::prepareAndExecute($sql, array(':timeNow'=>$p_timeNow)); - - return $row; - } - - /* - * - * @param DateTime $p_startDateTime - * - * @param DateTime $p_endDateTime - * - * @return array $scheduledItems - * - */ - public static function GetScheduleDetailItems($p_start, $p_end, $p_shows) - { - $con = Propel::getConnection(); - - $p_start_str = $p_start->format("Y-m-d H:i:s"); - $p_end_str = $p_end->format("Y-m-d H:i:s"); - - - //We need to search 24 hours before and after the show times so that that we - //capture all of the show's contents. - $p_track_start= $p_start->sub(new DateInterval("PT24H"))->format("Y-m-d H:i:s"); - $p_track_end = $p_end->add(new DateInterval("PT24H"))->format("Y-m-d H:i:s"); - - $templateSql = <<= '{$p_track_start}' - AND sched.starts < '{$p_track_end}') - OR (sched.ends > '{$p_track_start}' - AND sched.ends <= '{$p_track_end}') - OR (sched.starts <= '{$p_track_start}' - AND sched.ends >= '{$p_track_end}')) - ) -SQL; - - - $filesSql = str_replace("%%columns%%", - $filesColumns, - $templateSql); - $filesSql= str_replace("%%join%%", - $filesJoin, - $filesSql); - - $streamColumns = <<= '{$p_track_start}' - AND sched.starts < '{$p_track_end}') - OR (sched.ends > '{$p_track_start}' - AND sched.ends <= '{$p_track_end}') - OR (sched.starts <= '{$p_track_start}' - AND sched.ends >= '{$p_track_end}')) - ) - LEFT JOIN cc_subjs AS sub ON (ws.creator_id = sub.id) -SQL; - - $streamSql = str_replace("%%columns%%", - $streamColumns, - $templateSql); - $streamSql = str_replace("%%join%%", - $streamJoin, - $streamSql); - - - $showPredicate = ""; - if (count($p_shows) > 0) { - $showPredicate = " AND show_id IN (".implode(",", $p_shows).")"; - } - - $sql = <<= '{$p_start_str}' - AND si.starts < '{$p_end_str}') - OR (si.ends > '{$p_start_str}' - AND si.ends <= '{$p_end_str}') - OR (si.starts <= '{$p_start_str}' - AND si.ends >= '{$p_end_str}')) -ORDER BY si_starts, - sched_starts; -SQL; - - $rows = $con->query($sql)->fetchAll(PDO::FETCH_ASSOC); - - return $rows; - } - - public static function UpdateMediaPlayedStatus($p_id) - { - $con = Propel::getConnection(); - $sql = "UPDATE cc_schedule" - ." SET media_item_played=TRUE"; - // we need to update 'broadcasted' column as well - // check the current switch status - $live_dj = Application_Model_Preference::GetSourceSwitchStatus('live_dj') == 'on'; - $master_dj = Application_Model_Preference::GetSourceSwitchStatus('master_dj') == 'on'; - $scheduled_play = Application_Model_Preference::GetSourceSwitchStatus('scheduled_play') == 'on'; - - if (!$live_dj && !$master_dj && $scheduled_play) { - $sql .= ", broadcasted=1"; - } - - $sql .= " WHERE id=$p_id"; - - $retVal = $con->exec($sql); - - return $retVal; - } - - public static function UpdateBrodcastedStatus($dateTime, $value) - { - $now = $dateTime->format("Y-m-d H:i:s"); - - $sql = <<= :ends::TIMESTAMP -SQL; - - $retVal = Application_Common_Database::prepareAndExecute($sql, array( - ':broadcastedValue' => $value, - ':starts' => $now, - ':ends' => $now), 'execute'); - return $retVal; - } - - public static function getSchduledPlaylistCount() - { - $con = Propel::getConnection(); - $sql = "SELECT count(*) as cnt FROM cc_schedule"; - - return $con->query($sql)->fetchColumn(0); - } - - /** - * Convert a time string in the format "YYYY-MM-DD HH:mm:SS" - * to "YYYY-MM-DD-HH-mm-SS". - * - * @param string $p_time - * @return string - */ - private static function AirtimeTimeToPypoTime($p_time) - { - $p_time = substr($p_time, 0, 19); - $p_time = str_replace(" ", "-", $p_time); - $p_time = str_replace(":", "-", $p_time); - - return $p_time; - } - - /** - * Convert a time string in the format "YYYY-MM-DD-HH-mm-SS" to - * "YYYY-MM-DD HH:mm:SS". - * - * @param string $p_time - * @return string - */ - private static function PypoTimeToAirtimeTime($p_time) - { - $t = explode("-", $p_time); - - return $t[0]."-".$t[1]."-".$t[2]." ".$t[3].":".$t[4].":00"; - } - - /** - * Return true if the input string is in the format YYYY-MM-DD-HH-mm - * - * @param string $p_time - * @return boolean - */ - public static function ValidPypoTimeFormat($p_time) - { - $t = explode("-", $p_time); - if (count($t) != 5) { - return false; - } - foreach ($t as $part) { - if (!is_numeric($part)) { - return false; - } - } - - return true; - } - - /** - * Converts a time value as a string (with format HH:MM:SS.mmmmmm) to - * millisecs. - * - * @param string $p_time - * @return int - */ - public static function WallTimeToMillisecs($p_time) - { - $t = explode(":", $p_time); - $millisecs = 0; - if (strpos($t[2], ".")) { - $secParts = explode(".", $t[2]); - $millisecs = $secParts[1]; - $millisecs = str_pad(substr($millisecs, 0, 3),3, '0'); - $millisecs = intval($millisecs); - $seconds = intval($secParts[0]); - } else { - $seconds = intval($t[2]); - } - $ret = $millisecs + ($seconds * 1000) + ($t[1] * 60 * 1000) + ($t[0] * 60 * 60 * 1000); - - return $ret; - } - - /** - * Compute the difference between two times in the format . - * "HH:MM:SS.mmmmmm" Note: currently only supports calculating . - * millisec differences . - * - * @param string $p_time1 - * @param string $p_time2 - * @return double - */ - private static function TimeDiff($p_time1, $p_time2) - { - $parts1 = explode(".", $p_time1); - $parts2 = explode(".", $p_time2); - $diff = 0; - if ( (count($parts1) > 1) && (count($parts2) > 1) ) { - $millisec1 = substr($parts1[1], 0, 3); - $millisec1 = str_pad($millisec1, 3, "0"); - $millisec1 = intval($millisec1); - $millisec2 = substr($parts2[1], 0, 3); - $millisec2 = str_pad($millisec2, 3, "0"); - $millisec2 = intval($millisec2); - $diff = abs($millisec1 - $millisec2)/1000; - } - - return $diff; - } - - /** - * Returns an array of schedule items from cc_schedule table. Tries - * to return at least 3 items (if they are available). The parameters - * $p_startTime and $p_endTime specify the range. Schedule items returned - * do not have to be entirely within this range. It is enough that the end - * or beginning of the scheduled item is in the range. - * - * - * @param string $p_startTime - * In the format YYYY-MM-DD HH:MM:SS.nnnnnn - * @param string $p_endTime - * In the format YYYY-MM-DD HH:MM:SS.nnnnnn - * @return array - * Returns null if nothing found, else an array of associative - * arrays representing each row. - */ - public static function getItems($p_startTime, $p_endTime) - { - $baseQuery = << :startTime1 - AND st.starts < :endTime - AND st.playout_status > 0 - AND si.ends > :startTime2 - AND si.modified_instance = 'f' -ORDER BY st.starts -SQL; - - $sql = $baseQuery." ".$predicates; - - $rows = Application_Common_Database::prepareAndExecute($sql, array( - ':startTime1' => $p_startTime, - ':endTime' => $p_endTime, - ':startTime2' => $p_startTime)); - - if (count($rows) < 3) { - $dt = new DateTime("@".time()); - $dt->add(new DateInterval("PT24H")); - $range_end = $dt->format("Y-m-d H:i:s"); - - $predicates = << :startTime1 - AND st.starts < :rangeEnd - AND st.playout_status > 0 - AND si.ends > :startTime2 - AND si.modified_instance = 'f' -ORDER BY st.starts LIMIT 3 -SQL; - - $sql = $baseQuery." ".$predicates." "; - $rows = Application_Common_Database::prepareAndExecute($sql, - array( - ':startTime1' => $p_startTime, - ':rangeEnd' => $range_end, - ':startTime2' => $p_startTime)); - } - - return $rows; - } - - /** - * This function will ensure that an existing index in the - * associative array is never overwritten, instead appending - * _0, _1, _2, ... to the end of the key to make sure it is unique - */ - private static function appendScheduleItem(&$data, $time, $item) - { - $key = $time; - $i = 0; - - while (array_key_exists($key, $data["media"])) { - $key = "{$time}_{$i}"; - $i++; - } - - $data["media"][$key] = $item; - } - - private static function createInputHarborKickTimes(&$data, $range_start, $range_end) - { - $utcTimeZone = new DateTimeZone("UTC"); - $kick_times = Application_Model_ShowInstance::GetEndTimeOfNextShowWithLiveDJ($range_start, $range_end); - foreach ($kick_times as $kick_time_info) { - $kick_time = $kick_time_info['ends']; - $temp = explode('.', Application_Model_Preference::GetDefaultTransitionFade()); - // we round down transition time since PHP cannot handle millisecond. We need to - // handle this better in the future - $transition_time = intval($temp[0]); - $switchOffDataTime = new DateTime($kick_time, $utcTimeZone); - $switch_off_time = $switchOffDataTime->sub(new DateInterval('PT'.$transition_time.'S')); - $switch_off_time = $switch_off_time->format("Y-m-d H:i:s"); - - $kick_start = self::AirtimeTimeToPypoTime($kick_time); - $data["media"][$kick_start]['start'] = $kick_start; - $data["media"][$kick_start]['end'] = $kick_start; - $data["media"][$kick_start]['event_type'] = "kick_out"; - $data["media"][$kick_start]['type'] = "event"; - $data["media"][$kick_start]['independent_event'] = true; - - if ($kick_time !== $switch_off_time) { - $switch_start = self::AirtimeTimeToPypoTime($switch_off_time); - $data["media"][$switch_start]['start'] = $switch_start; - $data["media"][$switch_start]['end'] = $switch_start; - $data["media"][$switch_start]['event_type'] = "switch_off"; - $data["media"][$switch_start]['type'] = "event"; - $data["media"][$switch_start]['independent_event'] = true; - } - } - } - - private static function createFileScheduleEvent(&$data, $item, $media_id, $uri) - { - $start = self::AirtimeTimeToPypoTime($item["start"]); - $end = self::AirtimeTimeToPypoTime($item["end"]); - - list(,,,$start_hour,,) = explode("-", $start); - list(,,,$end_hour,,) = explode("-", $end); - - $same_hour = $start_hour == $end_hour; - $independent_event = !$same_hour; - - $replay_gain = is_null($item["replay_gain"]) ? "0": $item["replay_gain"]; - $replay_gain += Application_Model_Preference::getReplayGainModifier(); - - if ( !Application_Model_Preference::GetEnableReplayGain() ) { - $replay_gain = 0; - } - - $schedule_item = array( - 'id' => $media_id, - 'type' => 'file', - 'row_id' => $item["id"], - 'uri' => $uri, - 'fade_in' => Application_Model_Schedule::WallTimeToMillisecs($item["fade_in"]), - 'fade_out' => Application_Model_Schedule::WallTimeToMillisecs($item["fade_out"]), - 'cue_in' => Application_Common_DateHelper::CalculateLengthInSeconds($item["cue_in"]), - 'cue_out' => Application_Common_DateHelper::CalculateLengthInSeconds($item["cue_out"]), - 'start' => $start, - 'end' => $end, - 'show_name' => $item["show_name"], - 'replay_gain' => $replay_gain, - 'independent_event' => $independent_event, - ); - - if ($schedule_item['cue_in'] > $schedule_item['cue_out']) { - $schedule_item['cue_in'] = $schedule_item['cue_out']; - } - self::appendScheduleItem($data, $start, $schedule_item); - } - - private static function createStreamScheduleEvent(&$data, $item, $media_id, $uri) - { - $start = self::AirtimeTimeToPypoTime($item["start"]); - $end = self::AirtimeTimeToPypoTime($item["end"]); - - //create an event to start stream buffering 5 seconds ahead of the streams actual time. - $buffer_start = new DateTime($item["start"], new DateTimeZone('UTC')); - $buffer_start->sub(new DateInterval("PT5S")); - - $stream_buffer_start = self::AirtimeTimeToPypoTime($buffer_start->format("Y-m-d H:i:s")); - - $schedule_item = array( - 'start' => $stream_buffer_start, - 'end' => $stream_buffer_start, - 'uri' => $uri, - 'row_id' => $item["id"], - 'type' => 'stream_buffer_start', - 'independent_event' => true - ); - - self::appendScheduleItem($data, $start, $schedule_item); - - $schedule_item = array( - 'id' => $media_id, - 'type' => 'stream_output_start', - 'row_id' => $item["id"], - 'uri' => $uri, - 'start' => $start, - 'end' => $end, - 'show_name' => $item["show_name"], - 'row_id' => $item["id"], - 'independent_event' => true - ); - self::appendScheduleItem($data, $start, $schedule_item); - - //since a stream never ends we have to insert an additional "kick stream" event. The "start" - //time of this event is the "end" time of the stream minus 1 second. - $dt = new DateTime($item["end"], new DateTimeZone('UTC')); - $dt->sub(new DateInterval("PT1S")); - - $stream_end = self::AirtimeTimeToPypoTime($dt->format("Y-m-d H:i:s")); - - $schedule_item = array( - 'start' => $stream_end, - 'end' => $stream_end, - 'uri' => $uri, - 'type' => 'stream_buffer_end', - 'row_id' => $item["id"], - 'independent_event' => true - ); - self::appendScheduleItem($data, $stream_end, $schedule_item); - - $schedule_item = array( - 'start' => $stream_end, - 'end' => $stream_end, - 'uri' => $uri, - 'type' => 'stream_output_end', - 'independent_event' => true - ); - self::appendScheduleItem($data, $stream_end, $schedule_item); - } - - private static function getRangeStartAndEnd($p_fromDateTime, $p_toDateTime) - { - $CC_CONFIG = Config::getConfig(); - - /* if $p_fromDateTime and $p_toDateTime function parameters are null, - then set range * from "now" to "now + 24 hours". */ - if (is_null($p_fromDateTime)) { - $t1 = new DateTime("@".time()); - $range_start = $t1->format("Y-m-d H:i:s"); - } else { - $range_start = Application_Model_Schedule::PypoTimeToAirtimeTime($p_fromDateTime); - } - if (is_null($p_fromDateTime)) { - $t2 = new DateTime("@".time()); - - $cache_ahead_hours = $CC_CONFIG["cache_ahead_hours"]; - - if (is_numeric($cache_ahead_hours)) { - //make sure we are not dealing with a float - $cache_ahead_hours = intval($cache_ahead_hours); - } else { - $cache_ahead_hours = 1; - } - - $t2->add(new DateInterval("PT".$cache_ahead_hours."H")); - $range_end = $t2->format("Y-m-d H:i:s"); - } else { - $range_end = Application_Model_Schedule::PypoTimeToAirtimeTime($p_toDateTime); - } - - return array($range_start, $range_end); - } - - - private static function createScheduledEvents(&$data, $range_start, $range_end) - { - $utcTimeZone = new DateTimeZone("UTC"); - $items = self::getItems($range_start, $range_end); - foreach ($items as $item) { - $showEndDateTime = new DateTime($item["show_end"], $utcTimeZone); - - $trackStartDateTime = new DateTime($item["start"], $utcTimeZone); - $trackEndDateTime = new DateTime($item["end"], $utcTimeZone); - - if ($trackStartDateTime->getTimestamp() > $showEndDateTime->getTimestamp()) { - //do not send any tracks that start past their show's end time - continue; - } - - if ($trackEndDateTime->getTimestamp() > $showEndDateTime->getTimestamp()) { - $di = $trackStartDateTime->diff($showEndDateTime); - - $item["cue_out"] = $di->format("%H:%i:%s").".000"; - $item["end"] = $showEndDateTime->format("Y-m-d H:i:s"); - } - - if (!is_null($item['file_id'])) { - //row is from "file" - $media_id = $item['file_id']; - $storedFile = Application_Model_StoredFile::Recall($media_id); - $uri = $storedFile->getFilePath(); - self::createFileScheduleEvent($data, $item, $media_id, $uri); - } elseif (!is_null($item['stream_id'])) { - //row is type "webstream" - $media_id = $item['stream_id']; - $uri = $item['url']; - self::createStreamScheduleEvent($data, $item, $media_id, $uri); - } else { - throw new Exception("Unknown schedule type: ".print_r($item, true)); - } - - } - } - - /* Check if two events are less than or equal to 1 second apart - */ - public static function areEventsLinked($event1, $event2) { - $dt1 = DateTime::createFromFormat("Y-m-d-H-i-s", $event1['start']); - $dt2 = DateTime::createFromFormat("Y-m-d-H-i-s", $event2['start']); - - $seconds = $dt2->getTimestamp() - $dt1->getTimestamp(); - return $seconds <= 1; - } - - /** - * Streams are a 4 stage process. - * 1) start buffering stream 5 seconds ahead of its start time - * 2) at the start time tell liquidsoap to switch to this source - * 3) at the end time, tell liquidsoap to stop reading this stream - * 4) at the end time, tell liquidsoap to switch away from input.http source. - * - * When we have two streams back-to-back, some of these steps are unnecessary - * for the second stream. Instead of sending commands 1,2,3,4,1,2,3,4 we should - * send 1,2,1,2,3,4 - We don't need to tell liquidsoap to stop reading (#3), because #1 - * of the next stream implies this when we pass in a new url. We also don't need #4. - * - * There's a special case here is well. When the back-to-back streams are the same, we - * can collapse the instructions 1,2,(3,4,1,2),3,4 to 1,2,3,4. We basically cut out the - * middle part. This function handles this. - */ - private static function foldData(&$data) - { - $previous_key = null; - $previous_val = null; - $previous_previous_key = null; - $previous_previous_val = null; - $previous_previous_previous_key = null; - $previous_previous_previous_val = null; - foreach ($data as $k => $v) { - - if ($v["type"] == "stream_output_start" - && !is_null($previous_previous_val) - && $previous_previous_val["type"] == "stream_output_end" - && self::areEventsLinked($previous_previous_val, $v)) { - - unset($data[$previous_previous_previous_key]); - unset($data[$previous_previous_key]); - unset($data[$previous_key]); - if ($previous_previous_val['uri'] == $v['uri']) { - unset($data[$k]); - } - } - - $previous_previous_previous_key = $previous_previous_key; - $previous_previous_previous_val = $previous_previous_val; - $previous_previous_key = $previous_key; - $previous_previous_val = $previous_val; - $previous_key = $k; - $previous_val = $v; - } - } - - public static function getSchedule($p_fromDateTime = null, $p_toDateTime = null) - { - list($range_start, $range_end) = self::getRangeStartAndEnd($p_fromDateTime, $p_toDateTime); - - $data = array(); - $data["media"] = array(); - - //Harbor kick times *MUST* be ahead of schedule events, so that pypo - //executes them first. - self::createInputHarborKickTimes($data, $range_start, $range_end); - self::createScheduledEvents($data, $range_start, $range_end); - - self::foldData($data["media"]); - return $data; - } - - public static function deleteAll() - { - $con = Propel::getConnection(); - $con->exec("TRUNCATE TABLE cc_schedule"); - } - - public static function deleteWithFileId($fileId) - { - $sql = "DELETE FROM cc_schedule WHERE file_id=:file_id"; - Application_Common_Database::prepareAndExecute($sql, array(':file_id'=>$fileId), 'execute'); - } - - public static function createNewFormSections($p_view) - { - $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(); - - $formWhat->removeDecorator('DtDdWrapper'); - $formWho->removeDecorator('DtDdWrapper'); - $formWhen->removeDecorator('DtDdWrapper'); - $formRepeats->removeDecorator('DtDdWrapper'); - $formStyle->removeDecorator('DtDdWrapper'); - $formLive->removeDecorator('DtDdWrapper'); - - $p_view->what = $formWhat; - $p_view->when = $formWhen; - $p_view->repeats = $formRepeats; - $p_view->who = $formWho; - $p_view->style = $formStyle; - $p_view->live = $formLive; - - $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"))); - - $formRecord = new Application_Form_AddShowRR(); - $formAbsoluteRebroadcast = new Application_Form_AddShowAbsoluteRebroadcastDates(); - $formRebroadcast = new Application_Form_AddShowRebroadcastDates(); - - $formRecord->removeDecorator('DtDdWrapper'); - $formAbsoluteRebroadcast->removeDecorator('DtDdWrapper'); - $formRebroadcast->removeDecorator('DtDdWrapper'); - - $p_view->rr = $formRecord; - $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). - * There is still lots of clean-up to do. For example we shouldn't be passing $controller into - * this method to manipulate the view (this should be done inside the controller function). With - * 2.1 deadline looming, this is OK for now. -Martin */ - public static function updateShowInstance($data, $controller) - { - $formWhat = new Application_Form_AddShowWhat(); - $formWhen = new Application_Form_AddShowWhen(); - $formRepeats = new Application_Form_AddShowRepeats(); - $formWho = new Application_Form_AddShowWho(); - $formStyle = new Application_Form_AddShowStyle(); - $formLive = new Application_Form_AddShowLiveStream(); - - $formWhat->removeDecorator('DtDdWrapper'); - $formWhen->removeDecorator('DtDdWrapper'); - $formRepeats->removeDecorator('DtDdWrapper'); - $formWho->removeDecorator('DtDdWrapper'); - $formStyle->removeDecorator('DtDdWrapper'); - $formLive->removeDecorator('DtDdWrapper'); - - $formRecord = new Application_Form_AddShowRR(); - $formAbsoluteRebroadcast = new Application_Form_AddShowAbsoluteRebroadcastDates(); - $formRebroadcast = new Application_Form_AddShowRebroadcastDates(); - - $formRecord->removeDecorator('DtDdWrapper'); - $formAbsoluteRebroadcast->removeDecorator('DtDdWrapper'); - $formRebroadcast->removeDecorator('DtDdWrapper'); - $when = $formWhen->isValid($data); - - if ($when && $formWhen->checkReliantFields($data, true, null, true)) { - $start_dt = new DateTime($data['add_show_start_date']." ".$data['add_show_start_time'], - new DateTimeZone(date_default_timezone_get())); - $start_dt->setTimezone(new DateTimeZone('UTC')); - - $end_dt = new DateTime($data['add_show_end_date_no_repeat']." ".$data['add_show_end_time'], - new DateTimeZone(date_default_timezone_get())); - $end_dt->setTimezone(new DateTimeZone('UTC')); - - $ccShowInstance = CcShowInstancesQuery::create()->findPK($data["add_show_instance_id"]); - $ccShowInstance->setDbStarts($start_dt); - $ccShowInstance->setDbEnds($end_dt); - $ccShowInstance->save(); - - Application_Model_Schedule::createNewFormSections($controller->view); - - return true; - } else { - $formWhat->disable(); - $formWhen->disableRepeatCheckbox(); - $formRepeats->disable(); - $formWho->disable(); - $formStyle->disable(); - //$formLive->disable(); - - $controller->view->what = $formWhat; - $controller->view->when = $formWhen; - $controller->view->repeats = $formRepeats; - $controller->view->who = $formWho; - $controller->view->style = $formStyle; - $controller->view->live = $formLive; - $controller->view->rr = $formRecord; - $controller->view->absoluteRebroadcast = $formAbsoluteRebroadcast; - $controller->view->rebroadcast = $formRebroadcast; - - //$formRecord->disable(); - //$formAbsoluteRebroadcast->disable(); - //$formRebroadcast->disable(); - - return false; - } - } - - /* This function is responsible for handling the case where the entire show (not a single show instance) - * was edited (via the context menu in the Calendar). - * There is still lots of clean-up to do. For example we shouldn't be passing $controller into - * this method to manipulate the view (this should be done inside the controller function). With - * 2.1 deadline looming, this is OK for now. - * Another clean-up is to move all the form manipulation to the proper form class..... - * -Martin - */ - public static function addUpdateShow($data, $controller, $validateStartDate, - $originalStartDate=null, $update=false, $instanceId=null) - { - $userInfo = Zend_Auth::getInstance()->getStorage()->read(); - $user = new Application_Model_User($userInfo->id); - $isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER)); - - $record = false; - - $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(); - - $formWhat->removeDecorator('DtDdWrapper'); - $formWho->removeDecorator('DtDdWrapper'); - $formWhen->removeDecorator('DtDdWrapper'); - $formRepeats->removeDecorator('DtDdWrapper'); - $formStyle->removeDecorator('DtDdWrapper'); - $formLive->removeDecorator('DtDdWrapper'); - - $what = $formWhat->isValid($data); - $when = $formWhen->isValid($data); - $live = $formLive->isValid($data); - if ($when) { - $when = $formWhen->checkReliantFields($data, $validateStartDate, $originalStartDate, $update, $instanceId); - } - - //The way the following code works is that is parses the hour and - //minute from a string with the format "1h 20m" or "2h" or "36m". - //So we are detecting whether an hour or minute value exists via strpos - //and then parse appropriately. A better way to do this in the future is - //actually pass the format from javascript in the format hh:mm so we don't - //have to do this extra String parsing. - $hPos = strpos($data["add_show_duration"], 'h'); - $mPos = strpos($data["add_show_duration"], 'm'); - - $hValue = 0; - $mValue = 0; - - if ($hPos !== false) { - $hValue = trim(substr($data["add_show_duration"], 0, $hPos)); - } - if ($mPos !== false) { - $hPos = $hPos === false ? 0 : $hPos+1; - $mValue = trim(substr($data["add_show_duration"], $hPos, -1 )); - } - - $data["add_show_duration"] = $hValue.":".$mValue; - - $formRecord = new Application_Form_AddShowRR(); - $formAbsoluteRebroadcast = new Application_Form_AddShowAbsoluteRebroadcastDates(); - $formRebroadcast = new Application_Form_AddShowRebroadcastDates(); - - $formRecord->removeDecorator('DtDdWrapper'); - $formAbsoluteRebroadcast->removeDecorator('DtDdWrapper'); - $formRebroadcast->removeDecorator('DtDdWrapper'); - - - $record = $formRecord->isValid($data); - - if ($data["add_show_repeats"]) { - $repeats = $formRepeats->isValid($data); - if ($repeats) { - $repeats = $formRepeats->checkReliantFields($data); - } - $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; - } - } else { - $repeats = 1; - $formRebroadcast->reset(); - //make it valid, results don't matter anyways. - $rebroad = 1; - - if ($data["add_show_rebroadcast"]) { - $rebroadAb = $formAbsoluteRebroadcast->isValid($data); - if ($rebroadAb) { - $rebroadAb = $formAbsoluteRebroadcast->checkReliantFields($data); - } - } else { - $rebroadAb = 1; - } - } - - $who = $formWho->isValid($data); - $style = $formStyle->isValid($data); - if ($what && $when && $repeats && $who && $style && $live) { - if ($record && $rebroadAb && $rebroad) { - if ($isAdminOrPM) { - Application_Model_Show::create($data); - } - - //send back a new form for the user. - Application_Model_Schedule::createNewFormSections($controller->view); - - //$controller->view->newForm = $controller->view->render('schedule/add-show-form.phtml'); - return true; - } else { - $controller->view->what = $formWhat; - $controller->view->when = $formWhen; - $controller->view->repeats = $formRepeats; - $controller->view->who = $formWho; - $controller->view->style = $formStyle; - $controller->view->rr = $formRecord; - $controller->view->absoluteRebroadcast = $formAbsoluteRebroadcast; - $controller->view->rebroadcast = $formRebroadcast; - $controller->view->live = $formLive; - //$controller->view->addNewShow = !$editShow; - - //$controller->view->form = $controller->view->render('schedule/add-show-form.phtml'); - return false; - - } - } else { - $controller->view->what = $formWhat; - $controller->view->when = $formWhen; - $controller->view->repeats = $formRepeats; - $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->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) - { - $overlapping = false; - - $params = array( - ':show_end1' => $show_end->format('Y-m-d H:i:s'), - ':show_end2' => $show_end->format('Y-m-d H:i:s'), - ':show_end3' => $show_end->format('Y-m-d H:i:s') - ); - - - /* If a show is being edited, exclude it from the query - * In both cases (new and edit) we only grab shows that - * are scheduled 2 days prior - */ - if ($update) { - $sql = <<= (date(:show_end3) - INTERVAL '2 days') - AND modified_instance = FALSE -SQL; - if (is_null($showId)) { - $sql .= <<= (date(:show_end3) - INTERVAL '2 days') - AND modified_instance = FALSE -ORDER BY ends -SQL; - - $rows = Application_Common_Database::prepareAndExecute($sql, array( - ':show_end1' => $show_end->format('Y-m-d H:i:s'), - ':show_end2' => $show_end->format('Y-m-d H:i:s'), - ':show_end3' => $show_end->format('Y-m-d H:i:s')), 'all'); - } - - foreach ($rows as $row) { - $start = new DateTime($row["starts"], new DateTimeZone('UTC')); - $end = new DateTime($row["ends"], new DateTimeZone('UTC')); - - if ($show_start->getTimestamp() < $end->getTimestamp() && - $show_end->getTimestamp() > $start->getTimestamp()) { - $overlapping = true; - break; - } - } - - return $overlapping; - } - - public static function GetType($p_scheduleId){ - $scheduledItem = CcScheduleQuery::create()->findPK($p_scheduleId); - if ($scheduledItem->getDbFileId() == null) { - return 'webstream'; - } else { - return 'file'; - } - } - - public static function GetFileId($p_scheduleId) - { - $scheduledItem = CcScheduleQuery::create()->findPK($p_scheduleId); - - return $scheduledItem->getDbFileId(); - } - - public static function GetStreamId($p_scheduleId) - { - $scheduledItem = CcScheduleQuery::create()->findPK($p_scheduleId); - - return $scheduledItem->getDbStreamId(); - } -} diff --git a/airtime_mvc/application/models/_old_Show.php b/airtime_mvc/application/models/_old_Show.php deleted file mode 100644 index f485e41bc..000000000 --- a/airtime_mvc/application/models/_old_Show.php +++ /dev/null @@ -1,2241 +0,0 @@ -_showId = $showId; - } - - public function getName() - { - $show = CcShowQuery::create()->findPK($this->_showId); - - return $show->getDbName(); - } - - public function setName($name) - { - $show = CcShowQuery::create()->findPK($this->_showId); - $show->setDbName($name); - Application_Model_RabbitMq::PushSchedule(); - } - - public function setAirtimeAuthFlag($flag) - { - $show = CcShowQuery::create()->findPK($this->_showId); - $show->setDbLiveStreamUsingAirtimeAuth($flag); - $show->save(); - } - - public function setCustomAuthFlag($flag) - { - $show = CcShowQuery::create()->findPK($this->_showId); - $show->setDbLiveStreamUsingCustomAuth($flag); - $show->save(); - } - - public function setCustomUsername($username) - { - $show = CcShowQuery::create()->findPK($this->_showId); - $show->setDbLiveStreamUser($username); - $show->save(); - } - - public function setCustomPassword($password) - { - $show = CcShowQuery::create()->findPK($this->_showId); - $show->setDbLiveStreamPass($password); - $show->save(); - } - - public function getDescription() - { - $show = CcShowQuery::create()->findPK($this->_showId); - - return $show->getDbDescription(); - } - - public function setDescription($description) - { - $show = CcShowQuery::create()->findPK($this->_showId); - $show->setDbDescription($description); - } - - public function getColor() - { - $show = CcShowQuery::create()->findPK($this->_showId); - - return $show->getDbColor(); - } - - public function setColor($color) - { - $show = CcShowQuery::create()->findPK($this->_showId); - $show->setDbColor($color); - } - - public function getUrl() - { - $show = CcShowQuery::create()->findPK($this->_showId); - - return $show->getDbUrl(); - } - - /*TODO : This method is not actually used anywhere as far as I can tell. We - can safely remove it and probably many other superfluous methods. - --RG*/ - - public function setUrl($p_url) - { - $show = CcShowQuery::create()->findPK($this->_showId); - $show->setDbUrl($p_url); - } - - public function getGenre() - { - $show = CcShowQuery::create()->findPK($this->_showId); - - return $show->getDbGenre(); - } - - public function setGenre($p_genre) - { - $show = CcShowQuery::create()->findPK($this->_showId); - $show->setDbGenre($p_genre); - } - - public function getBackgroundColor() - { - $show = CcShowQuery::create()->findPK($this->_showId); - - return $show->getDbBackgroundColor(); - } - - public function setBackgroundColor($backgroundColor) - { - $show = CcShowQuery::create()->findPK($this->_showId); - $show->setDbBackgroundColor($backgroundColor); - } - - public function getId() - { - return $this->_showId; - } - - public function getHosts() - { - $sql = << $this->getId() ), 'all'); - - $res = array(); - foreach ($hosts as $host) { - $res[] = $host['first_name']." ".$host['last_name']; - } - return $res; - } - - public function getHostsIds() - { - $sql = << $this->getId() ), 'all'); - - return $hosts; - } - - /** - * remove everything about this show. - */ - public function delete() - { - //usually we hide the show-instance, but in this case we are deleting the show template - //so delete all show-instances as well. - CcShowInstancesQuery::create()->filterByDbOriginalShow($this->_showId)->delete(); - - $show = CcShowQuery::create()->findPK($this->_showId); - $show->delete(); - } - - public function resizeShow($deltaDay, $deltaMin) - { - $con = Propel::getConnection(); - - if ($deltaDay > 0) { - return _("Shows can have a max length of 24 hours."); - } - - $utc = new DateTimeZone("UTC"); - - $nowDateTime = new DateTime("now", $utc); - - $showInstances = CcShowInstancesQuery::create() - ->filterByDbShowId($this->_showId) - ->find($con); - - /* Check two things: - 1. If the show being resized and any of its repeats end in the past - 2. If the show being resized and any of its repeats overlap - with other scheduled shows */ - - foreach ($showInstances as $si) { - $startsDateTime = new DateTime($si->getDbStarts(), new DateTimeZone("UTC")); - $endsDateTime = new DateTime($si->getDbEnds(), new DateTimeZone("UTC")); - - /* 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 local * timestamp and - then converted back to UTC to avoid show time changes */ - $startsDateTime->setTimezone(new DateTimeZone(date_default_timezone_get())); - $endsDateTime->setTimezone(new DateTimeZone(date_default_timezone_get())); - - $newStartsDateTime = Application_Model_ShowInstance::addDeltas($startsDateTime, $deltaDay, $deltaMin); - $newEndsDateTime = Application_Model_ShowInstance::addDeltas($endsDateTime, $deltaDay, $deltaMin); - - if ($newEndsDateTime->getTimestamp() < $nowDateTime->getTimestamp()) { - return _("End date/time cannot be in the past"); - } - - //convert our new starts/ends to UTC. - $newStartsDateTime->setTimezone($utc); - $newEndsDateTime->setTimezone($utc); - - $overlapping = Application_Model_Schedule::checkOverlappingShows( - $newStartsDateTime, $newEndsDateTime, true, $si->getDbId()); - - if ($overlapping) { - return _("Cannot schedule overlapping shows.\nNote: Resizing a repeating show ". - "affects all of its repeats."); - } - } - - $hours = $deltaMin/60; - $hours = ($hours > 0) ? floor($hours) : ceil($hours); - $mins = abs($deltaMin % 60); - - //current timesamp in UTC. - $current_timestamp = gmdate("Y-m-d H:i:s"); - - $sql_gen = << :current_timestamp1) - AND ((ends + :deltaDay2::INTERVAL + :interval2::INTERVAL - starts) <= interval '24:00') -SQL; - - Application_Common_Database::prepareAndExecute($sql_gen, - array( - ':deltaDay1' => "$deltaDay days", - ':interval1' => "$hours:$mins", - ':show_id1' => $this->_showId, - ':current_timestamp1' => $current_timestamp, - ':deltaDay2' => "$deltaDay days", - ':interval2' => "$hours:$mins" - ), "execute"); - - $sql_gen = << "$deltaDay days", - ':interval3' => "$hours:$mins", - ':show_id2' => $this->_showId, - ':deltaDay4' => "$deltaDay days", - ':interval4' => "$hours:$mins" - ), "execute"); - - $con = Propel::getConnection(CcSchedulePeer::DATABASE_NAME); - $con->beginTransaction(); - - try { - //update the status flag in cc_schedule. - - /* Since we didn't use a propel object when updating - * cc_show_instances table we need to clear the instances - * so the correct information is retrieved from the db - */ - CcShowInstancesPeer::clearInstancePool(); - - $instances = CcShowInstancesQuery::create() - ->filterByDbEnds($current_timestamp, Criteria::GREATER_THAN) - ->filterByDbShowId($this->_showId) - ->find($con); - - foreach ($instances as $instance) { - $instance->updateScheduleStatus($con); - } - - $con->commit(); - } catch (Exception $e) { - $con->rollback(); - Logging::info("Couldn't update schedule status."); - Logging::info($e->getMessage()); - } - - Application_Model_RabbitMq::PushSchedule(); - } - - public function cancelShow($day_timestamp) - { - $timeinfo = explode(" ", $day_timestamp); - - CcShowDaysQuery::create() - ->filterByDbShowId($this->_showId) - ->update(array('DbLastShow' => $timeinfo[0])); - - $sql = <<= :dayTimestamp::TIMESTAMP - AND show_id = :showId -SQL; - - $rows = Application_Common_Database::prepareAndExecute( $sql, array( - ':dayTimestamp' => $day_timestamp, - ':showId' => $this->getId()), 'all'); - - foreach ($rows as $row) { - try { - $showInstance = new Application_Model_ShowInstance($row["id"]); - $showInstance->delete($rabbitmqPush = false); - } catch (Exception $e) { - Logging::info($e->getMessage()); - } - } - - Application_Model_RabbitMq::PushSchedule(); - } - - /** - * This function is called when a repeating show is edited and the - * days that is repeats on have changed. More specifically, a day - * that the show originally repeated on has been "unchecked". - * - * Removes Show Instances that occur on days of the week specified - * by input array. For example, if array contains one value of "0", - * (0 = Sunday, 1=Monday) then all show instances that occur on - * Sunday are removed. - * - * @param array p_uncheckedDays - * An array specifying which days should be removed. (in the local timezone) - */ - public function removeUncheckedDaysInstances($p_uncheckedDays) - { - //need to convert local doftw to UTC doftw (change made for 2.0 since shows are stored in UTC) - $daysRemovedUTC = array(); - - $showDays = CcShowDaysQuery::create() - ->filterByDbShowId($this->getId()) - ->find(); - - Logging::info("Unchecked days:"); - foreach ($p_uncheckedDays as $day) { - Logging::info($day); - } - - foreach ($showDays as $showDay) { - //Logging::info("Local show day is: {$showDay->getDbDay()}"); - //Logging::info("First show day is: {$showDay->getDbFirstShow()}"); - //Logging::info("Id show days is: {$showDay->getDbId()}"); - - if (in_array($showDay->getDbDay(), $p_uncheckedDays)) { - $showDay->reload(); - //Logging::info("Local show day is: {$showDay->getDbDay()}"); - //Logging::info("First show day is: {$showDay->getDbFirstShow()}"); - //Logging::info("Id show days is: {$showDay->getDbId()}"); - $startDay = new DateTime("{$showDay->getDbFirstShow()} {$showDay->getDbStartTime()}", new DateTimeZone($showDay->getDbTimezone())); - //Logging::info("Show start day: {$startDay->format('Y-m-d H:i:s')}"); - $startDay->setTimezone(new DateTimeZone("UTC")); - //Logging::info("Show start day UTC: {$startDay->format('Y-m-d H:i:s')}"); - $daysRemovedUTC[] = $startDay->format('w'); - //Logging::info("UTC show day is: {$startDay->format('w')}"); - } - } - - $uncheckedDaysImploded = implode(",", $daysRemovedUTC); - $showId = $this->getId(); - - $esc_uncheckedDays = pg_escape_string($uncheckedDaysImploded); - $timestamp = gmdate("Y-m-d H:i:s"); - - $sql = << :timestamp::TIMESTAMP - AND show_id = :showId -SQL; - - Application_Common_Database::prepareAndExecute( $sql, - array( - ":timestamp" => $timestamp, - ":showId" => $showId, - ), "execute"); - } - - /** - * Check whether the current show originated - * from a recording. - * - * @return boolean - * true if originated from recording, otherwise false. - */ - public function isRecorded() - { - $showInstancesRow = CcShowInstancesQuery::create() - ->filterByDbShowId($this->getId()) - ->filterByDbRecord(1) - ->filterByDbModifiedInstance(false) - ->findOne(); - - return !is_null($showInstancesRow); - } - - /** - * Check whether the current show has rebroadcasts of a recorded - * show. Should be used in conjunction with isRecorded(). - * - * @return boolean - * true if show has rebroadcasts, otherwise false. - */ - public function isRebroadcast() - { - $showInstancesRow = CcShowInstancesQuery::create() - ->filterByDbShowId($this->_showId) - ->filterByDbRebroadcast(1) - ->filterByDbModifiedInstance(false) - ->findOne(); - - return !is_null($showInstancesRow); - } - - /** - * Get start time and absolute start date for a recorded - * shows rebroadcasts. For example start date format would be - * YYYY-MM-DD and time would HH:MM - * - * @return array - * array of associate arrays containing "start_date" and "start_time" - */ - public function getRebroadcastsAbsolute() - { - $sql = << $this->getId() ), 'all' ); - - $rebroadcastsLocal = array(); - //get each rebroadcast show in cc_show_instances, convert to current timezone to get start date/time. - /*TODO: refactor the following code to get rid of the $i temporary - variable. -- RG*/ - $i = 0; - - $utc = new DateTimeZone("UTC"); - $dtz = new DateTimeZone( date_default_timezone_get() ); - - foreach ($rebroadcasts as $show) { - $startDateTime = new DateTime($show["starts"], $utc); - $startDateTime->setTimezone($dtz); - - $rebroadcastsLocal[$i]["start_date"] = - $startDateTime->format("Y-m-d"); - $rebroadcastsLocal[$i]["start_time"] = - $startDateTime->format("H:i"); - - $i = $i + 1; - } - - return $rebroadcastsLocal; - } - - /** - * Get start time and relative start date for a recorded - * shows rebroadcasts. For example start date format would be - * "x days" and time would HH:MM:SS - * - * @return array - * array of associate arrays containing "day_offset" and "start_time" - */ - public function getRebroadcastsRelative() - { - $sql = << $this->getId() ), 'all' ); - } - - /** - * Check whether the current show is set to repeat - * repeating shows. - * - * @return boolean - * true if repeating shows, otherwise false. - */ - public function isRepeating() - { - $showDaysRow = CcShowDaysQuery::create() - ->filterByDbShowId($this->_showId) - ->findOne(); - - if (!is_null($showDaysRow)) { - return ($showDaysRow->getDbRepeatType() != -1); - } else { - return false; - } - } - - /** - * Get the repeat type of the show. Show can have repeat - * type of "weekly", "bi-weekly" and "monthly". These values - * are represented by 0, 1, and 2 respectively. - * - * @return int - * Return the integer corresponding to the repeat type. - */ - public function getRepeatType() - { - $showDaysRow = CcShowDaysQuery::create() - ->filterByDbShowId($this->_showId) - ->findOne(); - - if (!is_null($showDaysRow)) - return $showDaysRow->getDbRepeatType(); - else - return -1; - } - - /** - * Get the end date for a repeating show in the format yyyy-mm-dd - * - * @return string - * Return the end date for the repeating show or the empty - * string if there is no end. - */ - public function getRepeatingEndDate() - { - $sql = << $this->getId() ), 'column' ); - - /* TODO: Why return empty string instead of false? very confusing --RG - */ - return ($query !== false) ? $query : ""; - } - - /** - * Deletes all future instances of the current show object - * from the show_instances table. This function is used when - * a show is being edited - in some cases, when a show is edited - * we just destroy all future show instances, and let another function - * regenerate them later on. Note that this isn't always the most - * desirable thing to do. Deleting a show instance and regenerating - * it cause any scheduled playlists within those show instances to - * be gone for good. - */ - public function deleteAllInstances() - { - $sql = << :timestamp::TIMESTAMP - AND show_id = :showId -SQL; - Application_Common_Database::prepareAndExecute( $sql, - array( ':timestamp' => gmdate("Y-m-d H:i:s"), - ':showId' => $this->getId()), 'execute'); - } - - /** - * Deletes all future rebroadcast instances of the current - * show object from the show_instances table. - */ - public function deleteAllRebroadcasts() - { - $sql = << :timestamp::TIMESTAMP - AND show_id :showId - AND rebroadcast 1 -SQL; - Application_Common_Database::prepareAndExecute( $sql, - array( ':showId' => $this->getId(), - ':timestamp' => gmdate("Y-m-d H:i:s")), 'execute'); - - $con->exec($sql); - } - - /** - * Deletes all show instances of current show after a - * certain date. Note that although not enforced, $p_date - * should never be in the past, as we never want to allow - * deletion of shows that have already occured. - * - * @param string $p_date - * The date which to delete after, if null deletes from the current timestamp. - */ - public function removeAllInstancesFromDate($p_date=null) - { - $con = Propel::getConnection(); - - $timestamp = gmdate("Y-m-d H:i:s"); - - if (is_null($p_date)) { - $date = new Application_Common_DateHelper; - $p_date = $date->getDate(); - } - - $showId = $this->getId(); - $sql = "DELETE FROM cc_show_instances " - ." WHERE date(starts) >= DATE '$p_date'" - ." AND starts > TIMESTAMP '$timestamp'" - ." AND show_id = $showId"; - - $con->exec($sql); - - } - - /** - * Deletes all show instances of current show before a - * certain date. - * - * This function is used in the case where a repeating show is being - * edited and the start date of the first show has been changed more - * into the future. In this case, delete any show instances that - * exist before the new start date. - * - * @param string $p_date - * The date which to delete before - */ - public function removeAllInstancesBeforeDate($p_date) - { - $con = Propel::getConnection(); - - $timestamp = gmdate("Y-m-d H:i:s"); - - $showId = $this->getId(); - $sql = "DELETE FROM cc_show_instances " - ." WHERE date(starts) < DATE '$p_date'" - ." AND starts > TIMESTAMP '$timestamp'" - ." AND show_id = $showId"; - - $con->exec($sql); - } - - public 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->getId() ), 'all' ); - - foreach ($result as $r) { - $show["starts"] = new DateTime($r["starts"], new DateTimeZone('UTC')); - $show["ends"] = new DateTime($r["ends"], new DateTimeZone('UTC')); - } - $currentUser = Application_Model_User::getCurrentUser(); - $currentUserId = $currentUser->getId(); - $userTimezone = Application_Model_Preference::GetUserTimezone($currentUserId); - $show["starts"]->setTimezone(new DateTimeZone($userTimezone)); - $show["ends"]->setTimezone(new DateTimeZone($userTimezone)); - return $show; - } - - /** - * Get the start date of the current show in UTC timezone. - * - * @return string - * The start date in the format YYYY-MM-DD or empty string in case - * start date could not be found - */ - public function getStartDateAndTime() - { - $con = Propel::getConnection(); - - $showId = $this->getId(); - $stmt = $con->prepare( - "SELECT first_show, start_time, timezone FROM cc_show_days" - ." WHERE show_id = :showId" - ." ORDER BY first_show" - ." LIMIT 1"); - - $stmt->bindParam(':showId', $showId); - $stmt->execute(); - - if (!$stmt) { - return ""; - } - - $rows = $stmt->fetchAll(); - $row = $rows[0]; - - $dt = new DateTime($row["first_show"]." ".$row["start_time"], new DateTimeZone($row["timezone"])); - $dt->setTimezone(new DateTimeZone("UTC")); - - return $dt->format("Y-m-d H:i"); - } - - /** - * Get the start date of the current show in UTC timezone. - * - * @return string - * The start date in the format YYYY-MM-DD - */ - public function getStartDate() - { - list($date,) = explode(" ", $this->getStartDateAndTime()); - - return $date; - } - - /** - * Get the start time of the current show in UTC timezone. - * - * @return string - * The start time in the format HH:MM - */ - - public function getStartTime() - { - list(,$time) = explode(" ", $this->getStartDateAndTime()); - - return $time; - } - - /** - * Get the end date of the current show. - * Note that this is not the end date of repeated show - * - * @return string - * The end date in the format YYYY-MM-DD - */ - public function getEndDate() - { - $startDate = $this->getStartDate(); - $startTime = $this->getStartTime(); - $duration = $this->getDuration(); - - $startDateTime = new DateTime($startDate.' '.$startTime); - $duration = explode(":", $duration); - - $endDate = $startDateTime->add(new DateInterval('PT'.$duration[0].'H'.$duration[1].'M')); - - return $endDate->format('Y-m-d'); - } - - /** - * Get the end time of the current show. - * - * @return string - * The start time in the format HH:MM:SS - */ - public function getEndTime() - { - $startDate = $this->getStartDate(); - $startTime = $this->getStartTime(); - $duration = $this->getDuration(); - - $startDateTime = new DateTime($startDate.' '.$startTime); - $duration = explode(":", $duration); - - $endDate = $startDateTime->add(new DateInterval('PT'.$duration[0].'H'.$duration[1].'M')); - - return $endDate->format('H:i:s'); - } - - /** - * Indicate whether the starting point of the show is in the - * past. - * - * @return boolean - * true if the StartDate is in the past, false otherwise - */ - public function isStartDateTimeInPast() - { - $date = new Application_Common_DateHelper; - $current_timestamp = $date->getUtcTimestamp(); - - return ($current_timestamp > ($this->getStartDate()." ".$this->getStartTime())); - } - - /** - * Get the ID's of future instance of the current show. - * - * @return array - * A simple array containing all ID's of show instance - * scheduled in the future. - */ - public function getAllFutureInstanceIds() - { - $sql = << :timestamp::TIMESTAMP - AND modified_instance != TRUE -SQL; - $rows = Application_Common_Database::prepareAndExecute($sql, - array( ':showId' => $this->getId(), - ':timestamp' => gmdate("Y-m-d H:i:s")), "all"); - - $res = array(); - foreach ($rows as $r) { - $res[] = $r['id']; - } - return $res; - } - - /* Called when a show's duration is changed (edited). - * - * @param array $p_data - * array containing the POST data about the show from the - * browser. - * - */ - private function updateDurationTime($p_data) - { - //need to update cc_show_instances, cc_show_days - $con = Propel::getConnection(); - - $date = new Application_Common_DateHelper; - $timestamp = $date->getUtcTimestamp(); - - $stmt = $con->prepare("UPDATE cc_show_days " - ."SET duration = :add_show_duration " - ."WHERE show_id = :add_show_id" ); - $stmt->execute( array( - ':add_show_duration' => $p_data['add_show_duration'], - ':add_show_id' => $p_data['add_show_id'] - )); - - - $sql = << :timestamp::TIMESTAMP -SQL; - - Application_Common_Database::prepareAndExecute( $sql, array( - ':add_show_duration' => $p_data['add_show_duration'], - ':show_id' => $p_data['add_show_id'], - ':timestamp' => $timestamp), "execute"); - } - - private function updateStartDateTime($p_data, $p_endDate) - { - //need to update cc_schedule, cc_show_instances, cc_show_days - $con = Propel::getConnection(); - - $date = new Application_Common_DateHelper; - $timestamp = $date->getTimestamp(); - - //TODO fix this from overwriting info. - $sql = "UPDATE cc_show_days " - ."SET start_time = TIME '$p_data[add_show_start_time]', " - ."first_show = DATE '$p_data[add_show_start_date]', "; - if (strlen ($p_endDate) == 0) { - $sql .= "last_show = NULL "; - } else { - $sql .= "last_show = DATE '$p_endDate' "; - } - $sql .= "WHERE show_id = $p_data[add_show_id]"; - $con->exec($sql); - - $dtOld = new DateTime($this->getStartDate()." ".$this->getStartTime(), new DateTimeZone("UTC")); - $dtNew = new DateTime($p_data['add_show_start_date']." ".$p_data['add_show_start_time'], new DateTimeZone(date_default_timezone_get())); - $diff = $dtOld->getTimestamp() - $dtNew->getTimestamp(); - - $sql = "UPDATE cc_show_instances " - ."SET starts = starts + INTERVAL '$diff sec', " - ."ends = ends + INTERVAL '$diff sec' " - ."WHERE show_id = $p_data[add_show_id] " - ."AND starts > TIMESTAMP '$timestamp'"; - $con->exec($sql); - - $showInstanceIds = $this->getAllFutureInstanceIds(); - if (count($showInstanceIds) > 0 && $diff != 0) { - $showIdsImploded = implode(",", $showInstanceIds); - $sql = "UPDATE cc_schedule " - ."SET starts = starts + INTERVAL '$diff sec', " - ."ends = ends + INTERVAL '$diff sec' " - ."WHERE instance_id IN ($showIdsImploded)"; - $con->exec($sql); - } - } - - public function getDuration($format=false) - { - $showDay = CcShowDaysQuery::create()->filterByDbShowId($this->getId())->findOne(); - if (!$format) { - return $showDay->getDbDuration(); - } else { - $info = explode(':',$showDay->getDbDuration()); - - return str_pad(intval($info[0]),2,'0',STR_PAD_LEFT).'h '.str_pad(intval($info[1]),2,'0',STR_PAD_LEFT).'m'; - } - } - - public function getShowDays() - { - $showDays = CcShowDaysQuery::create()->filterByDbShowId( - $this->getId())->find(); - $res = array(); - foreach ($showDays as $showDay) { - $res[] = $showDay->getDbDay(); - } - return $res; - } - - /* Only used for shows that aren't repeating. - * - * @return Boolean: true if show has an instance, otherwise false. */ - public function hasInstance() - { - return (!is_null($this->getInstance())); - } - - /* Only used for shows that aren't repeating. - * - * @return CcShowInstancesQuery: An propel object representing a - * row in the cc_show_instances table. */ - public function getInstance() - { - $showInstance = CcShowInstancesQuery::create() - ->filterByDbShowId($this->getId()) - ->findOne(); - - return $showInstance; - } - - /** - * returns info about live stream override info - */ - public function getLiveStreamInfo() - { - $info = array(); - if ($this->getId() == null) { - return $info; - } else { - $ccShow = CcShowQuery::create()->findPK($this->_showId); - $info['custom_username'] = $ccShow->getDbLiveStreamUser(); - $info['cb_airtime_auth'] = $ccShow->getDbLiveStreamUsingAirtimeAuth(); - $info['cb_custom_auth'] = $ccShow->getDbLiveStreamUsingCustomAuth(); - $info['custom_username'] = $ccShow->getDbLiveStreamUser(); - $info['custom_password'] = $ccShow->getDbLiveStreamPass(); - return $info; - } - } - - /* Only used for shows that are repeating. Note that this will return - * true even for dates that only have a "modified" show instance (does not - * check if the "modified_instance" column is set to true). This is intended - * behaviour. - * - * @param $p_dateTime: Date for which we are checking if instance - * exists. - * - * @return Boolean: true if show has an instance on $p_dateTime, - * otherwise false. */ - public function hasInstanceOnDate($p_dateTime) - { - return (!is_null($this->getInstanceOnDate($p_dateTime))); - } - - /* Only used for shows that are repeating. Note that this will return - * shows that have been "modified" (does not check if the "modified_instance" - * column is set to true). This is intended behaviour. - * - * @param $p_dateTime: Date for which we are getting an instance. - * - * @return CcShowInstancesQuery: An propel object representing a - * row in the cc_show_instances table. */ - public function getInstanceOnDate($p_dateTime) - { - $timestamp = $p_dateTime->format("Y-m-d H:i:s"); - $sql = << $this->getId(), - ':timestamp' => $timestamp ), 'column'); - return CcShowInstancesQuery::create() - ->findPk($row); - } catch (Exception $e) { - return null; - } - - } - - public function deletePossiblyInvalidInstances($p_data, $p_endDate, $isRecorded, $repeatType) - { - if ($p_data['add_show_repeats'] != $this->isRepeating()) { - //repeat option was toggled - $this->deleteAllInstances(); - } - - if ($p_data['add_show_duration'] != $this->getDuration()) { - //duration has changed - $this->updateDurationTime($p_data); - } - - if ($p_data['add_show_repeats']) { - if (($repeatType == 1 || $repeatType == 2) && - $p_data['add_show_start_date'] != $this->getStartDate()){ - - //start date has changed when repeat type is bi-weekly or monthly. - //This screws up the repeating positions of show instances, so lets - //just delete them for now. (CC-2351) - - $this->deleteAllInstances(); - } - - if ($repeatType != $this->getRepeatType()) { - //repeat type changed. - $this->deleteAllInstances(); - } else { - //repeat type is the same, check if the days of the week are the same - $repeatingDaysChanged = false; - $showDaysArray = $this->getShowDays(); - if (count($p_data['add_show_day_check']) == count($showDaysArray)) { - //same number of days checked, lets see if they are the same numbers - $intersect = array_intersect($p_data['add_show_day_check'], $showDaysArray); - if (count($intersect) != count($p_data['add_show_day_check'])) { - $repeatingDaysChanged = true; - } - } else { - $repeatingDaysChanged = true; - } - - if ($repeatingDaysChanged) { - $daysRemoved = array_diff($showDaysArray, $p_data['add_show_day_check']); - - if (count($daysRemoved) > 0) { - - $this->removeUncheckedDaysInstances($daysRemoved); - } - } - - if ($p_data['add_show_start_date'] != $this->getStartDate() - || $p_data['add_show_start_time'] != $this->getStartTime()){ - //start date/time has changed - - $newDate = strtotime($p_data['add_show_start_date']); - $oldDate = strtotime($this->getStartDate()); - if ($newDate > $oldDate) { - $this->removeAllInstancesBeforeDate($p_data['add_show_start_date']); - } - - $this->updateStartDateTime($p_data, $p_endDate); - } - } - - //Check if end date for the repeat option has changed. If so, need to take care - //of deleting possible invalid Show Instances. - if ((strlen($this->getRepeatingEndDate()) == 0) == $p_data['add_show_no_end']) { - //show "Never Ends" option was toggled. - if ($p_data['add_show_no_end']) { - } else { - $this->removeAllInstancesFromDate($p_endDate); - } - } - if ($this->getRepeatingEndDate() != $p_data['add_show_end_date']) { - //end date was changed. - - $newDate = strtotime($p_data['add_show_end_date']); - $oldDate = strtotime($this->getRepeatingEndDate()); - if ($newDate < $oldDate) { - $this->removeAllInstancesFromDate($p_endDate); - } - } - } - } - - /** - * Create a show. - * - * Note: end dates are non inclusive. - * - * @param array $data - * @return int - * Show ID - */ - 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')); - - if ($data['add_show_no_end']) { - $endDate = NULL; - } elseif ($data['add_show_repeats']) { - $endDateTime = new DateTime($data['add_show_end_date']); - //$endDateTime->setTimezone(new DateTimeZone('UTC')); - $endDateTime->add(new DateInterval("P1D")); - $endDate = $endDateTime->format("Y-m-d"); - } else { - $endDateTime = new DateTime($data['add_show_start_date']); - //$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()); - 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; - - 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->setDbDescription($data['add_show_description']); - $ccShow->setDbUrl($data['add_show_url']); - $ccShow->setDbGenre($data['add_show_genre']); - $ccShow->setDbColor($data['add_show_color']); - $ccShow->setDbBackgroundColor($data['add_show_background_color']); - $ccShow->setDbLiveStreamUsingAirtimeAuth($data['cb_airtime_auth'] == 1); - $ccShow->setDbLiveStreamUsingCustomAuth($data['cb_custom_auth'] == 1); - $ccShow->setDbLiveStreamUser($data['custom_username']); - $ccShow->setDbLiveStreamPass($data['custom_password']); - $ccShow->save(); - - $showId = $ccShow->getDbId(); - - $isRecorded = (isset($data['add_show_record']) && $data['add_show_record']) ? 1 : 0; - - if ($data['add_show_id'] != -1) { - $show = new Application_Model_Show($showId); - $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) { - 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) { - $showDay = new CcShowDays(); - $showDay->setDbFirstShow($startDateTime->format("Y-m-d")); - $showDay->setDbLastShow($endDate); - $showDay->setDbStartTime($startDateTime->format("H:i:s")); - $showDay->setDbTimezone(date_default_timezone_get()); - $showDay->setDbDuration($data['add_show_duration']); - $showDay->setDbRepeatType($repeatType); - $showDay->setDbShowId($showId); - $showDay->setDbRecord($isRecorded); - $showDay->save(); - } else { - foreach ($data['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(date_default_timezone_get()); - $showDay->setDbDuration($data['add_show_duration']); - $showDay->setDbDay($day); - $showDay->setDbRepeatType($repeatType); - $showDay->setDbShowId($showId); - $showDay->setDbRecord($isRecorded); - $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']) { - 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)) { - for ($i=1; $i<=10; $i++) { - if ($data['add_show_rebroadcast_date_'.$i]) { - $showRebroad = new CcShowRebroadcast(); - $showRebroad->setDbDayOffset($data['add_show_rebroadcast_date_'.$i]); - $showRebroad->setDbStartTime($data['add_show_rebroadcast_time_'.$i]); - $showRebroad->setDbShowId($showId); - $showRebroad->save(); - } - } - } elseif ($isRecorded && $data['add_show_rebroadcast'] && ($repeatType == -1)) { - for ($i=1; $i<=10; $i++) { - if ($data['add_show_rebroadcast_date_absolute_'.$i]) { - //$con = Propel::getConnection(CcShowPeer::DATABASE_NAME); - //$sql = "SELECT date '{$data['add_show_rebroadcast_date_absolute_'.$i]}' - date '{$data['add_show_start_date']}' "; - $sql = << - $data["add_show_rebroadcast_date_absolute_$i"], - 'start' => - $data['add_show_start_date']), "column" ); - - //$r = $con->query($sql); - //$offset_days = $r->fetchColumn(0); - - $showRebroad = new CcShowRebroadcast(); - $showRebroad->setDbDayOffset($offset_days." days"); - $showRebroad->setDbStartTime($data['add_show_rebroadcast_time_absolute_'.$i]); - $showRebroad->setDbShowId($showId); - $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) { - CcShowHostsQuery::create()->filterByDbShow($data['add_show_id'])->delete(); - } - 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(); - $showHost->setDbShow($showId); - $showHost->setDbHost($host); - $showHost->save(); - } - } - - if ($data['add_show_id'] != -1) { - $con = Propel::getConnection(CcSchedulePeer::DATABASE_NAME); - $con->beginTransaction(); - - - //current timesamp in UTC. - $current_timestamp = gmdate("Y-m-d H:i:s"); - - try { - //update the status flag in cc_schedule. - $instances = CcShowInstancesQuery::create() - ->filterByDbEnds($current_timestamp, Criteria::GREATER_THAN) - ->filterByDbShowId($data['add_show_id']) - ->find($con); - - foreach ($instances as $instance) { - $instance->updateScheduleStatus($con); - } - - $con->commit(); - } catch (Exception $e) { - $con->rollback(); - Logging::info("Couldn't update schedule status."); - Logging::info($e->getMessage()); - } - } - - Application_Model_Show::populateShowUntil($showId); - Application_Model_RabbitMq::PushSchedule(); - - return $showId; - } - - /** - * Generate repeating show instances for a single show up to the given date. - * It will always try to use enddate from DB but if that's empty, it will use - * time now. - * - * @param int $p_showId - */ - public static function populateShowUntil($p_showId) - { - $con = Propel::getConnection(); - $date = Application_Model_Preference::GetShowsPopulatedUntil(); - - if (is_null($date)) { - $p_populateUntilDateTime = new DateTime("now", new DateTimeZone('UTC')); - Application_Model_Preference::SetShowsPopulatedUntil($p_populateUntilDateTime); - } else { - $p_populateUntilDateTime = $date; - } - - $stmt = $con->prepare("SELECT * FROM cc_show_days WHERE show_id = :show_id"); - $stmt->bindParam(':show_id', $p_showId); - $stmt->execute(); - - $res = $stmt->fetchAll(); - - 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 - * is basically a dispatcher that looks at the show template, and sends it to the correct function - * so that Show Instance generation can begin. After the all show instances have been created, pushes - * the schedule to Pypo. - * - * @param array $p_showRow - * A row from cc_show_days table - * @param DateTime $p_populateUntilDateTime - * DateTime object in UTC time. - */ - 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 - if ($p_showDaysRow["repeat_type"] == -1) { - Application_Model_Show::populateNonRepeatingShow($p_showDaysRow, $p_populateUntilDateTime); - } elseif ($p_showDaysRow["repeat_type"] == 0) { - Application_Model_Show::populateRepeatingShow($p_showDaysRow, $p_populateUntilDateTime, 'P7D'); - } elseif ($p_showDaysRow["repeat_type"] == 1) { - Application_Model_Show::populateRepeatingShow($p_showDaysRow, $p_populateUntilDateTime, 'P14D'); - } elseif ($p_showDaysRow["repeat_type"] == 2) { - 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 - * rebroadcast dates, and so this function will create those as well. - * - * @param array $p_showRow - * A row from cc_show_days table - * @param DateTime $p_populateUntilDateTime - * DateTime object in UTC time. - */ - private static function populateNonRepeatingShow($p_showRow, $p_populateUntilDateTime) - { - $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"]; - $record = $p_showRow["record"]; - $timezone = $p_showRow["timezone"]; - $start = $first_show." ".$start_time; - - //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"); - - $show = new Application_Model_Show($show_id); - if ($show->hasInstance()) { - $ccShowInstance = $show->getInstance(); - $newInstance = false; - } else { - $ccShowInstance = new CcShowInstances(); - $newInstance = true; - } - - 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); - - if (!$newInstance) { - $showInstance->correctScheduleStartTimes(); - } - - $sql = "SELECT * FROM cc_show_rebroadcast WHERE show_id=:show_id"; - $rebroadcasts = Application_Common_Database::prepareAndExecute($sql, - array( ':show_id' => $show_id ), 'all'); - - if ($showInstance->isRecorded()) { - $showInstance->deleteRebroadcasts(); - self::createRebroadcastInstances($rebroadcasts, $currentUtcTimestamp, $show_id, $show_instance_id, $start, $duration, $timezone); - } - } - } - - /** - * Creates a 1 or more than 1 show instances (user has stated this show repeats). If the show - * is recorded, it may have multiple rebroadcast dates, and so this function will create - * those as well. - * - * @param array $p_showRow - * A row from cc_show_days table - * @param DateTime $p_populateUntilDateTime - * DateTime object in UTC time. "shows_populated_until" date YY-mm-dd in cc_pref - * @param string $p_interval - * Period of time between repeating shows (in php DateInterval notation 'P7D') - */ - private static function populateRepeatingShow($p_showDaysRow, $p_populateUntilDateTime, $p_interval) - { - $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 - $start_time = $p_showDaysRow["start_time"]; //non-UTC - $duration = $p_showDaysRow["duration"]; - $day = $p_showDaysRow["day"]; - $record = $p_showDaysRow["record"]; - $timezone = $p_showDaysRow["timezone"]; - - $currentUtcTimestamp = gmdate("Y-m-d H:i:s"); - - if (isset($next_pop_date)) { - $start = $next_pop_date." ".$start_time; - } else { - $start = $first_show." ".$start_time; - } - - $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; - - $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); - - while ($utcStartDateTime->getTimestamp() <= $p_populateUntilDateTime->getTimestamp() - && (is_null($utcLastShowDateTime) || $utcStartDateTime->getTimestamp() < $utcLastShowDateTime->getTimestamp())){ - - list($utcStartDateTime, $utcEndDateTime) = self::createUTCStartEndDateTime($start, $duration, $timezone); - - if ($show->hasInstanceOnDate($utcStartDateTime)) { - $ccShowInstance = $show->getInstanceOnDate($utcStartDateTime); - - if ($ccShowInstance->getDbModifiedInstance()) { - //show instance on this date has been deleted. - list($start, $utcStartDateTime) = self::advanceRepeatingDate($p_interval, $start, $timezone); - continue; - } - - $newInstance = false; - } 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) { - $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); - - /* If we are updating a show then make sure that the scheduled content within - * the show is updated to the correct time. */ - if (!$newInstance) { - $showInstance->correctScheduleStartTimes(); - } - - $showInstance->deleteRebroadcasts(); - self::createRebroadcastInstances($rebroadcasts, $currentUtcTimestamp, $show_id, $show_instance_id, $start, $duration, $timezone); - list($start, $utcStartDateTime) = self::advanceRepeatingDate($p_interval, $start, $timezone); - - } - - Application_Model_Show::setNextPop($start, $show_id, $day); - } - - private static function advanceRepeatingDate($p_interval, $start, $timezone) - { - $startDt = new DateTime($start, new DateTimeZone($timezone)); - if ($p_interval == 'P1M') { - /* When adding months, there is a problem if we are on January 31st and add one month with PHP. - * What ends up happening is that since February 31st doesn't exist, the date returned is - * March 3rd. For now let's ignore the day and assume we are always working with the - * first of each month, and use PHP to add 1 month to this (this will take care of rolling - * over the years 2011->2012, etc.). Then let's append the actual day, and use the php - * checkdate() function, to see if it is valid. If not, then we'll just skip this month. */ - - /* pass in only the year and month (not the day) */ - $dt = new DateTime($startDt->format("Y-m"), new DateTimeZone($timezone)); - - - /* Keep adding 1 month, until we find the next month that contains the day - * we are looking for (31st day for example) */ - do { - $dt->add(new DateInterval($p_interval)); - } while (!checkdate($dt->format("m"), $startDt->format("d"), $dt->format("Y"))); - - $dt->setDate($dt->format("Y"), $dt->format("m"), $startDt->format("d")); - - } else { - $dt = new DateTime($start, new DateTimeZone($timezone)); - $dt->add(new DateInterval($p_interval)); - } - - $start = $dt->format("Y-m-d H:i:s"); - - $dt->setTimezone(new DateTimeZone('UTC')); - $utcStartDateTime = $dt; - - return array($start, $utcStartDateTime); - } - - /* - * @param $p_start - * timestring format "Y-m-d H:i:s" (not UTC) - * @param $p_duration - * string time interval (h)h:(m)m(:ss) - * @param $p_timezone - * string "Europe/Prague" - * @param $p_offset - * array (days, hours, mins) used for rebroadcast shows. - * - * @return - * array of 2 DateTime objects, start/end time of the show in UTC. - */ - private static function createUTCStartEndDateTime($p_start, $p_duration, $p_timezone=null, $p_offset=null) - { - $timezone = $p_timezone ? $p_timezone : date_default_timezone_get(); - - $startDateTime = new DateTime($p_start, new DateTimeZone($timezone)); - if (isset($p_offset)) { - $startDateTime->add(new DateInterval("P{$p_offset["days"]}DT{$p_offset["hours"]}H{$p_offset["mins"]}M")); - } - //convert time to UTC - $startDateTime->setTimezone(new DateTimeZone('UTC')); - - $endDateTime = clone $startDateTime; - $duration = explode(":", $p_duration); - list($hours, $mins) = array_slice($duration, 0, 2); - $endDateTime->add(new DateInterval("PT{$hours}H{$mins}M")); - - return array($startDateTime, $endDateTime); - } - - /* Create rebroadcast instances for a created show marked for recording - * - * @param $p_rebroadcasts - * rows gotten from the db table cc_show_rebroadcasts, tells airtime when to schedule the rebroadcasts. - * @param $p_currentUtcTimestamp - * a timestring in format "Y-m-d H:i:s", current UTC time. - * @param $p_showId - * int of the show it belongs to (from cc_show) - * @param $p_showInstanceId - * the instance id of the created recorded show instance - * (from cc_show_instances), used to associate rebroadcasts to this show. - * @param $p_startTime - * a timestring in format "Y-m-d H:i:s" in the timezone, not UTC of the rebroadcasts' parent recorded show. - * @param $p_duration - * string time interval (h)h:(m)m:(ss) length of the show. - * @param $p_timezone - * string of user's timezone "Europe/Prague" - * - */ - private static function createRebroadcastInstances($p_rebroadcasts, $p_currentUtcTimestamp, $p_showId, $p_showInstanceId, $p_startTime, $p_duration, $p_timezone=null) - { - //Y-m-d - //use only the date part of the show start time stamp for the offsets to work properly. - $date = explode(" ", $p_startTime); - $start_date = $date[0]; - - foreach ($p_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) = Application_Model_Show::createUTCStartEndDateTime($start_date, $p_duration, $p_timezone, $offset); - - if ($utcStartDateTime->format("Y-m-d H:i:s") > $p_currentUtcTimestamp) { - - $newRebroadcastInstance = new CcShowInstances(); - $newRebroadcastInstance->setDbShowId($p_showId); - $newRebroadcastInstance->setDbStarts($utcStartDateTime); - $newRebroadcastInstance->setDbEnds($utcEndDateTime); - $newRebroadcastInstance->setDbRecord(0); - $newRebroadcastInstance->setDbRebroadcast(1); - $newRebroadcastInstance->setDbOriginalShow($p_showInstanceId); - $newRebroadcastInstance->save(); - } - } - } - - /** - * Get all the show instances in the given time range (inclusive). - * - * @param DateTime $start_timestamp - * In UTC time. - * @param DateTime $end_timestamp - * In UTC time. - * @param unknown_type $excludeInstance - * @param boolean $onlyRecord - * @return array - */ - public static function getShows($start_timestamp, $end_timestamp, $onlyRecord=FALSE) - { - //UTC DateTime object - $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); - Application_Model_Preference::SetShowsPopulatedUntil($end_timestamp); - } - - $sql = <<format("Y-m-d H:i:s"); - $end_string = $end_timestamp->format("Y-m-d H:i:s"); - if ($onlyRecord) { - $sql .= " AND (si1.starts >= :start::TIMESTAMP AND si1.starts < :end::TIMESTAMP)"; - $sql .= " AND (si1.record = 1)"; - - return Application_Common_Database::prepareAndExecute( $sql, - array( ':start' => $start_string, - ':end' => $end_string ), 'all'); - - } else { - $sql .= " ". <<= :start1::TIMESTAMP AND si1.starts < :end1::TIMESTAMP) - OR (si1.ends > :start2::TIMESTAMP AND si1.ends <= :end2::TIMESTAMP) - OR (si1.starts <= :start3::TIMESTAMP AND si1.ends >= :end3::TIMESTAMP)) -SQL; - return Application_Common_Database::prepareAndExecute( $sql, - array( - 'start1' => $start_string, - 'start2' => $start_string, - 'start3' => $start_string, - 'end1' => $end_string, - 'end2' => $end_string, - 'end3' => $end_string - ), 'all'); - } - } - - private static function setNextPop($next_date, $show_id, $day) - { - $nextInfo = explode(" ", $next_date); - - $repeatInfo = CcShowDaysQuery::create() - ->filterByDbShowId($show_id) - ->filterByDbDay($day) - ->findOne(); - - $repeatInfo->setDbNextPopDate($nextInfo[0]) - ->save(); - } - - /** - * Generate all the repeating shows in the given range. - * - * @param DateTime $p_startTimestamp - * In UTC format. - * @param DateTime $p_endTimestamp - * In UTC format. - */ - public static function populateAllShowsInRange($p_startTimestamp, $p_endTimestamp) - { - $con = Propel::getConnection(); - - $endTimeString = $p_endTimestamp->format("Y-m-d H:i:s"); - if (!is_null($p_startTimestamp)) { - $startTimeString = $p_startTimestamp->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"); - } - - $stmt = $con->prepare(" - SELECT * FROM cc_show_days - WHERE last_show IS NULL - OR first_show < :endTimeString AND last_show > :startTimeString"); - - $stmt->bindParam(':endTimeString', $endTimeString); - $stmt->bindParam(':startTimeString', $startTimeString); - $stmt->execute(); - - $res = $stmt->fetchAll(); - foreach ($res as $row) { - Application_Model_Show::populateShow($row, $p_endTimestamp); - } - } - - /** - * - * @param DateTime $start - * -in UTC time - * @param DateTime $end - * -in UTC time - * @param boolean $editable - */ - public static function &getFullCalendarEvents($p_start, $p_end, $p_editable=false) - { - $events = array(); - $interval = $p_start->diff($p_end); - $days = $interval->format('%a'); - $shows = Application_Model_Show::getShows($p_start, $p_end); - $content_count = Application_Model_ShowInstance::getContentCount( - $p_start, $p_end); - $isFull = Application_Model_ShowInstance::getIsFull($p_start, $p_end); - $timezone = date_default_timezone_get(); - $current_timezone = new DateTimeZone($timezone); - $utc = new DateTimeZone("UTC"); - $now = new DateTime("now", $utc); - - foreach ($shows as &$show) { - $options = array(); - - //only bother calculating percent for week or day view. - if (intval($days) <= 7) { - $options["percent"] = Application_Model_Show::getPercentScheduled($show["starts"], $show["ends"], $show["time_filled"]); - } - - if (isset($show["parent_starts"])) { - $parentStartsDT = new DateTime($show["parent_starts"], $utc); - } - - $startsDT = DateTime::createFromFormat("Y-m-d G:i:s", - $show["starts"],$utc); - $endsDT = DateTime::createFromFormat("Y-m-d G:i:s", - $show["ends"], $utc); - - if( $p_editable ) { - if ($show["record"] && $now > $startsDT) { - $options["editable"] = false; - } elseif ($show["rebroadcast"] && - $now > $parentStartsDT) { - $options["editable"] = false; - } elseif ($now < $endsDT) { - $options["editable"] = true; - } - } - - $startsDT->setTimezone($current_timezone); - $endsDT->setTimezone($current_timezone); - - $options["show_empty"] = (array_key_exists($show['instance_id'], - $content_count)) ? 0 : 1; - - $options["show_partial_filled"] = !$isFull[$show['instance_id']]; - - $event = array(); - - $event["id"] = intval($show["instance_id"]); - $event["title"] = $show["name"]; - $event["start"] = $startsDT->format("Y-m-d H:i:s"); - $event["end"] = $endsDT->format("Y-m-d H:i:s"); - $event["allDay"] = false; - $event["showId"] = intval($show["show_id"]); - $event["record"] = intval($show["record"]); - $event["rebroadcast"] = intval($show["rebroadcast"]); - $event["soundcloud_id"] = is_null($show["soundcloud_id"]) - ? -1 : $show["soundcloud_id"]; - - //event colouring - if ($show["color"] != "") { - $event["textColor"] = "#".$show["color"]; - } - - if ($show["background_color"] != "") { - $event["color"] = "#".$show["background_color"]; - } - - foreach ($options as $key => $value) { - $event[$key] = $value; - } - - $events[] = $event; - } - return $events; - } - - /** - * Calculates the percentage of a show scheduled given the start and end times in date/time format - * and the time_filled as the total time the schow is scheduled for in time format. - **/ - private static function getPercentScheduled($p_starts, $p_ends, $p_time_filled) - { - $durationSeconds = (strtotime($p_ends) - strtotime($p_starts)); - $time_filled = Application_Model_Schedule::WallTimeToMillisecs($p_time_filled) / 1000; - $percent = ceil(( $time_filled / $durationSeconds) * 100); - - return $percent; - } - -/* private static function &makeFullCalendarEvent(&$show, $options=array(), $startDateTime, $endDateTime, $startsEpoch, $endsEpoch) - { - $event = array(); - - $event["id"] = intval($show["instance_id"]); - $event["title"] = $show["name"]; - $event["start"] = $startDateTime->format("Y-m-d H:i:s"); - $event["startUnix"] = $startsEpoch; - $event["end"] = $endDateTime->format("Y-m-d H:i:s"); - $event["endUnix"] = $endsEpoch; - $event["allDay"] = false; - $event["showId"] = intval($show["show_id"]); - $event["record"] = intval($show["record"]); - $event["rebroadcast"] = intval($show["rebroadcast"]); - $event["soundcloud_id"] = is_null($show["soundcloud_id"]) - ? -1 : $show["soundcloud_id"]; - - //event colouring - if ($show["color"] != "") { - $event["textColor"] = "#".$show["color"]; - } - - if ($show["background_color"] != "") { - $event["color"] = "#".$show["background_color"]; - } - - foreach ($options as $key => $value) { - $event[$key] = $value; - } - - return $event; - }*/ - - /* Takes in a UTC DateTime object. - * Converts this to local time, since cc_show days - * requires local time. */ - public function setShowFirstShow($p_dt) - { - //clone object since we are modifying it and it was passed by reference. - $dt = clone $p_dt; - - $dt->setTimezone(new DateTimeZone(date_default_timezone_get())); - - $showDay = CcShowDaysQuery::create() - ->filterByDbShowId($this->_showId) - ->findOne(); - - $showDay->setDbFirstShow($dt)->setDbStartTime($dt) - ->save(); - - //Logging::info("setting show's first show."); - } - - /* Takes in a UTC DateTime object - * Converts this to local time, since cc_show days - * requires local time. */ - public function setShowLastShow($p_dt) - { - //clone object since we are modifying it and it was passed by reference. - $dt = clone $p_dt; - - $dt->setTimezone(new DateTimeZone(date_default_timezone_get())); - - //add one day since the Last Show date in CcShowDays is non-inclusive. - $dt->add(new DateInterval("P1D")); - - $showDay = CcShowDaysQuery::create() - ->filterByDbShowId($this->_showId) - ->findOne(); - - $showDay->setDbLastShow($dt) - ->save(); - } - - /** - * Given time $timeNow, returns the show being played right now. - * Times are all in UTC time. - * - * @param String $timeNow - current time (in UTC) - * @return array - show being played right now - */ - public static function getCurrentShow($timeNow=null) - { - $CC_CONFIG = Config::getConfig(); - $con = Propel::getConnection(); - if ($timeNow == null) { - $date = new Application_Common_DateHelper; - $timeNow = $date->getUtcTimestamp(); - } - //TODO, returning starts + ends twice (once with an alias). Unify this after the 2.0 release. --Martin - $sql = << :timeNow2::timestamp - AND modified_instance != TRUE -SQL; - - $stmt = $con->prepare($sql); - $stmt->bindParam(':timeNow1', $timeNow); - $stmt->bindParam(':timeNow2', $timeNow); - - if ($stmt->execute()) { - $rows = $stmt->fetchAll(); - } else { - $msg = implode(',', $stmt->errorInfo()); - throw new Exception("Error: $msg"); - } - - return $rows; - } - - /** - * Gets the current show, previous and next with an 2day window from - * the given timeNow, so timeNow-2days and timeNow+2days. - */ - public static function getPrevCurrentNext($p_timeNow) - { - $CC_CONFIG = Config::getConfig(); - $con = Propel::getConnection(); - // - //TODO, returning starts + ends twice (once with an alias). Unify this after the 2.0 release. --Martin - $sql = << :timeNow1::timestamp - INTERVAL '2 days' - AND si.ends < :timeNow2::timestamp + INTERVAL '2 days' - AND modified_instance != TRUE -ORDER BY si.starts -SQL; - - $stmt = $con->prepare($sql); - - $stmt->bindValue(':timeNow1', $p_timeNow); - $stmt->bindValue(':timeNow2', $p_timeNow); - - if ($stmt->execute()) { - $rows = $stmt->fetchAll(); - } else { - $msg = implode(',', $stmt->errorInfo()); - throw new Exception("Error: $msg"); - } - - $numberOfRows = count($rows); - - $results['previousShow'] = array(); - $results['currentShow'] = array(); - $results['nextShow'] = array(); - - $timeNowAsMillis = strtotime($p_timeNow); - - for ($i = 0; $i < $numberOfRows; ++$i) { - //Find the show that is within the current time. - if ((strtotime($rows[$i]['starts']) <= $timeNowAsMillis) - && (strtotime($rows[$i]['ends']) > $timeNowAsMillis)) { - if ($i-1 >= 0) { - $results['previousShow'][0] = array( - "id" => $rows[$i-1]['id'], - "instance_id" => $rows[$i-1]['instance_id'], - "name" => $rows[$i-1]['name'], - "url" => $rows[$i-1]['url'], - "start_timestamp" => $rows[$i-1]['start_timestamp'], - "end_timestamp" => $rows[$i-1]['end_timestamp'], - "starts" => $rows[$i-1]['starts'], - "ends" => $rows[$i-1]['ends'], - "record" => $rows[$i-1]['record'], - "type" => "show"); - } - - $results['currentShow'][0] = $rows[$i]; - - if (isset($rows[$i+1])) { - $results['nextShow'][0] = array( - "id" => $rows[$i+1]['id'], - "instance_id" => $rows[$i+1]['instance_id'], - "name" => $rows[$i+1]['name'], - "url" => $rows[$i+1]['url'], - "start_timestamp" => $rows[$i+1]['start_timestamp'], - "end_timestamp" => $rows[$i+1]['end_timestamp'], - "starts" => $rows[$i+1]['starts'], - "ends" => $rows[$i+1]['ends'], - "record" => $rows[$i+1]['record'], - "type" => "show"); - } - break; - } - //Previous is any row that ends after time now capture it in case we need it later. - if (strtotime($rows[$i]['ends']) < $timeNowAsMillis ) { - $previousShowIndex = $i; - } - //if we hit this we know we've gone to far and can stop looping. - if (strtotime($rows[$i]['starts']) > $timeNowAsMillis) { - $results['nextShow'][0] = array( - "id" => $rows[$i]['id'], - "instance_id" => $rows[$i]['instance_id'], - "name" => $rows[$i]['name'], - "url" => $rows[$i]['url'], - "start_timestamp" => $rows[$i]['start_timestamp'], - "end_timestamp" => $rows[$i]['end_timestamp'], - "starts" => $rows[$i]['starts'], - "ends" => $rows[$i]['ends'], - "record" => $rows[$i]['record'], - "type" => "show"); - break; - } - } - //If we didn't find a a current show because the time didn't fit we may still have - //found a previous show so use it. - if (count($results['previousShow']) == 0 && isset($previousShowIndex)) { - $results['previousShow'][0] = array( - "id" => $rows[$previousShowIndex]['id'], - "instance_id" => $rows[$previousShowIndex]['instance_id'], - "name" => $rows[$previousShowIndex]['name'], - "start_timestamp" => $rows[$previousShowIndex]['start_timestamp'], - "end_timestamp" => $rows[$previousShowIndex]['end_timestamp'], - "starts" => $rows[$previousShowIndex]['starts'], - "ends" => $rows[$previousShowIndex]['ends'], - "record" => $rows[$previousShowIndex]['record'], - "type" => "show"); - } - - return $results; - } - - /** - * Given a start time $timeStart and end time $timeEnd, returns the next $limit - * number of shows within the time interval - * If $timeEnd not given, shows within next 48 hours from $timeStart are returned - * If $limit not given, all shows within the intervals are returned - * Times are all in UTC time. - * - * @param String $timeStart - interval start time (in UTC) - * @param int $limit - number of shows to return - * @param String $timeEnd - interval end time (in UTC) - * @return array - the next $limit number of shows within the time interval - */ - public static function getNextShows($timeStart, $limit = "ALL", $timeEnd = "") - { - // defaults to retrieving shows from next 2 days if no end time has - // been specified - if ($timeEnd == "") { - $timeEnd = "'$timeStart' + INTERVAL '2 days'"; - } - - //TODO, returning starts + ends twice (once with an alias). Unify this after the 2.0 release. --Martin - $sql = <<= :timeStart::timestamp - AND si.starts < :timeEnd::timestamp - AND modified_instance != TRUE -ORDER BY si.starts -SQL; - - //PDO won't accept "ALL" as a limit value (complains it is not an - //integer, and so we must completely remove the limit clause if we - //want to show all results - MK - if ($limit != "ALL") { - $sql .= PHP_EOL."LIMIT :lim"; - $params = array( - ':timeStart' => $timeStart, - ':timeEnd' => $timeEnd, - ':lim' => $limit); - } else { - $params = array( - ':timeStart' => $timeStart, - ':timeEnd' => $timeEnd); - } - - return Application_Common_Database::prepareAndExecute( $sql, $params, 'all'); - } - - /** - * Convert the columns given in the array $columnsToConvert in the - * database result $rows to local timezone. - * - * @param type $rows arrays of arrays containing database query result - * @param type $columnsToConvert array of column names to convert - */ - public static function convertToLocalTimeZone(&$rows, $columnsToConvert) - { - if (!is_array($rows)) { - return; - } - foreach ($rows as &$row) { - foreach ($columnsToConvert as $column) { - $row[$column] = Application_Common_DateHelper::ConvertToLocalDateTimeString($row[$column]); - } - } - } - - public static function getMaxLengths() - { - $con = Propel::getConnection(); - $sql = << 0 -SQL; - $result = $con->query($sql)->fetchAll(); - $assocArray = array(); - foreach ($result as $row) { - $assocArray[$row['column_name']] = $row['character_maximum_length']; - } - return $assocArray; - } - - public static function getStartEndCurrentMonthView() { - $first_day_of_calendar_month_view = mktime(0, 0, 0, date("n"), 1); - $weekStart = Application_Model_Preference::GetWeekStartDay(); - while (date('w', $first_day_of_calendar_month_view) != $weekStart) { - $first_day_of_calendar_month_view -= 60*60*24; - } - $last_day_of_calendar_view = $first_day_of_calendar_month_view + 3600*24*42; - - $start = new DateTime("@".$first_day_of_calendar_month_view); - $end = new DateTime("@".$last_day_of_calendar_view); - - return array($start, $end); - } - - public static function getStartEndCurrentWeekView() { - $first_day_of_calendar_week_view = mktime(0, 0, 0, date("n"), date("j")); - $weekStart = Application_Model_Preference::GetWeekStartDay(); - while (date('w', $first_day_of_calendar_week_view) != $weekStart) { - $first_day_of_calendar_week_view -= 60*60*24; - } - $last_day_of_calendar_view = $first_day_of_calendar_week_view + 3600*24*7; - - $start = new DateTime("@".$first_day_of_calendar_week_view); - $end = new DateTime("@".$last_day_of_calendar_view); - - return array($start, $end); - } - - public static function getStartEndCurrentDayView() { - $today = mktime(0, 0, 0, date("n"), date("j")); - $tomorrow = $today + 3600*24; - - $start = new DateTime("@".$today); - $end = new DateTime("@".$tomorrow); - - return array($start, $end); - } -} diff --git a/airtime_mvc/application/models/airtime/CcShow.php b/airtime_mvc/application/models/airtime/CcShow.php index 12139a3ff..5e300f00c 100644 --- a/airtime_mvc/application/models/airtime/CcShow.php +++ b/airtime_mvc/application/models/airtime/CcShow.php @@ -163,6 +163,7 @@ class CcShow extends BaseCcShow { $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) { diff --git a/airtime_mvc/application/services/ShowService.php b/airtime_mvc/application/services/ShowService.php index c5e205e48..50707b3f8 100644 --- a/airtime_mvc/application/services/ShowService.php +++ b/airtime_mvc/application/services/ShowService.php @@ -836,7 +836,10 @@ SQL; $utcLastShowDateTime = $last_show ? Application_Common_DateHelper::ConvertToUtcDateTime($last_show, $timezone) : null; + $utcStartDateTime = new DateTime("now"); foreach ($datePeriod as $date) { + Logging::info($date); + Logging::info($duration); list($utcStartDateTime, $utcEndDateTime) = $this->createUTCStartEndDateTime( $date, $duration); /* From 1384c5d39d0e3f7573e61e4e73968ce130406de1 Mon Sep 17 00:00:00 2001 From: denise Date: Mon, 29 Apr 2013 15:57:59 -0400 Subject: [PATCH 70/73] Function call was missing an argument --- airtime_mvc/application/services/ShowService.php | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/airtime_mvc/application/services/ShowService.php b/airtime_mvc/application/services/ShowService.php index 50707b3f8..a829d88bb 100644 --- a/airtime_mvc/application/services/ShowService.php +++ b/airtime_mvc/application/services/ShowService.php @@ -206,7 +206,7 @@ class Application_Service_ShowService break; case REPEAT_MONTHLY_WEEKLY: $this->createRepeatingInstances($day, $populateUntil, REPEAT_MONTHLY_WEEKLY, - null, $fillInstances); + null, $daysAdded, $fillInstances); break; } } @@ -838,8 +838,6 @@ SQL; $utcStartDateTime = new DateTime("now"); foreach ($datePeriod as $date) { - Logging::info($date); - Logging::info($duration); list($utcStartDateTime, $utcEndDateTime) = $this->createUTCStartEndDateTime( $date, $duration); /* From 4ca60ca676e3199b90b81a25d203a06e32327f0e Mon Sep 17 00:00:00 2001 From: denise Date: Tue, 30 Apr 2013 13:58:03 -0400 Subject: [PATCH 71/73] CC-5074: Editing a linked instance sets incorrect schedule start times --- airtime_mvc/application/models/Scheduler.php | 3 --- .../models/airtime/CcShowInstances.php | 6 ++++++ .../application/services/SchedulerService.php | 9 +++++++-- airtime_mvc/application/services/ShowService.php | 16 ++++++++-------- 4 files changed, 21 insertions(+), 13 deletions(-) diff --git a/airtime_mvc/application/models/Scheduler.php b/airtime_mvc/application/models/Scheduler.php index 7aec81574..3778cf007 100644 --- a/airtime_mvc/application/models/Scheduler.php +++ b/airtime_mvc/application/models/Scheduler.php @@ -634,10 +634,7 @@ class Application_Model_Scheduler $pstart = microtime(true); //recalculate the start/end times after the inserted items. - Logging::info($excludeIds); - Logging::info($initalStartDT); foreach ($followingSchedItems as $item) { - Logging::info($item); $endTimeDT = $this->findEndTime($nextStartDT, $item->getDbClipLength()); $item->setDbStarts($nextStartDT); diff --git a/airtime_mvc/application/models/airtime/CcShowInstances.php b/airtime_mvc/application/models/airtime/CcShowInstances.php index fb886f684..6fdaaf8a2 100644 --- a/airtime_mvc/application/models/airtime/CcShowInstances.php +++ b/airtime_mvc/application/models/airtime/CcShowInstances.php @@ -185,4 +185,10 @@ class CcShowInstances extends BaseCcShowInstances { 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/services/SchedulerService.php b/airtime_mvc/application/services/SchedulerService.php index 99f2ae609..b8086e4a2 100644 --- a/airtime_mvc/application/services/SchedulerService.php +++ b/airtime_mvc/application/services/SchedulerService.php @@ -69,9 +69,14 @@ class Application_Service_SchedulerService ->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($ccSchedule->getDbStarts() + $diff) - ->setDbEnds($ccSchedule->getDbEnds() + $diff) + ->setDbStarts($newStart->format("Y-m-d H:i:s")) + ->setDbEnds($newEnd->format("Y-m-d H:i:s")) ->save(); } } diff --git a/airtime_mvc/application/services/ShowService.php b/airtime_mvc/application/services/ShowService.php index a829d88bb..f737cf3b6 100644 --- a/airtime_mvc/application/services/ShowService.php +++ b/airtime_mvc/application/services/ShowService.php @@ -52,18 +52,21 @@ class Application_Service_ShowService //so we can get the original start date and time $oldCcShow = CcShowQuery::create() ->findPk($showData["add_show_id"]); - $currentShowDay = $oldCcShow->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())); + $ccShowInstanceOrig = CcShowInstancesQuery::create() + ->findPk($showData["add_show_instance_id"]); $diff = $this->calculateShowStartDiff($newStartDateTime, - $currentShowDay->getLocalStartDateAndTime()); + $ccShowInstanceOrig->getLocalStartDateTime()); - Application_Service_SchedulerService::updateScheduleStartTime( - array($showData["add_show_instance_id"]), $diff); + if ($diff > 0) { + Application_Service_SchedulerService::updateScheduleStartTime( + array($showData["add_show_instance_id"]), $diff); + } /****** UPDATE SCHEDULE START TIME ENDS******/ $this->setCcShow($showData); @@ -89,10 +92,7 @@ class Application_Service_ShowService } //delete the edited instance from the repeating sequence - CcShowInstancesQuery::create() - ->findPk($showData["add_show_instance_id"]) - ->setDbModifiedInstance(true) - ->save(); + $ccShowInstanceOrig->setDbModifiedInstance(true)->save(); $service_showForm = new Application_Service_ShowFormService($showData["add_show_id"]); list($start, $end) = $service_showForm->getNextFutureRepeatShowTime(); From de4934a31745aa59bd83e5866f37b8a42e290645 Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Tue, 30 Apr 2013 15:00:31 -0400 Subject: [PATCH 72/73] ensure that uploaded file is UTF-8 encoded --- airtime_mvc/application/models/StoredFile.php | 3 +++ 1 file changed, 3 insertions(+) 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 From ec2f36efa8441befd1b8ab11b91ea6fbf0296fe1 Mon Sep 17 00:00:00 2001 From: denise Date: Tue, 30 Apr 2013 15:54:04 -0400 Subject: [PATCH 73/73] CC-5077: Calendar -> Context menu -> Show Content -> shows incorrect time filled on edited repeat instances - We weren't updating the time_filled column in cc_show_instances when creating the new show --- .../application/services/ShowFormService.php | 24 +++++++------------ .../application/services/ShowService.php | 3 +++ 2 files changed, 12 insertions(+), 15 deletions(-) diff --git a/airtime_mvc/application/services/ShowFormService.php b/airtime_mvc/application/services/ShowFormService.php index 2494b9c0d..e9cb8c5ea 100644 --- a/airtime_mvc/application/services/ShowFormService.php +++ b/airtime_mvc/application/services/ShowFormService.php @@ -343,22 +343,16 @@ class Application_Service_ShowFormService */ public function getNextFutureRepeatShowTime() { - $sql = << now() at time zone 'UTC' -AND show_id = :showId -AND modified_instance = FALSE -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')); - } + $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)); diff --git a/airtime_mvc/application/services/ShowService.php b/airtime_mvc/application/services/ShowService.php index f737cf3b6..b5806a638 100644 --- a/airtime_mvc/application/services/ShowService.php +++ b/airtime_mvc/application/services/ShowService.php @@ -91,6 +91,9 @@ class Application_Service_ShowService $ccSchedule->save(); } + $con = Propel::getConnection(CcShowInstancesPeer::DATABASE_NAME); + $ccShowInstance->updateDbTimeFilled($con); + //delete the edited instance from the repeating sequence $ccShowInstanceOrig->setDbModifiedInstance(true)->save();