diff --git a/.gitignore b/.gitignore index a14bfa6df..bc3c72ed9 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,2 @@ .* *.pyc -/files -build/build.properties diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index 937e8eb94..000000000 --- a/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "python_apps/pypo/liquidsoap_bin"] - path = python_apps/pypo/liquidsoap_bin - url = git://github.com/sourcefabric/airtime-liquidsoap.git diff --git a/.zfproject.xml b/.zfproject.xml index 1ff9e3914..1f805497f 100644 --- a/.zfproject.xml +++ b/.zfproject.xml @@ -36,7 +36,7 @@ - + @@ -304,7 +304,7 @@ - + diff --git a/CREDITS b/CREDITS index d303519ef..2594f4dc5 100644 --- a/CREDITS +++ b/CREDITS @@ -1,3 +1,32 @@ +======= +CREDITS +======= +Version 2.2.0 +------------- +Martin Konecny (martin.konecny@sourcefabric.org) + Role: Developer Team Lead + +Naomi Aro (naomi.aro@sourcefabric.org) + Role: Software Developer + +James Moon (james.moon@sourcefabric.org) + Role: Software Developer + +Denise Rigato (denise.rigato@sourcefabric.org) + Role: Software Developer + +Rudi Grinberg (rudi.grinberg@sourcefabric.org) + Role: Software Developer + +Cliff Wang (cliff.wang@sourcefabric.org) + Role: QA + +Mikayel Karapetian (michael.karapetian@sourcefabric.org) + Role: QA + +Daniel James (daniel.james@sourcefabric.org) + Role: Documentor & QA + ======= CREDITS ======= diff --git a/VERSION b/VERSION index 682777c6f..c7aac0e6d 100644 --- a/VERSION +++ b/VERSION @@ -1,2 +1,2 @@ PRODUCT_ID=Airtime -PRODUCT_RELEASE=2.1.3 +PRODUCT_RELEASE=2.2.0 diff --git a/airtime_mvc/application/Bootstrap.php b/airtime_mvc/application/Bootstrap.php index 8e9f875e8..cb35a8a9c 100644 --- a/airtime_mvc/application/Bootstrap.php +++ b/airtime_mvc/application/Bootstrap.php @@ -1,25 +1,23 @@ registerPlugin(new RabbitMqPlugin()); + /* The bootstrap class should only be used to initialize actions that return a view. Actions that return JSON will not use the bootstrap class! */ class Bootstrap extends Zend_Application_Bootstrap_Bootstrap @@ -50,13 +49,13 @@ class Bootstrap extends Zend_Application_Bootstrap_Bootstrap $view = $this->getResource('view'); $baseUrl = Zend_Controller_Front::getInstance()->getBaseUrl(); - $baseDir = dirname($_SERVER['SCRIPT_FILENAME']); $view->headLink()->appendStylesheet($baseUrl.'/css/redmond/jquery-ui-1.8.8.custom.css?'.$CC_CONFIG['airtime_version']); $view->headLink()->appendStylesheet($baseUrl.'/css/pro_dropdown_3.css?'.$CC_CONFIG['airtime_version']); $view->headLink()->appendStylesheet($baseUrl.'/css/qtip/jquery.qtip.min.css?'.$CC_CONFIG['airtime_version']); $view->headLink()->appendStylesheet($baseUrl.'/css/styles.css?'.$CC_CONFIG['airtime_version']); $view->headLink()->appendStylesheet($baseUrl.'/css/masterpanel.css?'.$CC_CONFIG['airtime_version']); + $view->headLink()->appendStylesheet($baseUrl.'/css/bootstrap.css?'.$CC_CONFIG['airtime_version']); } protected function _initHeadScript() @@ -65,38 +64,35 @@ class Bootstrap extends Zend_Application_Bootstrap_Bootstrap $view = $this->getResource('view'); $baseUrl = Zend_Controller_Front::getInstance()->getBaseUrl(); - $baseDir = dirname($_SERVER['SCRIPT_FILENAME']); - $view->headScript()->appendFile($baseUrl.'/js/libs/jquery-1.7.2.min.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); - $view->headScript()->appendFile($baseUrl.'/js/libs/jquery-ui-1.8.18.custom.min.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); - $view->headScript()->appendFile($baseUrl.'/js/libs/jquery.stickyPanel.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); - $view->headScript()->appendFile($baseUrl.'/js/qtip/jquery.qtip.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + $view->headScript()->appendFile($baseUrl.'/js/libs/jquery-1.7.2.min.js?'.$CC_CONFIG['airtime_version'], 'text/javascript'); + $view->headScript()->appendFile($baseUrl.'/js/libs/jquery-ui-1.8.18.custom.min.js?'.$CC_CONFIG['airtime_version'], 'text/javascript'); + $view->headScript()->appendFile($baseUrl.'/js/libs/jquery.stickyPanel.js?'.$CC_CONFIG['airtime_version'], 'text/javascript'); + $view->headScript()->appendFile($baseUrl.'/js/qtip/jquery.qtip.js?'.$CC_CONFIG['airtime_version'], 'text/javascript'); $view->headScript()->appendFile($baseUrl.'/js/jplayer/jquery.jplayer.min.js?'.$CC_CONFIG['airtime_version'], 'text/javascript'); $view->headScript()->appendFile($baseUrl.'/js/sprintf/sprintf-0.7-beta1.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + $view->headScript()->appendFile($baseUrl.'/js/bootstrap/bootstrap.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $view->headScript()->appendScript("var baseUrl='$baseUrl/'"); //scripts for now playing bar + $view->headScript()->appendFile($baseUrl.'/js/airtime/airtime_bootstrap.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $view->headScript()->appendFile($baseUrl.'/js/airtime/dashboard/helperfunctions.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $view->headScript()->appendFile($baseUrl.'/js/airtime/dashboard/dashboard.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $view->headScript()->appendFile($baseUrl.'/js/airtime/dashboard/versiontooltip.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $view->headScript()->appendFile($baseUrl.'/js/airtime/common/common.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + $view->headScript()->appendFile($baseUrl.'/js/airtime/common/audioplaytest.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); - $user = Application_Model_User::GetCurrentUser(); + $user = Application_Model_User::getCurrentUser(); if (!is_null($user)){ $userType = $user->getType(); } else { $userType = ""; } $view->headScript()->appendScript("var userType = '$userType';"); - if (Application_Model_Preference::GetPlanLevel() != "disabled" - && !($_SERVER['REQUEST_URI'] == '/Dashboard/stream-player' || $_SERVER['REQUEST_URI'] == '/audiopreview/audio-preview-player')) { - $client_id = Application_Model_Preference::GetClientId(); - $view->headScript()->appendScript("var livechat_client_id = '$client_id';"); - $view->headScript()->appendFile($baseUrl . '/js/airtime/common/livechat.js?'.$CC_CONFIG['airtime_version'], 'text/javascript'); - } - if(isset($CC_CONFIG['demo']) && $CC_CONFIG['demo'] == 1){ + + if (isset($CC_CONFIG['demo']) && $CC_CONFIG['demo'] == 1) { $view->headScript()->appendFile($baseUrl.'/js/libs/google-analytics.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); } } @@ -115,7 +111,11 @@ class Bootstrap extends Zend_Application_Bootstrap_Bootstrap protected function _initZFDebug() { - if (APPLICATION_ENV == "development"){ + + Zend_Controller_Front::getInstance()->throwExceptions(true); + + /* + if (APPLICATION_ENV == "development") { $autoloader = Zend_Loader_Autoloader::getInstance(); $autoloader->registerNamespace('ZFDebug'); @@ -131,11 +131,12 @@ class Bootstrap extends Zend_Application_Bootstrap_Bootstrap $frontController = $this->getResource('frontController'); $frontController->registerPlugin($debug); } + */ } protected function _initRouter() { - $front = Zend_Controller_Front::getInstance(); + $front = Zend_Controller_Front::getInstance(); $router = $front->getRouter(); $router->addRoute( diff --git a/airtime_mvc/application/common/Database.php b/airtime_mvc/application/common/Database.php new file mode 100644 index 000000000..2c61bc589 --- /dev/null +++ b/airtime_mvc/application/common/Database.php @@ -0,0 +1,57 @@ +prepare($sql); + foreach ($paramValueMap as $param => $v) { + $stmt->bindValue($param, $v); + } + $rows = array(); + if ($stmt->execute()) { + if ($type == 'single') { + $rows = $stmt->fetch($fetchType); + } else if ($type == 'column'){ + $rows = $stmt->fetchColumn(); + } else if ($type == 'all') { + $rows = $stmt->fetchAll($fetchType); + } else if ($type == 'execute') { + $rows = null; + } else { + $msg = "bad type passed: type($type)"; + throw new Exception("Error: $msg"); + } + } else { + $msg = implode(',', $stmt->errorInfo()); + throw new Exception("Error: $msg"); + } + return $rows; + } + /* + Wrapper around prepareAndExecute that allows you to use multipe :xx's + in one query. Transforms $sql to :xx1, :xx2, .... + */ + public static function smartPrepareAndExecute($sql, array $params, + $type='all', $fetchType=PDO::FETCH_ASSOC) + { + $new_params = array(); + $new_sql = $sql; + foreach ($params as $k => $v) { + $matches_count = substr_count($sql, $k); + if ($matches_count == 0) { + throw new Exception("Argument $k is not inside $sql"); + } elseif ($matches_count == 1) { + $new_params[$k] = $new_params[$v]; + } else { + foreach ( range(1,$matches_count) as $i ) { + preg_replace( "/$k(\D)/", "$k$i${1}", $sql, 1); + $new_params[ $k.$i ] = $v; + } + } + } + return Application_Common_Database::prepareAndExecute( $new_sql, + $new_params, $type, $fetchType); + } +} diff --git a/airtime_mvc/application/common/DateHelper.php b/airtime_mvc/application/common/DateHelper.php index 747b85868..c13543d8e 100644 --- a/airtime_mvc/application/common/DateHelper.php +++ b/airtime_mvc/application/common/DateHelper.php @@ -152,6 +152,11 @@ class Application_Common_DateHelper { return strtotime($time2) - strtotime($time1); } + + public static function TimeAdd($time1, $time2) + { + return strtotime($time2) + strtotime($time1); + } public static function ConvertMSToHHMMSSmm($time) { @@ -305,5 +310,112 @@ class Application_Common_DateHelper return new DateInterval("PT{$hour}H{$min}M{$sec}S"); } + + /** + * returns true or false depending on input is wether in + * valid range of SQL date/time + * @param string $p_datetime + * should be in format of '0000-00-00 00:00:00' + */ + public static function checkDateTimeRangeForSQL($p_datetime){ + $info = explode(' ', $p_datetime); + $dateInfo = explode('-', $info[0]); + if (isset($info[1])) { + $timeInfo = explode(':', $info[1]); + } + $retVal = array(); + $retVal["success"] = true; + + $year = $dateInfo[0]; + $month = $dateInfo[1]; + $day = $dateInfo[2]; + // if year is < 1753 or > 9999 it's out of range + if ($year < 1753) { + $retVal['success'] = false; + $retVal['errMsg'] = "The year '$year' must be within the range of 1753 - 9999"; + } else if (!checkdate($month, $day, $year)) { + $retVal['success'] = false; + $retVal['errMsg'] = "'$year-$month-$day' is not a valid date"; + } else { + // check time + if (isset($timeInfo)) { + if (isset($timeInfo[0]) && $timeInfo[0] != "") { + $hour = intval($timeInfo[0]); + } else { + $hour = -1; + } + + if (isset($timeInfo[1]) && $timeInfo[1] != "") { + $min = intval($timeInfo[1]); + } else { + $min = -1; + } + + if (isset($timeInfo[2]) && $timeInfo[2] != "") { + $sec = intval($timeInfo[2]); + } else { + $sec = -1; + } + + if ( ($hour < 0 || $hour > 23) || ($min < 0 || $min > 59) || ($sec < 0 || $sec > 59) ) { + $retVal['success'] = false; + $retVal['errMsg'] = "'$timeInfo[0]:$timeInfo[1]:$timeInfo[2]' is not a valid time"; + } + } + } + return $retVal; + } + + /** + * This function is used for calculations! Don't modify for display purposes! + * + * Convert playlist time value to float seconds + * + * @param string $plt + * playlist interval value (HH:mm:ss.dddddd) + * @return int + * seconds + */ + public static function playlistTimeToSeconds($plt) + { + $arr = preg_split('/:/', $plt); + if (isset($arr[2])) { + return (intval($arr[0])*60 + intval($arr[1]))*60 + floatval($arr[2]); + } + if (isset($arr[1])) { + return intval($arr[0])*60 + floatval($arr[1]); + } + + return floatval($arr[0]); + } + + + /** + * This function is used for calculations! Don't modify for display purposes! + * + * Convert float seconds value to playlist time format + * + * @param float $seconds + * @return string + * interval in playlist time format (HH:mm:ss.d) + */ + public static function secondsToPlaylistTime($p_seconds) + { + $info = explode('.', $p_seconds); + $seconds = $info[0]; + if (!isset($info[1])) { + $milliStr = 0; + } else { + $milliStr = $info[1]; + } + $hours = floor($seconds / 3600); + $seconds -= $hours * 3600; + $minutes = floor($seconds / 60); + $seconds -= $minutes * 60; + + $res = sprintf("%02d:%02d:%02d.%s", $hours, $minutes, $seconds, $milliStr); + + return $res; + } } diff --git a/airtime_mvc/application/configs/ACL.php b/airtime_mvc/application/configs/ACL.php index 6b44865ba..b89057194 100644 --- a/airtime_mvc/application/configs/ACL.php +++ b/airtime_mvc/application/configs/ACL.php @@ -10,31 +10,33 @@ $ccAcl->addRole(new Zend_Acl_Role('G')) ->addRole(new Zend_Acl_Role('A'), 'P'); $ccAcl->add(new Zend_Acl_Resource('library')) - ->add(new Zend_Acl_Resource('index')) - ->add(new Zend_Acl_Resource('user')) - ->add(new Zend_Acl_Resource('error')) + ->add(new Zend_Acl_Resource('index')) + ->add(new Zend_Acl_Resource('user')) + ->add(new Zend_Acl_Resource('error')) ->add(new Zend_Acl_Resource('login')) - ->add(new Zend_Acl_Resource('playlist')) - ->add(new Zend_Acl_Resource('plupload')) - ->add(new Zend_Acl_Resource('schedule')) - ->add(new Zend_Acl_Resource('api')) - ->add(new Zend_Acl_Resource('systemstatus')) + ->add(new Zend_Acl_Resource('playlist')) + ->add(new Zend_Acl_Resource('plupload')) + ->add(new Zend_Acl_Resource('schedule')) + ->add(new Zend_Acl_Resource('api')) + ->add(new Zend_Acl_Resource('systemstatus')) ->add(new Zend_Acl_Resource('dashboard')) ->add(new Zend_Acl_Resource('preference')) ->add(new Zend_Acl_Resource('showbuilder')) ->add(new Zend_Acl_Resource('playouthistory')) ->add(new Zend_Acl_Resource('usersettings')) - ->add(new Zend_Acl_Resource('audiopreview')); + ->add(new Zend_Acl_Resource('audiopreview')) + ->add(new Zend_Acl_Resource('webstream')); /** Creating permissions */ $ccAcl->allow('G', 'index') - ->allow('G', 'login') - ->allow('G', 'error') - ->allow('G', 'showbuilder') - ->allow('G', 'api') + ->allow('G', 'login') + ->allow('G', 'error') + ->allow('G', 'showbuilder') + ->allow('G', 'api') ->allow('G', 'schedule') ->allow('G', 'dashboard') ->allow('G', 'audiopreview') + ->allow('G', 'webstream') ->allow('H', 'preference', 'is-import-in-progress') ->allow('H', 'usersettings') ->allow('H', 'plupload') diff --git a/airtime_mvc/application/configs/airtime-conf.php b/airtime_mvc/application/configs/airtime-conf.php index 74936f1ca..5ec20343b 100644 --- a/airtime_mvc/application/configs/airtime-conf.php +++ b/airtime_mvc/application/configs/airtime-conf.php @@ -1,6 +1,6 @@ array ( diff --git a/airtime_mvc/application/configs/classmap-airtime-conf.php b/airtime_mvc/application/configs/classmap-airtime-conf.php index 692e0c3e4..caaf5c8d6 100644 --- a/airtime_mvc/application/configs/classmap-airtime-conf.php +++ b/airtime_mvc/application/configs/classmap-airtime-conf.php @@ -1,13 +1,6 @@ 'airtime/map/CcAccessTableMap.php', - 'CcAccessPeer' => 'airtime/CcAccessPeer.php', - 'CcAccess' => 'airtime/CcAccess.php', - 'CcAccessQuery' => 'airtime/CcAccessQuery.php', - 'BaseCcAccessPeer' => 'airtime/om/BaseCcAccessPeer.php', - 'BaseCcAccess' => 'airtime/om/BaseCcAccess.php', - 'BaseCcAccessQuery' => 'airtime/om/BaseCcAccessQuery.php', 'CcMusicDirsTableMap' => 'airtime/map/CcMusicDirsTableMap.php', 'CcMusicDirsPeer' => 'airtime/CcMusicDirsPeer.php', 'CcMusicDirs' => 'airtime/CcMusicDirs.php', @@ -78,6 +71,27 @@ return array ( 'BaseCcPlaylistcontentsPeer' => 'airtime/om/BaseCcPlaylistcontentsPeer.php', 'BaseCcPlaylistcontents' => 'airtime/om/BaseCcPlaylistcontents.php', 'BaseCcPlaylistcontentsQuery' => 'airtime/om/BaseCcPlaylistcontentsQuery.php', + 'CcBlockTableMap' => 'airtime/map/CcBlockTableMap.php', + 'CcBlockPeer' => 'airtime/CcBlockPeer.php', + 'CcBlock' => 'airtime/CcBlock.php', + 'CcBlockQuery' => 'airtime/CcBlockQuery.php', + 'BaseCcBlockPeer' => 'airtime/om/BaseCcBlockPeer.php', + 'BaseCcBlock' => 'airtime/om/BaseCcBlock.php', + 'BaseCcBlockQuery' => 'airtime/om/BaseCcBlockQuery.php', + 'CcBlockcontentsTableMap' => 'airtime/map/CcBlockcontentsTableMap.php', + 'CcBlockcontentsPeer' => 'airtime/CcBlockcontentsPeer.php', + 'CcBlockcontents' => 'airtime/CcBlockcontents.php', + 'CcBlockcontentsQuery' => 'airtime/CcBlockcontentsQuery.php', + 'BaseCcBlockcontentsPeer' => 'airtime/om/BaseCcBlockcontentsPeer.php', + 'BaseCcBlockcontents' => 'airtime/om/BaseCcBlockcontents.php', + 'BaseCcBlockcontentsQuery' => 'airtime/om/BaseCcBlockcontentsQuery.php', + 'CcBlockcriteriaTableMap' => 'airtime/map/CcBlockcriteriaTableMap.php', + 'CcBlockcriteriaPeer' => 'airtime/CcBlockcriteriaPeer.php', + 'CcBlockcriteria' => 'airtime/CcBlockcriteria.php', + 'CcBlockcriteriaQuery' => 'airtime/CcBlockcriteriaQuery.php', + 'BaseCcBlockcriteriaPeer' => 'airtime/om/BaseCcBlockcriteriaPeer.php', + 'BaseCcBlockcriteria' => 'airtime/om/BaseCcBlockcriteria.php', + 'BaseCcBlockcriteriaQuery' => 'airtime/om/BaseCcBlockcriteriaQuery.php', 'CcPrefTableMap' => 'airtime/map/CcPrefTableMap.php', 'CcPrefPeer' => 'airtime/CcPrefPeer.php', 'CcPref' => 'airtime/CcPref.php', @@ -155,4 +169,18 @@ return array ( 'BaseCcLiveLogPeer' => 'airtime/om/BaseCcLiveLogPeer.php', 'BaseCcLiveLog' => 'airtime/om/BaseCcLiveLog.php', 'BaseCcLiveLogQuery' => 'airtime/om/BaseCcLiveLogQuery.php', + 'CcWebstreamTableMap' => 'airtime/map/CcWebstreamTableMap.php', + 'CcWebstreamPeer' => 'airtime/CcWebstreamPeer.php', + 'CcWebstream' => 'airtime/CcWebstream.php', + 'CcWebstreamQuery' => 'airtime/CcWebstreamQuery.php', + 'BaseCcWebstreamPeer' => 'airtime/om/BaseCcWebstreamPeer.php', + 'BaseCcWebstream' => 'airtime/om/BaseCcWebstream.php', + 'BaseCcWebstreamQuery' => 'airtime/om/BaseCcWebstreamQuery.php', + 'CcWebstreamMetadataTableMap' => 'airtime/map/CcWebstreamMetadataTableMap.php', + 'CcWebstreamMetadataPeer' => 'airtime/CcWebstreamMetadataPeer.php', + 'CcWebstreamMetadata' => 'airtime/CcWebstreamMetadata.php', + 'CcWebstreamMetadataQuery' => 'airtime/CcWebstreamMetadataQuery.php', + 'BaseCcWebstreamMetadataPeer' => 'airtime/om/BaseCcWebstreamMetadataPeer.php', + 'BaseCcWebstreamMetadata' => 'airtime/om/BaseCcWebstreamMetadata.php', + 'BaseCcWebstreamMetadataQuery' => 'airtime/om/BaseCcWebstreamMetadataQuery.php', ); \ No newline at end of file diff --git a/airtime_mvc/application/configs/constants.php b/airtime_mvc/application/configs/constants.php index 1a39ddb43..1d1ed55e4 100644 --- a/airtime_mvc/application/configs/constants.php +++ b/airtime_mvc/application/configs/constants.php @@ -2,7 +2,7 @@ define('AIRTIME_COPYRIGHT_DATE', '2010-2012'); define('AIRTIME_REST_VERSION', '1.1'); -define('AIRTIME_API_VERSION', '1.0'); +define('AIRTIME_API_VERSION', '1.1'); // Metadata Keys for files define('MDATA_KEY_FILEPATH', 'filepath'); @@ -30,12 +30,16 @@ define('MDATA_KEY_BPM', 'bpm'); define('MDATA_KEY_TRACKNUMBER', 'track_number'); define('MDATA_KEY_CONDUCTOR', 'conductor'); define('MDATA_KEY_LANGUAGE', 'language'); +define('MDATA_KEY_REPLAYGAIN', 'replay_gain'); +define('MDATA_KEY_OWNER_ID', 'owner_id'); define('UI_MDATA_VALUE_FORMAT_FILE', 'File'); define('UI_MDATA_VALUE_FORMAT_STREAM', 'live stream'); // Session Keys -define('UI_PLAYLIST_SESSNAME', 'PLAYLIST'); +define('UI_PLAYLISTCONTROLLER_OBJ_SESSNAME', 'PLAYLISTCONTROLLER_OBJ'); +/*define('UI_PLAYLIST_SESSNAME', 'PLAYLIST'); +define('UI_BLOCK_SESSNAME', 'BLOCK');*/ // Soundcloud contants diff --git a/airtime_mvc/application/configs/navigation.php b/airtime_mvc/application/configs/navigation.php index 878920901..724fa4c40 100644 --- a/airtime_mvc/application/configs/navigation.php +++ b/airtime_mvc/application/configs/navigation.php @@ -8,38 +8,38 @@ * the navigation container below. */ $pages = array( - array( + array( 'label' => 'Now Playing', 'module' => 'default', 'controller' => 'Showbuilder', 'action' => 'index', - 'resource' => 'showbuilder' - ), - array( - 'label' => 'Add Media', - 'module' => 'default', - 'controller' => 'Plupload', - 'action' => 'index', - 'resource' => 'plupload' - ), - array( - 'label' => 'Playlist Builder', - 'module' => 'default', - 'controller' => 'Playlist', - 'action' => 'index', - 'resource' => 'playlist' - ), - array( + 'resource' => 'showbuilder' + ), + array( + 'label' => 'Add Media', + 'module' => 'default', + 'controller' => 'Plupload', + 'action' => 'index', + 'resource' => 'plupload' + ), + array( + 'label' => 'Library', + 'module' => 'default', + 'controller' => 'Library', + 'action' => 'index', + 'resource' => 'playlist' + ), + array( 'label' => 'Calendar', 'module' => 'default', 'controller' => 'Schedule', 'action' => 'index', - 'resource' => 'schedule' - ), + 'resource' => 'schedule' + ), array( 'label' => 'System', - 'uri' => '#', - 'resource' => 'preference', + 'uri' => '#', + 'resource' => 'preference', 'pages' => array( array( 'label' => 'Preferences', @@ -51,14 +51,14 @@ $pages = array( 'module' => 'default', 'controller' => 'user', 'action' => 'add-user', - 'resource' => 'user' + 'resource' => 'user' ), array( 'label' => 'Media Folders', 'module' => 'default', 'controller' => 'Preference', 'action' => 'directory-config', - 'id' => 'manage_folder' + 'id' => 'manage_folder' ), array( 'label' => 'Streams', @@ -77,28 +77,28 @@ $pages = array( 'module' => 'default', 'controller' => 'systemstatus', 'action' => 'index', - 'resource' => 'systemstatus' + 'resource' => 'systemstatus' ), - array( - 'label' => 'Playout History', - 'module' => 'default', - 'controller' => 'playouthistory', - 'action' => 'index', - 'resource' => 'playouthistory' - ) + array( + 'label' => 'Playout History', + 'module' => 'default', + 'controller' => 'playouthistory', + 'action' => 'index', + 'resource' => 'playouthistory' + ) ) ), - array( - 'label' => 'Help', - 'uri' => '#', - 'resource' => 'dashboard', + array( + 'label' => 'Help', + 'uri' => '#', + 'resource' => 'dashboard', 'pages' => array( array( 'label' => 'Getting Started', 'module' => 'default', 'controller' => 'dashboard', 'action' => 'help', - 'resource' => 'dashboard' + 'resource' => 'dashboard' ), array( 'label' => 'User Manual', @@ -110,10 +110,10 @@ $pages = array( 'module' => 'default', 'controller' => 'dashboard', 'action' => 'about', - 'resource' => 'dashboard' + 'resource' => 'dashboard' ) ) - ) + ) ); diff --git a/airtime_mvc/application/controllers/ApiController.php b/airtime_mvc/application/controllers/ApiController.php index 8d9d1d8f4..1a1876ce9 100644 --- a/airtime_mvc/application/controllers/ApiController.php +++ b/airtime_mvc/application/controllers/ApiController.php @@ -5,67 +5,65 @@ class ApiController extends Zend_Controller_Action public function init() { + $ignoreAuth = array("live-info", "week-info"); + + $params = $this->getRequest()->getParams(); + if (!in_array($params['action'], $ignoreAuth)) { + $this->checkAuth(); + } /* Initialize action controller here */ $context = $this->_helper->getHelper('contextSwitch'); - $context->addActionContext('version', 'json') - ->addActionContext('recorded-shows', 'json') - ->addActionContext('calendar-init', 'json') - ->addActionContext('upload-file', 'json') - ->addActionContext('upload-recorded', 'json') - ->addActionContext('media-monitor-setup', 'json') - ->addActionContext('media-item-status', 'json') - ->addActionContext('reload-metadata', 'json') - ->addActionContext('list-all-files', 'json') - ->addActionContext('list-all-watched-dirs', 'json') - ->addActionContext('add-watched-dir', 'json') - ->addActionContext('remove-watched-dir', 'json') - ->addActionContext('set-storage-dir', 'json') - ->addActionContext('get-stream-setting', 'json') - ->addActionContext('status', 'json') - ->addActionContext('register-component', 'json') - ->addActionContext('update-liquidsoap-status', 'json') - ->addActionContext('live-chat', 'json') - ->addActionContext('update-file-system-mount', 'json') - ->addActionContext('handle-watched-dir-missing', 'json') - ->addActionContext('rabbitmq-do-push', 'json') - ->addActionContext('check-live-stream-auth', 'json') - ->addActionContext('update-source-status', 'json') - ->addActionContext('get-bootstrap-info', 'json') + $context->addActionContext('version' , 'json') + ->addActionContext('recorded-shows' , 'json') + ->addActionContext('calendar-init' , 'json') + ->addActionContext('upload-file' , 'json') + ->addActionContext('upload-recorded' , 'json') + ->addActionContext('media-monitor-setup' , 'json') + ->addActionContext('media-item-status' , 'json') + ->addActionContext('reload-metadata' , 'json') + ->addActionContext('list-all-files' , 'json') + ->addActionContext('list-all-watched-dirs' , 'json') + ->addActionContext('add-watched-dir' , 'json') + ->addActionContext('remove-watched-dir' , 'json') + ->addActionContext('set-storage-dir' , 'json') + ->addActionContext('get-stream-setting' , 'json') + ->addActionContext('status' , 'json') + ->addActionContext('register-component' , 'json') + ->addActionContext('update-liquidsoap-status' , 'json') + ->addActionContext('live-chat' , 'json') + ->addActionContext('update-file-system-mount' , 'json') + ->addActionContext('handle-watched-dir-missing' , 'json') + ->addActionContext('rabbitmq-do-push' , 'json') + ->addActionContext('check-live-stream-auth' , 'json') + ->addActionContext('update-source-status' , 'json') + ->addActionContext('get-bootstrap-info' , 'json') + ->addActionContext('get-files-without-replay-gain' , 'json') + ->addActionContext('reload-metadata-group' , 'json') + ->addActionContext('notify-webstream-data' , 'json') ->initContext(); } - public function indexAction() - { - // action body - } - - /** - * Returns Airtime version. i.e "1.7.0-beta" - * - * First checks to ensure the correct API key was - * supplied, then returns AIRTIME_VERSION as defined - * in the database - * - * @return void - * - */ - public function versionAction() + public function checkAuth() { global $CC_CONFIG; - - // disable the view and the layout - $this->view->layout()->disableLayout(); - $this->_helper->viewRenderer->setNoRender(true); - $api_key = $this->_getParam('api_key'); + if (!in_array($api_key, $CC_CONFIG["apiKey"]) && - is_null(Zend_Auth::getInstance()->getStorage()->read())) - { + is_null(Zend_Auth::getInstance()->getStorage()->read())) { header('HTTP/1.0 401 Unauthorized'); print 'You are not allowed to access this resource.'; exit; } - $jsonStr = json_encode(array("version"=>Application_Model_Preference::GetAirtimeVersion())); + } + + public function versionAction() + { + // disable the view and the layout + $this->view->layout()->disableLayout(); + $this->_helper->viewRenderer->setNoRender(true); + + $jsonStr = json_encode( array( + "version" => Application_Model_Preference::GetAirtimeVersion())); echo $jsonStr; } @@ -73,22 +71,24 @@ class ApiController extends Zend_Controller_Action * Sets up and send init values used in the Calendar. * This is only being used by schedule.js at the moment. */ - public function calendarInitAction(){ - $this->view->layout()->disableLayout(); + public function calendarInitAction() + { + $this->view->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); - if(is_null(Zend_Auth::getInstance()->getStorage()->read())) { + if (is_null(Zend_Auth::getInstance()->getStorage()->read())) { header('HTTP/1.0 401 Unauthorized'); print 'You are not allowed to access this resource.'; + return; } - $this->view->calendarInit = array( - "timestamp" => time(), - "timezoneOffset" => date("Z"), - "timeScale" => Application_Model_Preference::GetCalendarTimeScale(), - "timeInterval" => Application_Model_Preference::GetCalendarTimeInterval(), - "weekStartDay" => Application_Model_Preference::GetWeekStartDay() + $this->view->calendarInit = array( + "timestamp" => time(), + "timezoneOffset" => date("Z"), + "timeScale" => Application_Model_Preference::GetCalendarTimeScale(), + "timeInterval" => Application_Model_Preference::GetCalendarTimeInterval(), + "weekStartDay" => Application_Model_Preference::GetWeekStartDay() ); } @@ -100,75 +100,50 @@ class ApiController extends Zend_Controller_Action */ public function getMediaAction() { - global $CC_CONFIG; - // disable the view and the layout $this->view->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); - $api_key = $this->_getParam('api_key'); + $fileId = $this->_getParam("file"); - if(!in_array($api_key, $CC_CONFIG["apiKey"]) && - is_null(Zend_Auth::getInstance()->getStorage()->read())) - { - header('HTTP/1.0 401 Unauthorized'); - print 'You are not allowed to access this resource.'; - Logging::log("401 Unauthorized"); - return; - } - - $fileID = $this->_getParam("file"); - $file_id = substr($fileID, 0, strpos($fileID, ".")); - - if (ctype_alnum($file_id) && strlen($file_id) == 32) - { - $media = Application_Model_StoredFile::RecallByGunid($file_id); - if ( $media != null ) - { - - $filepath = $media->getFilePath(); - if(is_file($filepath)){ - $full_path = $media->getPropelOrm()->getDbFilepath(); - - $file_base_name = strrchr($full_path, '/'); - /* If $full_path does not contain a '/', strrchr will return false, - * in which case we can use $full_path as the base name. - */ - if (!$file_base_name) { - $file_base_name = $full_path; - } else { - $file_base_name = substr($file_base_name, 1); - } + $media = Application_Model_StoredFile::Recall($fileId); + if ($media != null) { - // possibly use fileinfo module here in the future. - // http://www.php.net/manual/en/book.fileinfo.php - $ext = pathinfo($fileID, PATHINFO_EXTENSION); - //Download user left clicks a track and selects Download. - if ("true" == $this->_getParam('download')){ - //path_info breaks up a file path into seperate pieces of informaiton. - //We just want the basename which is the file name with the path - //information stripped away. We are using Content-Disposition to specify - //to the browser what name the file should be saved as. - // - // By james.moon: - // I'm removing pathinfo() since it strips away UTF-8 characters. - // Using manualy parsing - header('Content-Disposition: attachment; filename="'.$file_base_name.'"'); - }else{ - //user clicks play button for track and downloads it. - header('Content-Disposition: inline; filename="'.$file_base_name.'"'); - } - if (strtolower($ext) === 'mp3'){ - $this->smartReadFile($filepath, 'audio/mpeg'); - } else { - $this->smartReadFile($filepath, 'audio/'.$ext); - } - exit; - }else{ - header ("HTTP/1.1 404 Not Found"); + $filepath = $media->getFilePath(); + // Make sure we don't have some wrong result beecause of caching + clearstatcache(); + if (is_file($filepath)) { + $full_path = $media->getPropelOrm()->getDbFilepath(); + + $file_base_name = strrchr($full_path, '/'); + /* If $full_path does not contain a '/', strrchr will return false, + * in which case we can use $full_path as the base name. + */ + if (!$file_base_name) { + $file_base_name = $full_path; + } else { + $file_base_name = substr($file_base_name, 1); } + + //Download user left clicks a track and selects Download. + if ("true" == $this->_getParam('download')) { + //path_info breaks up a file path into seperate pieces of informaiton. + //We just want the basename which is the file name with the path + //information stripped away. We are using Content-Disposition to specify + //to the browser what name the file should be saved as. + header('Content-Disposition: attachment; filename="'.$file_base_name.'"'); + } else { + //user clicks play button for track and downloads it. + header('Content-Disposition: inline; filename="'.$file_base_name.'"'); + } + + $this->smartReadFile($filepath, $media->getPropelOrm()->getDbMime()); + exit; + } else { + header ("HTTP/1.1 404 Not Found"); } } + return; } @@ -184,39 +159,33 @@ class ApiController extends Zend_Controller_Action * @link https://groups.google.com/d/msg/jplayer/nSM2UmnSKKA/Hu76jDZS4xcJ * @link http://php.net/manual/en/function.readfile.php#86244 */ - function smartReadFile($location, $mimeType = 'audio/mp3') + public function smartReadFile($location, $mimeType = 'audio/mp3') { $size= filesize($location); $time= date('r', filemtime($location)); $fm = @fopen($location, 'rb'); - if (!$fm) - { + if (!$fm) { header ("HTTP/1.1 505 Internal server error"); + return; } - $begin= 0; - $end= $size - 1; + $begin = 0; + $end = $size - 1; - if (isset($_SERVER['HTTP_RANGE'])) - { - if (preg_match('/bytes=\h*(\d+)-(\d*)[\D.*]?/i', $_SERVER['HTTP_RANGE'], $matches)) - { + if (isset($_SERVER['HTTP_RANGE'])) { + if (preg_match('/bytes=\h*(\d+)-(\d*)[\D.*]?/i', $_SERVER['HTTP_RANGE'], $matches)) { $begin = intval($matches[1]); - if (!empty($matches[2])) - { + if (!empty($matches[2])) { $end = intval($matches[2]); } } } - if (isset($_SERVER['HTTP_RANGE'])) - { + if (isset($_SERVER['HTTP_RANGE'])) { header('HTTP/1.1 206 Partial Content'); - } - else - { + } else { header('HTTP/1.1 200 OK'); } header("Content-Type: $mimeType"); @@ -224,8 +193,7 @@ class ApiController extends Zend_Controller_Action header('Pragma: no-cache'); header('Accept-Ranges: bytes'); header('Content-Length:' . (($end - $begin) + 1)); - if (isset($_SERVER['HTTP_RANGE'])) - { + if (isset($_SERVER['HTTP_RANGE'])) { header("Content-Range: bytes $begin-$end/$size"); } header("Content-Transfer-Encoding: binary"); @@ -239,8 +207,7 @@ class ApiController extends Zend_Controller_Action $cur = $begin; fseek($fm, $begin, 0); - while(!feof($fm) && $cur <= $end && (connection_status() == 0)) - { + while (!feof($fm) && $cur <= $end && (connection_status() == 0)) { echo fread($fm, min(1024 * 16, ($end - $cur) + 1)); $cur += 1024 * 16; } @@ -263,44 +230,54 @@ class ApiController extends Zend_Controller_Action */ public function liveInfoAction() { - if (Application_Model_Preference::GetAllow3rdPartyApi()){ + if (Application_Model_Preference::GetAllow3rdPartyApi()) { // disable the view and the layout $this->view->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); $date = new Application_Common_DateHelper; $utcTimeNow = $date->getUtcTimestamp(); - $utcTimeEnd = ""; // if empty, GetNextShows will use interval instead of end of day + $utcTimeEnd = ""; // if empty, getNextShows will use interval instead of end of day $request = $this->getRequest(); $type = $request->getParam('type'); - if($type == "endofday") { - // make GetNextShows use end of day + /* This is some *extremely* lazy programming that needs to bi fixed. For some reason + * we are using two entirely different codepaths for very similar functionality (type = endofday + * vs type = interval). Needs to be fixed for 2.3 - MK */ + if ($type == "endofday") { + $limit = $request->getParam('limit'); + if ($limit == "" || !is_numeric($limit)) { + $limit = "5"; + } + + // make getNextShows use end of day $utcTimeEnd = Application_Common_DateHelper::GetDayEndTimestampInUtc(); $result = array("env"=>APPLICATION_ENV, "schedulerTime"=>gmdate("Y-m-d H:i:s"), - "nextShow"=>Application_Model_Show::GetNextShows($utcTimeNow, 5, $utcTimeEnd)); - - Application_Model_Show::ConvertToLocalTimeZone($result["nextShow"], array("starts", "ends", "start_timestamp", "end_timestamp")); - }else{ - - $limit = $request->getParam('limit'); - if($limit == "" || !is_numeric($limit)) { - $limit = "5"; - } - - $result = Application_Model_Schedule::GetPlayOrderRange(); - - //Convert from UTC to localtime for user. - Application_Model_Show::ConvertToLocalTimeZone($result["currentShow"], array("starts", "ends", "start_timestamp", "end_timestamp")); - Application_Model_Show::ConvertToLocalTimeZone($result["nextShow"], array("starts", "ends", "start_timestamp", "end_timestamp")); - } - - $result['AIRTIME_API_VERSION'] = AIRTIME_API_VERSION; //used by caller to determine if the airtime they are running or widgets in use is out of date. + "currentShow"=>Application_Model_Show::getCurrentShow($utcTimeNow), + "nextShow"=>Application_Model_Show::getNextShows($utcTimeNow, $limit, $utcTimeEnd) + ); - //echo json_encode($result); + Application_Model_Show::convertToLocalTimeZone($result["currentShow"], + array("starts", "ends", "start_timestamp", "end_timestamp")); + Application_Model_Show::convertToLocalTimeZone($result["nextShow"], + array("starts", "ends", "start_timestamp", "end_timestamp")); + } else { + $result = Application_Model_Schedule::GetPlayOrderRange(); + + //Convert from UTC to localtime for Web Browser. + Application_Model_Show::ConvertToLocalTimeZone($result["currentShow"], + array("starts", "ends", "start_timestamp", "end_timestamp")); + Application_Model_Show::ConvertToLocalTimeZone($result["nextShow"], + array("starts", "ends", "start_timestamp", "end_timestamp")); + } + + //used by caller to determine if the airtime they are running or widgets in use is out of date. + $result['AIRTIME_API_VERSION'] = AIRTIME_API_VERSION; header("Content-type: text/javascript"); - echo $_GET['callback'].'('.json_encode($result).')'; + + // If a callback is not given, then just provide the raw JSON. + echo isset($_GET['callback']) ? $_GET['callback'].'('.json_encode($result).')' : json_encode($result); } else { header('HTTP/1.0 401 Unauthorized'); print 'You are not allowed to access this resource. '; @@ -310,7 +287,7 @@ class ApiController extends Zend_Controller_Action public function weekInfoAction() { - if (Application_Model_Preference::GetAllow3rdPartyApi()){ + if (Application_Model_Preference::GetAllow3rdPartyApi()) { // disable the view and the layout $this->view->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); @@ -319,21 +296,27 @@ class ApiController extends Zend_Controller_Action $dayStart = $date->getWeekStartDate(); $utcDayStart = Application_Common_DateHelper::ConvertToUtcDateTimeString($dayStart); - $dow = array("monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"); + $dow = array("monday", "tuesday", "wednesday", "thursday", "friday", + "saturday", "sunday"); $result = array(); - for ($i=0; $i<7; $i++){ + for ($i=0; $i<7; $i++) { $utcDayEnd = Application_Common_DateHelper::GetDayEndTimestamp($utcDayStart); - $shows = Application_Model_Show::GetNextShows($utcDayStart, "0", $utcDayEnd); + $shows = Application_Model_Show::getNextShows($utcDayStart, "ALL", $utcDayEnd); $utcDayStart = $utcDayEnd; - Application_Model_Show::ConvertToLocalTimeZone($shows, array("starts", "ends", "start_timestamp", "end_timestamp")); + Application_Model_Show::convertToLocalTimeZone($shows, + array("starts", "ends", "start_timestamp", + "end_timestamp")); $result[$dow[$i]] = $shows; } - $result['AIRTIME_API_VERSION'] = AIRTIME_API_VERSION; //used by caller to determine if the airtime they are running or widgets in use is out of date. + + //used by caller to determine if the airtime they are running or widgets in use is out of date. + $result['AIRTIME_API_VERSION'] = AIRTIME_API_VERSION; header("Content-type: text/javascript"); - echo $_GET['callback'].'('.json_encode($result).')'; + // If a callback is not given, then just provide the raw JSON. + echo isset($_GET['callback']) ? $_GET['callback'].'('.json_encode($result).')' : json_encode($result); } else { header('HTTP/1.0 401 Unauthorized'); print 'You are not allowed to access this resource. '; @@ -343,96 +326,79 @@ class ApiController extends Zend_Controller_Action public function scheduleAction() { - global $CC_CONFIG; - // disable the view and the layout $this->view->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); - $api_key = $this->_getParam('api_key'); - - if(!in_array($api_key, $CC_CONFIG["apiKey"]) && - is_null(Zend_Auth::getInstance()->getStorage()->read())) - { - header('HTTP/1.0 401 Unauthorized'); - print 'You are not allowed to access this resource. '; - exit; - } - - $data = Application_Model_Schedule::GetScheduledPlaylists(); + $data = Application_Model_Schedule::getSchedule(); + header("Content-Type: application/json"); echo json_encode($data, JSON_FORCE_OBJECT); } public function notifyMediaItemStartPlayAction() { - global $CC_CONFIG; - // disable the view and the layout $this->view->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); - $api_key = $this->_getParam('api_key'); - if(!in_array($api_key, $CC_CONFIG["apiKey"]) && - is_null(Zend_Auth::getInstance()->getStorage()->read())) - { - header('HTTP/1.0 401 Unauthorized'); - print 'You are not allowed to access this resource.'; - exit; + $media_id = $this->_getParam("media_id"); + Logging::debug("Received notification of new media item start: $media_id"); + Application_Model_Schedule::UpdateMediaPlayedStatus($media_id); + + //set a 'last played' timestamp for media item + //needed for smart blocks + try { + $mediaType = Application_Model_Schedule::GetType($media_id); + if ($mediaType == 'file') { + $file_id = Application_Model_Schedule::GetFileId($media_id); + if (!is_null($file_id)) { + //we are dealing with a file not a stream + $file = Application_Model_StoredFile::Recall($file_id); + $now = new DateTime("now", new DateTimeZone("UTC")); + $file->setLastPlayedTime($now); + } + } else { + // webstream + $stream_id = Application_Model_Schedule::GetStreamId($media_id); + if (!is_null($stream_id)) { + $webStream = new Application_Model_Webstream($stream_id); + $now = new DateTime("now", new DateTimeZone("UTC")); + $webStream->setLastPlayed($now); + } + } + } catch (Exception $e) { + Logging::info($e); } - $schedule_group_id = $this->_getParam("schedule_id"); - $media_id = $this->_getParam("media_id"); - $result = Application_Model_Schedule::UpdateMediaPlayedStatus($media_id); echo json_encode(array("status"=>1, "message"=>"")); } public function recordedShowsAction() { - global $CC_CONFIG; - - $api_key = $this->_getParam('api_key'); - if (!in_array($api_key, $CC_CONFIG["apiKey"]) && - is_null(Zend_Auth::getInstance()->getStorage()->read())) - { - header('HTTP/1.0 401 Unauthorized'); - print 'You are not allowed to access this resource.'; - exit; - } - $today_timestamp = date("Y-m-d H:i:s"); - $now = new DateTime($today_timestamp); - $end_timestamp = $now->add(new DateInterval("PT2H")); - $end_timestamp = $end_timestamp->format("Y-m-d H:i:s"); - - $this->view->shows = Application_Model_Show::getShows(Application_Common_DateHelper::ConvertToUtcDateTime($today_timestamp, date_default_timezone_get()), - Application_Common_DateHelper::ConvertToUtcDateTime($end_timestamp, date_default_timezone_get()), - $excludeInstance=NULL, $onlyRecord=TRUE); + $now = new DateTime($today_timestamp); + $end_timestamp = $now->add(new DateInterval("PT2H")); + $end_timestamp = $end_timestamp->format("Y-m-d H:i:s"); + $this->view->shows = + Application_Model_Show::getShows( + Application_Common_DateHelper::ConvertToUtcDateTime($today_timestamp, date_default_timezone_get()), + Application_Common_DateHelper::ConvertToUtcDateTime($end_timestamp, date_default_timezone_get()), + $onlyRecord = true); $this->view->is_recording = false; $this->view->server_timezone = Application_Model_Preference::GetTimezone(); - $rows = Application_Model_Show::GetCurrentShow($today_timestamp); - Application_Model_Show::ConvertToLocalTimeZone($rows, array("starts", "ends", "start_timestamp", "end_timestamp")); + $rows = Application_Model_Show::getCurrentShow($today_timestamp); + Application_Model_Show::convertToLocalTimeZone($rows, array("starts", "ends", "start_timestamp", "end_timestamp")); - if (count($rows) > 0){ + if (count($rows) > 0) { $this->view->is_recording = ($rows[0]['record'] == 1); } } public function uploadFileAction() { - global $CC_CONFIG; - - $api_key = $this->_getParam('api_key'); - if (!in_array($api_key, $CC_CONFIG["apiKey"]) && - is_null(Zend_Auth::getInstance()->getStorage()->read())) - { - header('HTTP/1.0 401 Unauthorized'); - print 'You are not allowed to access this resource.'; - exit; - } - $upload_dir = ini_get("upload_tmp_dir"); $tempFilePath = Application_Model_StoredFile::uploadFile($upload_dir); $tempFileName = basename($tempFilePath); @@ -440,244 +406,210 @@ class ApiController extends Zend_Controller_Action $fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : ''; $result = Application_Model_StoredFile::copyFileToStor($upload_dir, $fileName, $tempFileName); - if (!is_null($result)){ - die('{"jsonrpc" : "2.0", "error" : {"code": '.$result[code].', "message" : "'.$result[message].'"}}'); + if (!is_null($result)) { + die('{"jsonrpc" : "2.0", "error" : {"code": '.$result['code'].', "message" : "'.$result['message'].'"}}'); } } public function uploadRecordedAction() { - global $CC_CONFIG; - - $api_key = $this->_getParam('api_key'); - if (!in_array($api_key, $CC_CONFIG["apiKey"]) && - is_null(Zend_Auth::getInstance()->getStorage()->read())) - { - header('HTTP/1.0 401 Unauthorized'); - print 'You are not allowed to access this resource.'; - exit; - } - - //this file id is the recording for this show instance. - $show_instance_id = $this->_getParam('showinstanceid'); - $file_id = $this->_getParam('fileid'); - - $this->view->fileid = $file_id; + $show_instance_id = $this->_getParam('showinstanceid'); + $file_id = $this->_getParam('fileid'); + $this->view->fileid = $file_id; $this->view->showinstanceid = $show_instance_id; + $this->uploadRecordedActionParam($show_instance_id, $file_id); + } - - $showCanceled = false; - $file = Application_Model_StoredFile::Recall($file_id); + // The paramterized version of the uploadRecordedAction controller. + // We want this controller's action to be invokable from other + // controllers instead being of only through http + public function uploadRecordedActionParam($show_instance_id, $file_id) + { + $showCanceled = false; + $file = Application_Model_StoredFile::Recall($file_id); //$show_instance = $this->_getParam('show_instance'); - $show_name = null; try { $show_inst = new Application_Model_ShowInstance($show_instance_id); - $show_inst->setRecordedFile($file_id); - $show_name = $show_inst->getName(); - $show_genre = $show_inst->getGenre(); - $show_start_time = Application_Common_DateHelper::ConvertToLocalDateTimeString($show_inst->getShowInstanceStart()); + //$show_start_time = Application_Common_DateHelper::ConvertToLocalDateTimeString($show_inst->getShowInstanceStart()); - } catch (Exception $e){ + } catch (Exception $e) { //we've reached here probably because the show was - //cancelled, and therefore the show instance does not - //exist anymore (ShowInstance constructor threw this error). - //We've done all we can do (upload the file and put it in - //the library), now lets just return. + //cancelled, and therefore the show instance does not exist + //anymore (ShowInstance constructor threw this error). We've + //done all we can do (upload the file and put it in the + //library), now lets just return. $showCanceled = true; } - if (isset($show_name)) { - - $show_name = str_replace(" ", "-", $show_name); - - //2011-12-09-19-28-00-ofirrr-256kbps - $filename = $file->getName(); - - //replace the showname in the filepath incase it has been edited since the show started recording - //(some old bug) - $filename_parts = explode("-", $filename); - $new_name = array_slice($filename_parts, 0, 6); - $new_name[] = $show_name; - $new_name[] = $filename_parts[count($filename_parts)-1]; - - $tmpTitle = implode("-", $new_name); - } - else { - $tmpTitle = $file->getName(); - } - - //$file->setMetadataValue('MDATA_KEY_TITLE', $tmpTitle); + // TODO : the following is inefficient because it calls save on both + // fields $file->setMetadataValue('MDATA_KEY_CREATOR', "Airtime Show Recorder"); $file->setMetadataValue('MDATA_KEY_TRACKNUMBER', $show_instance_id); - if (!$showCanceled && Application_Model_Preference::GetAutoUploadRecordedShowToSoundcloud()) - { - $id = $file->getId(); - $res = exec("/usr/lib/airtime/utils/soundcloud-uploader $id > /dev/null &"); + if (!$showCanceled && Application_Model_Preference::GetAutoUploadRecordedShowToSoundcloud()) { + $id = $file->getId(); + Application_Model_Soundcloud::uploadSoundcloud($id); } } - public function mediaMonitorSetupAction() { - global $CC_CONFIG; - + public function mediaMonitorSetupAction() + { // disable the view and the layout $this->view->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); - $api_key = $this->_getParam('api_key'); - if (!in_array($api_key, $CC_CONFIG["apiKey"]) && - is_null(Zend_Auth::getInstance()->getStorage()->read())) - { - header('HTTP/1.0 401 Unauthorized'); - print 'You are not allowed to access this resource.'; - exit; - } - $this->view->stor = Application_Model_MusicDir::getStorDir()->getDirectory(); $watchedDirs = Application_Model_MusicDir::getWatchedDirs(); $watchedDirsPath = array(); - foreach($watchedDirs as $wd){ + foreach ($watchedDirs as $wd) { $watchedDirsPath[] = $wd->getDirectory(); } $this->view->watched_dirs = $watchedDirsPath; } - public function reloadMetadataAction() { - global $CC_CONFIG; - - $request = $this->getRequest(); - $api_key = $request->getParam('api_key'); - if (!in_array($api_key, $CC_CONFIG["apiKey"]) && - is_null(Zend_Auth::getInstance()->getStorage()->read())) - { - header('HTTP/1.0 401 Unauthorized'); - print 'You are not allowed to access this resource.'; - exit; - } - - $mode = $request->getParam('mode'); - $params = $request->getParams(); - - $md = array(); - //extract all file metadata params from the request. - foreach ($params as $key => $value) { - if (preg_match('/^MDATA_KEY/', $key)) { - $md[$key] = $value; - } - } - - // update import timestamp + public function dispatchMetadata($md, $mode) + { + $return_hash = array(); Application_Model_Preference::SetImportTimestamp(); + //Logging::info("--->Mode: $mode || file: {$md['MDATA_KEY_FILEPATH']} "); + //Logging::info( $md ); + + // create also modifies the file if it exists if ($mode == "create") { $filepath = $md['MDATA_KEY_FILEPATH']; - $filepath = str_replace("\\", "", $filepath); - $filepath = str_replace("//", "/", $filepath); - + $filepath = Application_Common_OsPath::normpath($filepath); $file = Application_Model_StoredFile::RecallByFilepath($filepath); if (is_null($file)) { $file = Application_Model_StoredFile::Insert($md); + } else { + // If the file already exists we will update and make sure that + // it's marked as 'exists'. + $file->setFileExistsFlag(true); + $file->setMetadata($md); } - else { - // path already exist - if($file->getFileExistsFlag()){ - // file marked as exists - $this->view->error = "File already exists in Airtime."; - return; - }else{ - // file marked as not exists - $file->setFileExistsFlag(true); - $file->setMetadata($md); - } + if ($md['is_record'] != 0) { + $this->uploadRecordedActionParam($md['MDATA_KEY_TRACKNUMBER'], $file->getId()); } - } - else if ($mode == "modify") { + + } elseif ($mode == "modify") { $filepath = $md['MDATA_KEY_FILEPATH']; - $filepath = str_replace("\\", "", $filepath); $file = Application_Model_StoredFile::RecallByFilepath($filepath); //File is not in database anymore. if (is_null($file)) { - $this->view->error = "File does not exist in Airtime."; - return; + $return_hash['error'] = "File does not exist in Airtime."; + + return $return_hash; } //Updating a metadata change. else { $file->setMetadata($md); } - } - else if ($mode == "moved") { - $md5 = $md['MDATA_KEY_MD5']; - $file = Application_Model_StoredFile::RecallByMd5($md5); + } elseif ($mode == "moved") { + $file = Application_Model_StoredFile::RecallByFilepath( + $md['MDATA_KEY_ORIGINAL_PATH']); if (is_null($file)) { - $this->view->error = "File doesn't exist in Airtime."; - return; - } - else { + $return_hash['error'] = 'File does not exist in Airtime'; + } else { $filepath = $md['MDATA_KEY_FILEPATH']; - $filepath = str_replace("\\", "", $filepath); + //$filepath = str_replace("\\", "", $filepath); $file->setFilePath($filepath); } - } - else if ($mode == "delete") { + } elseif ($mode == "delete") { $filepath = $md['MDATA_KEY_FILEPATH']; $filepath = str_replace("\\", "", $filepath); $file = Application_Model_StoredFile::RecallByFilepath($filepath); - + if (is_null($file)) { - $this->view->error = "File doesn't exist in Airtime."; - return; - } - else { + $return_hash['error'] = "File doesn't exist in Airtime."; + Logging::warn("Attempt to delete file that doesn't exist. + Path: '$filepath'"); + + return $return_hash; + } else { $file->deleteByMediaMonitor(); } - } - else if ($mode == "delete_dir") { + } elseif ($mode == "delete_dir") { $filepath = $md['MDATA_KEY_FILEPATH']; - $filepath = str_replace("\\", "", $filepath); + //$filepath = str_replace("\\", "", $filepath); $files = Application_Model_StoredFile::RecallByPartialFilepath($filepath); - foreach($files as $file){ + foreach ($files as $file) { $file->deleteByMediaMonitor(); } - return; + $return_hash['success'] = 1; + + return $return_hash; } - $this->view->id = $file->getId(); + + $return_hash['fileid'] = is_null($file) ? '-1' : $file->getId(); + + return $return_hash; } - public function listAllFilesAction() { - global $CC_CONFIG; - - $request = $this->getRequest(); - $api_key = $request->getParam('api_key'); - if (!in_array($api_key, $CC_CONFIG["apiKey"]) && - is_null(Zend_Auth::getInstance()->getStorage()->read())) - { - header('HTTP/1.0 401 Unauthorized'); - print 'You are not allowed to access this resource.'; - exit; + public function reloadMetadataGroupAction() + { + // extract all file metadata params from the request. + // The value is a json encoded hash that has all the information related to this action + // The key(mdXXX) does not have any meaning as of yet but it could potentially correspond + // to some unique id. + $request = $this->getRequest(); + $responses = array(); + $params = $request->getParams(); + $valid_modes = array('delete_dir', 'delete', 'moved', 'modify', 'create'); + foreach ($params as $k => $raw_json) { + // Valid requests must start with mdXXX where XXX represents at + // least 1 digit + if ( !preg_match('/^md\d+$/', $k) ) { continue; } + $info_json = json_decode($raw_json, $assoc = true); + // Log invalid requests + if ( !array_key_exists('mode', $info_json) ) { + Logging::info("Received bad request(key=$k), no 'mode' parameter. Bad request is:"); + Logging::info( $info_json ); + array_push( $responses, array( + 'error' => "Bad request. no 'mode' parameter passed.", + 'key' => $k)); + continue; + } elseif ( !in_array($info_json['mode'], $valid_modes) ) { + // A request still has a chance of being invalid even if it + // exists but it's validated by $valid_modes array + $mode = $info_json['mode']; + Logging::info("Received bad request(key=$k). 'mode' parameter was invalid with value: '$mode'. Request:"); + Logging::info( $info_json ); + array_push( $responses, array( + 'error' => "Bad request. 'mode' parameter is invalid", + 'key' => $k, + 'mode' => $mode ) ); + continue; + } + // Removing 'mode' key from $info_json might not be necessary... + $mode = $info_json['mode']; + unset( $info_json['mode'] ); + $response = $this->dispatchMetadata($info_json, $mode); + // We tack on the 'key' back to every request in case the would like to associate + // his requests with particular responses + $response['key'] = $k; + array_push($responses, $response); } + die( json_encode($responses) ); + } + + public function listAllFilesAction() + { + $request = $this->getRequest(); $dir_id = $request->getParam('dir_id'); + $all = $request->getParam('all'); - $this->view->files = Application_Model_StoredFile::listAllFiles($dir_id); + $this->view->files = + Application_Model_StoredFile::listAllFiles($dir_id,$all); } - public function listAllWatchedDirsAction() { - global $CC_CONFIG; - - $request = $this->getRequest(); - $api_key = $request->getParam('api_key'); - if (!in_array($api_key, $CC_CONFIG["apiKey"]) && - is_null(Zend_Auth::getInstance()->getStorage()->read())) - { - header('HTTP/1.0 401 Unauthorized'); - print 'You are not allowed to access this resource.'; - exit; - } - + public function listAllWatchedDirsAction() + { $result = array(); $arrWatchedDirs = Application_Model_MusicDir::getWatchedDirs(); @@ -685,98 +617,47 @@ class ApiController extends Zend_Controller_Action $result[$storDir->getId()] = $storDir->getDirectory(); - foreach ($arrWatchedDirs as $watchedDir){ + foreach ($arrWatchedDirs as $watchedDir) { $result[$watchedDir->getId()] = $watchedDir->getDirectory(); } $this->view->dirs = $result; } - public function addWatchedDirAction() { - global $CC_CONFIG; - + public function addWatchedDirAction() + { $request = $this->getRequest(); - $api_key = $request->getParam('api_key'); $path = base64_decode($request->getParam('path')); - if (!in_array($api_key, $CC_CONFIG["apiKey"]) && - is_null(Zend_Auth::getInstance()->getStorage()->read())) - { - header('HTTP/1.0 401 Unauthorized'); - print 'You are not allowed to access this resource.'; - exit; - } - $this->view->msg = Application_Model_MusicDir::addWatchedDir($path); } - public function removeWatchedDirAction() { - global $CC_CONFIG; - + public function removeWatchedDirAction() + { $request = $this->getRequest(); - $api_key = $request->getParam('api_key'); $path = base64_decode($request->getParam('path')); - if (!in_array($api_key, $CC_CONFIG["apiKey"]) && - is_null(Zend_Auth::getInstance()->getStorage()->read())) - { - header('HTTP/1.0 401 Unauthorized'); - print 'You are not allowed to access this resource.'; - exit; - } - $this->view->msg = Application_Model_MusicDir::removeWatchedDir($path); } - public function setStorageDirAction() { - global $CC_CONFIG; - + public function setStorageDirAction() + { $request = $this->getRequest(); - $api_key = $request->getParam('api_key'); $path = base64_decode($request->getParam('path')); - if (!in_array($api_key, $CC_CONFIG["apiKey"]) && - is_null(Zend_Auth::getInstance()->getStorage()->read())) - { - header('HTTP/1.0 401 Unauthorized'); - print 'You are not allowed to access this resource.'; - exit; - } - $this->view->msg = Application_Model_MusicDir::setStorDir($path); } - public function getStreamSettingAction() { - global $CC_CONFIG; - - $request = $this->getRequest(); - $api_key = $request->getParam('api_key'); - if (!in_array($api_key, $CC_CONFIG["apiKey"]) && - is_null(Zend_Auth::getInstance()->getStorage()->read())) - { - header('HTTP/1.0 401 Unauthorized'); - print 'You are not allowed to access this resource.'; - exit; - } - + public function getStreamSettingAction() + { $info = Application_Model_StreamSetting::getStreamSetting(); $this->view->msg = $info; } - public function statusAction() { - global $CC_CONFIG; - + public function statusAction() + { $request = $this->getRequest(); - $api_key = $request->getParam('api_key'); $getDiskInfo = $request->getParam('diskinfo') == "true"; - - if (!in_array($api_key, $CC_CONFIG["apiKey"]) && - is_null(Zend_Auth::getInstance()->getStorage()->read())) - { - header('HTTP/1.0 401 Unauthorized'); - print 'You are not allowed to access this resource.'; - exit; - } $status = array( "platform"=>Application_Model_Systemstatus::GetPlatformInfo(), @@ -789,24 +670,26 @@ class ApiController extends Zend_Controller_Action ) ); - if ($getDiskInfo){ + if ($getDiskInfo) { $status["partitions"] = Application_Model_Systemstatus::GetDiskInfo(); } $this->view->status = $status; } - public function registerComponentAction(){ + public function registerComponentAction() + { $request = $this->getRequest(); $component = $request->getParam('component'); - $remoteAddr = $_SERVER['REMOTE_ADDR']; - Logging::log("Registered Component: ".$component."@".$remoteAddr); + $remoteAddr = Application_Model_ServiceRegister::GetRemoteIpAddr(); + Logging::info("Registered Component: ".$component."@".$remoteAddr); Application_Model_ServiceRegister::Register($component, $remoteAddr); } - public function updateLiquidsoapStatusAction(){ + public function updateLiquidsoapStatusAction() + { $request = $this->getRequest(); $msg = $request->getParam('msg'); @@ -816,22 +699,22 @@ class ApiController extends Zend_Controller_Action Application_Model_StreamSetting::setLiquidsoapError($stream_id, $msg, $boot_time); } - public function updateSourceStatusAction(){ + public function updateSourceStatusAction() + { $request = $this->getRequest(); - $msg = $request->getParam('msg'); $sourcename = $request->getParam('sourcename'); $status = $request->getParam('status'); - + // on source disconnection sent msg to pypo to turn off the switch // Added AutoTransition option - if($status == "false" && Application_Model_Preference::GetAutoTransition()){ + if ($status == "false" && Application_Model_Preference::GetAutoTransition()) { $data = array("sourcename"=>$sourcename, "status"=>"off"); Application_Model_RabbitMq::SendMessageToPypo("switch_source", $data); Application_Model_Preference::SetSourceSwitchStatus($sourcename, "off"); Application_Model_LiveLog::SetEndTime($sourcename == 'scheduled_play'?'S':'L', new DateTime("now", new DateTimeZone('UTC'))); - }elseif($status == "true" && Application_Model_Preference::GetAutoSwitch()){ + } elseif ($status == "true" && Application_Model_Preference::GetAutoSwitch()) { $data = array("sourcename"=>$sourcename, "status"=>"on"); Application_Model_RabbitMq::SendMessageToPypo("switch_source", $data); Application_Model_Preference::SetSourceSwitchStatus($sourcename, "on"); @@ -842,93 +725,74 @@ class ApiController extends Zend_Controller_Action } // handles addition/deletion of mount point which watched dirs reside - public function updateFileSystemMountAction(){ - global $CC_CONFIG; - + public function updateFileSystemMountAction() + { $request = $this->getRequest(); - $api_key = $request->getParam('api_key'); - if (!in_array($api_key, $CC_CONFIG["apiKey"]) && - is_null(Zend_Auth::getInstance()->getStorage()->read())) - { - header('HTTP/1.0 401 Unauthorized'); - print 'You are not allowed to access this resource.'; - exit; - } $params = $request->getParams(); - $added_list = empty($params['added_dir'])?array():explode(',',$params['added_dir']); - $removed_list = empty($params['removed_dir'])?array():explode(',',$params['removed_dir']); + $added_list = empty($params['added_dir'])?array():explode(',', $params['added_dir']); + $removed_list = empty($params['removed_dir'])?array():explode(',', $params['removed_dir']); // get all watched dirs - $watched_dirs = Application_Model_MusicDir::getWatchedDirs(null,null); + $watched_dirs = Application_Model_MusicDir::getWatchedDirs(null, null); - foreach( $added_list as $ad){ - $ad .= '/'; - foreach( $watched_dirs as $dir ){ - $dirPath = $dir->getDirectory(); + foreach ($added_list as $ad) { + $ad .= '/'; + foreach ($watched_dirs as $dir) { + $dirPath = $dir->getDirectory(); - // if mount path itself was watched - if($dirPath == $ad){ - Application_Model_MusicDir::addWatchedDir($dirPath, false); - } + // if mount path itself was watched + if ($dirPath == $ad) { + Application_Model_MusicDir::addWatchedDir($dirPath, false); + } elseif (substr($dirPath, 0, strlen($ad)) === $ad && $dir->getExistsFlag() == false) { // if dir contains any dir in removed_list( if watched dir resides on new mounted path ) - else if(substr($dirPath, 0, strlen($ad)) === $ad && $dir->getExistsFlag() == false){ - Application_Model_MusicDir::addWatchedDir($dirPath, false); - } + Application_Model_MusicDir::addWatchedDir($dirPath, false); + } elseif (substr($ad, 0, strlen($dirPath)) === $dirPath) { // is new mount point within the watched dir? // pyinotify doesn't notify anyhing in this case, so we add this mount point as // watched dir - else if(substr($ad, 0, strlen($dirPath)) === $dirPath){ - // bypass nested loop check - Application_Model_MusicDir::addWatchedDir($ad, false, true); - } + // bypass nested loop check + Application_Model_MusicDir::addWatchedDir($ad, false, true); } } - foreach( $removed_list as $rd){ - $rd .= '/'; - foreach( $watched_dirs as $dir ){ - $dirPath = $dir->getDirectory(); - // if dir contains any dir in removed_list( if watched dir resides on new mounted path ) - if(substr($dirPath, 0, strlen($rd)) === $rd && $dir->getExistsFlag() == true){ - Application_Model_MusicDir::removeWatchedDir($dirPath, false); - } + } + + foreach ($removed_list as $rd) { + $rd .= '/'; + foreach ($watched_dirs as $dir) { + $dirPath = $dir->getDirectory(); + // if dir contains any dir in removed_list( if watched dir resides on new mounted path ) + if (substr($dirPath, 0, strlen($rd)) === $rd && $dir->getExistsFlag() == true) { + Application_Model_MusicDir::removeWatchedDir($dirPath, false); + } elseif (substr($rd, 0, strlen($dirPath)) === $dirPath) { // is new mount point within the watched dir? // pyinotify doesn't notify anyhing in this case, so we walk through all files within // this watched dir in DB and mark them deleted. // In case of h) of use cases, due to pyinotify behaviour of noticing mounted dir, we need to // compare agaisnt all files in cc_files table - else if(substr($rd, 0, strlen($dirPath)) === $dirPath ){ - $watchDir = Application_Model_MusicDir::getDirByPath($rd); - // get all the files that is under $dirPath - $files = Application_Model_StoredFile::listAllFiles($dir->getId(), true); - foreach($files as $f){ - // if the file is from this mount - if(substr( $f->getFilePath(),0,strlen($rd) ) === $rd){ - $f->delete(); - } - } - if($watchDir){ - Application_Model_MusicDir::removeWatchedDir($rd, false); + + $watchDir = Application_Model_MusicDir::getDirByPath($rd); + // get all the files that is under $dirPath + $files = Application_Model_StoredFile::listAllFiles( + $dir->getId(),$all=false, true); + foreach ($files as $f) { + // if the file is from this mount + if (substr($f->getFilePath(), 0, strlen($rd)) === $rd) { + $f->delete(); } } + if ($watchDir) { + Application_Model_MusicDir::removeWatchedDir($rd, false); + } } } - + } } // handles case where watched dir is missing - public function handleWatchedDirMissingAction(){ - global $CC_CONFIG; - + public function handleWatchedDirMissingAction() + { $request = $this->getRequest(); - $api_key = $request->getParam('api_key'); - if (!in_array($api_key, $CC_CONFIG["apiKey"]) && - is_null(Zend_Auth::getInstance()->getStorage()->read())) - { - header('HTTP/1.0 401 Unauthorized'); - print 'You are not allowed to access this resource.'; - exit; - } $dir = base64_decode($request->getParam('dir')); Application_Model_MusicDir::removeWatchedDir($dir, false); @@ -937,24 +801,16 @@ class ApiController extends Zend_Controller_Action /* This action is for use by our dev scripts, that make * a change to the database and we want rabbitmq to send * out a message to pypo that a potential change has been made. */ - public function rabbitmqDoPushAction(){ - global $CC_CONFIG; - - $request = $this->getRequest(); - $api_key = $request->getParam('api_key'); - if (!in_array($api_key, $CC_CONFIG["apiKey"]) && - is_null(Zend_Auth::getInstance()->getStorage()->read())) - { - header('HTTP/1.0 401 Unauthorized'); - print 'You are not allowed to access this resource.'; - exit; - } - Logging::log("Notifying RabbitMQ to send message to pypo"); + public function rabbitmqDoPushAction() + { + Logging::info("Notifying RabbitMQ to send message to pypo"); + Application_Model_RabbitMq::SendMessageToPypo("reset_liquidsoap_bootstrap", array()); Application_Model_RabbitMq::PushSchedule(); } - public function getBootstrapInfoAction(){ + public function getBootstrapInfoAction() + { $live_dj = Application_Model_Preference::GetSourceSwitchStatus('live_dj'); $master_dj = Application_Model_Preference::GetSourceSwitchStatus('master_dj'); $scheduled_play = Application_Model_Preference::GetSourceSwitchStatus('scheduled_play'); @@ -967,36 +823,27 @@ class ApiController extends Zend_Controller_Action } /* This is used but Liquidsoap to check authentication of live streams*/ - public function checkLiveStreamAuthAction(){ - global $CC_CONFIG; - + public function checkLiveStreamAuthAction() + { $request = $this->getRequest(); - $api_key = $request->getParam('api_key'); $username = $request->getParam('username'); $password = $request->getParam('password'); $djtype = $request->getParam('djtype'); - - if (!in_array($api_key, $CC_CONFIG["apiKey"]) && - is_null(Zend_Auth::getInstance()->getStorage()->read())) - { - header('HTTP/1.0 401 Unauthorized'); - print 'You are not allowed to access this resource.'; - exit; - } - if($djtype == 'master'){ + if ($djtype == 'master') { //check against master - if($username == Application_Model_Preference::GetLiveSteamMasterUsername() && $password == Application_Model_Preference::GetLiveSteamMasterPassword()){ + if ($username == Application_Model_Preference::GetLiveStreamMasterUsername() + && $password == Application_Model_Preference::GetLiveStreamMasterPassword()) { $this->view->msg = true; - }else{ + } else { $this->view->msg = false; } - }elseif($djtype == "dj"){ + } elseif ($djtype == "dj") { //check against show dj auth - $showInfo = Application_Model_Show::GetCurrentShow(); + $showInfo = Application_Model_Show::getCurrentShow(); // there is current playing show - if(isset($showInfo[0]['id'])){ + if (isset($showInfo[0]['id'])) { $current_show_id = $showInfo[0]['id']; $CcShow = CcShowQuery::create()->findPK($current_show_id); @@ -1009,31 +856,105 @@ class ApiController extends Zend_Controller_Action $hosts_ids = $show->getHostsIds(); // check against hosts auth - if($CcShow->getDbLiveStreamUsingAirtimeAuth()){ - foreach( $hosts_ids as $host){ + if ($CcShow->getDbLiveStreamUsingAirtimeAuth()) { + foreach ($hosts_ids as $host) { $h = new Application_Model_User($host['subjs_id']); - if($username == $h->getLogin() && md5($password) == $h->getPassword()){ + if ($username == $h->getLogin() && md5($password) == $h->getPassword()) { $this->view->msg = true; + return; } } } // check against custom auth - if($CcShow->getDbLiveStreamUsingCustomAuth()){ - if($username == $custom_user && $password == $custom_pass){ + if ($CcShow->getDbLiveStreamUsingCustomAuth()) { + if ($username == $custom_user && $password == $custom_pass) { $this->view->msg = true; - }else{ + } else { $this->view->msg = false; } - } - else{ + } else { $this->view->msg = false; } - }else{ + } else { // no show is currently playing $this->view->msg = false; } } } -} + /* This action is for use by our dev scripts, that make + * a change to the database and we want rabbitmq to send + * 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); + } + + public function updateReplayGainValueAction() + { + // disable layout + $this->view->layout()->disableLayout(); + $this->_helper->viewRenderer->setNoRender(true); + + $request = $this->getRequest(); + $data = json_decode($request->getParam('data')); + + foreach ($data as $pair) { + list($id, $gain) = $pair; + // TODO : move this code into model -- RG + $file = Application_Model_StoredFile::Recall($p_id = $id)->getPropelOrm(); + $file->setDbReplayGain($gain); + $file->save(); + } + } + + public function notifyWebstreamDataAction() + { + $request = $this->getRequest(); + $data = $request->getParam("data"); + $media_id = $request->getParam("media_id"); + + $data_arr = json_decode($data); + + if (!is_null($media_id) && isset($data_arr->title) && strlen($data_arr->title) < 1024) { + + $previous_metadata = CcWebstreamMetadataQuery::create() + ->orderByDbStartTime('desc') + ->filterByDbInstanceId($media_id) + ->findOne(); + + $do_insert = true; + if ($previous_metadata) { + if ($previous_metadata->getDbLiquidsoapData() == $data_arr->title) { + Logging::debug("Duplicate found: ".$data_arr->title); + $do_insert = false; + } + } + + if ($do_insert) { + $webstream_metadata = new CcWebstreamMetadata(); + $webstream_metadata->setDbInstanceId($media_id); + $webstream_metadata->setDbStartTime(new DateTime("now", new DateTimeZone("UTC"))); + $webstream_metadata->setDbLiquidsoapData($data_arr->title); + $webstream_metadata->save(); + } + + } else { + throw new Error("Unexpected error. media_id $media_id has a null stream value in cc_schedule!"); + } + + $this->view->response = $data; + $this->view->media_id = $media_id; + } + +} diff --git a/airtime_mvc/application/controllers/AudiopreviewController.php b/airtime_mvc/application/controllers/AudiopreviewController.php index df31d8cd0..3718a86a0 100644 --- a/airtime_mvc/application/controllers/AudiopreviewController.php +++ b/airtime_mvc/application/controllers/AudiopreviewController.php @@ -20,30 +20,50 @@ class AudiopreviewController extends Zend_Controller_Action public function audioPreviewAction() { global $CC_CONFIG; - - $audioFileID = $this->_getParam('audioFileID'); + + $audioFileID = $this->_getParam('audioFileID'); $audioFileArtist = $this->_getParam('audioFileArtist'); - $audioFileTitle = $this->_getParam('audioFileTitle'); - + $audioFileTitle = $this->_getParam('audioFileTitle'); + $type = $this->_getParam('type'); + $request = $this->getRequest(); $baseUrl = $request->getBaseUrl(); - - $baseDir = dirname($_SERVER['SCRIPT_FILENAME']); - $this->view->headScript()->appendFile($baseUrl.'/js/airtime/audiopreview/preview_jplayer.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); - $this->view->headScript()->appendFile($baseUrl.'/js/jplayer/jplayer.playlist.min.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); - $this->view->headLink()->appendStylesheet($baseUrl.'/js/jplayer/skin/jplayer.airtime.audio.preview.css?'.$CC_CONFIG['airtime_version']); + $this->view->headScript()->appendFile( + $baseUrl.'/js/airtime/audiopreview/preview_jplayer.js?'.$CC_CONFIG['airtime_version'], + 'text/javascript'); + $this->view->headScript()->appendFile( + $baseUrl.'/js/jplayer/jplayer.playlist.min.js?'.$CC_CONFIG['airtime_version'], + 'text/javascript'); + $this->view->headLink()->appendStylesheet( + $baseUrl.'/js/jplayer/skin/jplayer.airtime.audio.preview.css?'.$CC_CONFIG['airtime_version']); $this->_helper->layout->setLayout('audioPlayer'); $logo = Application_Model_Preference::GetStationLogo(); - if($logo){ + if ($logo) { $this->view->logo = "data:image/png;base64,$logo"; } else { $this->view->logo = "$baseUrl/css/images/airtime_logo_jp.png"; } - $this->view->audioFileID = $audioFileID; + + if ($type == "audioclip") { + $uri = "/api/get-media/file/".$audioFileID; + $media = Application_Model_StoredFile::Recall($audioFileID); + $mime = $media->getPropelOrm()->getDbMime(); + } elseif ($type == "stream") { + $webstream = CcWebstreamQuery::create()->findPk($audioFileID); + $uri = $webstream->getDbUrl(); + $mime = $webstream->getDbMime(); + } else { + throw new Exception("Unknown type for audio preview!.Type=$type"); + } + + $this->view->uri = $uri; + $this->view->mime = $mime; + $this->view->audioFileID = $audioFileID; $this->view->audioFileArtist = $audioFileArtist; - $this->view->audioFileTitle = $audioFileTitle; + $this->view->audioFileTitle = $audioFileTitle; + $this->view->type = $type; $this->_helper->viewRenderer->setRender('audio-preview'); } @@ -55,14 +75,12 @@ class AudiopreviewController extends Zend_Controller_Action public function playlistPreviewAction() { global $CC_CONFIG; - + $playlistIndex = $this->_getParam('playlistIndex'); $playlistID = $this->_getParam('playlistID'); $request = $this->getRequest(); $baseUrl = $request->getBaseUrl(); - - $baseDir = dirname($_SERVER['SCRIPT_FILENAME']); $this->view->headScript()->appendFile($baseUrl.'/js/airtime/audiopreview/preview_jplayer.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/jplayer/jplayer.playlist.min.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); @@ -70,7 +88,7 @@ class AudiopreviewController extends Zend_Controller_Action $this->_helper->layout->setLayout('audioPlayer'); $logo = Application_Model_Preference::GetStationLogo(); - if($logo){ + if ($logo) { $this->view->logo = "data:image/png;base64,$logo"; } else { $this->view->logo = "$baseUrl/css/images/airtime_logo_jp.png"; @@ -81,44 +99,128 @@ class AudiopreviewController extends Zend_Controller_Action $this->_helper->viewRenderer->setRender('audio-preview'); } - /** - *Function will load and return the contents of the requested playlist. - */ - public function getPlaylistAction(){ + public function blockPreviewAction() + { + global $CC_CONFIG; + + $blockIndex = $this->_getParam('blockIndex'); + $blockId = $this->_getParam('blockId'); + + $request = $this->getRequest(); + $baseUrl = $request->getBaseUrl(); + + $this->view->headScript()->appendFile($baseUrl.'/js/airtime/audiopreview/preview_jplayer.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + $this->view->headScript()->appendFile($baseUrl.'/js/jplayer/jplayer.playlist.min.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + $this->view->headLink()->appendStylesheet($baseUrl.'/js/jplayer/skin/jplayer.airtime.audio.preview.css?'.$CC_CONFIG['airtime_version']); + $this->_helper->layout->setLayout('audioPlayer'); + + $logo = Application_Model_Preference::GetStationLogo(); + if ($logo) { + $this->view->logo = "data:image/png;base64,$logo"; + } else { + $this->view->logo = "$baseUrl/css/images/airtime_logo_jp.png"; + } + $this->view->blockIndex= $blockIndex; + $this->view->blockId = $blockId; + + $this->_helper->viewRenderer->setRender('audio-preview'); + } + public function getBlockAction() + { // disable the view and the layout $this->view->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); - - $playlistID = $this->_getParam('playlistID'); - - if (!isset($playlistID)){ + + $blockId = $this->_getParam('blockId'); + + if (!isset($blockId)) { return; } - + + $bl = new Application_Model_Block($blockId); + $result = array(); + foreach ($bl->getContents(true) as $ele) { + $result[] = $this->createElementMap($ele); + } + $this->_helper->json($result); + } + /** + *Function will load and return the contents of the requested playlist. + */ + public function getPlaylistAction() + { + // disable the view and the layout + $this->view->layout()->disableLayout(); + $this->_helper->viewRenderer->setNoRender(true); + + $playlistID = $this->_getParam('playlistID'); + + if (!isset($playlistID)) { + return; + } + $pl = new Application_Model_Playlist($playlistID); $result = Array(); - - foreach ( $pl->getContents(true) as $track ){ - - $elementMap = array( 'element_title' => isset($track['CcFiles']['track_title'])?$track['CcFiles']['track_title']:"", - 'element_artist' => isset($track['CcFiles']['artist_name'])?$track['CcFiles']['artist_name']:"", - 'element_id' => isset($track['id'])?$track['id']:"", - 'element_position' => isset($track['position'])?$track['position']:"", - ); - $fileExtension = pathinfo($track['CcFiles']['filepath'], PATHINFO_EXTENSION); - if (strtolower($fileExtension) === 'mp3'){ - $elementMap['element_mp3'] = $track['CcFiles']['gunid'].'.'.$fileExtension; - } else if(strtolower($fileExtension) === 'ogg') { - $elementMap['element_oga'] = $track['CcFiles']['gunid'].'.'.$fileExtension; + + foreach ($pl->getContents(true) as $ele) { + if ($ele['type'] == 2) { + // if element is a block expand and add + $bl = new Application_Model_Block($ele['item_id']); + if ($bl->isStatic()) { + foreach ($bl->getContents(true) as $track) { + $result[] = $this->createElementMap($track); + } + } } else { - //the media was neither mp3 or ogg + $result[] = $this->createElementMap($ele); } - $result[] = $elementMap; } - $this->_helper->json($result); } + private function createElementMap($track) + { + $elementMap = array( 'element_title' => isset($track['track_title'])?$track['track_title']:"", + 'element_artist' => isset($track['artist_name'])?$track['artist_name']:"", + 'element_id' => isset($track['id'])?$track['id']:"", + 'element_position' => isset($track['position'])?$track['position']:"", + 'mime' => isset($track['mime'])?$track['mime']:"" + ); + + /* If the track type is static we know it must be + * a track because static blocks can only contain + * tracks + */ + if ($track['type'] == 'static') { + $track['type'] = 0; + } + $elementMap['type'] = $track['type']; + + if ($track['type'] == 0) { + $mime = $track['mime']; + //type is file + if (strtolower($mime) === 'audio/mp3') { + $elementMap['element_mp3'] = $track['item_id']; + } elseif (strtolower($mime) === 'audio/ogg') { + $elementMap['element_oga'] = $track['item_id']; + } elseif (strtolower($mime) === 'audio/mp4') { + $elementMap['element_m4a'] = $track['item_id']; + } elseif (strtolower($mime) === 'audio/wav') { + $elementMap['element_wav'] = $track['item_id']; + } elseif (strtolower($mime) === 'audio/x-flac') { + $elementMap['element_flac'] = $track['item_id']; + } else { + throw new Exception("Unknown file type: $mime"); + } + + $elementMap['uri'] = "/api/get-media/file/".$track['item_id']; + } else { + $elementMap['uri'] = $track['path']; + } + + return $elementMap; + } + /** * Simply sets up the view to play the required show track. * Gets the parameters from the request and sets them to the view. @@ -126,14 +228,12 @@ class AudiopreviewController extends Zend_Controller_Action public function showPreviewAction() { global $CC_CONFIG; - + $showID = $this->_getParam('showID'); $showIndex = $this->_getParam('showIndex'); - + $request = $this->getRequest(); $baseUrl = $request->getBaseUrl(); - - $baseDir = dirname($_SERVER['SCRIPT_FILENAME']); $this->view->headScript()->appendFile($baseUrl.'/js/airtime/audiopreview/preview_jplayer.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/jplayer/jplayer.playlist.min.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); @@ -141,18 +241,18 @@ class AudiopreviewController extends Zend_Controller_Action $this->_helper->layout->setLayout('audioPlayer'); $logo = Application_Model_Preference::GetStationLogo(); - if ($logo){ + if ($logo) { $this->view->logo = "data:image/png;base64,$logo"; } else { $this->view->logo = "$baseUrl/css/images/airtime_logo_jp.png"; } - + $this->view->showID = $showID; $this->view->showIndex = $showIndex; - + $this->_helper->viewRenderer->setRender('audio-preview'); } - + /** *Function will load and return the contents of the requested show. */ @@ -161,32 +261,46 @@ class AudiopreviewController extends Zend_Controller_Action // disable the view and the layout $this->view->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); - + $showID = $this->_getParam('showID'); - if (!isset($showID)){ + if (!isset($showID)) { return; } - + $showInstance = new Application_Model_ShowInstance($showID); $result = array(); $position = 0; - foreach ($showInstance->getShowListContent() as $track){ - - $elementMap = array( + foreach ($showInstance->getShowListContent() as $track) { + + $elementMap = array( 'element_title' => isset($track['track_title']) ? $track['track_title'] : "", - 'element_artist' => isset($track['artist_name']) ? $track['artist_name'] : "", + 'element_artist' => isset($track['creator']) ? $track['creator'] : "", 'element_position' => $position, 'element_id' => ++$position, + 'mime' => isset($track['mime'])?$track['mime']:"" ); - - $fileExtension = pathinfo($track['filepath'], PATHINFO_EXTENSION); - if (strtolower($fileExtension) === 'mp3'){ - $elementMap['element_mp3'] = $track['gunid'].'.'.$fileExtension; - } else if(strtolower($fileExtension) === 'ogg') { - $elementMap['element_oga'] = $track['gunid'].'.'.$fileExtension; + + $elementMap['type'] = $track['type']; + if ($track['type'] == 0) { + $mime = $track['mime']; + if (strtolower($mime) === 'audio/mp3') { + $elementMap['element_mp3'] = $track['item_id']; + } elseif (strtolower($mime) === 'audio/ogg') { + $elementMap['element_oga'] = $track['item_id']; + } elseif (strtolower($mime) === 'audio/mp4') { + $elementMap['element_m4a'] = $track['item_id']; + } elseif (strtolower($mime) === 'audio/wav') { + $elementMap['element_wav'] = $track['item_id']; + } elseif (strtolower($mime) === 'audio/x-flac') { + $elementMap['element_flac'] = $track['item_id']; + } else { + throw new Exception("Unknown file type: $mime"); + } + + $elementMap['uri'] = "/api/get-media/file/".$track['item_id']; } else { - //the media was neither mp3 or ogg + $elementMap['uri'] = $track['filepath']; } $result[] = $elementMap; } diff --git a/airtime_mvc/application/controllers/DashboardController.php b/airtime_mvc/application/controllers/DashboardController.php index 6a8c2995b..9609a1ef8 100644 --- a/airtime_mvc/application/controllers/DashboardController.php +++ b/airtime_mvc/application/controllers/DashboardController.php @@ -15,99 +15,97 @@ class DashboardController extends Zend_Controller_Action { // action body } - - public function disconnectSourceAction(){ + + public function disconnectSourceAction() + { $request = $this->getRequest(); $sourcename = $request->getParam('sourcename'); - + $userInfo = Zend_Auth::getInstance()->getStorage()->read(); $user = new Application_Model_User($userInfo->id); - - $show = Application_Model_Show::GetCurrentShow(); - - $show_id = isset($show['id'])?$show['id']:0; - + + $show = Application_Model_Show::getCurrentShow(); + $show_id = isset($show[0]['id'])?$show[0]['id']:0; $source_connected = Application_Model_Preference::GetSourceStatus($sourcename); - - if($user->canSchedule($show_id) && $source_connected){ + + if ($user->canSchedule($show_id) && $source_connected) { $data = array("sourcename"=>$sourcename); Application_Model_RabbitMq::SendMessageToPypo("disconnect_source", $data); - }else{ - if($source_connected){ + } else { + if ($source_connected) { $this->view->error = "You don't have permission to disconnect source."; - }else{ + } else { $this->view->error = "There is no source connected to this input."; } } } - - public function switchSourceAction(){ - $request = $this->getRequest(); + + public function switchSourceAction() + { $sourcename = $this->_getParam('sourcename'); $current_status = $this->_getParam('status'); - + $userInfo = Zend_Auth::getInstance()->getStorage()->read(); $user = new Application_Model_User($userInfo->id); - - $show = Application_Model_Show::GetCurrentShow(); + + $show = Application_Model_Show::getCurrentShow(); $show_id = isset($show[0]['id'])?$show[0]['id']:0; - + $source_connected = Application_Model_Preference::GetSourceStatus($sourcename); - if($user->canSchedule($show_id) && ($source_connected || $sourcename == 'scheduled_play' || $current_status == "on")){ - + if ($user->canSchedule($show_id) && ($source_connected || $sourcename == 'scheduled_play' || $current_status == "on")) { + $change_status_to = "on"; - - if(strtolower($current_status) == "on"){ + + if (strtolower($current_status) == "on") { $change_status_to = "off"; } - + $data = array("sourcename"=>$sourcename, "status"=>$change_status_to); Application_Model_RabbitMq::SendMessageToPypo("switch_source", $data); - if(strtolower($current_status) == "on"){ + if (strtolower($current_status) == "on") { Application_Model_Preference::SetSourceSwitchStatus($sourcename, "off"); $this->view->status = "OFF"; - + //Log table updates Application_Model_LiveLog::SetEndTime($sourcename == 'scheduled_play'?'S':'L', new DateTime("now", new DateTimeZone('UTC'))); - }else{ + } else { Application_Model_Preference::SetSourceSwitchStatus($sourcename, "on"); $this->view->status = "ON"; - + //Log table updates Application_Model_LiveLog::SetNewLogTime($sourcename == 'scheduled_play'?'S':'L', new DateTime("now", new DateTimeZone('UTC'))); } - } - else{ - if($source_connected){ + } else { + if ($source_connected) { $this->view->error = "You don't have permission to switch source."; - }else{ - if($sourcename == 'scheduled_play'){ + } else { + if ($sourcename == 'scheduled_play') { $this->view->error = "You don't have permission to disconnect source."; - }else{ + } else { $this->view->error = "There is no source connected to this input."; } } } } - - public function switchOffSource(){ - + + public function switchOffSource() + { } - + public function streamPlayerAction() { global $CC_CONFIG; - + $request = $this->getRequest(); $baseUrl = $request->getBaseUrl(); - + $this->view->headLink()->appendStylesheet($baseUrl.'/js/jplayer/skin/jplayer.blue.monday.css?'.$CC_CONFIG['airtime_version']); $this->_helper->layout->setLayout('bare'); $logo = Application_Model_Preference::GetStationLogo(); - if($logo){ + if ($logo) { $this->view->logo = "data:image/png;base64,$logo"; } else { $this->view->logo = "$baseUrl/css/images/airtime_logo_jp.png"; @@ -125,4 +123,3 @@ class DashboardController extends Zend_Controller_Action } } - diff --git a/airtime_mvc/application/controllers/ErrorController.php b/airtime_mvc/application/controllers/ErrorController.php index 70f73ee37..2c1aa0b87 100644 --- a/airtime_mvc/application/controllers/ErrorController.php +++ b/airtime_mvc/application/controllers/ErrorController.php @@ -6,12 +6,12 @@ class ErrorController extends Zend_Controller_Action public function errorAction() { $errors = $this->_getParam('error_handler'); - + switch ($errors->type) { case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE: case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER: case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION: - + // 404 error -- controller or action not found $this->getResponse()->setHttpResponseCode(404); $this->view->message = 'Page not found'; @@ -22,17 +22,17 @@ class ErrorController extends Zend_Controller_Action $this->view->message = 'Application error'; break; } - + // Log exception, if logger available if ($log = $this->getLog()) { $log->crit($this->view->message, $errors->exception); } - + // conditionally display exceptions if ($this->getInvokeArg('displayExceptions') == true) { $this->view->exception = $errors->exception; } - + $this->view->request = $errors->request; } @@ -43,6 +43,7 @@ class ErrorController extends Zend_Controller_Action return false; } $log = $bootstrap->getResource('Log'); + return $log; } @@ -51,8 +52,4 @@ class ErrorController extends Zend_Controller_Action // action body } - } - - - diff --git a/airtime_mvc/application/controllers/IndexController.php b/airtime_mvc/application/controllers/IndexController.php index c1129ae36..8dcdb3a64 100644 --- a/airtime_mvc/application/controllers/IndexController.php +++ b/airtime_mvc/application/controllers/IndexController.php @@ -5,7 +5,7 @@ class IndexController extends Zend_Controller_Action public function init() { - + } public function indexAction() @@ -14,15 +14,8 @@ class IndexController extends Zend_Controller_Action } public function mainAction() - { + { $this->_helper->layout->setLayout('layout'); } } - - - - - - - diff --git a/airtime_mvc/application/controllers/LibraryController.php b/airtime_mvc/application/controllers/LibraryController.php index 99fdd923f..a1d0d245e 100644 --- a/airtime_mvc/application/controllers/LibraryController.php +++ b/airtime_mvc/application/controllers/LibraryController.php @@ -7,9 +7,6 @@ require_once 'formatters/BitrateFormatter.php'; class LibraryController extends Zend_Controller_Action { - protected $pl_sess = null; - protected $search_sess = null; - public function init() { $ajaxContext = $this->_helper->getHelper('AjaxContext'); @@ -17,14 +14,130 @@ class LibraryController extends Zend_Controller_Action ->addActionContext('delete', 'json') ->addActionContext('delete-group', 'json') ->addActionContext('context-menu', 'json') - ->addActionContext('get-file-meta-data', 'html') + ->addActionContext('get-file-metadata', 'html') ->addActionContext('upload-file-soundcloud', 'json') ->addActionContext('get-upload-to-soundcloud-status', 'json') ->addActionContext('set-num-entries', 'json') ->initContext(); + } - $this->pl_sess = new Zend_Session_Namespace(UI_PLAYLIST_SESSNAME); - $this->search_sess = new Zend_Session_Namespace("search"); + public function indexAction() + { + global $CC_CONFIG; + + $request = $this->getRequest(); + $baseUrl = $request->getBaseUrl(); + + $this->view->headScript()->appendFile($baseUrl.'/js/blockui/jquery.blockUI.js?'.$CC_CONFIG['airtime_version'], 'text/javascript'); + $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.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/utilities/utilities.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/library/events/library_playlistbuilder.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->headScript()->appendFile($baseUrl.'/js/airtime/library/spl.js?'.$CC_CONFIG['airtime_version'], 'text/javascript'); + $this->view->headScript()->appendFile($baseUrl.'/js/airtime/playlist/smart_blockbuilder.js?'.$CC_CONFIG['airtime_version'], 'text/javascript'); + $this->view->headLink()->appendStylesheet($baseUrl.'/css/playlist_builder.css?'.$CC_CONFIG['airtime_version']); + + try { + + $obj_sess = new Zend_Session_Namespace(UI_PLAYLISTCONTROLLER_OBJ_SESSNAME); + if (isset($obj_sess->id)) { + $objInfo = Application_Model_Library::getObjInfo($obj_sess->type); + Logging::info($obj_sess->id); + Logging::info($obj_sess->type); + + $objInfo = Application_Model_Library::getObjInfo($obj_sess->type); + $obj = new $objInfo['className']($obj_sess->id); + $userInfo = Zend_Auth::getInstance()->getStorage()->read(); + $user = new Application_Model_User($userInfo->id); + $isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER)); + + if ($isAdminOrPM || $obj->getCreatorId() == $userInfo->id) { + $this->view->obj = $obj; + if ($obj_sess->type == "block") { + $form = new Application_Form_SmartBlockCriteria(); + $form->startForm($obj_sess->id); + $this->view->form = $form; + } + } + + $formatter = new LengthFormatter($obj->getLength()); + $this->view->length = $formatter->format(); + $this->view->type = $obj_sess->type; + } + } catch (PlaylistNotFoundException $e) { + $this->playlistNotFound($obj_sess->type); + } catch (Exception $e) { + $this->playlistNotFound($obj_sess->type); + Logging::info($e->getMessage()); + //$this->playlistUnknownError($e); + } + } + + protected function playlistNotFound($p_type) + { + $this->view->error = "$p_type not found"; + + Logging::info("$p_type not found"); + Application_Model_Library::changePlaylist(null, $p_type); + $this->createFullResponse(null); + } + + protected function playlistUnknownError($e) + { + $this->view->error = "Something went wrong."; + Logging::info($e->getMessage()); + } + + protected function createFullResponse($obj = null, $isJson = false) + { + $isBlock = false; + $viewPath = 'playlist/playlist.phtml'; + if ($obj instanceof Application_Model_Block) { + $isBlock = true; + $viewPath = 'playlist/smart-block.phtml'; + } + + if (isset($obj)) { + $formatter = new LengthFormatter($obj->getLength()); + $this->view->length = $formatter->format(); + + if ($isBlock) { + $form = new Application_Form_SmartBlockCriteria(); + $form->removeDecorator('DtDdWrapper'); + $form->startForm($obj->getId()); + + $this->view->form = $form; + $this->view->obj = $obj; + $this->view->id = $obj->getId(); + if ($isJson) { + return $this->view->render($viewPath); + } else { + $this->view->html = $this->view->render($viewPath); + } + } else { + $this->view->obj = $obj; + $this->view->id = $obj->getId(); + $this->view->html = $this->view->render($viewPath); + unset($this->view->obj); + } + } else { + $this->view->html = $this->view->render($viewPath); + } } public function contextMenuAction() @@ -39,21 +152,33 @@ class LibraryController extends Zend_Controller_Action $userInfo = Zend_Auth::getInstance()->getStorage()->read(); $user = new Application_Model_User($userInfo->id); - - //Open a jPlayer window and play the audio clip. - $menu["play"] = array("name"=> "Preview", "icon" => "play"); - + + //Open a jPlayer window and play the audio clip. + $menu["play"] = array("name"=> "Preview", "icon" => "play", "disabled" => false); + $isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER)); + $obj_sess = new Zend_Session_Namespace(UI_PLAYLISTCONTROLLER_OBJ_SESSNAME); + if ($type === "audioclip") { $file = Application_Model_StoredFile::Recall($id); - if (isset($this->pl_sess->id) && $screen == "playlist") { - // if the user is not admin or pm, check the creator and see if this person owns the playlist - $playlist = new Application_Model_Playlist($this->pl_sess->id); - if($isAdminOrPM || $playlist->getCreatorId() == $user->getId()){ - $menu["pl_add"] = array("name"=> "Add to Playlist", "icon" => "add-playlist", "icon" => "copy"); + $menu["play"]["mime"] = $file->getPropelOrm()->getDbMime(); + + if (isset($obj_sess->id) && $screen == "playlist") { + // if the user is not admin or pm, check the creator and see if this person owns the playlist or Block + if ($obj_sess->type == 'playlist') { + $obj = new Application_Model_Playlist($obj_sess->id); + } elseif ($obj_sess->type == 'block') { + $obj = new Application_Model_Block($obj_sess->id); + } + if ($isAdminOrPM || $obj->getCreatorId() == $user->getId()) { + if ($obj_sess->type === "playlist") { + $menu["pl_add"] = array("name"=> "Add to Playlist", "icon" => "add-playlist", "icon" => "copy"); + } elseif ($obj_sess->type === "block") { + $menu["pl_add"] = array("name"=> "Add to Smart Block", "icon" => "add-playlist", "icon" => "copy"); + } } } if ($isAdminOrPM) { @@ -63,46 +188,77 @@ class LibraryController extends Zend_Controller_Action $url = $file->getRelativeFileUrl($baseUrl).'/download/true'; $menu["download"] = array("name" => "Download", "icon" => "download", "url" => $url); - } - else if ($type === "playlist") { - $playlist = new Application_Model_Playlist($id); - if ($this->pl_sess->id !== $id && $screen == "playlist") { - if($isAdminOrPM || $playlist->getCreatorId() == $user->getId()){ + } elseif ($type === "playlist" || $type === "block") { + if ($type === 'playlist') { + $obj = new Application_Model_Playlist($id); + } elseif ($type === 'block') { + $obj = new Application_Model_Block($id); + if (!$obj->isStatic()) { + unset($menu["play"]); + } + if (($isAdminOrPM || $obj->getCreatorId() == $user->getId()) && $screen == "playlist") { + if ($obj_sess->type === "playlist") { + $menu["pl_add"] = array("name"=> "Add to Playlist", "icon" => "add-playlist", "icon" => "copy"); + } + } + } + + if ($obj_sess->id !== $id && $screen == "playlist") { + if ($isAdminOrPM || $obj->getCreatorId() == $user->getId()) { $menu["edit"] = array("name"=> "Edit", "icon" => "edit"); } } - if($isAdminOrPM || $playlist->getCreatorId() == $user->getId()){ + if ($isAdminOrPM || $obj->getCreatorId() == $user->getId()) { + $menu["del"] = array("name"=> "Delete", "icon" => "delete", "url" => "/library/delete"); + } + } elseif ($type == "stream") { + + $webstream = CcWebstreamQuery::create()->findPK($id); + $obj = new Application_Model_Webstream($webstream); + if (isset($obj_sess->id) && $screen == "playlist") { + if ($isAdminOrPM || $obj->getCreatorId() == $user->getId()) { + if ($obj_sess->type === "playlist") { + $menu["pl_add"] = array("name"=> "Add to Playlist", "icon" => "add-playlist", "icon" => "copy"); + } + } + } + if ($isAdminOrPM || $obj->getCreatorId() == $user->getId()) { + if ($screen == "playlist") { + $menu["edit"] = array("name"=> "Edit", "icon" => "edit", "url" => "/library/edit-file-md/id/{$id}"); + } $menu["del"] = array("name"=> "Delete", "icon" => "delete", "url" => "/library/delete"); } } - //SOUNDCLOUD MENU OPTIONS - if ($type === "audioclip" && Application_Model_Preference::GetUploadToSoundcloudOption()) { - - //create a menu separator - $menu["sep1"] = "-----------"; - - //create a sub menu for Soundcloud actions. - $menu["soundcloud"] = array("name" => "Soundcloud", "icon" => "soundcloud", "items" => array()); - + if ($type === "audioclip" && Application_Model_Preference::GetUploadToSoundcloudOption()) { + + //create a menu separator + $menu["sep1"] = "-----------"; + + //create a sub menu for Soundcloud actions. + $menu["soundcloud"] = array("name" => "Soundcloud", "icon" => "soundcloud", "items" => array()); + $scid = $file->getSoundCloudId(); - - if ($scid > 0){ - $url = $file->getSoundCloudLinkToFile(); - $menu["soundcloud"]["items"]["view"] = array("name" => "View on Soundcloud", "icon" => "soundcloud", "url" => $url); - } - - if (!is_null($scid)){ - $text = "Re-upload to SoundCloud"; - } - else { - $text = "Upload to SoundCloud"; - } - - $menu["soundcloud"]["items"]["upload"] = array("name" => $text, "icon" => "soundcloud", "url" => "/library/upload-file-soundcloud/id/{$id}"); + + if ($scid > 0) { + $url = $file->getSoundCloudLinkToFile(); + $menu["soundcloud"]["items"]["view"] = array("name" => "View on Soundcloud", "icon" => "soundcloud", "url" => $url); + } + + if (!is_null($scid)) { + $text = "Re-upload to SoundCloud"; + } else { + $text = "Upload to SoundCloud"; + } + + $menu["soundcloud"]["items"]["upload"] = array("name" => $text, "icon" => "soundcloud", "url" => "/library/upload-file-soundcloud/id/{$id}"); } - + + if (empty($menu)) { + $menu["noaction"] = array("name"=>"No action available"); + } + $this->view->items = $menu; } @@ -111,11 +267,13 @@ class LibraryController extends Zend_Controller_Action //array containing id and type of media to delete. $mediaItems = $this->_getParam('media', null); - $user = Application_Model_User::GetCurrentUser(); - $isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER)); + $user = Application_Model_User::getCurrentUser(); + //$isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER)); - $files = array(); + $files = array(); $playlists = array(); + $blocks = array(); + $streams = array(); $message = null; @@ -123,33 +281,34 @@ class LibraryController extends Zend_Controller_Action if ($media["type"] === "audioclip") { $files[] = intval($media["id"]); - } - else if ($media["type"] === "playlist") { + } elseif ($media["type"] === "playlist") { $playlists[] = intval($media["id"]); + } elseif ($media["type"] === "block") { + $blocks[] = intval($media["id"]); + } elseif ($media["type"] === "stream") { + $streams[] = intval($media["id"]); } } - $hasPermission = true; - if (count($playlists)) { - // make sure use has permission to delete all playslists in the list - if(!$isAdminOrPM){ - foreach($playlists as $pid){ - $pl = new Application_Model_Playlist($pid); - if($pl->getCreatorId() != $user->getId()){ - $hasPermission = false; - } - } - } - } + try { + Application_Model_Playlist::deletePlaylists($playlists, $user->getId()); + } catch (PlaylistNoPermissionException $e) { + $this->view->message = "You don't have permission to delete selected items."; - if (!$isAdminOrPM && count($files)) { - $hasPermission = false; - } - if(!$hasPermission){ - $this->view->message = "You don't have a permission to delete all playlists/files that are selected."; return; - }else{ - Application_Model_Playlist::DeletePlaylists($playlists); + } + + try { + Application_Model_Block::deleteBlocks($blocks, $user->getId()); + } catch (Exception $e) { + //TODO: warn user that not all blocks could be deleted. + } + + try { + Application_Model_Webstream::deleteStreams($streams, $user->getId()); + } catch (Exception $e) { + //TODO: warn user that not all streams could be deleted. + Logging::info($e); } foreach ($files as $id) { @@ -159,10 +318,10 @@ class LibraryController extends Zend_Controller_Action if (isset($file)) { try { $res = $file->delete(true); - } - //could throw a scheduled in future exception. - catch (Exception $e) { + } catch (Exception $e) { + //could throw a scheduled in future exception. $message = "Could not delete some scheduled files."; + Logging::debug($e->getMessage()); } } } @@ -175,41 +334,40 @@ class LibraryController extends Zend_Controller_Action public function contentsFeedAction() { $params = $this->getRequest()->getParams(); + $r = Application_Model_StoredFile::searchLibraryFiles($params); //TODO move this to the datatables row callback. foreach ($r["aaData"] as &$data) { - if ($data['ftype'] == 'audioclip'){ + if ($data['ftype'] == 'audioclip') { $file = Application_Model_StoredFile::Recall($data['id']); $scid = $file->getSoundCloudId(); - if ($scid == "-2"){ + if ($scid == "-2") { $data['track_title'] .= ''; - } - else if ($scid == "-3"){ + } elseif ($scid == "-3") { $data['track_title'] .= ''; - } - else if (!is_null($scid)){ + } elseif (!is_null($scid)) { $data['track_title'] .= ''; } } } - - $this->view->sEcho = $r["sEcho"]; - $this->view->iTotalDisplayRecords = $r["iTotalDisplayRecords"]; - $this->view->iTotalRecords = $r["iTotalRecords"]; + + $this->view->sEcho = $r["sEcho"]; + $this->view->iTotalDisplayRecords = $r["iTotalDisplayRecords"]; + $this->view->iTotalRecords = $r["iTotalRecords"]; $this->view->files = $r["aaData"]; } public function editFileMdAction() { - $user = Application_Model_User::GetCurrentUser(); + $user = Application_Model_User::getCurrentUser(); $isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER)); - if(!$isAdminOrPM){ + if (!$isAdminOrPM) { return; } - + $request = $this->getRequest(); $form = new Application_Form_EditAudioMD(); @@ -227,17 +385,17 @@ class LibraryController extends Zend_Controller_Action // set MDATA_KEY_FILEPATH $data['MDATA_KEY_FILEPATH'] = $file->getFilePath(); - Logging::log($data['MDATA_KEY_FILEPATH']); + Logging::info($data['MDATA_KEY_FILEPATH']); Application_Model_RabbitMq::SendMessageToMediaMonitor("md_update", $data); - $this->_redirect('playlist/index'); + $this->_redirect('Library'); } } $this->view->form = $form; } - public function getFileMetaDataAction() + public function getFileMetadataAction() { $id = $this->_getParam('id'); $type = $this->_getParam('type'); @@ -247,14 +405,14 @@ class LibraryController extends Zend_Controller_Action $file = Application_Model_StoredFile::Recall($id); $this->view->type = $type; $md = $file->getMetadata(); - + foreach ($md as $key => $value) { if ($key == 'MDATA_KEY_DIRECTORY') { $musicDir = Application_Model_MusicDir::getDirByPK($value); $md['MDATA_KEY_FILEPATH'] = Application_Common_OsPath::join($musicDir->getDirectory(), $md['MDATA_KEY_FILEPATH']); } } - + $formatter = new SamplerateFormatter($md["MDATA_KEY_SAMPLERATE"]); $md["MDATA_KEY_SAMPLERATE"] = $formatter->format(); @@ -266,8 +424,7 @@ class LibraryController extends Zend_Controller_Action $this->view->md = $md; - } - else if ($type == "playlist") { + } elseif ($type == "playlist") { $file = new Application_Model_Playlist($id); $this->view->type = $type; @@ -278,21 +435,47 @@ class LibraryController extends Zend_Controller_Action $this->view->md = $md; $this->view->contents = $file->getContents(); + } elseif ($type == "block") { + $block = new Application_Model_Block($id); + $this->view->type = $type; + $md = $block->getAllPLMetaData(); + + $formatter = new LengthFormatter($md["dcterms:extent"]); + $md["dcterms:extent"] = $formatter->format(); + + $this->view->md = $md; + if ($block->isStatic()) { + $this->view->blType = 'Static'; + $this->view->contents = $block->getContents(); + } else { + $this->view->blType = 'Dynamic'; + $this->view->contents = $block->getCriteria(); + } + $this->view->block = $block; + } elseif ($type == "stream") { + $webstream = CcWebstreamQuery::create()->findPK($id); + $ws = new Application_Model_Webstream($webstream); + + $md = $ws->getMetadata(); + + $this->view->md = $md; + $this->view->type = $type; } - } - catch (Exception $e) { - Logging::log($e->getMessage()); + } catch (Exception $e) { + Logging::info($e->getMessage()); } } - public function uploadFileSoundcloudAction(){ + public function uploadFileSoundcloudAction() + { $id = $this->_getParam('id'); - $res = exec("/usr/lib/airtime/utils/soundcloud-uploader $id > /dev/null &"); + Application_Model_Soundcloud::uploadSoundcloud($id); // we should die with ui info die(); } - public function getUploadToSoundcloudStatusAction(){ + public function getUploadToSoundcloudStatusAction() + { $id = $this->_getParam('id'); $type = $this->_getParam('type'); @@ -302,12 +485,13 @@ class LibraryController extends Zend_Controller_Action $file = $show_instance->getRecordedFile(); $this->view->error_code = $file->getSoundCloudErrorCode(); $this->view->error_msg = $file->getSoundCloudErrorMsg(); - } - else if ($type == "file") { - $file = Application_Model_StoredFile::Recall($id); - $this->view->sc_id = $file->getSoundCloudId(); + } elseif ($type == "file") { + $file = Application_Model_StoredFile::Recall($id); + $this->view->sc_id = $file->getSoundCloudId(); $this->view->error_code = $file->getSoundCloudErrorCode(); - $this->view->error_msg = $file->getSoundCloudErrorMsg(); + $this->view->error_msg = $file->getSoundCloudErrorMsg(); + } else { + Logging::warn("Trying to upload unknown type: $type with id: $id"); } } } diff --git a/airtime_mvc/application/controllers/LoginController.php b/airtime_mvc/application/controllers/LoginController.php index 6cef61761..e3eeccca4 100644 --- a/airtime_mvc/application/controllers/LoginController.php +++ b/airtime_mvc/application/controllers/LoginController.php @@ -11,67 +11,61 @@ class LoginController extends Zend_Controller_Action public function indexAction() { global $CC_CONFIG; - - if (Zend_Auth::getInstance()->hasIdentity()) - { + + if (Zend_Auth::getInstance()->hasIdentity()) { $this->_redirect('Showbuilder'); } - + //uses separate layout without a navigation. $this->_helper->layout->setLayout('login'); - + $error = false; $request = $this->getRequest(); $baseUrl = $request->getBaseUrl(); - + $this->view->headScript()->appendFile($baseUrl.'/js/airtime/login/login.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); - + $form = new Application_Form_Login(); - + $message = "Please enter your user name and password"; - if($request->isPost()) - { + if ($request->isPost()) { // if the post contains recaptcha field, which means form had recaptcha field. // Hence add the element for validation. - if(array_key_exists('recaptcha_response_field', $request->getPost())){ + if (array_key_exists('recaptcha_response_field', $request->getPost())) { $form->addRecaptcha(); } - if($form->isValid($request->getPost())) - { + if ($form->isValid($request->getPost())) { //get the username and password from the form $username = $form->getValue('username'); $password = $form->getValue('password'); - if(Application_Model_Subjects::getLoginAttempts($username) >= 3 && $form->getElement('captcha') == NULL){ + if (Application_Model_Subjects::getLoginAttempts($username) >= 3 && $form->getElement('captcha') == NULL) { $form->addRecaptcha(); - }else{ + } else { $authAdapter = Application_Model_Auth::getAuthAdapter(); //pass to the adapter the submitted username and password $authAdapter->setIdentity($username) ->setCredential($password); - + $auth = Zend_Auth::getInstance(); $result = $auth->authenticate($authAdapter); - if($result->isValid()) - { + if ($result->isValid()) { //all info about this user from the login table omit only the password $userInfo = $authAdapter->getResultRowObject(null, 'password'); - + //the default storage is a session with namespace Zend_Auth $authStorage = $auth->getStorage(); $authStorage->write($userInfo); - + Application_Model_LoginAttempts::resetAttempts($_SERVER['REMOTE_ADDR']); Application_Model_Subjects::resetLoginAttempts($username); - + $tempSess = new Zend_Session_Namespace("referrer"); $tempSess->referrer = 'login'; - + $this->_redirect('Showbuilder'); - } - else - { + } else { $message = "Wrong username or password provided. Please try again."; Application_Model_Subjects::increaseLoginAttempts($username); Application_Model_LoginAttempts::increaseAttempts($_SERVER['REMOTE_ADDR']); @@ -81,13 +75,13 @@ class LoginController extends Zend_Controller_Action } } } - + $this->view->message = $message; $this->view->error = $error; $this->view->form = $form; $this->view->airtimeVersion = Application_Model_Preference::GetAirtimeVersion(); $this->view->airtimeCopyright = AIRTIME_COPYRIGHT_DATE; - if(isset($CC_CONFIG['demo'])){ + if (isset($CC_CONFIG['demo'])) { $this->view->demo = $CC_CONFIG['demo']; } } @@ -97,103 +91,105 @@ class LoginController extends Zend_Controller_Action Zend_Auth::getInstance()->clearIdentity(); $this->_redirect('showbuilder/index'); } - - public function passwordRestoreAction() + + public function passwordRestoreAction() { global $CC_CONFIG; - + $request = $this->getRequest(); $baseUrl = $request->getBaseUrl(); $this->view->headScript()->appendFile($baseUrl.'/js/airtime/login/password-restore.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); - + if (!Application_Model_Preference::GetEnableSystemEmail()) { $this->_redirect('login'); - } - else { - //uses separate layout without a navigation. - $this->_helper->layout->setLayout('login'); - - $form = new Application_Form_PasswordRestore(); - - $request = $this->getRequest(); - if ($request->isPost() && $form->isValid($request->getPost())) { - $user = CcSubjsQuery::create() - ->filterByDbEmail($form->email->getValue()) - ->findOne(); - - if (!empty($user)) { - $auth = new Application_Model_Auth(); - + } else { + //uses separate layout without a navigation. + $this->_helper->layout->setLayout('login'); + + $form = new Application_Form_PasswordRestore(); + + $request = $this->getRequest(); + if ($request->isPost() && $form->isValid($request->getPost())) { + if (is_null($form->username->getValue()) || $form->username->getValue() == '') { + $user = CcSubjsQuery::create() + ->filterByDbEmail($form->email->getValue()) + ->findOne(); + } else { + $user = CcSubjsQuery::create() + ->filterByDbEmail($form->email->getValue()) + ->filterByDbLogin($form->username->getValue()) + ->findOne(); + } + + if (!empty($user)) { + $auth = new Application_Model_Auth(); + $success = $auth->sendPasswordRestoreLink($user, $this->view); - if ($success) { + if ($success) { $this->_helper->redirector('password-restore-after', 'login'); } else { $form->email->addError($this->view->translate("Email could not be sent. Check your mail server settings and ensure it has been configured properly.")); - } - } - else { - $form->email->addError($this->view->translate("Given email not found.")); - } + } + } else { + $form->email->addError($this->view->translate("Given email not found.")); + } } - + $this->view->form = $form; - } - } - - public function passwordRestoreAfterAction() - { - //uses separate layout without a navigation. - $this->_helper->layout->setLayout('login'); - } - - public function passwordChangeAction() - { - //uses separate layout without a navigation. - $this->_helper->layout->setLayout('login'); - - $request = $this->getRequest(); - $token = $request->getParam("token", false); - $user_id = $request->getParam("user_id", 0); - - $form = new Application_Form_PasswordChange(); - $auth = new Application_Model_Auth(); - $user = CcSubjsQuery::create()->findPK($user_id); - - //check validity of token - if (!$auth->checkToken($user_id, $token, 'password.restore')) { - Logging::debug("token not valid"); - $this->_helper->redirector('index', 'login'); - } - - if ($request->isPost() && $form->isValid($request->getPost())) { - - $user->setDbPass(md5($form->password->getValue())); - $user->save(); - - $auth->invalidateTokens($user, 'password.restore'); - - $zend_auth = Zend_Auth::getInstance(); - $zend_auth->clearIdentity(); - - $authAdapter = Application_Model_Auth::getAuthAdapter(); - $authAdapter->setIdentity($user->getDbLogin()) - ->setCredential($form->password->getValue()); - - $result = $zend_auth->authenticate($authAdapter); - - //all info about this user from the login table omit only the password - $userInfo = $authAdapter->getResultRowObject(null, 'password'); - - //the default storage is a session with namespace Zend_Auth - $authStorage = $zend_auth->getStorage(); - $authStorage->write($userInfo); - - $this->_helper->redirector('index', 'showbuilder'); - } - - $this->view->form = $form; + } + } + + public function passwordRestoreAfterAction() + { + //uses separate layout without a navigation. + $this->_helper->layout->setLayout('login'); + } + + public function passwordChangeAction() + { + //uses separate layout without a navigation. + $this->_helper->layout->setLayout('login'); + + $request = $this->getRequest(); + $token = $request->getParam("token", false); + $user_id = $request->getParam("user_id", 0); + + $form = new Application_Form_PasswordChange(); + $auth = new Application_Model_Auth(); + $user = CcSubjsQuery::create()->findPK($user_id); + + //check validity of token + if (!$auth->checkToken($user_id, $token, 'password.restore')) { + Logging::debug("token not valid"); + $this->_helper->redirector('index', 'login'); + } + + if ($request->isPost() && $form->isValid($request->getPost())) { + + $user->setDbPass(md5($form->password->getValue())); + $user->save(); + + $auth->invalidateTokens($user, 'password.restore'); + + $zend_auth = Zend_Auth::getInstance(); + $zend_auth->clearIdentity(); + + $authAdapter = Application_Model_Auth::getAuthAdapter(); + $authAdapter->setIdentity($user->getDbLogin()) + ->setCredential($form->password->getValue()); + + $zend_auth->authenticate($authAdapter); + + //all info about this user from the login table omit only the password + $userInfo = $authAdapter->getResultRowObject(null, 'password'); + + //the default storage is a session with namespace Zend_Auth + $authStorage = $zend_auth->getStorage(); + $authStorage->write($userInfo); + + $this->_helper->redirector('index', 'showbuilder'); + } + + $this->view->form = $form; } } - - - diff --git a/airtime_mvc/application/controllers/PlaylistController.php b/airtime_mvc/application/controllers/PlaylistController.php index f53a99754..2cca81ac2 100644 --- a/airtime_mvc/application/controllers/PlaylistController.php +++ b/airtime_mvc/application/controllers/PlaylistController.php @@ -2,7 +2,6 @@ class PlaylistController extends Zend_Controller_Action { - protected $pl_sess = null; public function init() { @@ -22,218 +21,274 @@ class PlaylistController extends Zend_Controller_Action ->addActionContext('set-playlist-description', 'json') ->addActionContext('playlist-preview', 'json') ->addActionContext('get-playlist', 'json') + ->addActionContext('save', 'json') + ->addActionContext('smart-block-generate', 'json') + ->addActionContext('smart-block-shuffle', 'json') + ->addActionContext('get-block-info', 'json') ->initContext(); - $this->pl_sess = new Zend_Session_Namespace(UI_PLAYLIST_SESSNAME); } - private function getPlaylist() + private function getPlaylist($p_type) { - $pl = null; + $obj = null; + $objInfo = Application_Model_Library::getObjInfo($p_type); - if (isset($this->pl_sess->id)) { - $pl = new Application_Model_Playlist($this->pl_sess->id); + $obj_sess = new Zend_Session_Namespace( UI_PLAYLISTCONTROLLER_OBJ_SESSNAME); + if (isset($obj_sess->id)) { + $obj = new $objInfo['className']($obj_sess->id); $modified = $this->_getParam('modified', null); - if ($pl->getLastModified("U") !== $modified) { - $this->createFullResponse($pl); - throw new PlaylistOutDatedException("You are viewing an older version of {$pl->getName()}"); + if ($obj->getLastModified("U") !== $modified) { + $this->createFullResponse($obj); + throw new PlaylistOutDatedException("You are viewing an older version of {$obj->getName()}"); } } - return $pl; + + return $obj; } - private function changePlaylist($pl_id) + private function createUpdateResponse($obj) { - if (is_null($pl_id)) { - unset($this->pl_sess->id); - } - else { - $this->pl_sess->id = intval($pl_id); - } - } - - private function createUpdateResponse($pl) - { - $formatter = new LengthFormatter($pl->getLength()); + $formatter = new LengthFormatter($obj->getLength()); $this->view->length = $formatter->format(); - $this->view->pl = $pl; + $this->view->obj = $obj; + $this->view->contents = $obj->getContents(); $this->view->html = $this->view->render('playlist/update.phtml'); - $this->view->name = $pl->getName(); - $this->view->description = $pl->getDescription(); - $this->view->modified = $pl->getLastModified("U"); + $this->view->name = $obj->getName(); + $this->view->description = $obj->getDescription(); + $this->view->modified = $obj->getLastModified("U"); - unset($this->view->pl); + unset($this->view->obj); } - private function createFullResponse($pl = null) + private function createFullResponse($obj = null, $isJson = false, + $formIsValid = false) { - if (isset($pl)) { - $formatter = new LengthFormatter($pl->getLength()); + $isBlock = false; + $viewPath = 'playlist/playlist.phtml'; + if ($obj instanceof Application_Model_Block) { + $isBlock = true; + $viewPath = 'playlist/smart-block.phtml'; + } + + if (isset($obj)) { + $formatter = new LengthFormatter($obj->getLength()); $this->view->length = $formatter->format(); - $this->view->pl = $pl; - $this->view->id = $pl->getId(); - $this->view->html = $this->view->render('playlist/playlist.phtml'); - unset($this->view->pl); - } - else { - $this->view->html = $this->view->render('playlist/playlist.phtml'); + if ($isBlock) { + $form = new Application_Form_SmartBlockCriteria(); + $form->removeDecorator('DtDdWrapper'); + $form->startForm($obj->getId(), $formIsValid); + + $this->view->form = $form; + $this->view->obj = $obj; + $this->view->id = $obj->getId(); + + if ($isJson) { + return $this->view->render($viewPath); + } else { + $this->view->html = $this->view->render($viewPath); + } + } else { + $this->view->obj = $obj; + $this->view->id = $obj->getId(); + $this->view->html = $this->view->render($viewPath); + unset($this->view->obj); + } + } else { + if ($isJson) { + return $this->view->render($viewPath); + } else { + $this->view->html = $this->view->render($viewPath); + } } } - private function playlistOutdated($pl, $e) + private function playlistOutdated($e) { $this->view->error = $e->getMessage(); } - private function playlistNotFound() + private function blockDynamic($obj) { - $this->view->error = "Playlist not found"; + $this->view->error = "You cannot add tracks to dynamic blocks."; + $this->createFullResponse($obj); + } - Logging::log("Playlist not found"); - $this->changePlaylist(null); + private function playlistNotFound($p_type, $p_isJson = false) + { + $p_type = ucfirst($p_type); + $this->view->error = "{$p_type} not found"; + + Logging::info("{$p_type} not found"); + Application_Model_Library::changePlaylist(null, $p_type); + + if (!$p_isJson) { + $this->createFullResponse(null); + } else { + die(json_encode(array("error"=>$this->view->error, "result"=>1, "html"=>$this->createFullResponse(null, $p_isJson)))); + } + } + + private function playlistNoPermission($p_type) + { + $this->view->error = "You don't have permission to delete selected {$p_type}(s)."; + $this->changePlaylist(null, $p_type); $this->createFullResponse(null); } private function playlistUnknownError($e) { $this->view->error = "Something went wrong."; - - Logging::log("{$e->getFile()}"); - Logging::log("{$e->getLine()}"); - Logging::log("{$e->getMessage()}"); + Logging::info($e->getMessage()); } - public function indexAction() + private function wrongTypeToBlock($obj) { - global $CC_CONFIG; + $this->view->error = "You can only add tracks to smart block."; + $this->createFullResponse($obj); + } - $request = $this->getRequest(); - $baseUrl = $request->getBaseUrl(); - - $this->view->headScript()->appendFile($baseUrl.'/js/blockui/jquery.blockUI.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); - $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/airtime/buttons/buttons.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); - $this->view->headScript()->appendFile($baseUrl.'/js/airtime/utilities/utilities.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($this->view->baseUrl('/js/airtime/library/events/library_playlistbuilder.js'),'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->headScript()->appendFile($baseUrl.'/js/airtime/library/spl.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); - $this->view->headLink()->appendStylesheet($baseUrl.'/css/playlist_builder.css?'.$CC_CONFIG['airtime_version']); - - try { - if (isset($this->pl_sess->id)) { - $pl = new Application_Model_Playlist($this->pl_sess->id); - $this->view->pl = $pl; - - $formatter = new LengthFormatter($pl->getLength()); - $this->view->length = $formatter->format(); - } - } - catch (PlaylistNotFoundException $e) { - $this->playlistNotFound(); - } - catch (Exception $e) { - $this->playlistUnknownError($e); - } + private function wrongTypeToPlaylist($obj) + { + $this->view->error = "You can only add tracks, smart blocks, and webstreams to playlists."; + $this->createFullResponse($obj); } public function newAction() { - $pl_sess = $this->pl_sess; - $userInfo = Zend_Auth::getInstance()->getStorage()->read(); + //$pl_sess = $this->pl_sess; + $userInfo = Zend_Auth::getInstance()->getStorage()->read(); + $type = $this->_getParam('type'); - $pl = new Application_Model_Playlist(); - $pl->setName("Untitled Playlist"); - $pl->setPLMetaData('dc:creator', $userInfo->id); + $objInfo = Application_Model_Library::getObjInfo($type); - $this->changePlaylist($pl->getId()); - $this->createFullResponse($pl); + $name = 'Untitled Playlist'; + if ($type == 'block') { + $name = 'Untitled Smart Block'; + } + + $obj = new $objInfo['className'](); + $obj->setName($name); + $obj->setMetadata('dc:creator', $userInfo->id); + + Application_Model_Library::changePlaylist($obj->getId(), $type); + $this->createFullResponse($obj); } public function editAction() { $id = $this->_getParam('id', null); - Logging::log("editing playlist {$id}"); + $type = $this->_getParam('type'); + $objInfo = Application_Model_Library::getObjInfo($type); + Logging::info("editing {$type} {$id}"); - if (!is_null($id)) { - $this->changePlaylist($id); - } + if (!is_null($id)) { + Application_Model_Library::changePlaylist($id, $type); + } - try { - $pl = new Application_Model_Playlist($id); - $this->createFullResponse($pl); - } - catch (PlaylistNotFoundException $e) { - $this->playlistNotFound(); - } - catch (Exception $e) { - $this->playlistUnknownError($e); - } + try { + $obj = new $objInfo['className']($id); + $this->createFullResponse($obj); + } catch (PlaylistNotFoundException $e) { + $this->playlistNotFound(); + } catch (Exception $e) { + $this->playlistUnknownError($e); + } } public function deleteAction() { - $ids = $this->_getParam('ids'); - $ids = (!is_array($ids)) ? array($ids) : $ids; - $pl = null; + $ids = $this->_getParam('ids'); + $ids = (!is_array($ids)) ? array($ids) : $ids; + $type = $this->_getParam('type'); + + $obj = null; + + $objInfo = Application_Model_Library::getObjInfo($type); + + $userInfo = Zend_Auth::getInstance()->getStorage()->read(); + + $obj_sess = new Zend_Session_Namespace( + UI_PLAYLISTCONTROLLER_OBJ_SESSNAME); try { - - Logging::log("Currently active playlist {$this->pl_sess->id}"); - if (in_array($this->pl_sess->id, $ids)) { - Logging::log("Deleting currently active playlist"); - $this->changePlaylist(null); - } - else { - Logging::log("Not deleting currently active playlist"); - $pl = new Application_Model_Playlist($this->pl_sess->id); + Logging::info("Currently active {$type} {$obj_sess->id}"); + if (in_array($obj_sess->id, $ids)) { + Logging::info("Deleting currently active {$type}"); + Application_Model_Library::changePlaylist(null, $type); + } else { + Logging::info("Not deleting currently active {$type}"); + $obj = new $objInfo['className']($obj_sess->id); } - Application_Model_Playlist::DeletePlaylists($ids); - $this->createFullResponse($pl); - } - catch (PlaylistNotFoundException $e) { - $this->playlistNotFound(); - } - catch (Exception $e) { + if (strcmp($objInfo['className'], 'Application_Model_Playlist')==0) { + Application_Model_Playlist::deletePlaylists($ids, $userInfo->id); + } else { + Application_Model_Block::deleteBlocks($ids, $userInfo->id); + } + $this->createFullResponse($obj); + } catch (PlaylistNoPermissionException $e) { + $this->playlistNoPermission($type); + } catch (BlockNoPermissionException $e) { + $this->playlistNoPermission($type); + } catch (PlaylistNotFoundException $e) { + $this->playlistNotFound($type); + } catch (Exception $e) { $this->playlistUnknownError($e); } } - + public function addItemsAction() { - $ids = $this->_getParam('ids', array()); + $ids = $this->_getParam('aItems', array()); $ids = (!is_array($ids)) ? array($ids) : $ids; - $afterItem = $this->_getParam('afterItem', null); - $addType = $this->_getParam('type', 'after'); + $afterItem = $this->_getParam('afterItem', null); + $addType = $this->_getParam('type', 'after'); + // this is the obj type of destination + $obj_type = $this->_getParam('obj_type'); try { - $pl = $this->getPlaylist(); - $pl->addAudioClips($ids, $afterItem, $addType); - $this->createUpdateResponse($pl); - } - catch (PlaylistOutDatedException $e) { - $this->playlistOutdated($pl, $e); - } - catch (PlaylistNotFoundException $e) { - $this->playlistNotFound(); - } - catch (Exception $e) { + $obj = $this->getPlaylist($obj_type); + if ($obj_type == 'playlist') { + foreach ($ids as $id) { + if (is_array($id) && isset($id[1])) { + if ($id[1] == 'playlist') { + throw new WrongTypeToPlaylistException; + } + } + } + $obj->addAudioClips($ids, $afterItem, $addType); + } elseif ($obj->isStatic()) { + // if the dest is a block object + //check if any items are playlists + foreach ($ids as $id) { + if (is_array($id) && isset($id[1])) { + if ($id[1] != 'audioclip') { + throw new WrongTypeToBlockException; + } + } + } + $obj->addAudioClips($ids, $afterItem, $addType); + } else { + throw new BlockDynamicException; + } + $this->createUpdateResponse($obj); + } catch (PlaylistOutDatedException $e) { + $this->playlistOutdated($e); + } catch (PlaylistNotFoundException $e) { + $this->playlistNotFound($obj_type); + } catch (WrongTypeToBlockException $e) { + $this->wrongTypeToBlock($obj); + } catch (WrongTypeToPlaylistException $e) { + $this->wrongTypeToPlaylist($obj); + } catch (BlockDynamicException $e) { + $this->blockDynamic($obj); + } catch (BlockNotFoundException $e) { + $this->playlistNotFound($obj_type); + } catch (Exception $e) { $this->playlistUnknownError($e); } } @@ -243,20 +298,17 @@ class PlaylistController extends Zend_Controller_Action $ids = $this->_getParam('ids'); $ids = (!is_array($ids)) ? array($ids) : $ids; $afterItem = $this->_getParam('afterItem', null); - $modified = $this->_getParam('modified'); + $type = $this->_getParam('obj_type'); try { - $pl = $this->getPlaylist(); - $pl->moveAudioClips($ids, $afterItem); - $this->createUpdateResponse($pl); - } - catch (PlaylistOutDatedException $e) { - $this->playlistOutdated($pl, $e); - } - catch (PlaylistNotFoundException $e) { - $this->playlistNotFound(); - } - catch (Exception $e) { + $obj = $this->getPlaylist($type); + $obj->moveAudioClips($ids, $afterItem); + $this->createUpdateResponse($obj); + } catch (PlaylistOutDatedException $e) { + $this->playlistOutdated($e); + } catch (PlaylistNotFoundException $e) { + $this->playlistNotFound($type); + } catch (Exception $e) { $this->playlistUnknownError($e); } } @@ -266,98 +318,88 @@ class PlaylistController extends Zend_Controller_Action $ids = $this->_getParam('ids'); $ids = (!is_array($ids)) ? array($ids) : $ids; $modified = $this->_getParam('modified'); + $type = $this->_getParam('obj_type'); try { - $pl = $this->getPlaylist(); - $pl->delAudioClips($ids); - $this->createUpdateResponse($pl); - } - catch (PlaylistOutDatedException $e) { - $this->playlistOutdated($pl, $e); - } - catch (PlaylistNotFoundException $e) { - $this->playlistNotFound(); - } - catch (Exception $e) { + $obj = $this->getPlaylist($type); + $obj->delAudioClips($ids); + $this->createUpdateResponse($obj); + } catch (PlaylistOutDatedException $e) { + $this->playlistOutdated($e); + } catch (PlaylistNotFoundException $e) { + $this->playlistNotFound($type); + } catch (Exception $e) { $this->playlistUnknownError($e); } } public function setCueAction() { - $id = $this->_getParam('id'); - $cueIn = $this->_getParam('cueIn', null); - $cueOut = $this->_getParam('cueOut', null); + $id = $this->_getParam('id'); + $cueIn = $this->_getParam('cueIn', null); + $cueOut = $this->_getParam('cueOut', null); + $type = $this->_getParam('type'); try { - $pl = $this->getPlaylist(); - $response = $pl->changeClipLength($id, $cueIn, $cueOut); + $obj = $this->getPlaylist($type); + $response = $obj->changeClipLength($id, $cueIn, $cueOut); if (!isset($response["error"])) { $this->view->response = $response; - $this->createUpdateResponse($pl); - } - else { + $this->createUpdateResponse($obj); + } else { $this->view->cue_error = $response["error"]; } - } - catch (PlaylistOutDatedException $e) { - $this->playlistOutdated($pl, $e); - } - catch (PlaylistNotFoundException $e) { - $this->playlistNotFound(); - } - catch (Exception $e) { + } catch (PlaylistOutDatedException $e) { + $this->playlistOutdated($e); + } catch (PlaylistNotFoundException $e) { + $this->playlistNotFound($type); + } catch (Exception $e) { $this->playlistUnknownError($e); } } public function setFadeAction() { - $id = $this->_getParam('id'); - $fadeIn = $this->_getParam('fadeIn', null); - $fadeOut = $this->_getParam('fadeOut', null); + $id = $this->_getParam('id'); + $fadeIn = $this->_getParam('fadeIn', null); + $fadeOut = $this->_getParam('fadeOut', null); + $type = $this->_getParam('type'); try { - $pl = $this->getPlaylist(); - $response = $pl->changeFadeInfo($id, $fadeIn, $fadeOut); + $obj = $this->getPlaylist($type); + $response = $obj->changeFadeInfo($id, $fadeIn, $fadeOut); if (!isset($response["error"])) { - $this->createUpdateResponse($pl); + $this->createUpdateResponse($obj); $this->view->response = $response; - } - else { + } else { $this->view->fade_error = $response["error"]; } - } - catch (PlaylistOutDatedException $e) { - $this->playlistOutdated($pl, $e); - } - catch (PlaylistNotFoundException $e) { - $this->playlistNotFound(); - } - catch (Exception $e) { + } catch (PlaylistOutDatedException $e) { + $this->playlistOutdated($e); + } catch (PlaylistNotFoundException $e) { + $this->playlistNotFound($type); + } catch (Exception $e) { $this->playlistUnknownError($e); } } public function getPlaylistFadesAction() { + $type = $this->_getParam('type'); try { - $pl = $this->getPlaylist(); - $fades = $pl->getFadeInfo(0); + $obj = $this->getPlaylist($type); + $fades = $obj->getFadeInfo(0); $this->view->fadeIn = $fades[0]; - $fades = $pl->getFadeInfo($pl->getSize()-1); + $fades = $obj->getFadeInfo($obj->getSize()-1); $this->view->fadeOut = $fades[1]; - } - catch (PlaylistOutDatedException $e) { - $this->playlistOutdated($pl, $e); - } - catch (PlaylistNotFoundException $e) { - $this->playlistNotFound(); - } - catch (Exception $e) { + } catch (PlaylistOutDatedException $e) { + $this->playlistOutdated($e); + } catch (PlaylistNotFoundException $e) { + $this->playlistNotFound($type); + } catch (Exception $e) { $this->playlistUnknownError($e); } } @@ -369,65 +411,147 @@ class PlaylistController extends Zend_Controller_Action **/ public function setPlaylistFadesAction() { - $fadeIn = $this->_getParam('fadeIn', null); - $fadeOut = $this->_getParam('fadeOut', null); + $fadeIn = $this->_getParam('fadeIn', null); + $fadeOut = $this->_getParam('fadeOut', null); + $type = $this->_getParam('type'); try { - $pl = $this->getPlaylist(); - $pl->setPlaylistfades($fadeIn, $fadeOut); - $this->view->modified = $pl->getLastModified("U"); - } - catch (PlaylistOutDatedException $e) { - $this->playlistOutdated($pl, $e); - } - catch (PlaylistNotFoundException $e) { - $this->playlistNotFound(); - } - catch (Exception $e) { + $obj = $this->getPlaylist($type); + $obj->setfades($fadeIn, $fadeOut); + $this->view->modified = $obj->getLastModified("U"); + } catch (PlaylistOutDatedException $e) { + $this->playlistOutdated($e); + } catch (PlaylistNotFoundException $e) { + $this->playlistNotFound($type); + } catch (Exception $e) { $this->playlistUnknownError($e); } } - public function setPlaylistNameAction() + public function setPlaylistNameDescAction() { $name = $this->_getParam('name', 'Unknown Playlist'); + $description = $this->_getParam('description', ""); + $type = $this->_getParam('type'); try { - $pl = $this->getPlaylist(); - $pl->setName($name); + $obj = $this->getPlaylist($type); + $obj->setName(trim($name)); + $obj->setDescription($description); + $this->view->description = $description; $this->view->playlistName = $name; - $this->view->modified = $pl->getLastModified("U"); - } - catch (PlaylistOutDatedException $e) { - $this->playlistOutdated($pl, $e); - } - catch (PlaylistNotFoundException $e) { - $this->playlistNotFound(); - } - catch (Exception $e) { + $this->view->modified = $obj->getLastModified("U"); + } catch (PlaylistOutDatedException $e) { + $this->playlistOutdated($e); + } catch (PlaylistNotFoundException $e) { + $this->playlistNotFound($type, true); + } catch (Exception $e) { $this->playlistUnknownError($e); } } - public function setPlaylistDescriptionAction() + public function saveAction() { - $description = $this->_getParam('description', ""); + $request = $this->getRequest(); + $params = $request->getPost(); + $result = array(); + + if ($params['type'] == 'block') { + try { + $bl = new Application_Model_Block($params['obj_id']); + } catch (BlockNotFoundException $e) { + $this->playlistNotFound('block', true); + } + $form = new Application_Form_SmartBlockCriteria(); + $form->startForm($params['obj_id']); + if ($form->isValid($params)) { + $this->setPlaylistNameDescAction(); + $bl->saveSmartBlockCriteria($params['data']); + $result['html'] = $this->createFullResponse($bl, true, true); + $result['result'] = 0; + } else { + $this->view->obj = $bl; + $this->view->id = $bl->getId(); + $this->view->form = $form; + $this->view->unsavedName = $params['name']; + $this->view->unsavedDesc = $params['description']; + $viewPath = 'playlist/smart-block.phtml'; + $result['html'] = $this->view->render($viewPath); + $result['result'] = 1; + } + } else if ($params['type'] == 'playlist') { + $this->setPlaylistNameDescAction(); + } + $result["modified"] = $this->view->modified; + die(json_encode($result)); + } + + public function smartBlockGenerateAction() + { + $request = $this->getRequest(); + $params = $request->getPost(); + + //make sure block exists try { - $pl = $this->getPlaylist(); - $pl->setDescription($description); - $this->view->description = $pl->getDescription(); - $this->view->modified = $pl->getLastModified("U"); - } - catch (PlaylistOutDatedException $e) { - $this->playlistOutdated($pl, $e); - } - catch (PlaylistNotFoundException $e) { - $this->playlistNotFound(); - } - catch (Exception $e) { + $bl = new Application_Model_Block($params['obj_id']); + + $form = new Application_Form_SmartBlockCriteria(); + $form->startForm($params['obj_id']); + if ($form->isValid($params)) { + $result = $bl->generateSmartBlock($params['data']); + die(json_encode(array("result"=>0, "html"=>$this->createFullResponse($bl, true, true)))); + } else { + $this->view->obj = $bl; + $this->view->id = $bl->getId(); + $this->view->form = $form; + $viewPath = 'playlist/smart-block.phtml'; + $result['html'] = $this->view->render($viewPath); + $result['result'] = 1; + die(json_encode($result)); + } + } catch (BlockNotFoundException $e) { + $this->playlistNotFound('block', true); + } catch (Exception $e) { $this->playlistUnknownError($e); } } + + public function smartBlockShuffleAction() + { + $request = $this->getRequest(); + $params = $request->getPost(); + try { + $bl = new Application_Model_Block($params['obj_id']); + $result = $bl->shuffleSmartBlock(); + + if ($result['result'] == 0) { + die(json_encode(array("result"=>0, "html"=>$this->createFullResponse($bl, true)))); + } else { + die(json_encode($result)); + } + } catch (BlockNotFoundException $e) { + $this->playlistNotFound('block', true); + } catch (Exception $e) { + $this->playlistUnknownError($e); + } + } + + public function getBlockInfoAction() + { + $request = $this->getRequest(); + $params = $request->getPost(); + $bl = new Application_Model_Block($params['id']); + if ($bl->isStatic()) { + $out = $bl->getContents(); + $out['isStatic'] = true; + } else { + $out = $bl->getCriteria(); + $out['isStatic'] = false; + } + die(json_encode($out)); + } } - +class WrongTypeToBlockException extends Exception {} +class WrongTypeToPlaylistException extends Exception {} +class BlockDynamicException extends Exception {} diff --git a/airtime_mvc/application/controllers/PlayouthistoryController.php b/airtime_mvc/application/controllers/PlayouthistoryController.php index 196456782..7a046da9b 100644 --- a/airtime_mvc/application/controllers/PlayouthistoryController.php +++ b/airtime_mvc/application/controllers/PlayouthistoryController.php @@ -1,20 +1,20 @@ _helper->getHelper('AjaxContext'); - $ajaxContext - ->addActionContext('playout-history-feed', 'json') - ->initContext(); - } - - public function indexAction() - { - global $CC_CONFIG; - - $request = $this->getRequest(); + public function init() + { + $ajaxContext = $this->_helper->getHelper('AjaxContext'); + $ajaxContext + ->addActionContext('playout-history-feed', 'json') + ->initContext(); + } + + public function indexAction() + { + global $CC_CONFIG; + + $request = $this->getRequest(); $baseUrl = $request->getBaseUrl(); //default time is the last 24 hours. @@ -35,50 +35,50 @@ class PlayoutHistoryController extends Zend_Controller_Action 'his_time_end' => $end->format("H:i") )); - $this->view->date_form = $form; - - $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/TableTools/js/ZeroClipboard.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); - $this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/TableTools/js/TableTools.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); - - $offset = date("Z") * -1; - $this->view->headScript()->appendScript("var serverTimezoneOffset = {$offset}; //in seconds"); - $this->view->headScript()->appendFile($baseUrl.'/js/timepicker/jquery.ui.timepicker.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/utilities/utilities.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); - $this->view->headScript()->appendFile($baseUrl.'/js/airtime/playouthistory/historytable.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); - - $this->view->headLink()->appendStylesheet($baseUrl.'/js/datatables/plugin/TableTools/css/TableTools.css?'.$CC_CONFIG['airtime_version']); - $this->view->headLink()->appendStylesheet($baseUrl.'/css/jquery.ui.timepicker.css?'.$CC_CONFIG['airtime_version']); - $this->view->headLink()->appendStylesheet($baseUrl.'/css/playouthistory.css?'.$CC_CONFIG['airtime_version']); - } - - public function playoutHistoryFeedAction() - { - $request = $this->getRequest(); - $current_time = time(); - - $params = $request->getParams(); - - $starts_epoch = $request->getParam("start", $current_time - (60*60*24)); - $ends_epoch = $request->getParam("end", $current_time); - - $startsDT = DateTime::createFromFormat("U", $starts_epoch, new DateTimeZone("UTC")); - $endsDT = DateTime::createFromFormat("U", $ends_epoch, new DateTimeZone("UTC")); - - Logging::log("history starts {$startsDT->format("Y-m-d H:i:s")}"); - Logging::log("history ends {$endsDT->format("Y-m-d H:i:s")}"); - - $history = new Application_Model_PlayoutHistory($startsDT, $endsDT, $params); - - $r = $history->getItems(); - - $this->view->sEcho = $r["sEcho"]; - $this->view->iTotalDisplayRecords = $r["iTotalDisplayRecords"]; - $this->view->iTotalRecords = $r["iTotalRecords"]; - $this->view->history = $r["history"]; - } -} \ No newline at end of file + $this->view->date_form = $form; + + $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/TableTools/js/ZeroClipboard.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + $this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/TableTools/js/TableTools.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + + $offset = date("Z") * -1; + $this->view->headScript()->appendScript("var serverTimezoneOffset = {$offset}; //in seconds"); + $this->view->headScript()->appendFile($baseUrl.'/js/timepicker/jquery.ui.timepicker.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/utilities/utilities.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + $this->view->headScript()->appendFile($baseUrl.'/js/airtime/playouthistory/historytable.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + + $this->view->headLink()->appendStylesheet($baseUrl.'/js/datatables/plugin/TableTools/css/TableTools.css?'.$CC_CONFIG['airtime_version']); + $this->view->headLink()->appendStylesheet($baseUrl.'/css/jquery.ui.timepicker.css?'.$CC_CONFIG['airtime_version']); + $this->view->headLink()->appendStylesheet($baseUrl.'/css/playouthistory.css?'.$CC_CONFIG['airtime_version']); + } + + public function playoutHistoryFeedAction() + { + $request = $this->getRequest(); + $current_time = time(); + + $params = $request->getParams(); + + $starts_epoch = $request->getParam("start", $current_time - (60*60*24)); + $ends_epoch = $request->getParam("end", $current_time); + + $startsDT = DateTime::createFromFormat("U", $starts_epoch, new DateTimeZone("UTC")); + $endsDT = DateTime::createFromFormat("U", $ends_epoch, new DateTimeZone("UTC")); + + Logging::info("history starts {$startsDT->format("Y-m-d H:i:s")}"); + Logging::info("history ends {$endsDT->format("Y-m-d H:i:s")}"); + + $history = new Application_Model_PlayoutHistory($startsDT, $endsDT, $params); + + $r = $history->getItems(); + + $this->view->sEcho = $r["sEcho"]; + $this->view->iTotalDisplayRecords = $r["iTotalDisplayRecords"]; + $this->view->iTotalRecords = $r["iTotalRecords"]; + $this->view->history = $r["history"]; + } +} diff --git a/airtime_mvc/application/controllers/PluploadController.php b/airtime_mvc/application/controllers/PluploadController.php index 909351d3c..271cda4e9 100644 --- a/airtime_mvc/application/controllers/PluploadController.php +++ b/airtime_mvc/application/controllers/PluploadController.php @@ -14,7 +14,7 @@ class PluploadController extends Zend_Controller_Action public function indexAction() { global $CC_CONFIG; - + $request = $this->getRequest(); $baseUrl = $request->getBaseUrl(); @@ -33,18 +33,17 @@ class PluploadController extends Zend_Controller_Action die('{"jsonrpc" : "2.0", "tempfilepath" : "'.$tempFileName.'" }'); } - - public function copyfileAction(){ + + public function copyfileAction() + { $upload_dir = ini_get("upload_tmp_dir") . DIRECTORY_SEPARATOR . "plupload"; $filename = $this->_getParam('name'); $tempname = $this->_getParam('tempname'); - $result = Application_Model_StoredFile::copyFileToStor($upload_dir, $filename, $tempname); + $result = Application_Model_StoredFile::copyFileToStor($upload_dir, + $filename, $tempname); if (!is_null($result)) - die('{"jsonrpc" : "2.0", "error" : {"code": '.$result['code'].', "message" : "'.$result['message'].'"}}'); + die('{"jsonrpc" : "2.0", "error" : '.json_encode($result).'}'); die('{"jsonrpc" : "2.0"}'); } } - - - diff --git a/airtime_mvc/application/controllers/PreferenceController.php b/airtime_mvc/application/controllers/PreferenceController.php index 376f5e142..5c375deab 100644 --- a/airtime_mvc/application/controllers/PreferenceController.php +++ b/airtime_mvc/application/controllers/PreferenceController.php @@ -21,9 +21,9 @@ class PreferenceController extends Zend_Controller_Action public function indexAction() { global $CC_CONFIG; - + $isSaas = Application_Model_Preference::GetPlanLevel() == 'disabled'?false:true; - + $request = $this->getRequest(); $baseUrl = $request->getBaseUrl(); @@ -41,7 +41,7 @@ class PreferenceController extends Zend_Controller_Action Application_Model_Preference::SetAllow3rdPartyApi($values["preferences_general"]["thirdPartyApi"]); Application_Model_Preference::SetTimezone($values["preferences_general"]["timezone"]); Application_Model_Preference::SetWeekStartDay($values["preferences_general"]["weekStartDay"]); - + if (!$isSaas) { Application_Model_Preference::SetEnableSystemEmail($values["preferences_email_server"]["enableSystemEmail"]); Application_Model_Preference::SetSystemEmail($values["preferences_email_server"]["systemEmail"]); @@ -50,6 +50,7 @@ class PreferenceController extends Zend_Controller_Action Application_Model_Preference::SetMailServerEmailAddress($values["preferences_email_server"]["email"]); Application_Model_Preference::SetMailServerPassword($values["preferences_email_server"]["ms_password"]); Application_Model_Preference::SetMailServerPort($values["preferences_email_server"]["port"]); + Application_Model_Preference::SetMailServerRequiresAuth($values["preferences_email_server"]["msRequiresAuth"]); } Application_Model_Preference::SetAutoUploadRecordedShowToSoundcloud($values["preferences_soundcloud"]["UseSoundCloud"]); @@ -84,18 +85,18 @@ class PreferenceController extends Zend_Controller_Action if ($request->isPost()) { $values = $request->getPost(); if ($form->isValid($values)) { - if (!$isSass && $values["Publicise"] != 1){ + if (!$isSass && $values["Publicise"] != 1) { Application_Model_Preference::SetSupportFeedback($values["SupportFeedback"]); Application_Model_Preference::SetPublicise($values["Publicise"]); - if(isset($values["Privacy"])){ + if (isset($values["Privacy"])) { Application_Model_Preference::SetPrivacyPolicyCheck($values["Privacy"]); } - }else{ + } else { Application_Model_Preference::SetHeadTitle($values["stationName"], $this->view); Application_Model_Preference::SetPhone($values["Phone"]); Application_Model_Preference::SetEmail($values["Email"]); Application_Model_Preference::SetStationWebSite($values["StationWebSite"]); - if(!$isSass){ + if (!$isSass) { Application_Model_Preference::SetSupportFeedback($values["SupportFeedback"]); Application_Model_Preference::SetPublicise($values["Publicise"]); } @@ -107,7 +108,7 @@ class PreferenceController extends Zend_Controller_Action Application_Model_Preference::SetStationCity($values["City"]); Application_Model_Preference::SetStationDescription($values["Description"]); Application_Model_Preference::SetStationLogo($imagePath); - if(!$isSass && isset($values["Privacy"])){ + if (!$isSass && isset($values["Privacy"])) { Application_Model_Preference::SetPrivacyPolicyCheck($values["Privacy"]); } } @@ -115,11 +116,11 @@ class PreferenceController extends Zend_Controller_Action } } $logo = Application_Model_Preference::GetStationLogo(); - if($logo){ + if ($logo) { $this->view->logoImg = $logo; } $privacyChecked = false; - if(Application_Model_Preference::GetPrivacyPolicyCheck() == 1){ + if (Application_Model_Preference::GetPrivacyPolicyCheck() == 1) { $privacyChecked = true; } $this->view->privacyChecked = $privacyChecked; @@ -132,7 +133,7 @@ class PreferenceController extends Zend_Controller_Action { global $CC_CONFIG; - if(Application_Model_Preference::GetPlanLevel() == 'disabled'){ + if (Application_Model_Preference::GetPlanLevel() == 'disabled') { $request = $this->getRequest(); $baseUrl = $request->getBaseUrl(); @@ -153,23 +154,22 @@ class PreferenceController extends Zend_Controller_Action $baseUrl = $request->getBaseUrl(); $this->view->headScript()->appendFile($baseUrl.'/js/airtime/preferences/streamsetting.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); - + $isSaas = Application_Model_Preference::GetPlanLevel() == 'disabled'?false:true; // get current settings $temp = Application_Model_StreamSetting::getStreamSetting(); $setting = array(); - foreach ($temp as $t){ + foreach ($temp as $t) { $setting[$t['keyname']] = $t['value']; } - // 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"){ + foreach ($temp_types as $type) { + if (trim($type) == "ogg") { $temp = "OGG/VORBIS"; - }else{ + } else { $temp = strtoupper(trim($type)); } $stream_types[trim($type)] = $temp; @@ -178,8 +178,8 @@ class PreferenceController extends Zend_Controller_Action $temp_bitrate = Application_Model_Preference::GetStreamBitrate(); $max_bitrate = intval(Application_Model_Preference::GetMaxBitrate()); $stream_bitrates = array(); - foreach ($temp_bitrate as $type){ - if(intval($type) <= $max_bitrate){ + foreach ($temp_bitrate as $type) { + if (intval($type) <= $max_bitrate) { $stream_bitrates[trim($type)] = strtoupper(trim($type))." Kbit/s"; } } @@ -189,11 +189,11 @@ class PreferenceController extends Zend_Controller_Action $form->setSetting($setting); $form->startFrom(); - + $live_stream_subform = new Application_Form_LiveStreamingPreferences(); $form->addSubForm($live_stream_subform, "live_stream_subform"); - for($i=1; $i<=$num_of_stream; $i++){ + for ($i=1; $i<=$num_of_stream; $i++) { $subform = new Application_Form_StreamSettingSubForm(); $subform->setPrefix($i); $subform->setSetting($setting); @@ -203,12 +203,11 @@ class PreferenceController extends Zend_Controller_Action $form->addSubForm($subform, "s".$i."_subform"); } if ($request->isPost()) { - $post_data = $request->getPost(); + $values = $request->getPost(); $error = false; - $values = $post_data; - - if($form->isValid($post_data)){ + + if ($form->isValid($values)) { if (!$isSaas) { $values['output_sound_device'] = $form->getValue('output_sound_device'); $values['output_sound_device_type'] = $form->getValue('output_sound_device_type'); @@ -218,66 +217,63 @@ class PreferenceController extends Zend_Controller_Action $values['streamFormat'] = $form->getValue('streamFormat'); Application_Model_StreamSetting::setStreamSetting($values); - + // this goes into cc_pref table Application_Model_Preference::SetStreamLabelFormat($values['streamFormat']); - Application_Model_Preference::SetLiveSteamMasterUsername($values["master_username"]); - Application_Model_Preference::SetLiveSteamMasterPassword($values["master_password"]); + Application_Model_Preference::SetLiveStreamMasterUsername($values["master_username"]); + Application_Model_Preference::SetLiveStreamMasterPassword($values["master_password"]); Application_Model_Preference::SetDefaultTransitionFade($values["transition_fade"]); Application_Model_Preference::SetAutoTransition($values["auto_transition"]); Application_Model_Preference::SetAutoSwitch($values["auto_switch"]); - + if (!$isSaas) { if (!Application_Model_Preference::GetMasterDjConnectionUrlOverride()) { $master_connection_url = "http://".$_SERVER['SERVER_NAME'].":".$values["master_harbor_input_port"]."/".$values["master_harbor_input_mount_point"]; if (empty($values["master_harbor_input_port"]) || empty($values["master_harbor_input_mount_point"])) { Application_Model_Preference::SetMasterDJSourceConnectionURL('N/A'); - } - else { + } else { Application_Model_Preference::SetMasterDJSourceConnectionURL($master_connection_url); } } else { Application_Model_Preference::SetMasterDJSourceConnectionURL($values["master_dj_connection_url"]); - } - - if (!Application_Model_Preference::GetLiveDjConnectionUrlOverride()) { + } + + if (!Application_Model_Preference::GetLiveDjConnectionUrlOverride()) { $live_connection_url = "http://".$_SERVER['SERVER_NAME'].":".$values["dj_harbor_input_port"]."/".$values["dj_harbor_input_mount_point"]; if (empty($values["dj_harbor_input_port"]) || empty($values["dj_harbor_input_mount_point"])) { Application_Model_Preference::SetLiveDJSourceConnectionURL('N/A'); - } - else { + } else { Application_Model_Preference::SetLiveDJSourceConnectionURL($live_connection_url); } - } - else { + } else { Application_Model_Preference::SetLiveDJSourceConnectionURL($values["live_dj_connection_url"]); } - + // extra info that goes into cc_stream_setting - Application_Model_StreamSetting::SetMasterLiveSteamPort($values["master_harbor_input_port"]); - Application_Model_StreamSetting::SetMasterLiveSteamMountPoint($values["master_harbor_input_mount_point"]); - Application_Model_StreamSetting::SetDJLiveSteamPort($values["dj_harbor_input_port"]); - Application_Model_StreamSetting::SetDJLiveSteamMountPoint($values["dj_harbor_input_mount_point"]); + Application_Model_StreamSetting::setMasterLiveStreamPort($values["master_harbor_input_port"]); + Application_Model_StreamSetting::setMasterLiveStreamMountPoint($values["master_harbor_input_mount_point"]); + Application_Model_StreamSetting::setDjLiveStreamPort($values["dj_harbor_input_port"]); + Application_Model_StreamSetting::setDjLiveStreamMountPoint($values["dj_harbor_input_mount_point"]); } - + // store stream update timestamp Application_Model_Preference::SetStreamUpdateTimestamp(); - + $data = array(); $info = Application_Model_StreamSetting::getStreamSetting(); $data['setting'] = $info; - for($i=1;$i<=$num_of_stream;$i++){ + for ($i=1; $i<=$num_of_stream; $i++) { Application_Model_StreamSetting::setLiquidsoapError($i, "waiting"); } - + Application_Model_RabbitMq::SendMessageToPypo("update_stream_setting", $data); $this->view->statusMsg = "
Stream Setting Updated.
"; } } - + $live_stream_subform->updateVariables(); $this->view->confirm_pypo_restart_text = "If you change the username or password values for an enabled stream the playout engine will be rebooted and your listeners will hear silence for 5-10 seconds. Changing the following fields will NOT cause a reboot: Stream Label (Global Settings), and Switch Transition Fade(s), Master Username, and Master Password (Input Stream Settings). If Airtime is recording, and if the change causes a playout engine restart, the recording will be interrupted."; - + $this->view->num_stream = $num_of_stream; $this->view->enable_stream_conf = Application_Model_Preference::GetEnableStreamConf(); $this->view->form = $form; @@ -290,19 +286,16 @@ class PreferenceController extends Zend_Controller_Action $result = array(); - if(is_null($path)) - { + if (is_null($path)) { $element = array(); $element["name"] = "path should be specified"; $element["isFolder"] = false; $element["isError"] = true; $result[$path] = $element; - } - else - { + } else { $path = $path.'/'; $handle = opendir($path); - if ($handle !== false){ + if ($handle !== false) { while (false !== ($file = readdir($handle))) { if ($file != "." && $file != "..") { //only show directories that aren't private. @@ -329,7 +322,7 @@ class PreferenceController extends Zend_Controller_Action $watched_dirs_form = new Application_Form_WatchedDirPreferences(); $res = Application_Model_MusicDir::setStorDir($chosen); - if($res['code'] != 0){ + if ($res['code'] != 0) { $watched_dirs_form->populate(array('storageFolder' => $chosen)); $watched_dirs_form->getElement($element)->setErrors(array($res['error'])); } @@ -344,14 +337,14 @@ class PreferenceController extends Zend_Controller_Action $watched_dirs_form = new Application_Form_WatchedDirPreferences(); $res = Application_Model_MusicDir::addWatchedDir($chosen); - if($res['code'] != 0){ + if ($res['code'] != 0) { $watched_dirs_form->populate(array('watchedFolder' => $chosen)); $watched_dirs_form->getElement($element)->setErrors(array($res['error'])); } $this->view->subform = $watched_dirs_form->render(); } - + public function rescanWatchDirectoryAction() { $dir = Application_Model_MusicDir::getDirByPath($this->getRequest()->getParam("dir")); @@ -373,46 +366,46 @@ class PreferenceController extends Zend_Controller_Action $this->view->subform = $watched_dirs_form->render(); } - public function isImportInProgressAction(){ + public function isImportInProgressAction() + { $now = time(); $res = false; - if(Application_Model_Preference::GetImportTimestamp()+10 > $now){ + if (Application_Model_Preference::GetImportTimestamp()+10 > $now) { $res = true; } die(json_encode($res)); } - public function getLiquidsoapStatusAction(){ + public function getLiquidsoapStatusAction() + { $out = array(); $num_of_stream = intval(Application_Model_Preference::GetNumOfStreams()); - for($i=1; $i<=$num_of_stream; $i++){ + for ($i=1; $i<=$num_of_stream; $i++) { $status = Application_Model_StreamSetting::getLiquidsoapError($i); $status = $status == NULL?"Problem with Liquidsoap...":$status; - if(!Application_Model_StreamSetting::getStreamEnabled($i)){ + if (!Application_Model_StreamSetting::getStreamEnabled($i)) { $status = "N/A"; } $out[] = array("id"=>$i, "status"=>$status); } die(json_encode($out)); } - - public function setSourceConnectionUrlAction(){ + + public function setSourceConnectionUrlAction() + { $request = $this->getRequest(); $type = $request->getParam("type", null); $url = urldecode($request->getParam("url", null)); $override = $request->getParam("override", false); - - if($type == 'masterdj'){ + + if ($type == 'masterdj') { Application_Model_Preference::SetMasterDJSourceConnectionURL($url); Application_Model_Preference::SetMasterDjConnectionUrlOverride($override); - }elseif($type == 'livedj'){ + } elseif ($type == 'livedj') { Application_Model_Preference::SetLiveDJSourceConnectionURL($url); Application_Model_Preference::SetLiveDjConnectionUrlOverride($override); } - + die(); } } - - - diff --git a/airtime_mvc/application/controllers/ScheduleController.php b/airtime_mvc/application/controllers/ScheduleController.php index 3e84b4940..a8b5b557c 100644 --- a/airtime_mvc/application/controllers/ScheduleController.php +++ b/airtime_mvc/application/controllers/ScheduleController.php @@ -10,16 +10,16 @@ class ScheduleController extends Zend_Controller_Action $ajaxContext = $this->_helper->getHelper('AjaxContext'); $ajaxContext->addActionContext('event-feed', '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('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('clear-show', 'json') ->addActionContext('get-current-playlist', 'json') - ->addActionContext('remove-group', 'json') + ->addActionContext('remove-group', 'json') ->addActionContext('populate-show-form', 'json') ->addActionContext('populate-show-instance-form', 'json') ->addActionContext('cancel-show', 'json') @@ -32,9 +32,10 @@ class ScheduleController extends Zend_Controller_Action ->addActionContext('edit-show-instance', 'json') ->addActionContext('dj-edit-show', 'json') ->addActionContext('calculate-duration', 'json') + ->addActionContext('get-current-show', 'json') ->initContext(); - $this->sched_sess = new Zend_Session_Namespace("schedule"); + $this->sched_sess = new Zend_Session_Namespace("schedule"); } public function indexAction() @@ -73,6 +74,7 @@ class ScheduleController extends Zend_Controller_Action $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($this->view->baseUrl('/js/airtime/library/events/library_showbuilder.js?'.$CC_CONFIG['airtime_version']),'text/javascript'); @@ -89,12 +91,12 @@ class ScheduleController extends Zend_Controller_Action Application_Model_Schedule::createNewFormSections($this->view); - $user = Application_Model_User::GetCurrentUser(); - - if($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))){ + $user = Application_Model_User::getCurrentUser(); + + if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) { $this->view->preloadShowForm = true; } - + $this->view->headScript()->appendScript("var weekStart = ".Application_Model_Preference::GetWeekStartDay().";"); } @@ -105,16 +107,27 @@ class ScheduleController extends Zend_Controller_Action $end = new DateTime($this->_getParam('end', null)); $end->setTimezone(new DateTimeZone("UTC")); - $userInfo = Zend_Auth::getInstance()->getStorage()->read(); + $userInfo = Zend_Auth::getInstance()->getStorage()->read(); $user = new Application_Model_User($userInfo->id); if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) { $editable = true; - } - else { + } else { $editable = false; } - $this->view->events = Application_Model_Show::getFullCalendarEvents($start, $end, $editable); + $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() @@ -129,8 +142,9 @@ class ScheduleController extends Zend_Controller_Action if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) { try { $showInstance = new Application_Model_ShowInstance($showInstanceId); - } catch (Exception $e){ + } catch (Exception $e) { $this->view->show_error = true; + return false; } $error = $showInstance->moveShow($deltaDay, $deltaMin); @@ -144,64 +158,66 @@ class ScheduleController extends Zend_Controller_Action public function resizeShowAction() { $deltaDay = $this->_getParam('day'); - $deltaMin = $this->_getParam('min'); - $showId = $this->_getParam('showId'); + $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{ + try { $show = new Application_Model_Show($showId); - }catch(Exception $e){ + } catch (Exception $e) { $this->view->show_error = true; + return false; } - $error = $show->resizeShow($deltaDay, $deltaMin); + $error = $show->resizeShow($deltaDay, $deltaMin); } - if (isset($error)) { - $this->view->error = $error; - } + 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); + $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){ + $showInstance = new Application_Model_ShowInstance($showInstanceId); + } catch (Exception $e) { + Logging::info($e->getMessage()); $this->view->show_error = true; + return false; } - $showInstance->delete(); + $showInstance->delete(); - $this->view->show_id = $showInstance->getShowId(); + $this->view->show_id = $showInstance->getShowId(); } } public function uploadToSoundCloudAction() { - global $CC_CONFIG; $show_instance = $this->_getParam('id'); - try{ + try { $show_inst = new Application_Model_ShowInstance($show_instance); - }catch(Exception $e){ + } catch (Exception $e) { $this->view->show_error = true; + return false; } $file = $show_inst->getRecordedFile(); $id = $file->getId(); - $res = exec("/usr/lib/airtime/utils/soundcloud-uploader $id > /dev/null &"); + Application_Model_Soundcloud::uploadSoundcloud($id); // we should die with ui info die(); } @@ -214,30 +230,31 @@ class ScheduleController extends Zend_Controller_Action $userInfo = Zend_Auth::getInstance()->getStorage()->read(); $user = new Application_Model_User($userInfo->id); - try{ + try { $instance = new Application_Model_ShowInstance($id); - }catch(Exception $e){ + } catch (Exception $e) { $this->view->show_error = true; + return false; } - + $isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER)); - $isDJ = $user->isHost($instance->getShowId()); + $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", + + $menu["view_recorded"] = array("name" => "View Recorded File Metadata", "icon" => "overview", "url" => "/library/edit-file-md/id/".$fileId); } if ($epochNow < $showStartLocalDT->getTimestamp()) { - if ( ($isAdminOrPM || $isDJ) + if ( ($isAdminOrPM || $isDJ) && !$instance->isRecorded() && !$instance->isRebroadcast()) { @@ -257,18 +274,18 @@ class ScheduleController extends Zend_Controller_Action if ($showEndLocalDT->getTimestamp() <= $epochNow && $instance->isRecorded() && Application_Model_Preference::GetUploadToSoundcloudOption()) { - - $file = $instance->getRecordedFile(); + + $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); + + 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"); + $menu["soundcloud_upload"] = array("name"=> $text, "icon" => "soundcloud"); } if ($showStartLocalDT->getTimestamp() <= $epochNow && @@ -276,8 +293,7 @@ class ScheduleController extends Zend_Controller_Action if ($instance->isRecorded()) { $menu["cancel_recorded"] = array("name"=> "Cancel Current Show", "icon" => "delete"); - } - else { + } else { if (!$instance->isRebroadcast()) { $menu["edit"] = array("name"=> "Edit Show", "icon" => "edit", "_type"=>"all", "url" => "/Schedule/populate-show-form"); @@ -301,8 +317,7 @@ class ScheduleController extends Zend_Controller_Action $menu["del"]["items"]["single"] = array("name"=> "Delete This Instance", "icon" => "delete", "url" => "/schedule/delete-show"); $menu["del"]["items"]["following"] = array("name"=> "Delete This Instance and All Following", "icon" => "delete", "url" => "/schedule/cancel-show"); - } - else if ($isAdminOrPM){ + } elseif ($isAdminOrPM) { $menu["del"] = array("name"=> "Delete", "icon" => "delete", "url" => "/schedule/delete-show"); } @@ -316,58 +331,59 @@ class ScheduleController extends Zend_Controller_Action $showInstanceId = $this->_getParam('id'); $userInfo = Zend_Auth::getInstance()->getStorage()->read(); $user = new Application_Model_User($userInfo->id); - try{ + try { $show = new Application_Model_ShowInstance($showInstanceId); - }catch(Exception $e){ + } catch (Exception $e) { $this->view->show_error = true; + return false; } - if($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER, UTYPE_HOST),$show->getShowId())) + 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(); + $show = Application_Model_Show::getCurrentShow(); /* Convert all UTC times to localtime before sending back to user. */ - if (isset($range["previous"])){ + 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"])){ + 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"])){ + 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")); - + 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"]:""; } @@ -376,44 +392,46 @@ class ScheduleController extends Zend_Controller_Action { $showInstanceId = $this->sched_sess->showInstanceId; $group_id = $this->_getParam('groupId'); - $search = $this->_getParam('search', null); - $userInfo = Zend_Auth::getInstance()->getStorage()->read(); + $userInfo = Zend_Auth::getInstance()->getStorage()->read(); $user = new Application_Model_User($userInfo->id); - try{ + try { $show = new Application_Model_ShowInstance($showInstanceId); - }catch(Exception $e){ + } catch (Exception $e) { $this->view->show_error = true; + return false; } - if($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER, UTYPE_HOST),$show->getShowId())) { - $show->removeGroupFromShow($group_id); + 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); + $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{ + try { $show = new Application_Model_ShowInstance($showInstanceId); - }catch(Exception $e){ + } catch (Exception $e) { $this->view->show_error = true; + return false; } $originalShowId = $show->isRebroadcast(); - if (!is_null($originalShowId)){ - try{ + if (!is_null($originalShowId)) { + try { $originalShow = new Application_Model_ShowInstance($originalShowId); - }catch(Exception $e){ + } catch (Exception $e) { $this->view->show_error = true; + return false; } $originalShowName = $originalShow->getName(); @@ -440,53 +458,53 @@ class ScheduleController extends Zend_Controller_Action // 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(); + $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'); + $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->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); + $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())); - + '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_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(); @@ -494,13 +512,11 @@ class ScheduleController extends Zend_Controller_Action $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'); }*/ @@ -513,48 +529,46 @@ class ScheduleController extends Zend_Controller_Action $isSaas = Application_Model_Preference::GetPlanLevel() == 'disabled'?false:true; $showInstanceId = $this->_getParam('id'); - // $type is used to determine if this edit is for the specific instance or for all - // repeating shows. It's value is either "instance","rebroadcast", or "all" - $type = $this->_getParam('type'); - + $this->view->action = "edit-show"; - try{ + try { $showInstance = new Application_Model_ShowInstance($showInstanceId); - }catch(Exception $e){ + } catch (Exception $e) { $this->view->show_error = true; + return false; } - + $isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER)); - $isDJ = $user->isHost($showInstance->getShowId()); - - if(!($isAdminOrPM || $isDJ)) { + $isDJ = $user->isHostOfShow($showInstance->getShowId()); + + if (!($isAdminOrPM || $isDJ)) { return; } - - if($isDJ){ + + if ($isDJ) { $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(); + $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'); + $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->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()); @@ -574,17 +588,17 @@ class ScheduleController extends Zend_Controller_Action $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_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()){ + 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()){ + if (!$showInstance->getShow()->isRepeating()) { $formWhen->disableStartDateAndTime(); - }else{ + } else { $formWhen->getElement('add_show_start_date')->setOptions(array('disabled' => true)); } } @@ -592,7 +606,7 @@ class ScheduleController extends Zend_Controller_Action //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){ + 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')); @@ -609,16 +623,16 @@ class ScheduleController extends Zend_Controller_Action $hosts = array(); $showHosts = CcShowHostsQuery::create()->filterByDbShow($showInstance->getShowId())->find(); - foreach($showHosts as $showHost){ + 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()); - if(!$isSaas){ + if (!$isSaas) { $formRecord = new Application_Form_AddShowRR(); $formAbsoluteRebroadcast = new Application_Form_AddShowAbsoluteRebroadcastDates(); $formRebroadcast = new Application_Form_AddShowRebroadcastDates(); @@ -641,7 +655,7 @@ class ScheduleController extends Zend_Controller_Action $rebroadcastsRelative = $show->getRebroadcastsRelative(); $rebroadcastFormValues = array(); $i = 1; - foreach ($rebroadcastsRelative as $rebroadcast){ + 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++; @@ -651,20 +665,20 @@ class ScheduleController extends Zend_Controller_Action $rebroadcastsAbsolute = $show->getRebroadcastsAbsolute(); $rebroadcastAbsoluteFormValues = array(); $i = 1; - foreach ($rebroadcastsAbsolute as $rebroadcast){ + 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){ + if (!$isAdminOrPM) { $formRecord->disable(); $formAbsoluteRebroadcast->disable(); $formRebroadcast->disable(); } } - - if(!$isAdminOrPM){ + + if (!$isAdminOrPM) { $formWhat->disable(); $formWho->disable(); $formWhen->disable(); @@ -676,46 +690,47 @@ class ScheduleController extends Zend_Controller_Action $this->view->entries = 5; } - public function getFormAction() { - - $user = Application_Model_User::GetCurrentUser(); - - if($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))){ + 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(){ + + public function djEditShowAction() + { $js = $this->_getParam('data'); $data = array(); //need to convert from serialized jQuery array. - foreach($js as $j){ + 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){ + foreach ($js as $j) { $data[$j["name"]] = $j["value"]; } - + $success = Application_Model_Schedule::updateShowInstance($data, $this); - if ($success){ + if ($success) { $this->view->addNewShow = true; $this->view->newForm = $this->view->render('schedule/add-show-form.phtml'); } else { @@ -723,54 +738,63 @@ class ScheduleController extends Zend_Controller_Action $this->view->form = $this->view->render('schedule/add-show-form.phtml'); } }*/ - - public function editShowAction(){ - + + 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){ + 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'] == "") { + 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)){ + 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)){ + + 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(); - + $origianlShowStartDateTime = Application_Common_DateHelper::ConvertToLocalDateTime($show->getStartDateAndTime()); - $success = Application_Model_Schedule::addUpdateShow($data, $this, $validateStartDate, $origianlShowStartDateTime); - - if ($success){ + + $success = Application_Model_Schedule::addUpdateShow($data, $this, + $validateStartDate, $origianlShowStartDateTime, 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){ + if (!$validateStartDate) { $this->view->when->getElement('add_show_start_date')->setOptions(array('disabled' => true)); } - if(!$validateStartTime){ + 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)); @@ -779,46 +803,53 @@ class ScheduleController extends Zend_Controller_Action $this->view->form = $this->view->render('schedule/add-show-form.phtml'); } } - - public function addShowAction(){ + + public function addShowAction() + { $js = $this->_getParam('data'); $data = array(); //need to convert from serialized jQuery array. - foreach($js as $j){ + foreach ($js as $j) { $data[$j["name"]] = $j["value"]; } - $data['add_show_hosts'] = $this->_getParam('hosts'); - $data['add_show_day_check'] = $this->_getParam('days'); + $data['add_show_hosts'] = $this->_getParam('hosts'); + $data['add_show_day_check'] = $this->_getParam('days'); - if($data['add_show_day_check'] == "") { + if ($data['add_show_day_check'] == "") { $data['add_show_day_check'] = null; } - + $validateStartDate = true; - $success = Application_Model_Schedule::addUpdateShow($data, $this, $validateStartDate); - - if ($success){ + $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'); + $this->view->newForm = $this->view->render( + 'schedule/add-show-form.phtml'); + Logging::debug("Show creation succeeded"); } else { $this->view->addNewShow = true; - $this->view->form = $this->view->render('schedule/add-show-form.phtml'); + $this->view->form = $this->view->render( + 'schedule/add-show-form.phtml'); + Logging::debug("Show creation failed"); } } public function cancelShowAction() { - $user = Application_Model_User::GetCurrentUser(); + $user = Application_Model_User::getCurrentUser(); if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) { - $showInstanceId = $this->_getParam('id'); + $showInstanceId = $this->_getParam('id'); - try { + try { $showInstance = new Application_Model_ShowInstance($showInstanceId); - } catch(Exception $e) { + } catch (Exception $e) { $this->view->show_error = true; + return false; } $show = new Application_Model_Show($showInstance->getShowId()); @@ -830,31 +861,29 @@ class ScheduleController extends Zend_Controller_Action public function cancelCurrentShowAction() { - $user = Application_Model_User::GetCurrentUser(); + $user = Application_Model_User::getCurrentUser(); if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) { $id = $this->_getParam('id'); - - try { - $scheduler = new Application_Model_Scheduler(); + + try { + $scheduler = new Application_Model_Scheduler(); $scheduler->cancelShow($id); // 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::log($e->getMessage()); - Logging::log("{$e->getFile()}"); - Logging::log("{$e->getLine()}"); + Application_Model_RabbitMq::SendMessageToPypo("disconnect_source", $data); + } catch (Exception $e) { + $this->view->error = $e->getMessage(); + Logging::info($e->getMessage()); } } } - public function contentContextMenuAction(){ - global $CC_CONFIG; + public function contentContextMenuAction() + { + global $CC_CONFIG; - $id = $this->_getParam('id'); + $id = $this->_getParam('id'); $params = '/format/json/id/#id#/'; @@ -869,7 +898,7 @@ class ScheduleController extends Zend_Controller_Action $baseUrl = $this->getRequest()->getBaseUrl(); $url = $file->getRelativeFileUrl($baseUrl).'/download/true'; $menu[] = array('action' => array('type' => 'gourl', 'url' => $url), - 'title' => 'Download'); + 'title' => 'Download'); //returns format jjmenu is looking for. die(json_encode($menu)); @@ -879,50 +908,52 @@ class ScheduleController extends Zend_Controller_Action * 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')); + 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 setTimeIntervalAction() + { + Application_Model_Preference::SetCalendarTimeInterval($this->_getParam('timeInterval')); } - - public function calculateDurationAction() { + + public function calculateDurationAction() + { global $CC_CONFIG; $startParam = $this->_getParam('startTime'); $endParam = $this->_getParam('endTime'); - - try{ + + 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){ + 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{ + } else { $result = $duration->format('%r%Hh %Im'); } - }catch (Exception $e){ + } catch (Exception $e) { $result = "Invalid Date"; } - + echo Zend_Json::encode($result); exit(); } } - diff --git a/airtime_mvc/application/controllers/ShowbuilderController.php b/airtime_mvc/application/controllers/ShowbuilderController.php index b16717bde..a31119cdb 100644 --- a/airtime_mvc/application/controllers/ShowbuilderController.php +++ b/airtime_mvc/application/controllers/ShowbuilderController.php @@ -16,142 +16,138 @@ class ShowbuilderController extends Zend_Controller_Action ->initContext(); } - public function indexAction() { - - global $CC_CONFIG; - - $request = $this->getRequest(); + public function indexAction() + { + global $CC_CONFIG; + + $request = $this->getRequest(); $baseUrl = $request->getBaseUrl(); - $user = Application_Model_User::GetCurrentUser(); - + $user = Application_Model_User::getCurrentUser(); + $userType = $user->getType(); $this->view->headScript()->appendScript("localStorage.setItem( 'user-type', '$userType' );"); - - $data = Application_Model_Preference::GetValue("library_datatable", true); - if ($data != "") { - $libraryTable = json_encode(unserialize($data)); - $this->view->headScript()->appendScript("localStorage.setItem( 'datatables-library', JSON.stringify($libraryTable) );"); - } - else { + + $data = Application_Model_Preference::getCurrentLibraryTableSetting(); + if (!is_null($data)) { + $libraryTable = json_encode($data); + $this->view->headScript()->appendScript("localStorage.setItem( 'datatables-library', JSON.stringify($libraryTable) );"); + } else { $this->view->headScript()->appendScript("localStorage.setItem( 'datatables-library', '' );"); } - - $data = Application_Model_Preference::GetValue("timeline_datatable", true); - if ($data != "") { - $timelineTable = json_encode(unserialize($data)); - $this->view->headScript()->appendScript("localStorage.setItem( 'datatables-timeline', JSON.stringify($timelineTable) );"); + + $data = Application_Model_Preference::getTimelineDatatableSetting(); + if (!is_null($data)) { + $timelineTable = json_encode($data); + $this->view->headScript()->appendScript("localStorage.setItem( 'datatables-timeline', JSON.stringify($timelineTable) );"); + } else { + $this->view->headScript()->appendScript("localStorage.setItem( 'datatables-timeline', '' );"); } - else { - $this->view->headScript()->appendScript("localStorage.setItem( 'datatables-timeline', '' );"); - } - - $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/blockui/jquery.blockUI.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/utilities/utilities.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->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->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.columnFilter.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->headScript()->appendFile($baseUrl.'/js/airtime/buttons/buttons.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + $this->view->headScript()->appendFile($baseUrl.'/js/airtime/utilities/utilities.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->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->headScript()->appendFile($this->view->baseUrl('/js/airtime/library/events/library_showbuilder.js?'.$CC_CONFIG['airtime_version']),'text/javascript'); - - $refer_sses = new Zend_Session_Namespace('referrer'); - - if ($request->isPost()) { - $form = new Application_Form_RegisterAirtime(); - - $values = $request->getPost(); - if ($values["Publicise"] != 1 && $form->isValid($values)) { - Application_Model_Preference::SetSupportFeedback($values["SupportFeedback"]); - - if (isset($values["Privacy"])) { - Application_Model_Preference::SetPrivacyPolicyCheck($values["Privacy"]); - } - // unset session - Zend_Session::namespaceUnset('referrer'); - } - else if ($values["Publicise"] == '1' && $form->isValid($values)) { - Application_Model_Preference::SetHeadTitle($values["stnName"], $this->view); - Application_Model_Preference::SetPhone($values["Phone"]); - Application_Model_Preference::SetEmail($values["Email"]); - Application_Model_Preference::SetStationWebSite($values["StationWebSite"]); - Application_Model_Preference::SetPublicise($values["Publicise"]); - - $form->Logo->receive(); - $imagePath = $form->Logo->getFileName(); - - Application_Model_Preference::SetStationCountry($values["Country"]); - Application_Model_Preference::SetStationCity($values["City"]); - Application_Model_Preference::SetStationDescription($values["Description"]); - Application_Model_Preference::SetStationLogo($imagePath); - Application_Model_Preference::SetSupportFeedback($values["SupportFeedback"]); - - if (isset($values["Privacy"])){ - Application_Model_Preference::SetPrivacyPolicyCheck($values["Privacy"]); - } - // unset session - Zend_Session::namespaceUnset('referrer'); - } - else { - $logo = Application_Model_Preference::GetStationLogo(); - if ($logo) { - $this->view->logoImg = $logo; - } - $this->view->dialog = $form; - $this->view->headScript()->appendFile($baseUrl.'/js/airtime/nowplaying/register.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); - } - } - - //popup if previous page was login - if ($refer_sses->referrer == 'login' && Application_Model_Preference::ShouldShowPopUp() - && !Application_Model_Preference::GetSupportFeedback() && $user->isAdmin()){ - - $form = new Application_Form_RegisterAirtime(); - - $logo = Application_Model_Preference::GetStationLogo(); - if ($logo) { - $this->view->logoImg = $logo; - } - $this->view->dialog = $form; - $this->view->headScript()->appendFile($baseUrl.'/js/airtime/nowplaying/register.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); - } - - //determine whether to remove/hide/display the library. - $showLib = false; - if (!$user->isGuest()) { - $disableLib = false; - $data = Application_Model_Preference::GetValue("nowplaying_screen", true); - if ($data != "") { - $settings = unserialize($data); - - if ($settings["library"] == "true") { - $showLib = true; - } + + $refer_sses = new Zend_Session_Namespace('referrer'); + + if ($request->isPost()) { + $form = new Application_Form_RegisterAirtime(); + + $values = $request->getPost(); + if ($values["Publicise"] != 1 && $form->isValid($values)) { + Application_Model_Preference::SetSupportFeedback($values["SupportFeedback"]); + + if (isset($values["Privacy"])) { + Application_Model_Preference::SetPrivacyPolicyCheck($values["Privacy"]); + } + // unset session + Zend_Session::namespaceUnset('referrer'); + } elseif ($values["Publicise"] == '1' && $form->isValid($values)) { + Application_Model_Preference::SetHeadTitle($values["stnName"], $this->view); + Application_Model_Preference::SetPhone($values["Phone"]); + Application_Model_Preference::SetEmail($values["Email"]); + Application_Model_Preference::SetStationWebSite($values["StationWebSite"]); + Application_Model_Preference::SetPublicise($values["Publicise"]); + + $form->Logo->receive(); + $imagePath = $form->Logo->getFileName(); + + Application_Model_Preference::SetStationCountry($values["Country"]); + Application_Model_Preference::SetStationCity($values["City"]); + Application_Model_Preference::SetStationDescription($values["Description"]); + Application_Model_Preference::SetStationLogo($imagePath); + Application_Model_Preference::SetSupportFeedback($values["SupportFeedback"]); + + if (isset($values["Privacy"])) { + Application_Model_Preference::SetPrivacyPolicyCheck($values["Privacy"]); + } + // unset session + Zend_Session::namespaceUnset('referrer'); + } else { + $logo = Application_Model_Preference::GetStationLogo(); + if ($logo) { + $this->view->logoImg = $logo; + } + $this->view->dialog = $form; + $this->view->headScript()->appendFile($baseUrl.'/js/airtime/nowplaying/register.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); } - } - else { - $disableLib = true; - } - $this->view->disableLib = $disableLib; - $this->view->showLib = $showLib; - + } + + //popup if previous page was login + if ($refer_sses->referrer == 'login' && Application_Model_Preference::ShouldShowPopUp() + && !Application_Model_Preference::GetSupportFeedback() && $user->isAdmin()){ + + $form = new Application_Form_RegisterAirtime(); + + $logo = Application_Model_Preference::GetStationLogo(); + if ($logo) { + $this->view->logoImg = $logo; + } + $this->view->dialog = $form; + $this->view->headScript()->appendFile($baseUrl.'/js/airtime/nowplaying/register.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + } + + //determine whether to remove/hide/display the library. + $showLib = false; + if (!$user->isGuest()) { + $disableLib = false; + + $data = Application_Model_Preference::getNowPlayingScreenSettings(); + if (!is_null($data)) { + if ($data["library"] == "true") { + $showLib = true; + } + } + } else { + $disableLib = true; + } + $this->view->disableLib = $disableLib; + $this->view->showLib = $showLib; + //populate date range form for show builder. - $now = time(); + $now = time(); $from = $request->getParam("from", $now); - $to = $request->getParam("to", $now + (24*60*60)); + $to = $request->getParam("to", $now + (24*60*60)); $start = DateTime::createFromFormat("U", $from, new DateTimeZone("UTC")); $start->setTimezone(new DateTimeZone(date_default_timezone_get())); + $end = DateTime::createFromFormat("U", $to, new DateTimeZone("UTC")); $end->setTimezone(new DateTimeZone(date_default_timezone_get())); @@ -159,8 +155,8 @@ class ShowbuilderController extends Zend_Controller_Action $form->populate(array( 'sb_date_start' => $start->format("Y-m-d"), 'sb_time_start' => $start->format("H:i"), - 'sb_date_end' => $end->format("Y-m-d"), - 'sb_time_end' => $end->format("H:i") + 'sb_date_end' => $end->format("Y-m-d"), + 'sb_time_end' => $end->format("H:i") )); $this->view->sb_form = $form; @@ -174,37 +170,36 @@ class ShowbuilderController extends Zend_Controller_Action $this->view->headLink()->appendStylesheet($baseUrl.'/css/jquery.ui.timepicker.css?'.$CC_CONFIG['airtime_version']); $this->view->headLink()->appendStylesheet($baseUrl.'/css/showbuilder.css?'.$CC_CONFIG['airtime_version']); } - - public function contextMenuAction() - { - $id = $this->_getParam('id'); - $now = floatval(microtime(true)); - - $request = $this->getRequest(); - $baseUrl = $request->getBaseUrl(); - $menu = array(); - - $user = Application_Model_User::GetCurrentUser(); - - $item = CcScheduleQuery::create()->findPK($id); - $instance = $item->getCcShowInstances(); - - $menu["preview"] = array("name"=> "Preview", "icon" => "play"); - //select the cursor - $menu["selCurs"] = array("name"=> "Select Cursor","icon" => "select-cursor"); - $menu["delCurs"] = array("name"=> "Remove Cursor","icon" => "select-cursor"); - - if ($now < floatval($item->getDbEnds("U.u")) && $user->canSchedule($instance->getDbShowId())) { - - //remove/truncate the item from the schedule - $menu["del"] = array("name"=> "Delete", "icon" => "delete", "url" => "/showbuilder/schedule-remove"); - } - - $this->view->items = $menu; + + public function contextMenuAction() + { + $id = $this->_getParam('id'); + $now = floatval(microtime(true)); + + $request = $this->getRequest(); + $menu = array(); + + $user = Application_Model_User::getCurrentUser(); + + $item = CcScheduleQuery::create()->findPK($id); + $instance = $item->getCcShowInstances(); + + $menu["preview"] = array("name"=> "Preview", "icon" => "play"); + //select the cursor + $menu["selCurs"] = array("name"=> "Select cursor","icon" => "select-cursor"); + $menu["delCurs"] = array("name"=> "Remove cursor","icon" => "select-cursor"); + + if ($now < floatval($item->getDbEnds("U.u")) && $user->canSchedule($instance->getDbShowId())) { + + //remove/truncate the item from the schedule + $menu["del"] = array("name"=> "Remove from show", "icon" => "delete", "url" => "/showbuilder/schedule-remove"); + } + + $this->view->items = $menu; } - public function builderDialogAction() { - + public function builderDialogAction() + { $request = $this->getRequest(); $id = $request->getParam("id"); @@ -212,6 +207,7 @@ class ShowbuilderController extends Zend_Controller_Action if (is_null($instance)) { $this->view->error = "show does not exist"; + return; } @@ -231,68 +227,56 @@ class ShowbuilderController extends Zend_Controller_Action $this->view->dialog = $this->view->render('showbuilder/builderDialog.phtml'); } - public function checkBuilderFeedAction() { - - $request = $this->getRequest(); + public function checkBuilderFeedAction() + { + $request = $this->getRequest(); $current_time = time(); $starts_epoch = $request->getParam("start", $current_time); //default ends is 24 hours after starts. - $ends_epoch = $request->getParam("end", $current_time + (60*60*24)); + $ends_epoch = $request->getParam("end", $current_time + (60*60*24)); $show_filter = intval($request->getParam("showFilter", 0)); - $my_shows = intval($request->getParam("myShows", 0)); - $timestamp = intval($request->getParam("timestamp", -1)); - $instances = $request->getParam("instances", array()); + $my_shows = intval($request->getParam("myShows", 0)); + $timestamp = intval($request->getParam("timestamp", -1)); + $instances = $request->getParam("instances", array()); $startsDT = DateTime::createFromFormat("U", $starts_epoch, new DateTimeZone("UTC")); - $endsDT = DateTime::createFromFormat("U", $ends_epoch, new DateTimeZone("UTC")); + $endsDT = DateTime::createFromFormat("U", $ends_epoch, new DateTimeZone("UTC")); - $opts = array("myShows" => $my_shows, "showFilter" => $show_filter); + $opts = array("myShows" => $my_shows, "showFilter" => $show_filter); $showBuilder = new Application_Model_ShowBuilder($startsDT, $endsDT, $opts); //only send the schedule back if updates have been made. // -1 default will always call the schedule to be sent back if no timestamp is defined. - if ($showBuilder->hasBeenUpdatedSince($timestamp, $instances)) { - $this->view->update = true; - } - else { - $this->view->update = false; - } + $this->view->update = $showBuilder->hasBeenUpdatedSince( + $timestamp, $instances); } - public function builderFeedAction() { - - $start = microtime(true); - - $request = $this->getRequest(); + public function builderFeedAction() + { + $request = $this->getRequest(); $current_time = time(); $starts_epoch = $request->getParam("start", $current_time); //default ends is 24 hours after starts. - $ends_epoch = $request->getParam("end", $current_time + (60*60*24)); + $ends_epoch = $request->getParam("end", $current_time + (60*60*24)); $show_filter = intval($request->getParam("showFilter", 0)); - $my_shows = intval($request->getParam("myShows", 0)); - $timestamp = intval($request->getParam("timestamp", -1)); + $my_shows = intval($request->getParam("myShows", 0)); $startsDT = DateTime::createFromFormat("U", $starts_epoch, new DateTimeZone("UTC")); - $endsDT = DateTime::createFromFormat("U", $ends_epoch, new DateTimeZone("UTC")); + $endsDT = DateTime::createFromFormat("U", $ends_epoch, new DateTimeZone("UTC")); $opts = array("myShows" => $my_shows, "showFilter" => $show_filter); $showBuilder = new Application_Model_ShowBuilder($startsDT, $endsDT, $opts); - $data = $showBuilder->GetItems(); + $data = $showBuilder->getItems(); $this->view->schedule = $data["schedule"]; $this->view->instances = $data["showInstances"]; $this->view->timestamp = $current_time; - - $end = microtime(true); - - Logging::debug("getting builder feed info took:"); - Logging::debug(floatval($end) - floatval($start)); } - public function scheduleAddAction() { - + public function scheduleAddAction() + { $request = $this->getRequest(); $mediaItems = $request->getParam("mediaIds", array()); $scheduledItems = $request->getParam("schedIds", array()); @@ -300,18 +284,12 @@ class ShowbuilderController extends Zend_Controller_Action try { $scheduler = new Application_Model_Scheduler(); $scheduler->scheduleAfter($scheduledItems, $mediaItems); - } - catch (OutDatedScheduleException $e) { + } catch (OutDatedScheduleException $e) { $this->view->error = $e->getMessage(); - Logging::log($e->getMessage()); - Logging::log("{$e->getFile()}"); - Logging::log("{$e->getLine()}"); - } - catch (Exception $e) { + Logging::info($e->getMessage()); + } catch (Exception $e) { $this->view->error = $e->getMessage(); - Logging::log($e->getMessage()); - Logging::log("{$e->getFile()}"); - Logging::log("{$e->getLine()}"); + Logging::info($e->getMessage()); } } @@ -323,23 +301,17 @@ class ShowbuilderController extends Zend_Controller_Action try { $scheduler = new Application_Model_Scheduler(); $scheduler->removeItems($items); - } - catch (OutDatedScheduleException $e) { + } catch (OutDatedScheduleException $e) { $this->view->error = $e->getMessage(); - Logging::log($e->getMessage()); - Logging::log("{$e->getFile()}"); - Logging::log("{$e->getLine()}"); - } - catch (Exception $e) { + Logging::info($e->getMessage()); + } catch (Exception $e) { $this->view->error = $e->getMessage(); - Logging::log($e->getMessage()); - Logging::log("{$e->getFile()}"); - Logging::log("{$e->getLine()}"); + Logging::info($e->getMessage()); } } - public function scheduleMoveAction() { - + public function scheduleMoveAction() + { $request = $this->getRequest(); $selectedItems = $request->getParam("selectedItem"); $afterItem = $request->getParam("afterItem"); @@ -347,25 +319,18 @@ class ShowbuilderController extends Zend_Controller_Action try { $scheduler = new Application_Model_Scheduler(); $scheduler->moveItem($selectedItems, $afterItem); - } - catch (OutDatedScheduleException $e) { + } catch (OutDatedScheduleException $e) { $this->view->error = $e->getMessage(); - Logging::log($e->getMessage()); - Logging::log("{$e->getFile()}"); - Logging::log("{$e->getLine()}"); - } - catch (Exception $e) { + Logging::info($e->getMessage()); + } catch (Exception $e) { $this->view->error = $e->getMessage(); - Logging::log($e->getMessage()); - Logging::log("{$e->getFile()}"); - Logging::log("{$e->getLine()}"); + Logging::info($e->getMessage()); } } - public function scheduleReorderAction() { - - $request = $this->getRequest(); - - $showInstance = $request->getParam("instanceId"); + public function scheduleReorderAction() + { + throw new Exception("this controller is/was a no-op please fix your + code"); } } diff --git a/airtime_mvc/application/controllers/SystemstatusController.php b/airtime_mvc/application/controllers/SystemstatusController.php index 8865b1663..aa2400f41 100644 --- a/airtime_mvc/application/controllers/SystemstatusController.php +++ b/airtime_mvc/application/controllers/SystemstatusController.php @@ -5,10 +5,10 @@ class SystemstatusController extends Zend_Controller_Action public function init() { global $CC_CONFIG; - + $request = $this->getRequest(); $baseUrl = $request->getBaseUrl(); - + $this->view->headScript()->appendFile($baseUrl.'/js/airtime/status/status.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); } @@ -22,7 +22,7 @@ class SystemstatusController extends Zend_Controller_Action ); $partitions = Application_Model_Systemstatus::GetDiskInfo(); - + $this->view->status = new StdClass; $this->view->status->services = $services; $this->view->status->partitions = $partitions; diff --git a/airtime_mvc/application/controllers/UserController.php b/airtime_mvc/application/controllers/UserController.php index 871f9825e..9c09ceecb 100644 --- a/airtime_mvc/application/controllers/UserController.php +++ b/airtime_mvc/application/controllers/UserController.php @@ -13,51 +13,59 @@ class UserController extends Zend_Controller_Action ->initContext(); } - public function indexAction() - { - } - public function addUserAction() { global $CC_CONFIG; - + $request = $this->getRequest(); $baseUrl = $request->getBaseUrl(); - - $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/airtime/user/user.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + + $js_files = array( + '/js/datatables/js/jquery.dataTables.js?', + '/js/datatables/plugin/dataTables.pluginAPI.js?', + '/js/airtime/user/user.js?' + ); + + foreach ($js_files as $js) { + $this->view->headScript()->appendFile( + $baseUrl.$js.$CC_CONFIG['airtime_version'],'text/javascript'); + } $this->view->headLink()->appendStylesheet($baseUrl.'/css/users.css?'.$CC_CONFIG['airtime_version']); $form = new Application_Form_AddUser(); $this->view->successMessage = ""; - + if ($request->isPost()) { - if ($form->isValid($request->getPost())) { - - $formdata = $form->getValues(); - if(isset($CC_CONFIG['demo']) && $CC_CONFIG['demo'] == 1 && $formdata['login'] == 'admin' && $formdata['user_id'] != 0){ + if ($form->isValid($request->getPost())) { + + $formdata = $form->getValues(); + if (isset($CC_CONFIG['demo']) && $CC_CONFIG['demo'] == 1 + && $formdata['login'] == 'admin' + && $formdata['user_id'] != 0) { $this->view->successMessage = "
Specific action is not allowed in demo version!
"; - } - else if ($form->validateLogin($formdata)){ + } elseif ($form->validateLogin($formdata)) { $user = new Application_Model_User($formdata['user_id']); $user->setFirstName($formdata['first_name']); $user->setLastName($formdata['last_name']); $user->setLogin($formdata['login']); - if ($formdata['password'] != "xxxxxx") + // We don't allow 6 x's as a password. + // The reason is because we that as a password placeholder + // on the client side. + if ($formdata['password'] != "xxxxxx") { $user->setPassword($formdata['password']); + } $user->setType($formdata['type']); $user->setEmail($formdata['email']); $user->setCellPhone($formdata['cell_phone']); $user->setSkype($formdata['skype']); $user->setJabber($formdata['jabber']); $user->save(); - + $form->reset(); - if (strlen($formdata['user_id']) == 0){ + if (strlen($formdata['user_id']) == 0) { $this->view->successMessage = "
User added successfully!
"; } else { $this->view->successMessage = "
User updated successfully!
"; @@ -65,14 +73,14 @@ class UserController extends Zend_Controller_Action } } } - + $this->view->form = $form; } public function getHostsAction() { - $search = $this->_getParam('term'); - $res = Application_Model_User::getHosts($search); + $search = $this->_getParam('term'); + $res = Application_Model_User::getHosts($search); $this->view->hosts = Application_Model_User::getHosts($search); } @@ -80,7 +88,7 @@ class UserController extends Zend_Controller_Action { $post = $this->getRequest()->getPost(); $users = Application_Model_User::getUsersDataTablesInfo($post); - + die(json_encode($users)); } @@ -94,27 +102,43 @@ class UserController extends Zend_Controller_Action { // action body $delId = $this->_getParam('id'); + $valid_actions = array("delete_cascade", "reassign_to"); + $files_action = $this->_getParam('deleted_files'); + + # TODO : remove this. we only use default for now not to break the UI. + if (!$files_action) { # set default action + $files_action = "reassign_to"; + $new_owner = Application_Model_User::getFirstAdmin(); + } + + # only delete when valid action is selected for the owned files + if (! in_array($files_action, $valid_actions) ) { + return; + } $userInfo = Zend_Auth::getInstance()->getStorage()->read(); $userId = $userInfo->id; - if ($delId != $userId){ - $user = new Application_Model_User($delId); - $this->view->entries = $user->delete(); + # Don't let users delete themselves + if ($delId == $userId) { + return; } - + + $user = new Application_Model_User($delId); + + # Take care of the user's files by either assigning them to somebody + # or deleting them all + if ($files_action == "delete_cascade") { + $user->deleteAllFiles(); + } elseif ($files_action == "reassign_to") { + // TODO : fix code to actually use the line below and pick a + // real owner instead of defaulting to the first found admin + //$new_owner_id = $this->_getParam("new_owner"); + //$new_owner = new Application_Model_User($new_owner_id); + $user->donateFilesTo( $new_owner ); + Logging::info("Reassign to user {$new_owner->getDbId()}"); + } + # Finally delete the user + $this->view->entries = $user->delete(); } - - } - - - - - - - - - - - diff --git a/airtime_mvc/application/controllers/UsersettingsController.php b/airtime_mvc/application/controllers/UsersettingsController.php index 2260d0400..238e67f3b 100644 --- a/airtime_mvc/application/controllers/UsersettingsController.php +++ b/airtime_mvc/application/controllers/UsersettingsController.php @@ -11,87 +11,84 @@ class UsersettingsController extends Zend_Controller_Action ->addActionContext('get-library-datatable', 'json') ->addActionContext('set-library-datatable', 'json') ->addActionContext('get-timeline-datatable', 'json') - ->addActionContext('set-timeline-datatable', 'json') + ->addActionContext('set-timeline-datatable', 'json') ->addActionContext('remindme', 'json') + ->addActionContext('remindme-never', 'json') ->addActionContext('donotshowregistrationpopup', 'json') ->initContext(); } - - public function setNowPlayingScreenSettingsAction() { - - $request = $this->getRequest(); - $settings = $request->getParam("settings"); - - $data = serialize($settings); - Application_Model_Preference::SetValue("nowplaying_screen", $data, true); - } - - public function getNowPlayingScreenSettingsAction() { - - $data = Application_Model_Preference::GetValue("nowplaying_screen", true); - if ($data != "") { - $this->view->settings = unserialize($data); - } - } - - public function setLibraryDatatableAction() { + public function setNowPlayingScreenSettingsAction() + { $request = $this->getRequest(); $settings = $request->getParam("settings"); - $data = serialize($settings); - Application_Model_Preference::SetValue("library_datatable", $data, true); + Application_Model_Preference::setNowPlayingScreenSettings($settings); } - public function getLibraryDatatableAction() { - - $data = Application_Model_Preference::GetValue("library_datatable", true); - if ($data != "") { - $this->view->settings = unserialize($data); + public function getNowPlayingScreenSettingsAction() + { + $data = Application_Model_Preference::getNowPlayingScreenSettings(); + if (!is_null($data)) { + $this->view->settings = $data; } } - public function setTimelineDatatableAction() { - - $start = microtime(true); - + public function setLibraryDatatableAction() + { $request = $this->getRequest(); $settings = $request->getParam("settings"); - $data = serialize($settings); - Application_Model_Preference::SetValue("timeline_datatable", $data, true); - + Application_Model_Preference::setCurrentLibraryTableSetting($settings); + } + + public function getLibraryDatatableAction() + { + $data = Application_Model_Preference::getCurrentLibraryTableSetting(); + if (!is_null($data)) { + $this->view->settings = $data; + } + } + + public function setTimelineDatatableAction() + { + $request = $this->getRequest(); + $settings = $request->getParam("settings"); + Application_Model_Preference::setTimelineDatatableSetting($settings); + } + + public function getTimelineDatatableAction() + { + $start = microtime(true); + + $data = Application_Model_Preference::getTimelineDatatableSetting(); + if (!is_null($data)) { + $this->view->settings = $data; + } + $end = microtime(true); - - Logging::debug("saving timeline datatables info took:"); + + Logging::debug("getting timeline datatables info took:"); Logging::debug(floatval($end) - floatval($start)); } - public function getTimelineDatatableAction() { - - $start = microtime(true); - - $data = Application_Model_Preference::GetValue("timeline_datatable", true); - if ($data != "") { - $this->view->settings = unserialize($data); - } - - $end = microtime(true); - - Logging::debug("getting timeline datatables info took:"); - Logging::debug(floatval($end) - floatval($start)); + public function remindmeAction() + { + // unset session + Zend_Session::namespaceUnset('referrer'); + Application_Model_Preference::SetRemindMeDate(); } - public function remindmeAction() - { - // unset session - Zend_Session::namespaceUnset('referrer'); - Application_Model_Preference::SetRemindMeDate(); - } - - public function donotshowregistrationpopupAction() - { - // unset session - Zend_Session::namespaceUnset('referrer'); + public function remindmeNeverAction() + { + Zend_Session::namespaceUnset('referrer'); + //pass in true to indicate 'Remind me never' was clicked + Application_Model_Preference::SetRemindMeDate(true); } -} \ No newline at end of file + + public function donotshowregistrationpopupAction() + { + // unset session + Zend_Session::namespaceUnset('referrer'); + } +} diff --git a/airtime_mvc/application/controllers/WebstreamController.php b/airtime_mvc/application/controllers/WebstreamController.php new file mode 100644 index 000000000..ebb5acbf6 --- /dev/null +++ b/airtime_mvc/application/controllers/WebstreamController.php @@ -0,0 +1,151 @@ +_helper->getHelper('AjaxContext'); + $ajaxContext->addActionContext('new', 'json') + ->addActionContext('save', 'json') + ->addActionContext('edit', 'json') + ->addActionContext('delete', 'json') + ->initContext(); + } + + public function newAction() + { + + $userInfo = Zend_Auth::getInstance()->getStorage()->read(); + if (!$this->isAuthorized(-1)) { + // TODO: this header call does not actually print any error message + header("Status: 401 Not Authorized"); + return; + } + + $webstream = new CcWebstream(); + + //we're not saving this primary key in the DB so it's OK to be -1 + $webstream->setDbId(-1); + $webstream->setDbName("Untitled Webstream"); + $webstream->setDbDescription(""); + $webstream->setDbUrl("http://"); + $webstream->setDbLength("00:30:00"); + $webstream->setDbName("Untitled Webstream"); + $webstream->setDbCreatorId($userInfo->id); + $webstream->setDbUtime(new DateTime("now", new DateTimeZone('UTC'))); + $webstream->setDbMtime(new DateTime("now", new DateTimeZone('UTC'))); + + //clear the session in case an old playlist was open: CC-4196 + Application_Model_Library::changePlaylist(null, null); + + $this->view->obj = new Application_Model_Webstream($webstream); + $this->view->action = "new"; + $this->view->html = $this->view->render('webstream/webstream.phtml'); + } + + public function editAction() + { + $request = $this->getRequest(); + + $id = $request->getParam("id"); + if (is_null($id)) { + throw new Exception("Missing parameter 'id'"); + } + + $webstream = CcWebstreamQuery::create()->findPK($id); + if ($webstream) { + Application_Model_Library::changePlaylist($id, "stream"); + } + $this->view->obj = new Application_Model_Webstream($webstream); + $this->view->action = "edit"; + $this->view->html = $this->view->render('webstream/webstream.phtml'); + } + + public function deleteAction() + { + $request = $this->getRequest(); + $id = $request->getParam("ids"); + + if (!$this->isAuthorized($id)) { + header("Status: 401 Not Authorized"); + + return; + } + + $type = "stream"; + Application_Model_Library::changePlaylist(null, $type); + + $webstream = CcWebstreamQuery::create()->findPK($id)->delete(); + + $this->view->obj = null; + $this->view->action = "delete"; + $this->view->html = $this->view->render('webstream/webstream.phtml'); + + } + + /*TODO : make a user object be passed a parameter into this function so + that it does not have to be fetched multiple times.*/ + public function isAuthorized($webstream_id) + { + $user = Application_Model_User::getCurrentUser(); + if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) { + return true; + } + + if ($user->isHost()) { + // not creating a webstream + if ($webstream_id != -1) { + $webstream = CcWebstreamQuery::create()->findPK($webstream_id); + /*we are updating a playlist. Ensure that if the user is a + host/dj, that he has the correct permission.*/ + $user = Application_Model_User::getCurrentUser(); + //only allow when webstream belongs to the DJ + return $webstream->getDbCreatorId() == $user->getId(); + } + /*we are creating a new stream. Don't need to check whether the + DJ/Host owns the stream*/ + return true; + } else { + Logging::info( $user ); + } + return false; + } + + public function saveAction() + { + $request = $this->getRequest(); + + $id = $request->getParam("id"); + + $parameters = array(); + foreach (array('id','length','name','description','url') as $p) { + $parameters[$p] = trim($request->getParam($p)); + } + + if (!$this->isAuthorized($id)) { + header("Status: 401 Not Authorized"); + return; + } + + + list($analysis, $mime, $mediaUrl, $di) = Application_Model_Webstream::analyzeFormData($parameters); + try { + if (Application_Model_Webstream::isValid($analysis)) { + $streamId = Application_Model_Webstream::save($parameters, $mime, $mediaUrl, $di); + + Application_Model_Library::changePlaylist($streamId, "stream"); + + $this->view->statusMessage = "
Webstream saved.
"; + $this->view->streamId = $streamId; + $this->view->length = $di->format("%Hh %Im"); + } else { + throw new Exception("isValid returned false"); + } + } catch (Exception $e) { + Logging::debug($e->getMessage()); + $this->view->statusMessage = "
Invalid form values.
"; + $this->view->streamId = -1; + $this->view->analysis = $analysis; + } + } +} diff --git a/airtime_mvc/application/controllers/plugins/Acl_plugin.php b/airtime_mvc/application/controllers/plugins/Acl_plugin.php index 0296362ed..b28de407a 100644 --- a/airtime_mvc/application/controllers/plugins/Acl_plugin.php +++ b/airtime_mvc/application/controllers/plugins/Acl_plugin.php @@ -26,8 +26,8 @@ class Zend_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract **/ public function __construct(Zend_Acl $aclData, $roleName = 'G') { - $this->_errorPage = array('module' => 'default', - 'controller' => 'error', + $this->_errorPage = array('module' => 'default', + 'controller' => 'error', 'action' => 'denied'); $this->_roleName = $roleName; @@ -40,7 +40,7 @@ class Zend_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract /** * Sets the ACL object * - * @param mixed $aclData + * @param mixed $aclData * @return void **/ public function setAcl(Zend_Acl $aclData) @@ -62,29 +62,29 @@ class Zend_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract * Returns the ACL role used * * @return string - * @author + * @author **/ public function getRoleName() { return $this->_roleName; } - public function setRoleName($type) - { - $this->_roleName = $type; - } + public function setRoleName($type) + { + $this->_roleName = $type; + } /** * Sets the error page * - * @param string $action - * @param string $controller - * @param string $module + * @param string $action + * @param string $controller + * @param string $module * @return void **/ public function setErrorPage($action, $controller = 'error', $module = null) { - $this->_errorPage = array('module' => $module, + $this->_errorPage = array('module' => $module, 'controller' => $controller, 'action' => $action); } @@ -108,58 +108,55 @@ class Zend_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract **/ public function preDispatch(Zend_Controller_Request_Abstract $request) { - $controller = strtolower($request->getControllerName()); - - if (in_array($controller, array("api", "auth"))){ - - $this->setRoleName("G"); - } - else if (!Zend_Auth::getInstance()->hasIdentity()){ - - if ($controller !== 'login') { + $controller = strtolower($request->getControllerName()); - if ($request->isXmlHttpRequest()) { + if (in_array($controller, array("api", "auth"))) { - $url = 'http://'.$request->getHttpHost().'/login'; - $json = Zend_Json::encode(array('auth' => false, 'url' => $url)); - - // Prepare response - $this->getResponse() - ->setHttpResponseCode(401) - ->setBody($json) - ->sendResponse(); + $this->setRoleName("G"); + } elseif (!Zend_Auth::getInstance()->hasIdentity()) { - //redirectAndExit() cleans up, sends the headers and stops the script - Zend_Controller_Action_HelperBroker::getStaticHelper('redirector')->redirectAndExit(); - } - else { - $r = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector'); - $r->gotoSimpleAndExit('index', 'login', $request->getModuleName()); - } - } - } - else { + if ($controller !== 'login') { - $userInfo = Zend_Auth::getInstance()->getStorage()->read(); - $this->setRoleName($userInfo->type); + if ($request->isXmlHttpRequest()) { + + $url = 'http://'.$request->getHttpHost().'/login'; + $json = Zend_Json::encode(array('auth' => false, 'url' => $url)); + + // Prepare response + $this->getResponse() + ->setHttpResponseCode(401) + ->setBody($json) + ->sendResponse(); + + //redirectAndExit() cleans up, sends the headers and stops the script + Zend_Controller_Action_HelperBroker::getStaticHelper('redirector')->redirectAndExit(); + } else { + $r = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector'); + $r->gotoSimpleAndExit('index', 'login', $request->getModuleName()); + } + } + } else { + + $userInfo = Zend_Auth::getInstance()->getStorage()->read(); + $this->setRoleName($userInfo->type); Zend_View_Helper_Navigation_HelperAbstract::setDefaultAcl($this->_acl); - Zend_View_Helper_Navigation_HelperAbstract::setDefaultRole($this->_roleName); - - $resourceName = ''; + Zend_View_Helper_Navigation_HelperAbstract::setDefaultRole($this->_roleName); - if ($request->getModuleName() != 'default') { - $resourceName .= strtolower($request->getModuleName()) . ':'; - } + $resourceName = ''; - $resourceName .= $controller; + if ($request->getModuleName() != 'default') { + $resourceName .= strtolower($request->getModuleName()) . ':'; + } - /** Check if the controller/action can be accessed by the current user */ - if (!$this->getAcl()->isAllowed($this->_roleName, $resourceName, $request->getActionName())) { - /** Redirect to access denied page */ - $this->denyAccess(); - } - } + $resourceName .= $controller; + + /** Check if the controller/action can be accessed by the current user */ + if (!$this->getAcl()->isAllowed($this->_roleName, $resourceName, $request->getActionName())) { + /** Redirect to access denied page */ + $this->denyAccess(); + } + } } /** diff --git a/airtime_mvc/application/controllers/plugins/RabbitMqPlugin.php b/airtime_mvc/application/controllers/plugins/RabbitMqPlugin.php index 07f58c742..617e26675 100644 --- a/airtime_mvc/application/controllers/plugins/RabbitMqPlugin.php +++ b/airtime_mvc/application/controllers/plugins/RabbitMqPlugin.php @@ -5,11 +5,19 @@ class RabbitMqPlugin extends Zend_Controller_Plugin_Abstract public function dispatchLoopShutdown() { if (Application_Model_RabbitMq::$doPush) { - $md = array('schedule' => Application_Model_Schedule::GetScheduledPlaylists()); + $md = array('schedule' => Application_Model_Schedule::getSchedule()); Application_Model_RabbitMq::SendMessageToPypo("update_schedule", $md); - if (!isset($_SERVER['AIRTIME_SRV'])){ + if (!isset($_SERVER['AIRTIME_SRV'])) { Application_Model_RabbitMq::SendMessageToShowRecorder("update_recorder_schedule"); } } + + if (memory_get_peak_usage() > 30*pow(2, 20)) { + + Logging::debug("Peak memory usage: " + .(memory_get_peak_usage()/1000000) + ." MB while accessing URI ".$_SERVER['REQUEST_URI']); + Logging::debug("Should try to keep memory footprint under 25 MB"); + } } } diff --git a/airtime_mvc/application/forms/AddShowAbsoluteRebroadcastDates.php b/airtime_mvc/application/forms/AddShowAbsoluteRebroadcastDates.php index 9107012d9..8bfa71b2f 100644 --- a/airtime_mvc/application/forms/AddShowAbsoluteRebroadcastDates.php +++ b/airtime_mvc/application/forms/AddShowAbsoluteRebroadcastDates.php @@ -9,7 +9,7 @@ class Application_Form_AddShowAbsoluteRebroadcastDates extends Zend_Form_SubForm array('ViewScript', array('viewScript' => 'form/add-show-rebroadcast-absolute.phtml')) )); - for($i=1; $i<=10; $i++) { + for ($i=1; $i<=10; $i++) { $text = new Zend_Form_Element_Text("add_show_rebroadcast_date_absolute_$i"); $text->setAttrib('class', 'input_text'); @@ -29,44 +29,42 @@ class Application_Form_AddShowAbsoluteRebroadcastDates extends Zend_Form_SubForm $this->addElement($text); } } - - public function disable(){ + + public function disable() + { $elements = $this->getElements(); - foreach ($elements as $element) - { - if ($element->getType() != 'Zend_Form_Element_Hidden') - { + foreach ($elements as $element) { + if ($element->getType() != 'Zend_Form_Element_Hidden') { $element->setAttrib('disabled','disabled'); } } } - public function checkReliantFields($formData) { - + public function checkReliantFields($formData) + { $noError = true; - for($i=1; $i<=10; $i++) { + for ($i=1; $i<=10; $i++) { $valid = true; $day = $formData['add_show_rebroadcast_date_absolute_'.$i]; $time = $formData['add_show_rebroadcast_time_absolute_'.$i]; - if(trim($day) == "" && trim($time) == "") { + if (trim($day) == "" && trim($time) == "") { continue; } - if (trim($day) == ""){ + if (trim($day) == "") { $this->getElement('add_show_rebroadcast_date_absolute_'.$i)->setErrors(array("Day must be specified")); $valid = false; } - - if (trim($time) == ""){ + if (trim($time) == "") { $this->getElement('add_show_rebroadcast_time_absolute_'.$i)->setErrors(array("Time must be specified")); $valid = false; } - if($valid === false) { + if ($valid === false) { $noError = false; continue; } @@ -84,7 +82,7 @@ class Application_Form_AddShowAbsoluteRebroadcastDates extends Zend_Form_SubForm $rebroad_start = $day." ".$formData['add_show_rebroadcast_time_absolute_'.$i]; $rebroad_start = new DateTime($rebroad_start); - if($rebroad_start < $show_end) { + if ($rebroad_start < $show_end) { $this->getElement('add_show_rebroadcast_time_absolute_'.$i)->setErrors(array("Must wait at least 1 hour to rebroadcast")); $valid = false; $noError = false; @@ -94,4 +92,3 @@ class Application_Form_AddShowAbsoluteRebroadcastDates extends Zend_Form_SubForm return $noError; } } - diff --git a/airtime_mvc/application/forms/AddShowLiveStream.php b/airtime_mvc/application/forms/AddShowLiveStream.php index c0c93a4ae..b241a54f0 100644 --- a/airtime_mvc/application/forms/AddShowLiveStream.php +++ b/airtime_mvc/application/forms/AddShowLiveStream.php @@ -11,13 +11,13 @@ class Application_Form_AddShowLiveStream extends Zend_Form_SubForm ->setRequired(false) ->setDecorators(array('ViewHelper')); $this->addElement($cb_airtime_auth); - + $cb_custom_auth = new Zend_Form_Element_Checkbox("cb_custom_auth"); $cb_custom_auth ->setLabel("Use Custom Authentication:") ->setRequired(false) ->setDecorators(array('ViewHelper')); $this->addElement($cb_custom_auth); - + //custom username $custom_username = new Zend_Form_Element_Text('custom_username'); $custom_username->setAttrib('class', 'input_text') @@ -29,7 +29,7 @@ class Application_Form_AddShowLiveStream extends Zend_Form_SubForm new ConditionalNotEmpty(array("cb_custom_auth"=>"1")))) ->setDecorators(array('ViewHelper')); $this->addElement($custom_username); - + //custom password $custom_password = new Zend_Form_Element_Password('custom_password'); $custom_password->setAttrib('class', 'input_text') @@ -42,32 +42,34 @@ class Application_Form_AddShowLiveStream extends Zend_Form_SubForm new ConditionalNotEmpty(array("cb_custom_auth"=>"1")))) ->setDecorators(array('ViewHelper')); $this->addElement($custom_password); - + $connection_url = Application_Model_Preference::GetLiveDJSourceConnectionURL(); - if(trim($connection_url) == ""){ + if (trim($connection_url) == "") { $connection_url = "N/A"; } - + $this->setDecorators(array( array('ViewScript', array('viewScript' => 'form/add-show-live-stream.phtml', "connection_url"=>$connection_url)) )); } - - public function isValid($data){ + + public function isValid($data) + { $isValid = parent::isValid($data); - - if($data['cb_custom_auth'] == 1){ - if(trim($data['custom_username']) == ''){ + + if ($data['cb_custom_auth'] == 1) { + if (trim($data['custom_username']) == '') { $element = $this->getElement("custom_username"); $element->addError("Username field cannot be empty."); $isValid = false; } - if(trim($data['custom_password']) == ''){ + if (trim($data['custom_password']) == '') { $element = $this->getElement("custom_password"); $element->addError("Password field cannot be empty."); $isValid = false; } } + return $isValid; } } diff --git a/airtime_mvc/application/forms/AddShowRR.php b/airtime_mvc/application/forms/AddShowRR.php index 9f3778df1..5c33723b6 100644 --- a/airtime_mvc/application/forms/AddShowRR.php +++ b/airtime_mvc/application/forms/AddShowRR.php @@ -6,28 +6,26 @@ class Application_Form_AddShowRR extends Zend_Form_SubForm public function init() { // Add record element - $this->addElement('checkbox', 'add_show_record', array( + $this->addElement('checkbox', 'add_show_record', array( 'label' => 'Record from Line In?', 'required' => false, - )); + )); // Add record element - $this->addElement('checkbox', 'add_show_rebroadcast', array( + $this->addElement('checkbox', 'add_show_rebroadcast', array( 'label' => 'Rebroadcast?', 'required' => false, - )); + )); } - public function disable(){ + public function disable() + { $elements = $this->getElements(); - foreach ($elements as $element) - { - if ($element->getType() != 'Zend_Form_Element_Hidden') - { + foreach ($elements as $element) { + if ($element->getType() != 'Zend_Form_Element_Hidden') { $element->setAttrib('disabled','disabled'); } } } } - diff --git a/airtime_mvc/application/forms/AddShowRebroadcastDates.php b/airtime_mvc/application/forms/AddShowRebroadcastDates.php index 42d1f8e86..7bf0ea3a4 100644 --- a/airtime_mvc/application/forms/AddShowRebroadcastDates.php +++ b/airtime_mvc/application/forms/AddShowRebroadcastDates.php @@ -11,11 +11,11 @@ class Application_Form_AddShowRebroadcastDates extends Zend_Form_SubForm $relativeDates = array(); $relativeDates[""] = ""; - for($i=0; $i<=30; $i++) { + for ($i=0; $i<=30; $i++) { $relativeDates["$i days"] = "+$i days"; } - for($i=1; $i<=10; $i++) { + for ($i=1; $i<=10; $i++) { $select = new Zend_Form_Element_Select("add_show_rebroadcast_date_$i"); $select->setAttrib('class', 'input_select'); @@ -34,44 +34,42 @@ class Application_Form_AddShowRebroadcastDates extends Zend_Form_SubForm $this->addElement($text); } } - - public function disable(){ + + public function disable() + { $elements = $this->getElements(); - foreach ($elements as $element) - { - if ($element->getType() != 'Zend_Form_Element_Hidden') - { + foreach ($elements as $element) { + if ($element->getType() != 'Zend_Form_Element_Hidden') { $element->setAttrib('disabled','disabled'); } } } - public function checkReliantFields($formData) { - + public function checkReliantFields($formData) + { $noError = true; - for($i=1; $i<=10; $i++) { + for ($i=1; $i<=10; $i++) { $valid = true; $days = $formData['add_show_rebroadcast_date_'.$i]; $time = $formData['add_show_rebroadcast_time_'.$i]; - if(trim($days) == "" && trim($time) == "") { + if (trim($days) == "" && trim($time) == "") { continue; } - if (trim($days) == ""){ + if (trim($days) == "") { $this->getElement('add_show_rebroadcast_date_'.$i)->setErrors(array("Day must be specified")); $valid = false; } - - if (trim($time) == ""){ + if (trim($time) == "") { $this->getElement('add_show_rebroadcast_time_'.$i)->setErrors(array("Time must be specified")); $valid = false; } - if($valid === false) { + if ($valid === false) { $noError = false; continue; } @@ -93,7 +91,7 @@ class Application_Form_AddShowRebroadcastDates extends Zend_Form_SubForm $rebroad_start = new DateTime($rebroad_start); $rebroad_start->add(new DateInterval("P".$day."D")); - if($rebroad_start < $show_end) { + if ($rebroad_start < $show_end) { $this->getElement('add_show_rebroadcast_time_'.$i)->setErrors(array("Must wait at least 1 hour to rebroadcast")); $valid = false; $noError = false; @@ -103,4 +101,3 @@ class Application_Form_AddShowRebroadcastDates extends Zend_Form_SubForm return $noError; } } - diff --git a/airtime_mvc/application/forms/AddShowRepeats.php b/airtime_mvc/application/forms/AddShowRepeats.php index 2315147fb..85bb7cb44 100644 --- a/airtime_mvc/application/forms/AddShowRepeats.php +++ b/airtime_mvc/application/forms/AddShowRepeats.php @@ -6,78 +6,78 @@ class Application_Form_AddShowRepeats extends Zend_Form_SubForm public function init() { //Add type select - $this->addElement('select', 'add_show_repeat_type', array( + $this->addElement('select', 'add_show_repeat_type', array( 'required' => true, 'label' => 'Repeat Type:', 'class' => ' input_select', 'multiOptions' => array( - "0" => "weekly", + "0" => "weekly", "1" => "bi-weekly", "2" => "monthly" ), )); // Add days checkboxes - $this->addElement( + $this->addElement( 'multiCheckbox', 'add_show_day_check', array( - 'label' => 'Select Days:', + 'label' => 'Select Days:', 'required' => false, 'multiOptions' => array( - "0" => "Sun", - "1" => "Mon", - "2" => "Tue", - "3" => "Wed", - "4" => "Thu", - "5" => "Fri", - "6" => "Sat", + "0" => "Sun", + "1" => "Mon", + "2" => "Tue", + "3" => "Wed", + "4" => "Thu", + "5" => "Fri", + "6" => "Sat", ), )); - // Add end date element + // Add end date element $this->addElement('text', 'add_show_end_date', array( 'label' => 'Date End:', 'class' => 'input_text', 'value' => date("Y-m-d"), 'required' => false, 'filters' => array('StringTrim'), - 'validators' => array( - 'NotEmpty', - array('date', false, array('YYYY-MM-DD')) - ) + 'validators' => array( + 'NotEmpty', + array('date', false, array('YYYY-MM-DD')) + ) )); - // Add no end element - $this->addElement('checkbox', 'add_show_no_end', array( + // Add no end element + $this->addElement('checkbox', 'add_show_no_end', array( 'label' => 'No End?', 'required' => false, 'checked' => true, - )); + )); } - - public function disable(){ + + public function disable() + { $elements = $this->getElements(); - foreach ($elements as $element) - { - if ($element->getType() != 'Zend_Form_Element_Hidden') - { + foreach ($elements as $element) { + if ($element->getType() != 'Zend_Form_Element_Hidden') { $element->setAttrib('disabled','disabled'); } } } - public function checkReliantFields($formData) { - - if (!$formData['add_show_no_end']){ + public function checkReliantFields($formData) + { + if (!$formData['add_show_no_end']) { $start_timestamp = $formData['add_show_start_date']; $end_timestamp = $formData['add_show_end_date']; - + $start_epoch = strtotime($start_timestamp); $end_epoch = strtotime($end_timestamp); - if($end_epoch < $start_epoch) { + if ($end_epoch < $start_epoch) { $this->getElement('add_show_end_date')->setErrors(array('End date must be after start date')); + return false; } } @@ -86,4 +86,3 @@ class Application_Form_AddShowRepeats extends Zend_Form_SubForm } } - diff --git a/airtime_mvc/application/forms/AddShowStyle.php b/airtime_mvc/application/forms/AddShowStyle.php index 8fe158faf..6ea301874 100644 --- a/airtime_mvc/application/forms/AddShowStyle.php +++ b/airtime_mvc/application/forms/AddShowStyle.php @@ -18,14 +18,13 @@ class Application_Form_AddShowStyle extends Zend_Form_SubForm 'viewScript' => 'form/add-show-style.phtml', 'class' => 'big' )))); - + $bg->setValidators(array( 'Hex', array('stringLength', false, array(6, 6)) )); - - // Add show color input + // Add show color input $this->addElement('text', 'add_show_color', array( 'label' => 'Text Colour:', 'class' => 'input_text', @@ -38,23 +37,21 @@ class Application_Form_AddShowStyle extends Zend_Form_SubForm 'viewScript' => 'form/add-show-style.phtml', 'class' => 'big' )))); - - $c->setValidators(array( - 'Hex', - array('stringLength', false, array(6, 6)) + + $c->setValidators(array( + 'Hex', + array('stringLength', false, array(6, 6)) )); } - public function disable(){ + public function disable() + { $elements = $this->getElements(); - foreach ($elements as $element) - { - if ($element->getType() != 'Zend_Form_Element_Hidden') - { + foreach ($elements as $element) { + if ($element->getType() != 'Zend_Form_Element_Hidden') { $element->setAttrib('disabled','disabled'); } } } } - diff --git a/airtime_mvc/application/forms/AddShowWhat.php b/airtime_mvc/application/forms/AddShowWhat.php index 5e91a38b4..7a092f4b5 100644 --- a/airtime_mvc/application/forms/AddShowWhat.php +++ b/airtime_mvc/application/forms/AddShowWhat.php @@ -4,22 +4,22 @@ class Application_Form_AddShowWhat extends Zend_Form_SubForm { public function init() { - // retrieves the length limit for each char field - // and store to assoc array - $maxLens = Application_Model_Show::GetMaxLengths(); - + // retrieves the length limit for each char field + // and store to assoc array + $maxLens = Application_Model_Show::getMaxLengths(); + // Hidden element to indicate whether the show is new or // whether we are updating an existing show. $this->addElement('hidden', 'add_show_id', array( 'decorators' => array('ViewHelper') )); - + // Hidden element to indicate the instance id of the show // being edited. $this->addElement('hidden', 'add_show_instance_id', array( 'decorators' => array('ViewHelper') )); - + // Add name element $this->addElement('text', 'add_show_name', array( 'label' => 'Name:', @@ -27,8 +27,8 @@ class Application_Form_AddShowWhat extends Zend_Form_SubForm 'required' => true, 'filters' => array('StringTrim'), 'validators' => array('NotEmpty'), - 'value' => 'Untitled Show', - 'validators' => array(array('StringLength', false, array(0, $maxLens['name']))) + 'value' => 'Untitled Show', + 'validators' => array(array('StringLength', false, array(0, $maxLens['name']))) )); // Add URL element @@ -46,16 +46,16 @@ class Application_Form_AddShowWhat extends Zend_Form_SubForm 'class' => 'input_text', 'required' => false, 'filters' => array('StringTrim'), - 'validators' => array(array('StringLength', false, array(0, $maxLens['genre']))) + 'validators' => array(array('StringLength', false, array(0, $maxLens['genre']))) )); - // Add the description element + // Add the description element $this->addElement('textarea', 'add_show_description', array( 'label' => 'Description:', 'required' => false, 'class' => 'input_text_area', - 'validators' => array(array('StringLength', false, array(0, $maxLens['description']))) - )); + 'validators' => array(array('StringLength', false, array(0, $maxLens['description']))) + )); $descText = $this->getElement('add_show_description'); @@ -65,16 +65,14 @@ class Application_Form_AddShowWhat extends Zend_Form_SubForm )))); } - - public function disable(){ + + public function disable() + { $elements = $this->getElements(); - foreach ($elements as $element) - { - if ($element->getType() != 'Zend_Form_Element_Hidden') - { + foreach ($elements as $element) { + if ($element->getType() != 'Zend_Form_Element_Hidden') { $element->setAttrib('disabled','disabled'); } } } } - diff --git a/airtime_mvc/application/forms/AddShowWhen.php b/airtime_mvc/application/forms/AddShowWhen.php index ba0a4df26..e6d164022 100644 --- a/airtime_mvc/application/forms/AddShowWhen.php +++ b/airtime_mvc/application/forms/AddShowWhen.php @@ -8,7 +8,7 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm $this->setDecorators(array( array('ViewScript', array('viewScript' => 'form/add-show-when.phtml')) )); - + // Add start date element $startDate = new Zend_Form_Element_Text('add_show_start_date'); $startDate->class = 'input_text'; @@ -22,7 +22,7 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm ->setDecorators(array('ViewHelper')); $startDate->setAttrib('alt', 'date'); $this->addElement($startDate); - + // Add start time element $startTime = new Zend_Form_Element_Text('add_show_start_time'); $startTime->class = 'input_text'; @@ -50,7 +50,7 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm ->setDecorators(array('ViewHelper')); $endDate->setAttrib('alt', 'date'); $this->addElement($endDate); - + // Add end time element $endTime = new Zend_Form_Element_Text('add_show_end_time'); $endTime->class = 'input_text'; @@ -64,7 +64,7 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm ->setDecorators(array('ViewHelper')); $endTime->setAttrib('alt', 'time'); $this->addElement($endTime); - + // Add duration element $this->addElement('text', 'add_show_duration', array( 'label' => 'Duration:', @@ -83,24 +83,25 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm } - public function checkReliantFields($formData, $validateStartDate, $originalStartDate=null) { + public function checkReliantFields($formData, $validateStartDate, $originalStartDate=null, $update=false, $instanceId=null) + { $valid = true; - + $start_time = $formData['add_show_start_date']." ".$formData['add_show_start_time']; $end_time = $formData['add_show_end_date_no_repeat']." ".$formData['add_show_end_time']; - + //DateTime stores $start_time in the current timezone $nowDateTime = new DateTime(); $showStartDateTime = new DateTime($start_time); $showEndDateTime = new DateTime($end_time); - if ($validateStartDate){ - if($showStartDateTime->getTimestamp() < $nowDateTime->getTimestamp()) { + if ($validateStartDate) { + if ($showStartDateTime->getTimestamp() < $nowDateTime->getTimestamp()) { $this->getElement('add_show_start_time')->setErrors(array('Cannot create show in the past')); $valid = false; } // if edit action, check if original show start time is in the past. CC-3864 - if($originalStartDate){ - if($originalStartDate->getTimestamp() < $nowDateTime->getTimestamp()) { + if ($originalStartDate) { + if ($originalStartDate->getTimestamp() < $nowDateTime->getTimestamp()) { $this->getElement('add_show_start_time')->setValue($originalStartDate->format("H:i")); $this->getElement('add_show_start_date')->setValue($originalStartDate->format("Y-m-d")); $this->getElement('add_show_start_time')->setErrors(array('Cannot modify start date/time of the show that is already started')); @@ -109,66 +110,258 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm } } } - + // if end time is in the past, return error - if($showEndDateTime->getTimestamp() < $nowDateTime->getTimestamp()) { + if ($showEndDateTime->getTimestamp() < $nowDateTime->getTimestamp()) { $this->getElement('add_show_end_time')->setErrors(array('End date/time cannot be in the past')); $valid = false; } - + $pattern = '/([0-9][0-9])h ([0-9][0-9])m/'; - + if (preg_match($pattern, $formData['add_show_duration'], $matches) && count($matches) == 3) { $hours = $matches[1]; $minutes = $matches[2]; - if( $formData["add_show_duration"] == "00h 00m" ) { + if ($formData["add_show_duration"] == "00h 00m") { $this->getElement('add_show_duration')->setErrors(array('Cannot have duration 00h 00m')); $valid = false; - }elseif(strpos($formData["add_show_duration"], 'h') !== false && $hours >= 24) { + } elseif (strpos($formData["add_show_duration"], 'h') !== false && $hours >= 24) { if ($hours > 24 || ($hours == 24 && $minutes > 0)) { $this->getElement('add_show_duration')->setErrors(array('Cannot have duration greater than 24h')); $valid = false; } - }elseif( strstr($formData["add_show_duration"], '-') ){ + } elseif ( strstr($formData["add_show_duration"], '-') ) { $this->getElement('add_show_duration')->setErrors(array('Cannot have duration < 0m')); $valid = false; } - } - else { + } else { $valid = false; } + /* Check if show is overlapping + * We will only do this check if the show is valid + * upto this point + */ + if ($valid) { + $utc = new DateTimeZone('UTC'); + $localTimezone = new DateTimeZone(Application_Model_Preference::GetTimezone()); + $show_start = new DateTime($start_time); + $show_start->setTimezone($utc); + $show_end = new DateTime($end_time); + $show_end->setTimezone($utc); + + if ($formData["add_show_repeats"]) { + + //get repeating show end date + if ($formData["add_show_no_end"]) { + $date = Application_Model_Preference::GetShowsPopulatedUntil(); + + if (is_null($date)) { + $populateUntilDateTime = new DateTime("now", $utc); + Application_Model_Preference::SetShowsPopulatedUntil($populateUntilDateTime); + } else { + $populateUntilDateTime = clone $date; + } + + } elseif (!$formData["add_show_no_end"]) { + $popUntil = $formData["add_show_end_date"]." ".$formData["add_show_end_time"]; + $populateUntilDateTime = new DateTime($popUntil); + $populateUntilDateTime->setTimezone($utc); + } + + //get repeat interval + if ($formData["add_show_repeat_type"] == 0) { + $interval = 'P7D'; + } elseif ($formData["add_show_repeat_type"] == 1) { + $interval = 'P14D'; + } elseif ($formData["add_show_repeat_type"] == 2) { + $interval = 'P1M'; + } + + /* Check first show + * Continue if the first show does not overlap + */ + if ($update) { + $overlapping = Application_Model_Schedule::checkOverlappingShows( + $show_start, $show_end, $update, null, $formData["add_show_id"]); + } else { + $overlapping = Application_Model_Schedule::checkOverlappingShows( + $show_start, $show_end); + } + //$overlapping = Application_Model_Schedule::checkOverlappingShows($show_start, $show_end, $update, $instanceId); + + /* Check if repeats overlap with previously scheduled shows + * Do this for each show day + */ + if (!$overlapping) { + $startDow = date("w", $show_start->getTimestamp()); + foreach ($formData["add_show_day_check"] as $day) { + $repeatShowStart = clone $show_start; + $repeatShowEnd = clone $show_end; + $daysAdd=0; + if ($startDow !== $day) { + if ($startDow > $day) + $daysAdd = 6 - $startDow + 1 + $day; + else + $daysAdd = $day - $startDow; + + /* In case we are crossing daylights saving time we need + * to convert show start and show end to local time before + * adding the interval for the next repeating show + */ + + $repeatShowStart->setTimezone($localTimezone); + $repeatShowEnd->setTimezone($localTimezone); + $repeatShowStart->add(new DateInterval("P".$daysAdd."D")); + $repeatShowEnd->add(new DateInterval("P".$daysAdd."D")); + //set back to UTC + $repeatShowStart->setTimezone($utc); + $repeatShowEnd->setTimezone($utc); + } + /* Here we are checking each repeating show by + * the show day. + * (i.e: every wednesday, then every thursday, etc.) + */ + while ($repeatShowStart->getTimestamp() < $populateUntilDateTime->getTimestamp()) { + if ($formData['add_show_id'] == -1) { + //this is a new show + $overlapping = Application_Model_Schedule::checkOverlappingShows( + $repeatShowStart, $repeatShowEnd); + + /* If the repeating show is rebroadcasted we need to check + * the rebroadcast dates relative to the repeating show + */ + if (!$overlapping && $formData['add_show_rebroadcast']) { + $overlapping = self::checkRebroadcastDates( + $repeatShowStart, $formData, $hours, $minutes); + } + } else { + $overlapping = Application_Model_Schedule::checkOverlappingShows( + $repeatShowStart, $repeatShowEnd, $update, null, $formData["add_show_id"]); + + if (!$overlapping && $formData['add_show_rebroadcast']) { + $overlapping = self::checkRebroadcastDates( + $repeatShowStart, $formData, $hours, $minutes, true); + } + } + + if ($overlapping) { + $valid = false; + $this->getElement('add_show_duration')->setErrors(array('Cannot schedule overlapping shows')); + break 1; + } else { + $repeatShowStart->setTimezone($localTimezone); + $repeatShowEnd->setTimezone($localTimezone); + $repeatShowStart->add(new DateInterval($interval)); + $repeatShowEnd->add(new DateInterval($interval)); + $repeatShowStart->setTimezone($utc); + $repeatShowEnd->setTimezone($utc); + } + } + } + } else { + $valid = false; + $this->getElement('add_show_duration')->setErrors(array('Cannot schedule overlapping shows')); + } + } elseif ($formData["add_show_rebroadcast"]) { + /* Check first show + * Continue if the first show does not overlap + */ + $overlapping = Application_Model_Schedule::checkOverlappingShows($show_start, $show_end, $update, $instanceId); + + if (!$overlapping) { + $durationToAdd = "PT".$hours."H".$minutes."M"; + for ($i = 1; $i <= 10; $i++) { + + if (empty($formData["add_show_rebroadcast_date_absolute_".$i])) break; + + $abs_rebroadcast_start = $formData["add_show_rebroadcast_date_absolute_".$i]." ". + $formData["add_show_rebroadcast_time_absolute_".$i]; + $rebroadcastShowStart = new DateTime($abs_rebroadcast_start); + $rebroadcastShowStart->setTimezone(new DateTimeZone('UTC')); + $rebroadcastShowEnd = clone $rebroadcastShowStart; + $rebroadcastShowEnd->add(new DateInterval($durationToAdd)); + $overlapping = Application_Model_Schedule::checkOverlappingShows($rebroadcastShowStart, $rebroadcastShowEnd, $update, $instanceId); + if ($overlapping) { + $valid = false; + $this->getElement('add_show_duration')->setErrors(array('Cannot schedule overlapping shows')); + break; + } + } + } else { + $valid = false; + $this->getElement('add_show_duration')->setErrors(array('Cannot schedule overlapping shows')); + } + } else { + $overlapping = Application_Model_Schedule::checkOverlappingShows($show_start, $show_end, $update, $instanceId); + if ($overlapping) { + $this->getElement('add_show_duration')->setErrors(array('Cannot schedule overlapping shows')); + $valid = false; + } + } + } + return $valid; } + + public function checkRebroadcastDates($repeatShowStart, $formData, $hours, $minutes, $showEdit=false) { + $overlapping = false; + for ($i = 1; $i <= 10; $i++) { + if (empty($formData["add_show_rebroadcast_date_".$i])) break; + $rebroadcastShowStart = clone $repeatShowStart; + /* formData is in local time so we need to set the + * show start back to local time + */ + $rebroadcastShowStart->setTimezone(new DateTimeZone( + Application_Model_Preference::GetTimezone())); + $rebroadcastWhenDays = explode(" ", $formData["add_show_rebroadcast_date_".$i]); + $rebroadcastWhenTime = explode(":", $formData["add_show_rebroadcast_time_".$i]); + $rebroadcastShowStart->add(new DateInterval("P".$rebroadcastWhenDays[0]."D")); + $rebroadcastShowStart->setTime($rebroadcastWhenTime[0], $rebroadcastWhenTime[1]); + $rebroadcastShowStart->setTimezone(new DateTimeZone('UTC')); + + $rebroadcastShowEnd = clone $rebroadcastShowStart; + $rebroadcastShowEnd->add(new DateInterval("PT".$hours."H".$minutes."M")); + + if ($showEdit) { + $overlapping = Application_Model_Schedule::checkOverlappingShows( + $rebroadcastShowStart, $rebroadcastShowEnd, true, null, $formData['add_show_id']); + } else { + $overlapping = Application_Model_Schedule::checkOverlappingShows( + $rebroadcastShowStart, $rebroadcastShowEnd); + } + + if ($overlapping) break; + } + + return $overlapping; + } - public function disable(){ + public function disable() + { $elements = $this->getElements(); - foreach ($elements as $element) - { - if ($element->getType() != 'Zend_Form_Element_Hidden') - { + foreach ($elements as $element) { + if ($element->getType() != 'Zend_Form_Element_Hidden') { $element->setAttrib('disabled','disabled'); } } } - - public function disableRepeatCheckbox(){ + + public function disableRepeatCheckbox() + { $element = $this->getElement('add_show_repeats'); - if ($element->getType() != 'Zend_Form_Element_Hidden') - { + if ($element->getType() != 'Zend_Form_Element_Hidden') { $element->setAttrib('disabled','disabled'); } } - - public function disableStartDateAndTime(){ + + public function disableStartDateAndTime() + { $elements = array($this->getElement('add_show_start_date'), $this->getElement('add_show_start_time')); - foreach ($elements as $element) - { - if ($element->getType() != 'Zend_Form_Element_Hidden') - { + foreach ($elements as $element) { + if ($element->getType() != 'Zend_Form_Element_Hidden') { $element->setAttrib('disabled','disabled'); } } } } - diff --git a/airtime_mvc/application/forms/AddShowWho.php b/airtime_mvc/application/forms/AddShowWho.php index 35b2aa52f..71d9f9fcc 100644 --- a/airtime_mvc/application/forms/AddShowWho.php +++ b/airtime_mvc/application/forms/AddShowWho.php @@ -10,32 +10,30 @@ class Application_Form_AddShowWho extends Zend_Form_SubForm 'label' => 'Search Users:', 'class' => 'input_text ui-autocomplete-input', 'required' => false - )); + )); - $options = array(); - $hosts = Application_Model_User::getHosts(); + $options = array(); + $hosts = Application_Model_User::getHosts(); - foreach ($hosts as $host) { - $options[$host['index']] = $host['label']; - } + foreach ($hosts as $host) { + $options[$host['index']] = $host['label']; + } - //Add hosts selection - $hosts = new Zend_Form_Element_MultiCheckbox('add_show_hosts'); - $hosts->setLabel('DJs:') - ->setMultiOptions($options); + //Add hosts selection + $hosts = new Zend_Form_Element_MultiCheckbox('add_show_hosts'); + $hosts->setLabel('DJs:') + ->setMultiOptions($options); - $this->addElement($hosts); + $this->addElement($hosts); } - public function disable(){ + public function disable() + { $elements = $this->getElements(); - foreach ($elements as $element) - { - if ($element->getType() != 'Zend_Form_Element_Hidden') - { + foreach ($elements as $element) { + if ($element->getType() != 'Zend_Form_Element_Hidden') { $element->setAttrib('disabled','disabled'); } } } } - diff --git a/airtime_mvc/application/forms/AddUser.php b/airtime_mvc/application/forms/AddUser.php index c603ed371..059dbe8af 100644 --- a/airtime_mvc/application/forms/AddUser.php +++ b/airtime_mvc/application/forms/AddUser.php @@ -10,11 +10,11 @@ class Application_Form_AddUser extends Zend_Form '../application/validate', 'validate'); * */ - + $hidden = new Zend_Form_Element_Hidden('user_id'); $hidden->setDecorators(array('ViewHelper')); $this->addElement($hidden); - + $login = new Zend_Form_Element_Text('login'); $login->setLabel('Username:'); $login->setAttrib('class', 'input_text'); @@ -22,7 +22,7 @@ class Application_Form_AddUser extends Zend_Form $login->addFilter('StringTrim'); //$login->addValidator('UserNameValidate'); $this->addElement($login); - + $password = new Zend_Form_Element_Password('password'); $password->setLabel('Password:'); $password->setAttrib('class', 'input_text'); @@ -30,21 +30,21 @@ class Application_Form_AddUser extends Zend_Form $password->addFilter('StringTrim'); $password->addValidator('NotEmpty'); $this->addElement($password); - + $firstName = new Zend_Form_Element_Text('first_name'); $firstName->setLabel('Firstname:'); $firstName->setAttrib('class', 'input_text'); $firstName->addFilter('StringTrim'); $firstName->addValidator('NotEmpty'); $this->addElement($firstName); - + $lastName = new Zend_Form_Element_Text('last_name'); $lastName->setLabel('Lastname:'); $lastName->setAttrib('class', 'input_text'); $lastName->addFilter('StringTrim'); $lastName->addValidator('NotEmpty'); $this->addElement($lastName); - + $email = new Zend_Form_Element_Text('email'); $email->setLabel('Email:'); $email->setAttrib('class', 'input_text'); @@ -52,7 +52,7 @@ class Application_Form_AddUser extends Zend_Form $email->setRequired(true); $email->addValidator('EmailAddress'); $this->addElement($email); - + $cellPhone = new Zend_Form_Element_Text('cell_phone'); $cellPhone->setLabel('Mobile Phone:'); $cellPhone->setAttrib('class', 'input_text'); @@ -79,31 +79,31 @@ class Application_Form_AddUser extends Zend_Form $select->setMultiOptions(array( "G" => "Guest", "H" => "DJ", - "P" => "Program Manager", + "P" => "Program Manager", "A" => "Admin" )); $select->setRequired(true); $this->addElement($select); - + $submit = new Zend_Form_Element_Submit('submit'); $submit->setAttrib('class', 'ui-button ui-state-default right-floated'); $submit->setIgnore(true); $submit->setLabel('Save'); $this->addElement($submit); } - - public function validateLogin($data){ - - if (strlen($data['user_id']) == 0){ + + public function validateLogin($data) + { + if (strlen($data['user_id']) == 0) { $count = CcSubjsQuery::create()->filterByDbLogin($data['login'])->count(); - - if ($count != 0){ + + if ($count != 0) { $this->getElement('login')->setErrors(array("Login name is not unique.")); + return false; } } - + return true; } } - diff --git a/airtime_mvc/application/forms/EditAudioMD.php b/airtime_mvc/application/forms/EditAudioMD.php index 76f48b062..2dc9e1f0f 100644 --- a/airtime_mvc/application/forms/EditAudioMD.php +++ b/airtime_mvc/application/forms/EditAudioMD.php @@ -7,21 +7,21 @@ class Application_Form_EditAudioMD extends Zend_Form // Set the method for the display form to POST $this->setMethod('post'); - // Add title field + // Add title field $this->addElement('text', 'track_title', array( 'label' => 'Title:', 'class' => 'input_text', 'filters' => array('StringTrim'), )); - // Add artist field + // Add artist field $this->addElement('text', 'artist_name', array( 'label' => 'Creator:', 'class' => 'input_text', 'filters' => array('StringTrim'), )); - // Add album field + // Add album field $this->addElement('text', 'album_title', array( 'label' => 'Album:', 'class' => 'input_text', @@ -32,44 +32,42 @@ class Application_Form_EditAudioMD extends Zend_Form $this->addElement('text', 'track_number', array( 'label' => 'Track:', 'class' => 'input_text', - 'filters' => array('StringTrim'), - 'validators' => array('Int'), - 'required' => true + 'filters' => array('StringTrim') )); - // Add genre field + // Add genre field $this->addElement('text', 'genre', array( 'label' => 'Genre:', 'class' => 'input_text', 'filters' => array('StringTrim') )); - // Add year field + // Add year field $this->addElement('text', 'year', array( 'label' => 'Year:', 'class' => 'input_text', 'filters' => array('StringTrim'), 'validators' => array( - array('date', false, array('YYYY-MM-DD')), + array('date', false, array('YYYY-MM-DD')), array('date', false, array('YYYY-MM')), - array('date', false, array('YYYY')) - ) + array('date', false, array('YYYY')) + ) )); - // Add label field + // Add label field $this->addElement('text', 'label', array( 'label' => 'Label:', 'class' => 'input_text', 'filters' => array('StringTrim') )); - // Add composer field + // Add composer field $this->addElement('text', 'composer', array( 'label' => 'Composer:', 'class' => 'input_text', 'filters' => array('StringTrim') )); - + // Add conductor field $this->addElement('text', 'conductor', array( 'label' => 'Conductor:', @@ -77,7 +75,7 @@ class Application_Form_EditAudioMD extends Zend_Form 'filters' => array('StringTrim') )); - // Add mood field + // Add mood field $this->addElement('text', 'mood', array( 'label' => 'Mood:', 'class' => 'input_text', @@ -122,22 +120,22 @@ class Application_Form_EditAudioMD extends Zend_Form 'filters' => array('StringTrim') )); - // Add the submit button + // Add the submit button $this->addElement('submit', 'submit', array( 'ignore' => true, - 'class' => 'ui-button ui-state-default', + 'class' => 'btn', 'label' => 'Save', 'decorators' => array( 'ViewHelper' ) )); - // Add the submit button + // Add the submit button $this->addElement('button', 'cancel', array( 'ignore' => true, - 'class' => 'ui-button ui-state-default ui-button-text-only md-cancel', + 'class' => 'btn md-cancel', 'label' => 'Cancel', - 'onclick' => 'javascript:document.location.href = "/Playlist"', + 'onclick' => 'javascript:document.location.href = "/Library"', 'decorators' => array( 'ViewHelper' ) @@ -151,6 +149,4 @@ class Application_Form_EditAudioMD extends Zend_Form )); } - } - diff --git a/airtime_mvc/application/forms/EmailServerPreferences.php b/airtime_mvc/application/forms/EmailServerPreferences.php index e513deee1..601cfb319 100644 --- a/airtime_mvc/application/forms/EmailServerPreferences.php +++ b/airtime_mvc/application/forms/EmailServerPreferences.php @@ -9,8 +9,8 @@ class Application_Form_EmailServerPreferences extends Zend_Form_SubForm public function init() { $isSaas = Application_Model_Preference::GetPlanLevel() == 'disabled'?false:true; - $this->isSaas = $isSaas; - + $this->isSaas = $isSaas; + $this->setDecorators(array( array('ViewScript', array('viewScript' => 'form/preferences_email_server.phtml', "isSaas" => $isSaas)) )); @@ -24,7 +24,7 @@ class Application_Form_EmailServerPreferences extends Zend_Form_SubForm 'ViewHelper' ) )); - + $this->addElement('text', 'systemEmail', array( 'class' => 'input_text', 'label' => 'Reset Password \'From\' Email', @@ -32,7 +32,7 @@ class Application_Form_EmailServerPreferences extends Zend_Form_SubForm 'readonly' => true, 'decorators' => array('viewHelper') )); - + $this->addElement('checkbox', 'configureMailServer', array( 'label' => 'Configure Mail Server', 'required' => false, @@ -41,7 +41,16 @@ class Application_Form_EmailServerPreferences extends Zend_Form_SubForm 'viewHelper' ) )); - + + $this->addElement('checkbox', 'msRequiresAuth', array( + 'label' => 'Requires Authentication', + 'required' => false, + 'value' => Application_Model_Preference::GetMailServerRequiresAuth(), + 'decorators' => array( + 'viewHelper' + ) + )); + $this->addElement('text', 'mailServer', array( 'class' => 'input_text', 'label' => 'Mail Server', @@ -50,10 +59,12 @@ class Application_Form_EmailServerPreferences extends Zend_Form_SubForm 'decorators' => array('viewHelper'), 'allowEmpty' => false, 'validators' => array( - new ConditionalNotEmpty(array('configureMailServer'=>'1')) + new ConditionalNotEmpty(array( + 'configureMailServer' => '1' + )) ) )); - + $this->addElement('text', 'email', array( 'class' => 'input_text', 'label' => 'Email Address', @@ -62,10 +73,13 @@ class Application_Form_EmailServerPreferences extends Zend_Form_SubForm 'decorators' => array('viewHelper'), 'allowEmpty' => false, 'validators' => array( - new ConditionalNotEmpty(array('configureMailServer'=>'1')) + new ConditionalNotEmpty(array( + 'configureMailServer' => '1', + 'msRequiresAuth' => '1' + )) ) )); - + $this->addElement('password', 'ms_password', array( 'class' => 'input_text', 'label' => 'Password', @@ -74,11 +88,14 @@ class Application_Form_EmailServerPreferences extends Zend_Form_SubForm 'decorators' => array('viewHelper'), 'allowEmpty' => false, 'validators' => array( - new ConditionalNotEmpty(array('configureMailServer'=>'1')) + new ConditionalNotEmpty(array( + 'configureMailServer' => '1', + 'msRequiresAuth' => '1' + )) ), 'renderPassword' => true )); - + $port = new Zend_Form_Element_Text('port'); $port->class = 'input_text'; $port->setRequired(false) @@ -86,11 +103,9 @@ class Application_Form_EmailServerPreferences extends Zend_Form_SubForm ->setLabel('Port') ->setAttrib('readonly', true) ->setDecorators(array('viewHelper')); - + $this->addElement($port); } - } - diff --git a/airtime_mvc/application/forms/GeneralPreferences.php b/airtime_mvc/application/forms/GeneralPreferences.php index 621984774..9bca14349 100644 --- a/airtime_mvc/application/forms/GeneralPreferences.php +++ b/airtime_mvc/application/forms/GeneralPreferences.php @@ -2,19 +2,19 @@ class Application_Form_GeneralPreferences extends Zend_Form_SubForm { - private $isSaas; - + private $isSaas; + public function init() { $isSaas = Application_Model_Preference::GetPlanLevel() == 'disabled'?false:true; - $this->isSaas = $isSaas; - + $this->isSaas = $isSaas; + $this->setDecorators(array( array('ViewScript', array('viewScript' => 'form/preferences_general.phtml', "isSaas" => $isSaas)) )); $defaultFade = Application_Model_Preference::GetDefaultFade(); - if($defaultFade == ""){ + if ($defaultFade == "") { $defaultFade = '0.500000'; } @@ -24,7 +24,7 @@ class Application_Form_GeneralPreferences extends Zend_Form_SubForm 'label' => 'Station Name', 'required' => false, 'filters' => array('StringTrim'), - 'value' => Application_Model_Preference::GetValue("station_name"), + 'value' => Application_Model_Preference::GetStationName(), 'decorators' => array( 'ViewHelper' ) @@ -70,7 +70,8 @@ class Application_Form_GeneralPreferences extends Zend_Form_SubForm $this->addElement($week_start_day); } - private function getTimezones(){ + private function getTimezones() + { $regions = array( 'Africa' => DateTimeZone::AFRICA, 'America' => DateTimeZone::AMERICA, @@ -86,9 +87,9 @@ class Application_Form_GeneralPreferences extends Zend_Form_SubForm $tzlist = array(); - foreach ($regions as $name => $mask){ + foreach ($regions as $name => $mask) { $ids = DateTimeZone::listIdentifiers($mask); - foreach ($ids as $id){ + foreach ($ids as $id) { $tzlist[$id] = str_replace("_", " ", $id); } } @@ -96,18 +97,18 @@ class Application_Form_GeneralPreferences extends Zend_Form_SubForm return $tzlist; } + private function getWeekStartDays() + { + $days = array( + 'Sunday', + 'Monday', + 'Tuesday', + 'Wednesday', + 'Thursday', + 'Friday', + 'Saturday' + ); - private function getWeekStartDays() { - $days = array( - 'Sunday', - 'Monday', - 'Tuesday', - 'Wednesday', - 'Thursday', - 'Friday', - 'Saturday' - ); - return $days; + return $days; } } - diff --git a/airtime_mvc/application/forms/LiveStreamingPreferences.php b/airtime_mvc/application/forms/LiveStreamingPreferences.php index 8a4e1a674..e66976c8b 100644 --- a/airtime_mvc/application/forms/LiveStreamingPreferences.php +++ b/airtime_mvc/application/forms/LiveStreamingPreferences.php @@ -2,33 +2,33 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm { - + public function init() { global $CC_CONFIG; $isDemo = isset($CC_CONFIG['demo']) && $CC_CONFIG['demo'] == 1; $isStreamConfigable = Application_Model_Preference::GetEnableStreamConf() == "true"; - + $isSaas = Application_Model_Preference::GetPlanLevel() == 'disabled'?false:true; $defaultFade = Application_Model_Preference::GetDefaultTransitionFade(); - if($defaultFade == ""){ + if ($defaultFade == "") { $defaultFade = '00.000000'; } - + // automatic trasition on source disconnection $auto_transition = new Zend_Form_Element_Checkbox("auto_transition"); $auto_transition->setLabel("Auto Switch Off") ->setValue(Application_Model_Preference::GetAutoTransition()) ->setDecorators(array('ViewHelper')); $this->addElement($auto_transition); - + // automatic switch on upon source connection $auto_switch = new Zend_Form_Element_Checkbox("auto_switch"); $auto_switch->setLabel("Auto Switch On") ->setValue(Application_Model_Preference::GetAutoSwitch()) ->setDecorators(array('ViewHelper')); $this->addElement($auto_switch); - + // Default transition fade $transition_fade = new Zend_Form_Element_Text("transition_fade"); $transition_fade->setLabel("Switch Transition Fade (s)") @@ -38,33 +38,33 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm ->setValue($defaultFade) ->setDecorators(array('ViewHelper')); $this->addElement($transition_fade); - + //Master username $master_username = new Zend_Form_Element_Text('master_username'); $master_username->setAttrib('autocomplete', 'off') ->setAllowEmpty(true) ->setLabel('Master Username') ->setFilters(array('StringTrim')) - ->setValue(Application_Model_Preference::GetLiveSteamMasterUsername()) + ->setValue(Application_Model_Preference::GetLiveStreamMasterUsername()) ->setDecorators(array('ViewHelper')); $this->addElement($master_username); - + //Master password - if($isDemo){ + if ($isDemo) { $master_password = new Zend_Form_Element_Text('master_password'); - }else{ + } else { $master_password = new Zend_Form_Element_Password('master_password'); $master_password->setAttrib('renderPassword','true'); } $master_password->setAttrib('autocomplete', 'off') ->setAttrib('renderPassword','true') ->setAllowEmpty(true) - ->setValue(Application_Model_Preference::GetLiveSteamMasterPassword()) + ->setValue(Application_Model_Preference::GetLiveStreamMasterPassword()) ->setLabel('Master Password') ->setFilters(array('StringTrim')) ->setDecorators(array('ViewHelper')); $this->addElement($master_password); - + //Master source connection url $master_dj_connection_url = new Zend_Form_Element_Text('master_dj_connection_url'); $master_dj_connection_url->setAttrib('readonly', true) @@ -72,7 +72,7 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm ->setValue(Application_Model_Preference::GetMasterDJSourceConnectionURL()) ->setDecorators(array('ViewHelper')); $this->addElement($master_dj_connection_url); - + //Show source connection url $live_dj_connection_url = new Zend_Form_Element_Text('live_dj_connection_url'); $live_dj_connection_url->setAttrib('readonly', true) @@ -80,10 +80,10 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm ->setValue(Application_Model_Preference::GetLiveDJSourceConnectionURL()) ->setDecorators(array('ViewHelper')); $this->addElement($live_dj_connection_url); - + //liquidsoap harbor.input port if (!$isSaas) { - $m_port = Application_Model_StreamSetting::GetMasterLiveSteamPort(); + $m_port = Application_Model_StreamSetting::getMasterLiveStreamPort(); $master_dj_port = new Zend_Form_Element_Text('master_harbor_input_port'); $master_dj_port->setLabel("Master Source Port") ->setValue($m_port) @@ -91,8 +91,8 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm ->addValidator('regex', false, array('pattern'=>'/^[0-9]+$/', 'messages'=>array('regexNotMatch'=>'Only numbers are allowed.'))) ->setDecorators(array('ViewHelper')); $this->addElement($master_dj_port); - - $m_mount = Application_Model_StreamSetting::GetMasterLiveSteamMountPoint(); + + $m_mount = Application_Model_StreamSetting::getMasterLiveStreamMountPoint(); $master_dj_mount = new Zend_Form_Element_Text('master_harbor_input_mount_point'); $master_dj_mount->setLabel("Master Source Mount Point") ->setValue($m_mount) @@ -100,9 +100,9 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm array('regex', false, array('/^[^ &<>]+$/', 'messages' => 'Invalid character entered')))) ->setDecorators(array('ViewHelper')); $this->addElement($master_dj_mount); - + //liquidsoap harbor.input port - $l_port = Application_Model_StreamSetting::GetDJLiveSteamPort(); + $l_port = Application_Model_StreamSetting::getDjLiveStreamPort(); $live_dj_port = new Zend_Form_Element_Text('dj_harbor_input_port'); $live_dj_port->setLabel("Show Source Port") ->setValue($l_port) @@ -110,8 +110,8 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm ->addValidator('regex', false, array('pattern'=>'/^[0-9]+$/', 'messages'=>array('regexNotMatch'=>'Only numbers are allowed.'))) ->setDecorators(array('ViewHelper')); $this->addElement($live_dj_port); - - $l_mount = Application_Model_StreamSetting::GetDJLiveSteamMountPoint(); + + $l_mount = Application_Model_StreamSetting::getDjLiveStreamMountPoint(); $live_dj_mount = new Zend_Form_Element_Text('dj_harbor_input_mount_point'); $live_dj_mount->setLabel("Show Source Mount Point") ->setValue($l_mount) @@ -121,76 +121,77 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm $this->addElement($live_dj_mount); } // demo only code - if(!$isStreamConfigable){ + if (!$isStreamConfigable) { $elements = $this->getElements(); - foreach ($elements as $element) - { - if ($element->getType() != 'Zend_Form_Element_Hidden') - { + foreach ($elements as $element) { + if ($element->getType() != 'Zend_Form_Element_Hidden') { $element->setAttrib("disabled", "disabled"); } } } } - - public function updateVariables(){ + + public function updateVariables() + { global $CC_CONFIG; - + $isSaas = Application_Model_Preference::GetPlanLevel() == 'disabled'?false:true; $isDemo = isset($CC_CONFIG['demo']) && $CC_CONFIG['demo'] == 1; $master_dj_connection_url = Application_Model_Preference::GetMasterDJSourceConnectionURL(); $live_dj_connection_url = Application_Model_Preference::GetLiveDJSourceConnectionURL(); - + $this->setDecorators(array( array('ViewScript', array('viewScript' => 'form/preferences_livestream.phtml', 'master_dj_connection_url'=>$master_dj_connection_url, 'live_dj_connection_url'=>$live_dj_connection_url, 'isSaas' => $isSaas, 'isDemo' => $isDemo)) )); } - - public function isValid($data){ + + public function isValid($data) + { $isSaas = Application_Model_Preference::GetPlanLevel() == 'disabled'?false:true; $isValid = parent::isValid($data); if (!$isSaas) { $master_harbor_input_port = $data['master_harbor_input_port']; $dj_harbor_input_port = $data['dj_harbor_input_port']; - - if($master_harbor_input_port == $dj_harbor_input_port && $master_harbor_input_port != ""){ + + if ($master_harbor_input_port == $dj_harbor_input_port && $master_harbor_input_port != "") { $element = $this->getElement("dj_harbor_input_port"); $element->addError("You cannot use same port as Master DJ port."); } - if($master_harbor_input_port != ""){ - if(is_numeric($master_harbor_input_port)){ - if($master_harbor_input_port != Application_Model_StreamSetting::GetMasterLiveSteamPort()){ + if ($master_harbor_input_port != "") { + if (is_numeric($master_harbor_input_port)) { + if ($master_harbor_input_port != Application_Model_StreamSetting::getMasterLiveStreamPort()) { $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); $res = socket_bind($sock, 0, $master_harbor_input_port); - if(!$res){ + if (!$res) { $element = $this->getElement("master_harbor_input_port"); $element->addError("Port '$master_harbor_input_port' is not available."); $isValid = false; } socket_close($sock); } - }else{ + } else { $isValid = false; } } - if($dj_harbor_input_port != ""){ - if(is_numeric($dj_harbor_input_port)){ - if($dj_harbor_input_port != Application_Model_StreamSetting::GetDJLiveSteamPort()){ + if ($dj_harbor_input_port != "") { + if (is_numeric($dj_harbor_input_port)) { + if ($dj_harbor_input_port != Application_Model_StreamSetting::getDjLiveStreamPort()) { $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); $res = socket_bind($sock, 0, $dj_harbor_input_port); - if(!$res){ + if (!$res) { $element = $this->getElement("dj_harbor_input_port"); $element->addError("Port '$dj_harbor_input_port' is not available."); $isValid = false; } socket_close($sock); } - }else{ + } else { $isValid = false; } } } + return $isValid; } - + } diff --git a/airtime_mvc/application/forms/Login.php b/airtime_mvc/application/forms/Login.php index c23e9ee84..3761ff939 100644 --- a/airtime_mvc/application/forms/Login.php +++ b/airtime_mvc/application/forms/Login.php @@ -4,17 +4,17 @@ class Application_Form_Login extends Zend_Form { public function init() - { + { global $CC_CONFIG; - - // Set the method for the display form to POST + + // Set the method for the display form to POST $this->setMethod('post'); - - $this->setDecorators(array( - array('ViewScript', array('viewScript' => 'form/login.phtml')) + + $this->setDecorators(array( + array('ViewScript', array('viewScript' => 'form/login.phtml')) )); - // Add username element + // Add username element $this->addElement('text', 'username', array( 'label' => 'Username:', 'class' => 'input_text', @@ -28,8 +28,8 @@ class Application_Form_Login extends Zend_Form 'ViewHelper' ) )); - - // Add password element + + // Add password element $this->addElement('password', 'password', array( 'label' => 'Password:', 'class' => 'input_text', @@ -43,17 +43,17 @@ class Application_Form_Login extends Zend_Form 'ViewHelper' ) )); - + $recaptchaNeeded = false; - if(Application_Model_LoginAttempts::getAttempts($_SERVER['REMOTE_ADDR']) >= 3){ + if (Application_Model_LoginAttempts::getAttempts($_SERVER['REMOTE_ADDR']) >= 3) { $recaptchaNeeded = true; } - if($recaptchaNeeded){ + if ($recaptchaNeeded) { // recaptcha $this->addRecaptcha(); } - - // Add the submit button + + // Add the submit button $this->addElement('submit', 'submit', array( 'ignore' => true, 'label' => 'Login', @@ -64,13 +64,14 @@ class Application_Form_Login extends Zend_Form )); } - - public function addRecaptcha(){ + + public function addRecaptcha() + { $pubKey = '6Ld4JsISAAAAAIxUKT4IjjOGi3DHqdoH2zk6WkYG'; $privKey = '6Ld4JsISAAAAAJynYlXdrE4hfTReTSxYFe5szdyv'; - + $recaptcha = new Zend_Service_ReCaptcha($pubKey, $privKey); - + $captcha = new Zend_Form_Element_Captcha('captcha', array( 'label' => 'Type the characters you see in the picture below.', @@ -84,6 +85,4 @@ class Application_Form_Login extends Zend_Form $this->addElement($captcha); } - } - diff --git a/airtime_mvc/application/forms/PasswordChange.php b/airtime_mvc/application/forms/PasswordChange.php index 333ef2bab..48efae5ff 100644 --- a/airtime_mvc/application/forms/PasswordChange.php +++ b/airtime_mvc/application/forms/PasswordChange.php @@ -6,10 +6,10 @@ class Application_Form_PasswordChange extends Zend_Form { public function init() { - $this->setDecorators(array( - array('ViewScript', array('viewScript' => 'form/password-change.phtml')) + $this->setDecorators(array( + array('ViewScript', array('viewScript' => 'form/password-change.phtml')) )); - + $this->addElement('password', 'password', array( 'label' => 'Password', 'required' => true, diff --git a/airtime_mvc/application/forms/PasswordRestore.php b/airtime_mvc/application/forms/PasswordRestore.php index 5544e0ec1..584e767ad 100644 --- a/airtime_mvc/application/forms/PasswordRestore.php +++ b/airtime_mvc/application/forms/PasswordRestore.php @@ -6,10 +6,10 @@ class Application_Form_PasswordRestore extends Zend_Form { public function init() { - $this->setDecorators(array( - array('ViewScript', array('viewScript' => 'form/password-restore.phtml')) + $this->setDecorators(array( + array('ViewScript', array('viewScript' => 'form/password-restore.phtml')) )); - + $this->addElement('text', 'email', array( 'label' => 'E-mail', 'required' => true, @@ -21,6 +21,17 @@ class Application_Form_PasswordRestore extends Zend_Form ) )); + $this->addElement('text', 'username', array( + 'label' => 'Username', + 'required' => false, + 'filters' => array( + 'stringTrim', + ), + 'decorators' => array( + 'ViewHelper' + ) + )); + $this->addElement('submit', 'submit', array( 'label' => 'Restore password', 'ignore' => true, @@ -29,7 +40,7 @@ class Application_Form_PasswordRestore extends Zend_Form 'ViewHelper' ) )); - + $cancel = new Zend_Form_Element_Button("cancel"); $cancel->class = 'ui-button ui-widget ui-state-default ui-button-text-only center'; $cancel->setLabel("Cancel") @@ -38,4 +49,4 @@ class Application_Form_PasswordRestore extends Zend_Form ->setDecorators(array('ViewHelper')); $this->addElement($cancel); } -} \ No newline at end of file +} diff --git a/airtime_mvc/application/forms/Preferences.php b/airtime_mvc/application/forms/Preferences.php index 707929394..878abe7f9 100644 --- a/airtime_mvc/application/forms/Preferences.php +++ b/airtime_mvc/application/forms/Preferences.php @@ -8,22 +8,22 @@ class Application_Form_Preferences extends Zend_Form { $this->setAction('/Preference'); $this->setMethod('post'); - + $isSaas = Application_Model_Preference::GetPlanLevel() == 'disabled'?false:true; - $this->isSaas = $isSaas; - + $this->isSaas = $isSaas; + $this->setDecorators(array( array('ViewScript', array('viewScript' => 'form/preferences.phtml', "isSaas" => $this->isSaas)) )); - + $general_pref = new Application_Form_GeneralPreferences(); $this->addSubForm($general_pref, 'preferences_general'); - + if (!$isSaas) { $email_pref = new Application_Form_EmailServerPreferences(); $this->addSubForm($email_pref, 'preferences_email_server'); } - + $soundcloud_pref = new Application_Form_SoundcloudPreferences(); $this->addSubForm($soundcloud_pref, 'preferences_soundcloud'); diff --git a/airtime_mvc/application/forms/RegisterAirtime.php b/airtime_mvc/application/forms/RegisterAirtime.php index 223422ae6..9ffd853e1 100644 --- a/airtime_mvc/application/forms/RegisterAirtime.php +++ b/airtime_mvc/application/forms/RegisterAirtime.php @@ -9,19 +9,22 @@ class Application_Form_RegisterAirtime extends Zend_Form { $this->setAction('/Showbuilder'); $this->setMethod('post'); - + $country_list = Application_Model_Preference::GetCountryList(); - + $privacyChecked = false; - if(Application_Model_Preference::GetPrivacyPolicyCheck() == 1){ + if (Application_Model_Preference::GetPrivacyPolicyCheck() == 1) { $privacyChecked = true; } - + $this->setDecorators(array( - array('ViewScript', array('viewScript' => 'form/register-dialog.phtml', 'privacyChecked'=>$privacyChecked)), - array('File', array('viewScript' => 'form/register-dialog.phtml', 'placement' => false))) + array('ViewScript', array('viewScript' => + 'form/register-dialog.phtml', 'privacyChecked'=>$privacyChecked)), + + array('File', array('viewScript' => 'form/register-dialog.phtml', + 'placement' => false))) ); - + // Station Name $stnName = new Zend_Form_Element_Text("stnName"); $stnName->setLabel("Station Name") @@ -29,14 +32,14 @@ class Application_Form_RegisterAirtime extends Zend_Form ->setValue(Application_Model_Preference::GetStationName()) ->setDecorators(array('ViewHelper')); $this->addElement($stnName); - + // Phone number $this->addElement('text', 'Phone', array( 'class' => 'input_text', 'label' => 'Phone:', 'required' => false, 'filters' => array('StringTrim'), - 'value' => Application_Model_Preference::GetPhone(), + 'value' => Application_Model_Preference::GetPhone(), 'decorators' => array( 'ViewHelper' ) @@ -48,7 +51,7 @@ class Application_Form_RegisterAirtime extends Zend_Form 'label' => 'Email:', 'required' => false, 'filters' => array('StringTrim'), - 'value' => Application_Model_Preference::GetEmail(), + 'value' => Application_Model_Preference::GetEmail(), 'decorators' => array( 'ViewHelper' ) @@ -63,20 +66,20 @@ class Application_Form_RegisterAirtime extends Zend_Form 'decorators' => array( 'ViewHelper' ) - )); + )); - // county list dropdown - $this->addElement('select', 'Country', array( - 'label' => 'Country:', - 'required' => false, - 'value' => Application_Model_Preference::GetStationCountry(), - 'multiOptions' => $country_list, - 'decorators' => array( + // county list dropdown + $this->addElement('select', 'Country', array( + 'label' => 'Country:', + 'required' => false, + 'value' => Application_Model_Preference::GetStationCountry(), + 'multiOptions' => $country_list, + 'decorators' => array( 'ViewHelper' ) - )); - - // Station city + )); + + // Station city $this->addElement('text', 'City', array( 'label' => 'City:', 'required' => false, @@ -85,29 +88,29 @@ class Application_Form_RegisterAirtime extends Zend_Form 'decorators' => array( 'ViewHelper' ) - )); - - // Station Description - $description = new Zend_Form_Element_Textarea('Description'); - $description->class = 'input_text_area'; - $description->setLabel('Station Description:') - ->setRequired(false) - ->setValue(Application_Model_Preference::GetStationDescription()) - ->setDecorators(array('ViewHelper')) - ->setAttrib('ROWS','2') - ->setAttrib('COLS','58'); - $this->addElement($description); - - // Station Logo - $upload = new Zend_Form_Element_File('Logo'); - $upload->setLabel('Station Logo:') - ->setRequired(false) - ->setDecorators(array('File')) - ->addValidator('Count', false, 1) - ->addValidator('Extension', false, 'jpg,jpeg,png,gif') - ->addFilter('ImageSize'); - $this->addElement($upload); - + )); + + // Station Description + $description = new Zend_Form_Element_Textarea('Description'); + $description->class = 'input_text_area'; + $description->setLabel('Station Description:') + ->setRequired(false) + ->setValue(Application_Model_Preference::GetStationDescription()) + ->setDecorators(array('ViewHelper')) + ->setAttrib('ROWS','2') + ->setAttrib('COLS','58'); + $this->addElement($description); + + // Station Logo + $upload = new Zend_Form_Element_File('Logo'); + $upload->setLabel('Station Logo:') + ->setRequired(false) + ->setDecorators(array('File')) + ->addValidator('Count', false, 1) + ->addValidator('Extension', false, 'jpg,jpeg,png,gif') + ->addFilter('ImageSize'); + $this->addElement($upload); + //enable support feedback $this->addElement('checkbox', 'SupportFeedback', array( 'label' => 'Send support feedback', @@ -116,52 +119,52 @@ class Application_Form_RegisterAirtime extends Zend_Form 'decorators' => array( 'ViewHelper' ) - )); + )); - // checkbox for publicise - $checkboxPublicise = new Zend_Form_Element_Checkbox("Publicise"); + // checkbox for publicise + $checkboxPublicise = new Zend_Form_Element_Checkbox("Publicise"); $checkboxPublicise->setLabel('Promote my station on Sourcefabric.org') ->setRequired(false) ->setDecorators(array('ViewHelper')) ->setValue(Application_Model_Preference::GetPublicise()); $this->addElement($checkboxPublicise); - - // text area for sending detail + + // text area for sending detail $this->addElement('textarea', 'SendInfo', array( - 'class' => 'sending_textarea', - 'required' => false, + 'class' => 'sending_textarea', + 'required' => false, 'filters' => array('StringTrim'), - 'readonly' => true, - 'rows' => 5, - 'cols' => 61, - 'value' => Application_Model_Preference::GetSystemInfo(false, true), + 'readonly' => true, + 'rows' => 5, + 'cols' => 61, + 'value' => Application_Model_Preference::GetSystemInfo(false, true), 'decorators' => array( 'ViewHelper' ) )); - + // checkbox for privacy policy $checkboxPrivacy = new Zend_Form_Element_Checkbox("Privacy"); $checkboxPrivacy->setLabel("By checking this box, I agree to Sourcefabric's privacy policy.") ->setDecorators(array('ViewHelper')); $this->addElement($checkboxPrivacy); } - + // overriding isValid function public function isValid ($data) { $isValid = parent::isValid($data); - if($data['Publicise'] != 1){ + if ($data['Publicise'] != 1) { $isValid = true; } - if(isset($data["Privacy"])){ + if (isset($data["Privacy"])) { $checkPrivacy = $this->getElement('Privacy'); - if($data["SupportFeedback"] == "1" && $data["Privacy"] != "1"){ + if ($data["SupportFeedback"] == "1" && $data["Privacy"] != "1") { $checkPrivacy->addError("You have to agree to privacy policy."); $isValid = false; } } + return $isValid; } } - diff --git a/airtime_mvc/application/forms/ScheduleShow.php b/airtime_mvc/application/forms/ScheduleShow.php index 85c7c91fb..5ec6f8174 100644 --- a/airtime_mvc/application/forms/ScheduleShow.php +++ b/airtime_mvc/application/forms/ScheduleShow.php @@ -8,6 +8,4 @@ class Application_Form_ScheduleShow extends Zend_Form /* Form Elements & Other Definitions Here ... */ } - } - diff --git a/airtime_mvc/application/forms/ShowBuilder.php b/airtime_mvc/application/forms/ShowBuilder.php index f1e1ed3fa..465d2dd71 100644 --- a/airtime_mvc/application/forms/ShowBuilder.php +++ b/airtime_mvc/application/forms/ShowBuilder.php @@ -5,7 +5,7 @@ class Application_Form_ShowBuilder extends Zend_Form_SubForm public function init() { - $user = Application_Model_User::GetCurrentUser(); + $user = Application_Model_User::getCurrentUser(); $this->setDecorators(array( array('ViewScript', array('viewScript' => 'form/showbuilder.phtml')) @@ -67,7 +67,6 @@ class Application_Form_ShowBuilder extends Zend_Form_SubForm $endTime->setAttrib('alt', 'time'); $this->addElement($endTime); - // add a select to choose a show. $showSelect = new Zend_Form_Element_Select("sb_show_filter"); $showSelect->setLabel("Show:"); @@ -84,8 +83,8 @@ class Application_Form_ShowBuilder extends Zend_Form_SubForm } } - private function getShowNames() { - + private function getShowNames() + { $showNames = array("0" => "-------------------------"); $shows = CcShowQuery::create() diff --git a/airtime_mvc/application/forms/SmartBlockCriteria.php b/airtime_mvc/application/forms/SmartBlockCriteria.php new file mode 100644 index 000000000..55a28c79a --- /dev/null +++ b/airtime_mvc/application/forms/SmartBlockCriteria.php @@ -0,0 +1,516 @@ + "Select criteria", + "album_title" => "Album", + "bit_rate" => "Bit Rate (Kbps)", + "bpm" => "BPM", + "composer" => "Composer", + "conductor" => "Conductor", + "copyright" => "Copyright", + "artist_name" => "Creator", + "encoded_by" => "Encoded By", + "genre" => "Genre", + "isrc_number" => "ISRC", + "label" => "Label", + "language" => "Language", + "mtime" => "Last Modified", + "lptime" => "Last Played", + "length" => "Length", + "mime" => "Mime", + "mood" => "Mood", + "owner_id" => "Owner", + "replay_gain" => "Replay Gain", + "sample_rate" => "Sample Rate (kHz)", + "track_title" => "Title", + "track_number" => "Track Number", + "utime" => "Uploaded", + "info_url" => "Website", + "year" => "Year" + ); + + private $criteriaTypes = array( + 0 => "", + "album_title" => "s", + "bit_rate" => "n", + "bpm" => "n", + "composer" => "s", + "conductor" => "s", + "copyright" => "s", + "artist_name" => "s", + "encoded_by" => "s", + "utime" => "n", + "mtime" => "n", + "lptime" => "n", + "genre" => "s", + "isrc_number" => "s", + "label" => "s", + "language" => "s", + "length" => "n", + "mime" => "s", + "mood" => "s", + "owner_id" => "s", + "replay_gain" => "n", + "sample_rate" => "n", + "track_title" => "s", + "track_number" => "n", + "info_url" => "s", + "year" => "n" + ); + + private $stringCriteriaOptions = array( + "0" => "Select modifier", + "contains" => "contains", + "does not contain" => "does not contain", + "is" => "is", + "is not" => "is not", + "starts with" => "starts with", + "ends with" => "ends with" + ); + + private $numericCriteriaOptions = array( + "0" => "Select modifier", + "is" => "is", + "is not" => "is not", + "is greater than" => "is greater than", + "is less than" => "is less than", + "is in the range" => "is in the range" + ); + + private $limitOptions = array( + "hours" => "hours", + "minutes" => "minutes", + "items" => "items" + ); + + public function init() + { + } + + public function startForm($p_blockId, $p_isValid = false) + { + // load type + $out = CcBlockQuery::create()->findPk($p_blockId); + if ($out->getDbType() == "static") { + $blockType = 0; + } else { + $blockType = 1; + } + + $spType = new Zend_Form_Element_Radio('sp_type'); + $spType->setLabel('Set smart block type:') + ->setDecorators(array('viewHelper')) + ->setMultiOptions(array( + 'static' => 'Static', + 'dynamic' => 'Dynamic' + )) + ->setValue($blockType); + $this->addElement($spType); + + $bl = new Application_Model_Block($p_blockId); + $storedCrit = $bl->getCriteria(); + + /* $modRoadMap stores the number of same criteria + * Ex: 3 Album titles, and 2 Track titles + * We need to know this so we display the form elements properly + */ + $modRowMap = array(); + + $openSmartBlockOption = false; + if (!empty($storedCrit)) { + $openSmartBlockOption = true; + } + + $criteriaKeys = array(); + if (isset($storedCrit["crit"])) { + $criteriaKeys = array_keys($storedCrit["crit"]); + } + $numElements = count($this->criteriaOptions); + for ($i = 0; $i < $numElements; $i++) { + $criteriaType = ""; + + if (isset($criteriaKeys[$i])) { + $critCount = count($storedCrit["crit"][$criteriaKeys[$i]]); + } else { + $critCount = 1; + } + + $modRowMap[$i] = $critCount; + + /* Loop through all criteria with the same field + * Ex: all criteria for 'Album' + */ + for ($j = 0; $j < $critCount; $j++) { + /****************** CRITERIA ***********/ + if ($j > 0) { + $invisible = ' sp-invisible'; + } else { + $invisible = ''; + } + + $criteria = new Zend_Form_Element_Select("sp_criteria_field_".$i."_".$j); + $criteria->setAttrib('class', 'input_select sp_input_select'.$invisible) + ->setValue('Select criteria') + ->setDecorators(array('viewHelper')) + ->setMultiOptions($this->criteriaOptions); + if ($i != 0 && !isset($criteriaKeys[$i])) { + $criteria->setAttrib('disabled', 'disabled'); + } + + if (isset($criteriaKeys[$i])) { + $criteriaType = $this->criteriaTypes[$storedCrit["crit"][$criteriaKeys[$i]][$j]["criteria"]]; + $criteria->setValue($storedCrit["crit"][$criteriaKeys[$i]][$j]["criteria"]); + } + $this->addElement($criteria); + + /****************** MODIFIER ***********/ + $criteriaModifers = new Zend_Form_Element_Select("sp_criteria_modifier_".$i."_".$j); + $criteriaModifers->setValue('Select modifier') + ->setAttrib('class', 'input_select sp_input_select') + ->setDecorators(array('viewHelper')); + if ($i != 0 && !isset($criteriaKeys[$i])) { + $criteriaModifers->setAttrib('disabled', 'disabled'); + } + if (isset($criteriaKeys[$i])) { + if ($criteriaType == "s") { + $criteriaModifers->setMultiOptions($this->stringCriteriaOptions); + } else { + $criteriaModifers->setMultiOptions($this->numericCriteriaOptions); + } + $criteriaModifers->setValue($storedCrit["crit"][$criteriaKeys[$i]][$j]["modifier"]); + } else { + $criteriaModifers->setMultiOptions(array('0' => 'Select modifier')); + } + $this->addElement($criteriaModifers); + + /****************** VALUE ***********/ + $criteriaValue = new Zend_Form_Element_Text("sp_criteria_value_".$i."_".$j); + $criteriaValue->setAttrib('class', 'input_text sp_input_text') + ->setDecorators(array('viewHelper')); + if ($i != 0 && !isset($criteriaKeys[$i])) { + $criteriaValue->setAttrib('disabled', 'disabled'); + } + if (isset($criteriaKeys[$i])) { + $criteriaValue->setValue($storedCrit["crit"][$criteriaKeys[$i]][$j]["value"]); + } + $this->addElement($criteriaValue); + + /****************** EXTRA ***********/ + $criteriaExtra = new Zend_Form_Element_Text("sp_criteria_extra_".$i."_".$j); + $criteriaExtra->setAttrib('class', 'input_text sp_extra_input_text') + ->setDecorators(array('viewHelper')); + if (isset($criteriaKeys[$i]) && isset($storedCrit["crit"][$criteriaKeys[$i]][$j]["extra"])) { + $criteriaExtra->setValue($storedCrit["crit"][$criteriaKeys[$i]][$j]["extra"]); + $criteriaValue->setAttrib('class', 'input_text sp_extra_input_text'); + } else { + $criteriaExtra->setAttrib('disabled', 'disabled'); + } + $this->addElement($criteriaExtra); + + }//for + + }//for + + $limit = new Zend_Form_Element_Select('sp_limit_options'); + $limit->setAttrib('class', 'sp_input_select') + ->setDecorators(array('viewHelper')) + ->setMultiOptions($this->limitOptions); + if (isset($storedCrit["limit"])) { + $limit->setValue($storedCrit["limit"]["modifier"]); + } + $this->addElement($limit); + + $limitValue = new Zend_Form_Element_Text('sp_limit_value'); + $limitValue->setAttrib('class', 'sp_input_text_limit') + ->setLabel('Limit to') + ->setDecorators(array('viewHelper')); + $this->addElement($limitValue); + if (isset($storedCrit["limit"])) { + $limitValue->setValue($storedCrit["limit"]["value"]); + } else { + // setting default to 1 hour + $limitValue->setValue(1); + } + + //getting block content candidate count that meets criteria + $bl = new Application_Model_Block($p_blockId); + if ($p_isValid) { + $files = $bl->getListofFilesMeetCriteria(); + $showPoolCount = true; + } else { + $files = null; + $showPoolCount = false; + } + + $generate = new Zend_Form_Element_Button('generate_button'); + $generate->setAttrib('class', 'btn btn-small'); + $generate->setAttrib('title', 'Generate playlist content and save criteria'); + $generate->setIgnore(true); + $generate->setLabel('Generate'); + $generate->setDecorators(array('viewHelper')); + $this->addElement($generate); + + $shuffle = new Zend_Form_Element_Button('shuffle_button'); + $shuffle->setAttrib('class', 'btn btn-small'); + $shuffle->setAttrib('title', 'Shuffle playlist content'); + $shuffle->setIgnore(true); + $shuffle->setLabel('Shuffle'); + $shuffle->setDecorators(array('viewHelper')); + $this->addElement($shuffle); + + $this->setDecorators(array( + array('ViewScript', array('viewScript' => 'form/smart-block-criteria.phtml', "openOption"=> $openSmartBlockOption, + 'criteriasLength' => count($this->criteriaOptions), 'poolCount' => $files['count'], 'modRowMap' => $modRowMap, + 'showPoolCount' => $showPoolCount)) + )); + } + + public function preValidation($params) + { + $data = Application_Model_Block::organizeSmartPlyalistCriteria($params['data']); + // add elelments that needs to be added + // set multioption for modifier according to creiteria_field + $modRowMap = array(); + foreach ($data['criteria'] as $critKey=>$d) { + $count = 1; + foreach ($d as $modKey=>$modInfo) { + if ($modKey == 0) { + $eleCrit = $this->getElement("sp_criteria_field_".$critKey."_".$modKey); + $eleCrit->setValue($this->criteriaOptions[$modInfo['sp_criteria_field']]); + $eleCrit->setAttrib("disabled", null); + + $eleMod = $this->getElement("sp_criteria_modifier_".$critKey."_".$modKey); + $criteriaType = $this->criteriaTypes[$modInfo['sp_criteria_field']]; + if ($criteriaType == "s") { + $eleMod->setMultiOptions($this->stringCriteriaOptions); + } elseif ($criteriaType == "n") { + $eleMod->setMultiOptions($this->numericCriteriaOptions); + } else { + $eleMod->setMultiOptions(array('0' => 'Select modifier')); + } + $eleMod->setValue($modInfo['sp_criteria_modifier']); + $eleMod->setAttrib("disabled", null); + + $eleValue = $this->getElement("sp_criteria_value_".$critKey."_".$modKey); + $eleValue->setValue($modInfo['sp_criteria_value']); + $eleValue->setAttrib("disabled", null); + + if (isset($modInfo['sp_criteria_extra'])) { + $eleExtra = $this->getElement("sp_criteria_extra_".$critKey."_".$modKey); + $eleExtra->setValue($modInfo['sp_criteria_extra']); + $eleValue->setAttrib('class', 'input_text sp_extra_input_text'); + $eleExtra->setAttrib("disabled", null); + } + + } else { + $criteria = new Zend_Form_Element_Select("sp_criteria_field_".$critKey."_".$modKey); + $criteria->setAttrib('class', 'input_select sp_input_select sp-invisible') + ->setValue('Select criteria') + ->setDecorators(array('viewHelper')) + ->setMultiOptions($this->criteriaOptions); + + $criteriaType = $this->criteriaTypes[$modInfo['sp_criteria_field']]; + $criteria->setValue($this->criteriaOptions[$modInfo['sp_criteria_field']]); + $this->addElement($criteria); + + /****************** MODIFIER ***********/ + $criteriaModifers = new Zend_Form_Element_Select("sp_criteria_modifier_".$critKey."_".$modKey); + $criteriaModifers->setValue('Select modifier') + ->setAttrib('class', 'input_select sp_input_select') + ->setDecorators(array('viewHelper')); + + if ($criteriaType == "s") { + $criteriaModifers->setMultiOptions($this->stringCriteriaOptions); + } elseif ($criteriaType == "n") { + $criteriaModifers->setMultiOptions($this->numericCriteriaOptions); + } else { + $criteriaModifers->setMultiOptions(array('0' => 'Select modifier')); + } + $criteriaModifers->setValue($modInfo['sp_criteria_modifier']); + $this->addElement($criteriaModifers); + + /****************** VALUE ***********/ + $criteriaValue = new Zend_Form_Element_Text("sp_criteria_value_".$critKey."_".$modKey); + $criteriaValue->setAttrib('class', 'input_text sp_input_text') + ->setDecorators(array('viewHelper')); + $criteriaValue->setValue($modInfo['sp_criteria_value']); + $this->addElement($criteriaValue); + + /****************** EXTRA ***********/ + $criteriaExtra = new Zend_Form_Element_Text("sp_criteria_extra_".$critKey."_".$modKey); + $criteriaExtra->setAttrib('class', 'input_text sp_extra_input_text') + ->setDecorators(array('viewHelper')); + if (isset($modInfo['sp_criteria_extra'])) { + $criteriaExtra->setValue($modInfo['sp_criteria_extra']); + $criteriaValue->setAttrib('class', 'input_text sp_extra_input_text'); + } else { + $criteriaExtra->setAttrib('disabled', 'disabled'); + } + $this->addElement($criteriaExtra); + $count++; + } + } + $modRowMap[$critKey] = $count; + } + + $decorator = $this->getDecorator("ViewScript"); + $existingModRow = $decorator->getOption("modRowMap"); + foreach ($modRowMap as $key=>$v) { + $existingModRow[$key] = $v; + } + $decorator->setOption("modRowMap", $existingModRow); + + // reconstruct the params['criteria'] so we can populate the form + $formData = array(); + foreach ($params['data'] as $ele) { + $formData[$ele['name']] = $ele['value']; + } + + $this->populate($formData); + + return $data; + } + + public function isValid($params) + { + $isValid = true; + $data = $this->preValidation($params); + $criteria2PeerMap = array( + 0 => "Select criteria", + "album_title" => "DbAlbumTitle", + "artist_name" => "DbArtistName", + "bit_rate" => "DbBitRate", + "bpm" => "DbBpm", + "composer" => "DbComposer", + "conductor" => "DbConductor", + "copyright" => "DbCopyright", + "encoded_by" => "DbEncodedBy", + "utime" => "DbUtime", + "mtime" => "DbMtime", + "lptime" => "DbLPtime", + "genre" => "DbGenre", + "info_url" => "DbInfoUrl", + "isrc_number" => "DbIsrcNumber", + "label" => "DbLabel", + "language" => "DbLanguage", + "length" => "DbLength", + "mime" => "DbMime", + "mood" => "DbMood", + "owner_id" => "DbOwnerId", + "replay_gain" => "DbReplayGain", + "sample_rate" => "DbSampleRate", + "track_title" => "DbTrackTitle", + "track_number" => "DbTrackNumber", + "year" => "DbYear" + ); + + // things we need to check + // 1. limit value shouldn't be empty and has upperbound of 24 hrs + // 2. sp_criteria or sp_criteria_modifier shouldn't be 0 + // 3. validate formate according to DB column type + $multiplier = 1; + $result = 0; + + // validation start + if ($data['etc']['sp_limit_options'] == 'hours') { + $multiplier = 60; + } + if ($data['etc']['sp_limit_options'] == 'hours' || $data['etc']['sp_limit_options'] == 'mins') { + $element = $this->getElement("sp_limit_value"); + if ($data['etc']['sp_limit_value'] == "" || floatval($data['etc']['sp_limit_value']) <= 0) { + $element->addError("Limit cannot be empty or smaller than 0"); + $isValid = false; + } else { + $mins = floatval($data['etc']['sp_limit_value']) * $multiplier; + if ($mins > 1440) { + $element->addError("Limit cannot be more than 24 hrs"); + $isValid = false; + } + } + } else { + $element = $this->getElement("sp_limit_value"); + if ($data['etc']['sp_limit_value'] == "" || floatval($data['etc']['sp_limit_value']) <= 0) { + $element->addError("Limit cannot be empty or smaller than 0"); + $isValid = false; + } elseif (!ctype_digit($data['etc']['sp_limit_value'])) { + $element->addError("The value should be an integer"); + $isValid = false; + } elseif (intval($data['etc']['sp_limit_value']) > 500) { + $element->addError("500 is the max item limit value you can set"); + $isValid = false; + } + } + + if (isset($data['criteria'])) { + foreach ($data['criteria'] as $rowKey=>$row) { + foreach ($row as $key=>$d) { + $element = $this->getElement("sp_criteria_field_".$rowKey."_".$key); + // check for not selected select box + if ($d['sp_criteria_field'] == "0" || $d['sp_criteria_modifier'] == "0") { + $element->addError("You must select Criteria and Modifier"); + $isValid = false; + } else { + $column = CcFilesPeer::getTableMap()->getColumnByPhpName($criteria2PeerMap[$d['sp_criteria_field']]); + // validation on type of column + if ($d['sp_criteria_field'] == 'length') { + if (!preg_match("/^(\d{2}):(\d{2}):(\d{2})/", $d['sp_criteria_value'])) { + $element->addError("'Length' should be in '00:00:00' format"); + $isValid = false; + } + } elseif ($column->getType() == PropelColumnTypes::TIMESTAMP) { + if (!preg_match("/(\d{4})-(\d{2})-(\d{2})/", $d['sp_criteria_value'])) { + $element->addError("The value should be in timestamp format(eg. 0000-00-00 or 00-00-00 00:00:00"); + $isValid = false; + } else { + $result = Application_Common_DateHelper::checkDateTimeRangeForSQL($d['sp_criteria_value']); + if (!$result["success"]) { + // check for if it is in valid range( 1753-01-01 ~ 12/31/9999 ) + $element->addError($result["errMsg"]); + $isValid = false; + } + } + + if (isset($d['sp_criteria_extra'])) { + if (!preg_match("/(\d{4})-(\d{2})-(\d{2})/", $d['sp_criteria_extra'])) { + $element->addError("The value should be in timestamp format(eg. 0000-00-00 or 00-00-00 00:00:00"); + $isValid = false; + } else { + $result = Application_Common_DateHelper::checkDateTimeRangeForSQL($d['sp_criteria_extra']); + if (!$result["success"]) { + // check for if it is in valid range( 1753-01-01 ~ 12/31/9999 ) + $element->addError($result["errMsg"]); + $isValid = false; + } + } + } + } elseif ($column->getType() == PropelColumnTypes::INTEGER && + $d['sp_criteria_field'] != 'owner_id') { + if (!is_numeric($d['sp_criteria_value'])) { + $element->addError("The value has to be numeric"); + $isValid = false; + } + // length check + if (intval($d['sp_criteria_value']) >= pow(2,31)) { + $element->addError("The value should be less then 2147483648"); + $isValid = false; + } + } elseif ($column->getType() == PropelColumnTypes::VARCHAR) { + if (strlen($d['sp_criteria_value']) > $column->getSize()) { + $element->addError("The value should be less ".$column->getSize()." characters"); + $isValid = false; + } + } + } + + if ($d['sp_criteria_value'] == "") { + $element->addError("Value cannot be empty"); + $isValid = false; + } + }//end foreach + }//for loop + }//if + + return $isValid; + } +} diff --git a/airtime_mvc/application/forms/SoundcloudPreferences.php b/airtime_mvc/application/forms/SoundcloudPreferences.php index 40ad3382c..d3840cbbf 100644 --- a/airtime_mvc/application/forms/SoundcloudPreferences.php +++ b/airtime_mvc/application/forms/SoundcloudPreferences.php @@ -30,7 +30,7 @@ class Application_Form_SoundcloudPreferences extends Zend_Form_SubForm 'ViewHelper' ) )); - + //enable downloadable for soundcloud $this->addElement('checkbox', 'SoundCloudDownloadbleOption', array( 'label' => 'Automatically Mark Files "Downloadable" on SoundCloud', @@ -51,7 +51,7 @@ class Application_Form_SoundcloudPreferences extends Zend_Form_SubForm 'decorators' => array( 'ViewHelper' ), - + // By default, 'allowEmpty' is true. This means that our custom // validators are going to be skipped if this field is empty, // which is something we don't want @@ -71,7 +71,7 @@ class Application_Form_SoundcloudPreferences extends Zend_Form_SubForm 'decorators' => array( 'ViewHelper' ), - + // By default, 'allowEmpty' is true. This means that our custom // validators are going to be skipped if this field is empty, // which is something we don't want @@ -79,7 +79,7 @@ class Application_Form_SoundcloudPreferences extends Zend_Form_SubForm 'validators' => array( new ConditionalNotEmpty(array('UploadToSoundcloudOption'=>'1')) ), - 'renderPassword' => true + 'renderPassword' => true )); // Add the description element @@ -91,7 +91,7 @@ class Application_Form_SoundcloudPreferences extends Zend_Form_SubForm 'decorators' => array( 'ViewHelper' ) - )); + )); //SoundCloud default genre $this->addElement('text', 'SoundCloudGenre', array( @@ -149,6 +149,4 @@ class Application_Form_SoundcloudPreferences extends Zend_Form_SubForm $this->addElement($select); } - } - diff --git a/airtime_mvc/application/forms/StreamSetting.php b/airtime_mvc/application/forms/StreamSetting.php index f6d639f8d..c3443a3e0 100644 --- a/airtime_mvc/application/forms/StreamSetting.php +++ b/airtime_mvc/application/forms/StreamSetting.php @@ -9,19 +9,21 @@ class Application_Form_StreamSetting extends Zend_Form } - public function setSetting($setting){ + public function setSetting($setting) + { $this->setting = $setting; } - public function startFrom() { + public function startFrom() + { $setting = $this->setting; - if(Application_Model_Preference::GetPlanLevel() == 'disabled'){ + if (Application_Model_Preference::GetPlanLevel() == 'disabled') { $output_sound_device = new Zend_Form_Element_Checkbox('output_sound_device'); $output_sound_device->setLabel('Hardware Audio Output') ->setRequired(false) ->setValue(($setting['output_sound_device'] == "true")?1:0) ->setDecorators(array('ViewHelper')); - if (Application_Model_Preference::GetEnableStreamConf() == "false"){ + if (Application_Model_Preference::GetEnableStreamConf() == "false") { $output_sound_device->setAttrib("readonly", true); } $this->addElement($output_sound_device); @@ -32,18 +34,18 @@ class Application_Form_StreamSetting extends Zend_Form ->setMultiOptions($output_types) ->setValue($setting['output_sound_device_type']) ->setDecorators(array('ViewHelper')); - if($setting['output_sound_device'] != "true"){ + if ($setting['output_sound_device'] != "true") { $output_type->setAttrib("disabled", "disabled"); } $this->addElement($output_type); } - + $icecast_vorbis_metadata = new Zend_Form_Element_Checkbox('icecast_vorbis_metadata'); $icecast_vorbis_metadata->setLabel('Icecast Vorbis Metadata') ->setRequired(false) ->setValue(($setting['icecast_vorbis_metadata'] == "true")?1:0) ->setDecorators(array('ViewHelper')); - if (Application_Model_Preference::GetEnableStreamConf() == "false"){ + if (Application_Model_Preference::GetEnableStreamConf() == "false") { $icecast_vorbis_metadata->setAttrib("readonly", true); } $this->addElement($icecast_vorbis_metadata); @@ -58,18 +60,20 @@ class Application_Form_StreamSetting extends Zend_Form $this->addElement($stream_format); } - public function isValid($data){ - if(isset($data['output_sound_device'])){ + public function isValid($data) + { + if (isset($data['output_sound_device'])) { $d = array(); $d["output_sound_device"] = $data['output_sound_device']; $d["icecast_vorbis_metadata"] = $data['icecast_vorbis_metadata']; - if(isset($data['output_sound_device_type'])){ + if (isset($data['output_sound_device_type'])) { $d["output_sound_device_type"] = $data['output_sound_device_type']; } $d["streamFormat"] = $data['streamFormat']; $this->populate($d); } $isValid = parent::isValid($data); + return $isValid; } } diff --git a/airtime_mvc/application/forms/StreamSettingSubForm.php b/airtime_mvc/application/forms/StreamSettingSubForm.php index bb0862794..6a243d12f 100644 --- a/airtime_mvc/application/forms/StreamSettingSubForm.php +++ b/airtime_mvc/application/forms/StreamSettingSubForm.php @@ -1,5 +1,6 @@ prefix = $prefix; } - public function setSetting($setting){ + public function setSetting($setting) + { $this->setting = $setting; } - public function setStreamTypes($stream_types){ + public function setStreamTypes($stream_types) + { $this->stream_types = $stream_types; } - public function setStreamBitrates($stream_bitrates){ + public function setStreamBitrates($stream_bitrates) + { $this->stream_bitrates = $stream_bitrates; } - public function startForm(){ + public function startForm() + { $prefix = "s".$this->prefix; $stream_number = $this->prefix; $setting = $this->setting; @@ -36,16 +42,13 @@ class Application_Form_StreamSettingSubForm extends Zend_Form_SubForm{ $this->setIsArray(true); $this->setElementsBelongTo($prefix."_data"); - $disable_all = false; - if(Application_Model_Preference::GetEnableStreamConf() == "false"){ - $disable_all = true; - } + $disable_all = Application_Model_Preference::GetEnableStreamConf() == "false"; $enable = new Zend_Form_Element_Checkbox('enable'); $enable->setLabel('Enabled:') ->setValue($setting[$prefix.'_enable'] == 'true' ? 1 : 0) ->setDecorators(array('ViewHelper')); - if($disable_all){ + if ($disable_all) { $enable->setAttrib("disabled", "disabled"); } $this->addElement($enable); @@ -55,7 +58,7 @@ class Application_Form_StreamSettingSubForm extends Zend_Form_SubForm{ ->setMultiOptions($stream_types) ->setValue(isset($setting[$prefix.'_type'])?$setting[$prefix.'_type']:0) ->setDecorators(array('ViewHelper')); - if($disable_all){ + if ($disable_all) { $type->setAttrib("disabled", "disabled"); } $this->addElement($type); @@ -65,7 +68,7 @@ class Application_Form_StreamSettingSubForm extends Zend_Form_SubForm{ ->setMultiOptions($stream_bitrates) ->setValue(isset($setting[$prefix.'_bitrate'])?$setting[$prefix.'_bitrate']:0) ->setDecorators(array('ViewHelper')); - if($disable_all){ + if ($disable_all) { $bitrate->setAttrib("disabled", "disabled"); } $this->addElement($bitrate); @@ -75,18 +78,28 @@ class Application_Form_StreamSettingSubForm extends Zend_Form_SubForm{ ->setMultiOptions(array("icecast"=>"Icecast", "shoutcast"=>"SHOUTcast")) ->setValue(isset($setting[$prefix.'_output'])?$setting[$prefix.'_output']:"icecast") ->setDecorators(array('ViewHelper')); - if($disable_all){ + if ($disable_all) { $output->setAttrib("disabled", "disabled"); } $this->addElement($output); + $channels = new Zend_Form_Element_Select('channels'); + $channels->setLabel("Channels:") + ->setMultiOptions(array("mono"=>"1 - Mono", "stereo"=>"2 - Stereo")) + ->setValue(isset($setting[$prefix.'_channels']) ? $setting[$prefix.'_channels'] : "stereo") + ->setDecorators(array('ViewHelper')); + if ($disable_all) { + $channels->setAttrib("disabled", "disabled"); + } + $this->addElement($channels); + $host = new Zend_Form_Element_Text('host'); $host->setLabel("Server") ->setValue(isset($setting[$prefix.'_host'])?$setting[$prefix.'_host']:"") ->setValidators(array( array('regex', false, array('/^[0-9a-zA-Z-_.]+$/', 'messages' => 'Invalid character entered')))) ->setDecorators(array('ViewHelper')); - if($disable_all){ + if ($disable_all) { $host->setAttrib("disabled", "disabled"); } $host->setAttrib('alt', 'domain'); @@ -98,7 +111,7 @@ class Application_Form_StreamSettingSubForm extends Zend_Form_SubForm{ ->setValidators(array(new Zend_Validate_Between(array('min'=>0, 'max'=>99999)))) ->addValidator('regex', false, array('pattern'=>'/^[0-9]+$/', 'messages'=>array('regexNotMatch'=>'Only numbers are allowed.'))) ->setDecorators(array('ViewHelper')); - if($disable_all){ + if ($disable_all) { $port->setAttrib("disabled", "disabled"); } $this->addElement($port); @@ -109,7 +122,7 @@ class Application_Form_StreamSettingSubForm extends Zend_Form_SubForm{ ->setValidators(array( array('regex', false, array('/^[^ &<>]+$/', 'messages' => 'Invalid character entered')))) ->setDecorators(array('ViewHelper')); - if($disable_all){ + if ($disable_all) { $pass->setAttrib("disabled", "disabled"); } $pass->setAttrib('alt', 'regular_text'); @@ -119,7 +132,7 @@ class Application_Form_StreamSettingSubForm extends Zend_Form_SubForm{ $genre->setLabel("Genre") ->setValue(isset($setting[$prefix.'_genre'])?$setting[$prefix.'_genre']:"") ->setDecorators(array('ViewHelper')); - if($disable_all){ + if ($disable_all) { $genre->setAttrib("disabled", "disabled"); } $this->addElement($genre); @@ -130,7 +143,7 @@ class Application_Form_StreamSettingSubForm extends Zend_Form_SubForm{ ->setValidators(array( array('regex', false, array('/^[0-9a-zA-Z\-_.:\/]+$/', 'messages' => 'Invalid character entered')))) ->setDecorators(array('ViewHelper')); - if($disable_all){ + if ($disable_all) { $url->setAttrib("disabled", "disabled"); } $url->setAttrib('alt', 'url'); @@ -140,7 +153,7 @@ class Application_Form_StreamSettingSubForm extends Zend_Form_SubForm{ $name->setLabel("Name") ->setValue(isset($setting[$prefix.'_name'])?$setting[$prefix.'_name']:"") ->setDecorators(array('ViewHelper')); - if($disable_all){ + if ($disable_all) { $name->setAttrib("disabled", "disabled"); } $this->addElement($name); @@ -149,7 +162,7 @@ class Application_Form_StreamSettingSubForm extends Zend_Form_SubForm{ $description->setLabel("Description") ->setValue(isset($setting[$prefix.'_description'])?$setting[$prefix.'_description']:"") ->setDecorators(array('ViewHelper')); - if($disable_all){ + if ($disable_all) { $description->setAttrib("disabled", "disabled"); } $this->addElement($description); @@ -160,7 +173,7 @@ class Application_Form_StreamSettingSubForm extends Zend_Form_SubForm{ ->setValidators(array( array('regex', false, array('/^[^ &<>]+$/', 'messages' => 'Invalid character entered')))) ->setDecorators(array('ViewHelper')); - if($disable_all){ + if ($disable_all) { $mount->setAttrib("disabled", "disabled"); } $mount->setAttrib('alt', 'regular_text'); @@ -172,41 +185,43 @@ class Application_Form_StreamSettingSubForm extends Zend_Form_SubForm{ ->setValidators(array( array('regex', false, array('/^[^ &<>]+$/', 'messages' => 'Invalid character entered')))) ->setDecorators(array('ViewHelper')); - if($disable_all){ + if ($disable_all) { $user->setAttrib("disabled", "disabled"); } $user->setAttrib('alt', 'regular_text'); $this->addElement($user); - + $liquidsopa_error_msg = '

Getting information from the server...

'; - + $this->setDecorators(array( array('ViewScript', array('viewScript' => 'form/stream-setting-form.phtml', "stream_number"=>$stream_number, "enabled"=>$enable->getValue(), "liquidsoap_error_msg"=>$liquidsopa_error_msg)) )); } - public function isValid ($data){ + public function isValid ($data) + { $f_data = $data['s'.$this->prefix."_data"]; $isValid = parent::isValid($f_data); - if($f_data['enable'] == 1){ - if($f_data['host'] == ''){ + if ($f_data['enable'] == 1) { + if ($f_data['host'] == '') { $element = $this->getElement("host"); $element->addError("Server cannot be empty."); $isValid = false; } - if($f_data['port'] == ''){ + if ($f_data['port'] == '') { $element = $this->getElement("port"); $element->addError("Port cannot be empty."); $isValid = false; } - if($f_data['output'] == 'icecast'){ - if($f_data['mount'] == ''){ + if ($f_data['output'] == 'icecast') { + if ($f_data['mount'] == '') { $element = $this->getElement("mount"); $element->addError("Mount cannot be empty with Icecast server."); $isValid = false; } } } + return $isValid; } } diff --git a/airtime_mvc/application/forms/SupportSettings.php b/airtime_mvc/application/forms/SupportSettings.php index 426db3831..cbd942970 100644 --- a/airtime_mvc/application/forms/SupportSettings.php +++ b/airtime_mvc/application/forms/SupportSettings.php @@ -5,18 +5,18 @@ require_once 'customfilters/ImageSize.php'; class Application_Form_SupportSettings extends Zend_Form { private $isSass; - + public function init() { $country_list = Application_Model_Preference::GetCountryList(); $isSass = Application_Model_Preference::GetPlanLevel() == 'disabled'?false:true; $this->isSass = $isSass; - + $this->setDecorators(array( array('ViewScript', array('viewScript' => 'form/support-setting.phtml', "isSaas" => $isSass)), array('File', array('viewScript' => 'form/support-setting.phtml', 'placement' => false))) ); - + //Station name $this->addElement('text', 'stationName', array( 'class' => 'input_text', @@ -24,7 +24,7 @@ class Application_Form_SupportSettings extends Zend_Form 'required' => true, 'filters' => array('StringTrim'), 'validator' => array('NotEmpty'), - 'value' => Application_Model_Preference::GetValue("station_name"), + 'value' => Application_Model_Preference::GetStationName(), 'decorators' => array( 'ViewHelper' ) @@ -63,20 +63,20 @@ class Application_Form_SupportSettings extends Zend_Form 'decorators' => array( 'ViewHelper' ) - )); + )); - // county list dropdown - $this->addElement('select', 'Country', array( - 'label' => 'Country:', - 'required' => false, - 'value' => Application_Model_Preference::GetStationCountry(), - 'multiOptions' => $country_list, - 'decorators' => array( + // county list dropdown + $this->addElement('select', 'Country', array( + 'label' => 'Country:', + 'required' => false, + 'value' => Application_Model_Preference::GetStationCountry(), + 'multiOptions' => $country_list, + 'decorators' => array( 'ViewHelper' ) - )); - - // Station city + )); + + // Station city $this->addElement('text', 'City', array( 'label' => 'City:', 'required' => false, @@ -85,31 +85,31 @@ class Application_Form_SupportSettings extends Zend_Form 'decorators' => array( 'ViewHelper' ) - )); - - // Station Description - $description = new Zend_Form_Element_Textarea('Description'); - $description->class = 'input_text_area'; - $description->setLabel('Station Description:') - ->setRequired(false) - ->setValue(Application_Model_Preference::GetStationDescription()) - ->setDecorators(array('ViewHelper')) - ->setAttrib('ROWS','2') - ->setAttrib('COLS','58'); - $this->addElement($description); - - // Station Logo - $upload = new Zend_Form_Element_File('Logo'); - $upload->setLabel('Station Logo:') - ->setRequired(false) - ->setDecorators(array('File')) - ->addValidator('Count', false, 1) - ->addValidator('Extension', false, 'jpg,jpeg,png,gif') - ->addFilter('ImageSize'); - $upload->setAttrib('accept', 'image/*'); - $this->addElement($upload); - - if(!$isSass){ + )); + + // Station Description + $description = new Zend_Form_Element_Textarea('Description'); + $description->class = 'input_text_area'; + $description->setLabel('Station Description:') + ->setRequired(false) + ->setValue(Application_Model_Preference::GetStationDescription()) + ->setDecorators(array('ViewHelper')) + ->setAttrib('ROWS','2') + ->setAttrib('COLS','58'); + $this->addElement($description); + + // Station Logo + $upload = new Zend_Form_Element_File('Logo'); + $upload->setLabel('Station Logo:') + ->setRequired(false) + ->setDecorators(array('File')) + ->addValidator('Count', false, 1) + ->addValidator('Extension', false, 'jpg,jpeg,png,gif') + ->addFilter('ImageSize'); + $upload->setAttrib('accept', 'image/*'); + $this->addElement($upload); + + if (!$isSass) { //enable support feedback $this->addElement('checkbox', 'SupportFeedback', array( 'label' => 'Send support feedback', @@ -118,40 +118,40 @@ class Application_Form_SupportSettings extends Zend_Form 'decorators' => array( 'ViewHelper' ) - )); - - // checkbox for publicise + )); + + // checkbox for publicise $checkboxPublicise = new Zend_Form_Element_Checkbox("Publicise"); $checkboxPublicise->setLabel('Promote my station on Sourcefabric.org') ->setRequired(false) ->setDecorators(array('ViewHelper')) ->setValue(Application_Model_Preference::GetPublicise()); - if(Application_Model_Preference::GetSupportFeedback() == '0'){ + if (Application_Model_Preference::GetSupportFeedback() == '0') { $checkboxPublicise->setAttrib("disabled", "disabled"); } $this->addElement($checkboxPublicise); - - // text area for sending detail + + // text area for sending detail $this->addElement('textarea', 'SendInfo', array( - 'class' => 'sending_textarea', - 'required' => false, + 'class' => 'sending_textarea', + 'required' => false, 'filters' => array('StringTrim'), - 'readonly' => true, - 'cols' => 61, - 'rows' => 5, + 'readonly' => true, + 'cols' => 61, + 'rows' => 5, 'value' => Application_Model_Preference::GetSystemInfo(false, true), 'decorators' => array( 'ViewHelper' ) )); - + // checkbox for privacy policy $checkboxPrivacy = new Zend_Form_Element_Checkbox("Privacy"); $checkboxPrivacy->setLabel("By checking this box, I agree to Sourcefabric's privacy policy.") ->setDecorators(array('ViewHelper')); $this->addElement($checkboxPrivacy); } - + // submit button $submit = new Zend_Form_Element_Submit("submit"); $submit->class = 'ui-button ui-state-default right-floated'; @@ -160,24 +160,24 @@ class Application_Form_SupportSettings extends Zend_Form ->setDecorators(array('ViewHelper')); $this->addElement($submit); } - + // overriding isValid function public function isValid ($data) { $isValid = parent::isValid($data); - if(!$this->isSass){ - if($data['Publicise'] != 1){ + if (!$this->isSass) { + if ($data['Publicise'] != 1) { $isValid = true; } - if(isset($data["Privacy"])){ + if (isset($data["Privacy"])) { $checkPrivacy = $this->getElement('Privacy'); - if($data["SupportFeedback"] == "1" && $data["Privacy"] != "1"){ + if ($data["SupportFeedback"] == "1" && $data["Privacy"] != "1") { $checkPrivacy->addError("You have to agree to privacy policy."); $isValid = false; } } } + return $isValid; } } - diff --git a/airtime_mvc/application/forms/WatchedDirPreferences.php b/airtime_mvc/application/forms/WatchedDirPreferences.php index 9e8021839..7fcf00893 100644 --- a/airtime_mvc/application/forms/WatchedDirPreferences.php +++ b/airtime_mvc/application/forms/WatchedDirPreferences.php @@ -32,20 +32,20 @@ class Application_Form_WatchedDirPreferences extends Zend_Form_SubForm )); } - public function verifyChosenFolder($p_form_element_id) { - + public function verifyChosenFolder($p_form_element_id) + { $element = $this->getElement($p_form_element_id); if (!is_dir($element->getValue())) { $element->setErrors(array('Not a valid Directory')); + return false; - } - else { + } else { $element->setValue(""); + return true; } } } - diff --git a/airtime_mvc/application/forms/customfilters/ImageSize.php b/airtime_mvc/application/forms/customfilters/ImageSize.php index 17c40228e..402c07e24 100644 --- a/airtime_mvc/application/forms/customfilters/ImageSize.php +++ b/airtime_mvc/application/forms/customfilters/ImageSize.php @@ -1,7 +1,9 @@ 1) { // img too big! create a scaled down image $newWidth = round($origWidth / $ratio); @@ -34,9 +36,7 @@ class Zend_Filter_ImageSize implements Zend_Filter_Interface { $writeFunc($resized, $value); } } - + return $value; } } - -?> diff --git a/airtime_mvc/application/forms/customvalidators/ConditionalNotEmpty.php b/airtime_mvc/application/forms/customvalidators/ConditionalNotEmpty.php index 2f89fe667..bd3ae5723 100644 --- a/airtime_mvc/application/forms/customvalidators/ConditionalNotEmpty.php +++ b/airtime_mvc/application/forms/customvalidators/ConditionalNotEmpty.php @@ -3,37 +3,37 @@ /** * Check if a field is empty but only when specific fields have specific values */ -class ConditionalNotEmpty extends Zend_Validate_Abstract { - +class ConditionalNotEmpty extends Zend_Validate_Abstract +{ const KEY_IS_EMPTY = 'keyIsEmpty'; - + protected $_messageTemplates = array( self::KEY_IS_EMPTY => 'Value is required and can\'t be empty' ); - + protected $_fieldValues; - + /** * Constructs a new ConditionalNotEmpty validator. - * + * * @param array $fieldValues - the names and expected values of the fields we're depending on; * E.g., if we have a field that should only be validated when two other - * fields PARENT_1 and PARENT_2 have values of '1' and '0' respectively, then + * fields PARENT_1 and PARENT_2 have values of '1' and '0' respectively, then * $fieldValues should contain ('PARENT_1'=>'1', 'PARENT_2'=>'0') */ public function __construct($fieldValues) { $this->_fieldValues = $fieldValues; } - + /** * Implements Zend_Validate_Abstract. * Given names and expected values of the fields we're depending on ($_fieldValues), * this function returns true if the expected values doesn't match the actual user input, * or if $value is not empty. Returns false otherwise. - * - * @param String $value - this field's value - * @param array $context - names and values of the rest of the fields in this form + * + * @param String $value - this field's value + * @param array $context - names and values of the rest of the fields in this form * @return boolean - true if valid; false otherwise */ public function isValid($value, $context = null) @@ -41,9 +41,9 @@ class ConditionalNotEmpty extends Zend_Validate_Abstract { if ($value != "") { return true; } - + if (is_array($context)) { - foreach($this->_fieldValues as $fieldName=>$fieldValue) { + foreach ($this->_fieldValues as $fieldName=>$fieldValue) { if (!isset($context[$fieldName]) || $context[$fieldName] != $fieldValue) { return true; } @@ -53,10 +53,9 @@ class ConditionalNotEmpty extends Zend_Validate_Abstract { return true; } } - + $this->_error(self::KEY_IS_EMPTY); + return false; } } - -?> diff --git a/airtime_mvc/application/forms/customvalidators/PasswordNotEmpty.php b/airtime_mvc/application/forms/customvalidators/PasswordNotEmpty.php index 11e62b933..5073c5d80 100644 --- a/airtime_mvc/application/forms/customvalidators/PasswordNotEmpty.php +++ b/airtime_mvc/application/forms/customvalidators/PasswordNotEmpty.php @@ -1,6 +1,7 @@ diff --git a/airtime_mvc/application/logging/Logging.php b/airtime_mvc/application/logging/Logging.php index bf9dbea92..dfe7e1fbe 100644 --- a/airtime_mvc/application/logging/Logging.php +++ b/airtime_mvc/application/logging/Logging.php @@ -5,11 +5,12 @@ class Logging { private static $_logger; private static $_path; - public static function getLogger(){ + public static function getLogger() + { if (!isset(self::$_logger)) { $writer = new Zend_Log_Writer_Stream(self::$_path); - if (Zend_Version::compareVersion("1.11") > 0){ + if (Zend_Version::compareVersion("1.11") > 0) { //Running Zend version 1.10 or lower. Need to instantiate our //own Zend Log class with backported code from 1.11. require_once __DIR__."/AirtimeLog.php"; @@ -22,33 +23,97 @@ class Logging { return self::$_logger; } - public static function setLogPath($path){ + public static function setLogPath($path) + { self::$_path = $path; } - public static function toString($p_msg){ - if (is_array($p_msg) || is_object($p_msg)){ + public static function toString($p_msg) + { + if (is_array($p_msg) || is_object($p_msg)) { return print_r($p_msg, true); } else { return $p_msg; } } - public static function log($p_msg){ + public static function info($p_msg) + { $bt = debug_backtrace(); + $caller = array_shift($bt); + $file = basename($caller['file']); + $line = $caller['line']; + $caller = array_shift($bt); + $function = $caller['function']; + $logger = self::getLogger(); - $logger->info(self::toString($p_msg)." - file:".$caller['file'].":".$caller['line']); + $logger->info("[$file : $function() : line $line] - ".self::toString($p_msg)); + } + + public static function warn($p_msg) + { + $bt = debug_backtrace(); + + $caller = array_shift($bt); + $file = basename($caller['file']); + $line = $caller['line']; + + $caller = array_shift($bt); + $function = $caller['function']; + + $logger = self::getLogger(); + $logger->warn("[$file : $function() : line $line] - " + . self::toString($p_msg)); } - public static function debug($p_msg){ - $bt = debug_backtrace(); - $caller = array_shift($bt); - - if (defined('APPLICATION_ENV') && APPLICATION_ENV == "development"){ - $logger = self::getLogger(); - $logger->debug(self::toString($p_msg)." - file:".$caller['file'].":".$caller['line']); + public static function debug($p_msg) + { + if (!(defined('APPLICATION_ENV') && APPLICATION_ENV == "development")) { + return; } + + $bt = debug_backtrace(); + + $caller = array_shift($bt); + $file = basename($caller['file']); + $line = $caller['line']; + + $caller = array_shift($bt); + $function = $caller['function']; + + $logger = self::getLogger(); + $logger->debug("[$file : $function() : line $line] - ".self::toString($p_msg)); } + // kind of like debug but for printing arrays more compactly (skipping + // empty elements + + public static function debug_sparse(array $p_msg) + { + Logging::debug("Sparse output:"); + Logging::debug( array_filter($p_msg) ); + } + + public static function enablePropelLogging() + { + $logger = Logging::getLogger(); + Propel::setLogger($logger); + + $con = Propel::getConnection(); + $con->useDebug(true); + + $config = Propel::getConfiguration(PropelConfiguration::TYPE_OBJECT); + $config->setParameter('debugpdo.logging.details.method.enabled', true); + $config->setParameter('debugpdo.logging.details.time.enabled', true); + $config->setParameter('debugpdo.logging.details.mem.enabled', true); + } + + public static function disablePropelLogging() + { + $con = Propel::getConnection(); + $con->useDebug(false); + Propel::setLogger(null); + } + } diff --git a/airtime_mvc/application/models/Auth.php b/airtime_mvc/application/models/Auth.php index cc3cfe4cf..2aef1ce81 100644 --- a/airtime_mvc/application/models/Auth.php +++ b/airtime_mvc/application/models/Auth.php @@ -1,53 +1,55 @@ setDbUserId($user_id); - $info->setDbAction($action); - $info->setDbToken(sha1($token.$salt)); - $info->setDbCreated(gmdate('Y-m-d H:i:s')); - $info->save(); - - Logging::debug("generated token {$token}"); - - return $token; - } - - public function sendPasswordRestoreLink($user, $view) - { +class Application_Model_Auth +{ + const TOKEN_LIFETIME = 'P2D'; // DateInterval syntax + + private function generateToken($action, $user_id) + { + $salt = md5("pro"); + $token = self::generateRandomString(); + + $info = new CcSubjsToken(); + $info->setDbUserId($user_id); + $info->setDbAction($action); + $info->setDbToken(sha1($token.$salt)); + $info->setDbCreated(gmdate('Y-m-d H:i:s')); + $info->save(); + + Logging::debug("generated token {$token}"); + + return $token; + } + + public function sendPasswordRestoreLink($user, $view) + { $token = $this->generateToken('password.restore', $user->getDbId()); - + $e_link_protocol = empty($_SERVER['HTTPS']) ? "http" : "https"; $e_link_base = $_SERVER['SERVER_NAME']; + $e_link_port = $_SERVER['SERVER_PORT']; $e_link_path = $view->url(array('user_id' => $user->getDbId(), 'token' => $token), 'password-change'); - - $message = "Click this link: {$e_link_protocol}://{$e_link_base}{$e_link_path}"; - - $success = Application_Model_Email::send('Airtime Password Reset', $message, $user->getDbEmail()); - - return $success; - } - - public function invalidateTokens($user, $action) - { - CcSubjsTokenQuery::create() - ->filterByDbAction($action) - ->filterByDbUserId($user->getDbId()) - ->delete(); - } - + + $message = "Hi {$user->getDbLogin()}, \n\nClick this link to reset your password: "; + $message .= "{$e_link_protocol}://{$e_link_base}:{$e_link_port}{$e_link_path}"; + + $success = Application_Model_Email::send('Airtime Password Reset', $message, $user->getDbEmail()); + + return $success; + } + + public function invalidateTokens($user, $action) + { + CcSubjsTokenQuery::create() + ->filterByDbAction($action) + ->filterByDbUserId($user->getDbId()) + ->delete(); + } + public function checkToken($user_id, $token, $action) { - $salt = md5("pro"); - + $salt = md5("pro"); + $token_info = CcSubjsTokenQuery::create() ->filterByDbAction($action) ->filterByDbUserId($user_id) @@ -61,10 +63,10 @@ class Application_Model_Auth { $now = new DateTime(); $token_life = new DateInterval(self::TOKEN_LIFETIME); $token_created = new DateTime($token_info->getDbCreated(), new DateTimeZone("UTC")); - + return $now->sub($token_life)->getTimestamp() < $token_created->getTimestamp(); - } - + } + /** * Gets the adapter for authentication against a database table * @@ -79,15 +81,15 @@ class Application_Model_Auth { ->setIdentityColumn('login') ->setCredentialColumn('pass') ->setCredentialTreatment('MD5(?)'); - + return $authAdapter; } - + /** * Get random string * - * @param int $length - * @param string $allowed_chars + * @param int $length + * @param string $allowed_chars * @return string */ final public function generateRandomString($length = 12, $allowed_chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') diff --git a/airtime_mvc/application/models/Block.php b/airtime_mvc/application/models/Block.php new file mode 100644 index 000000000..eb1aab691 --- /dev/null +++ b/airtime_mvc/application/models/Block.php @@ -0,0 +1,1388 @@ + "", + "pos" => "", + "cliplength" => "", + "cuein" => "00:00:00", + "cueout" => "00:00:00", + "fadein" => "0.0", + "fadeout" => "0.0", + ); + + //using propel's phpNames. + private $categories = array( + "dc:title" => "Name", + "dc:creator" => "Creator", + "dc:description" => "Description", + "dcterms:extent" => "Length" + ); + + private static $modifier2CriteriaMap = array( + "contains" => Criteria::ILIKE, + "does not contain" => Criteria::NOT_ILIKE, + "is" => Criteria::EQUAL, + "is not" => Criteria::NOT_EQUAL, + "starts with" => Criteria::ILIKE, + "ends with" => Criteria::ILIKE, + "is greater than" => Criteria::GREATER_THAN, + "is less than" => Criteria::LESS_THAN, + "is in the range" => Criteria::CUSTOM); + + private static $criteria2PeerMap = array( + 0 => "Select criteria", + "album_title" => "DbAlbumTitle", + "artist_name" => "DbArtistName", + "bit_rate" => "DbBitRate", + "bpm" => "DbBpm", + "composer" => "DbComposer", + "conductor" => "DbConductor", + "copyright" => "DbCopyright", + "encoded_by" => "DbEncodedBy", + "utime" => "DbUtime", + "mtime" => "DbMtime", + "lptime" => "DbLPtime", + "genre" => "DbGenre", + "info_url" => "DbInfoUrl", + "isrc_number" => "DbIsrcNumber", + "label" => "DbLabel", + "language" => "DbLanguage", + "length" => "DbLength", + "mime" => "DbMime", + "mood" => "DbMood", + "owner_id" => "DbOwnerId", + "replay_gain" => "DbReplayGain", + "sample_rate" => "DbSampleRate", + "track_title" => "DbTrackTitle", + "track_number" => "DbTrackNumber", + "year" => "DbYear" + ); + + public function __construct($id=null, $con=null) + { + if (isset($id)) { + $this->block = CcBlockQuery::create()->findPk($id); + + if (is_null($this->block)) { + throw new BlockNotFoundException(); + } + } else { + $this->block = new CcBlock(); + $this->block->setDbUTime(new DateTime("now", new DateTimeZone("UTC"))); + $this->block->save(); + } + + $defaultFade = Application_Model_Preference::GetDefaultFade(); + if ($defaultFade !== "") { + //fade is in format SS.uuuuuu + + $this->blockItem["fadein"] = $defaultFade; + $this->blockItem["fadeout"] = $defaultFade; + } + + $this->con = isset($con) ? $con : Propel::getConnection(CcBlockPeer::DATABASE_NAME); + $this->id = $this->block->getDbId(); + } + + /** + * Return local ID of virtual file. + * + * @return int + */ + public function getId() + { + return $this->id; + } + + /** + * Rename stored virtual block + * + * @param string $p_newname + */ + public function setName($p_newname) + { + $this->block->setDbName($p_newname); + $this->block->setDbMtime(new DateTime("now", new DateTimeZone("UTC"))); + $this->block->save($this->con); + } + + /** + * Get mnemonic block name + * + * @return string + */ + public function getName() + { + return $this->block->getDbName(); + } + + public function setDescription($p_description) + { + $this->block->setDbDescription($p_description); + $this->block->setDbMtime(new DateTime("now", new DateTimeZone("UTC"))); + $this->block->save($this->con); + } + + public function getDescription() + { + return $this->block->getDbDescription(); + } + + public function getCreator() + { + return $this->block->getCcSubjs()->getDbLogin(); + } + + public function getCreatorId() + { + return $this->block->getCcSubjs()->getDbId(); + } + + public function setCreator($p_id) + { + $this->block->setDbCreatorId($p_id); + $this->block->setDbMtime(new DateTime("now", new DateTimeZone("UTC"))); + $this->block->save($this->con); + } + + public function getLastModified($format = null) + { + return $this->block->getDbMtime($format); + } + + public function getSize() + { + return $this->block->countCcBlockcontentss(); + } + + /** + * Get the entire block as a two dimentional array, sorted in order of play. + * @param boolean $filterFiles if this is true, it will only return files that has + * file_exists flag set to true + * @return array + */ + public function getContents($filterFiles=false) + { + Logging::info("Getting contents for block {$this->id}"); + + $sql = <<$this->id)); + + $offset = 0; + foreach ($rows as &$row) { + + $clipSec = Application_Common_DateHelper::playlistTimeToSeconds($row['length']); + $offset += $clipSec; + $offset_cliplength = Application_Common_DateHelper::secondsToPlaylistTime($offset); + + //format the length for UI. + $formatter = new LengthFormatter($row['length']); + $row['length'] = $formatter->format(); + + $formatter = new LengthFormatter($offset_cliplength); + $row['offset'] = $formatter->format(); + + //format the fades in format 00(.0) + $fades = $this->getFadeInfo($row['position']); + $row['fadein'] = $fades[0]; + $row['fadeout'] = $fades[1]; + + // format the cues in format 00:00:00(.0) + // we need to add the '.0' for cues and not fades + // because propel takes care of this for us + // (we use propel to fetch the fades) + $row['cuein'] = str_pad(substr($row['cuein'], 0, 10), 10, '.0'); + $row['cueout'] = str_pad(substr($row['cueout'], 0, 10), 10, '.0'); + + //format original length + $formatter = new LengthFormatter($row['orig_length']); + $row['orig_length'] = $formatter->format(); + } + + return $rows; + } + + /** + * The database stores fades in 00:00:00 Time format with optional millisecond resolution .000000 + * but this isn't practical since fades shouldn't be very long usuall 1 second or less. This function + * will normalize the fade so that it looks like 00.000000 to the user. + **/ + public function normalizeFade($fade) + { + //First get rid of the first six characters 00:00: which will be added back later for db update + $fade = substr($fade, 6); + + //Second add .000000 if the fade does't have milliseconds format already + $dbFadeStrPos = strpos( $fade, '.' ); + if ( $dbFadeStrPos === False ) + $fade .= '.000000'; + else + while( strlen( $fade ) < 9 ) + $fade .= '0'; + + //done, just need to set back the formated values + return $fade; + } + + public function getUnformatedLength() + { + $this->block->reload(); + if ($this->isStatic()) { + $length = $this->block->getDbLength(); + } else { + $length = $this->getDynamicBlockLength(); + } + + return $length; + } + + public function getLength() + { + $this->block->reload(); + $prepend = ""; + if ($this->isStatic()) { + $length = $this->block->getDbLength(); + } else { + $length = $this->getDynamicBlockLength(); + if (!$this->hasItemLimit()) { + $prepend = "~"; + } + } + $formatter = new LengthFormatter($length); + $length = $prepend.$formatter->format(); + + return $length; + } + + public function getDynamicBlockLength() + { + list($value, $modifier) = $this->getLimitValueAndModifier(); + if ($modifier == "items") { + $length = $value." ".$modifier; + } else { + $hour = "00"; + if ($modifier == "minutes") { + if ($value >59) { + $hour = intval($value/60); + $value = $value%60; + + } + } elseif ($modifier == "hours") { + $mins = $value * 60; + if ($mins >59) { + $hour = intval($mins/60); + $hour = str_pad($hour, 2, "0", STR_PAD_LEFT); + $mins = $mins%60; + } + } + $hour = str_pad($hour, 2, "0", STR_PAD_LEFT); + $mins = str_pad($mins, 2, "0", STR_PAD_LEFT); + $length = $hour.":".$mins.":00"; + } + + return $length; + } + + public function getLimitValueAndModifier() + { + $result = CcBlockcriteriaQuery::create()->filterByDbBlockId($this->id) + ->filterByDbCriteria('limit')->findOne(); + $modifier = $result->getDbModifier(); + $value = $result->getDbValue(); + + return array($value, $modifier); + } + + // this function returns sum of all track length under this block. + public function getStaticLength() + { + $sql = <<$this->id), 'all', PDO::FETCH_NUM); + return $result[0][0]; + } + + private function insertBlockElement($info) + { + $row = new CcBlockcontents(); + $row->setDbBlockId($this->id); + $row->setDbFileId($info["id"]); + $row->setDbPosition($info["pos"]); + $row->setDbCliplength($info["cliplength"]); + $row->setDbCuein($info["cuein"]); + $row->setDbCueout($info["cueout"]); + $row->setDbFadein($info["fadein"]); + $row->setDbFadeout($info["fadeout"]); + $row->save($this->con); + // above save result update on cc_block table on length column. + // but $this->block doesn't get updated automatically + // so we need to manually grab it again from DB so it has updated values + // It is something to do FORMAT_ON_DEMAND( Lazy Loading ) + $this->block = CcBlockQuery::create()->findPK($this->id); + } + + /* + * + */ + private function buildEntry($p_item, $pos) + { + $file = CcFilesQuery::create()->findPK($p_item, $this->con); + + if (isset($file) && $file->getDbFileExists()) { + $entry = $this->blockItem; + $entry["id"] = $file->getDbId(); + $entry["pos"] = $pos; + $entry["cliplength"] = $file->getDbLength(); + $entry["cueout"] = $file->getDbLength(); + + return $entry; + } else { + throw new Exception("trying to add a file that does not exist."); + } + } + + public function isStatic() + { + if ($this->block->getDbType() == "static") { + return true; + } else { + return false; + } + } + + /* + * @param array $p_items + * an array of audioclips to add to the block + * @param int|null $p_afterItem + * item which to add the new items after in the block, null if added to the end. + * @param string (before|after) $addAfter + * whether to add the clips before or after the selected item. + */ + public function addAudioClips($p_items, $p_afterItem=NULL, $addType = 'after') + { + $this->con->beginTransaction(); + $contentsToUpdate = array(); + + try { + + if (is_numeric($p_afterItem)) { + Logging::info("Finding block content item {$p_afterItem}"); + + $afterItem = CcBlockcontentsQuery::create()->findPK($p_afterItem); + $index = $afterItem->getDbPosition(); + Logging::info("index is {$index}"); + $pos = ($addType == 'after') ? $index + 1 : $index; + + $contentsToUpdate = CcBlockcontentsQuery::create() + ->filterByDbBlockId($this->id) + ->filterByDbPosition($pos, Criteria::GREATER_EQUAL) + ->orderByDbPosition() + ->find($this->con); + + Logging::info("Adding to block"); + Logging::info("at position {$pos}"); + } else { + + //add to the end of the block + if ($addType == 'after') { + $pos = $this->getSize(); + } + //add to the beginning of the block. + else { + $pos = 0; + + $contentsToUpdate = CcBlockcontentsQuery::create() + ->filterByDbBlockId($this->id) + ->orderByDbPosition() + ->find($this->con); + } + + $contentsToUpdate = CcBlockcontentsQuery::create() + ->filterByDbBlockId($this->id) + ->filterByDbPosition($pos, Criteria::GREATER_EQUAL) + ->orderByDbPosition() + ->find($this->con); + + Logging::info("Adding to block"); + Logging::info("at position {$pos}"); + } + + foreach ($p_items as $ac) { + Logging::info("Adding audio file {$ac}"); + try { + if (is_array($ac) && $ac[1] == 'audioclip') { + $res = $this->insertBlockElement($this->buildEntry($ac[0], $pos)); + $pos = $pos + 1; + } elseif (!is_array($ac)) { + $res = $this->insertBlockElement($this->buildEntry($ac, $pos)); + $pos = $pos + 1; + } + } catch (Exception $e) { + Logging::info($e->getMessage()); + } + } + + //reset the positions of the remaining items. + for ($i = 0; $i < count($contentsToUpdate); $i++) { + $contentsToUpdate[$i]->setDbPosition($pos); + $contentsToUpdate[$i]->save($this->con); + $pos = $pos + 1; + } + + $this->block->setDbMtime(new DateTime("now", new DateTimeZone("UTC"))); + $this->block->save($this->con); + + $this->con->commit(); + + $this->updateBlockLengthInAllPlaylist(); + + } catch (Exception $e) { + $this->con->rollback(); + throw $e; + } + } + + /** + * Move audioClip to the new position in the block + * + * @param array $p_items + * array of unique ids of the selected items + * @param int $p_afterItem + * unique id of the item to move the clip after + */ + public function moveAudioClips($p_items, $p_afterItem=NULL) + { + $this->con->beginTransaction(); + + try { + + $contentsToMove = CcBlockcontentsQuery::create() + ->filterByDbId($p_items, Criteria::IN) + ->orderByDbPosition() + ->find($this->con); + + $otherContent = CcBlockcontentsQuery::create() + ->filterByDbId($p_items, Criteria::NOT_IN) + ->filterByDbBlockId($this->id) + ->orderByDbPosition() + ->find($this->con); + + $pos = 0; + //moving items to beginning of the block. + if (is_null($p_afterItem)) { + Logging::info("moving items to beginning of block"); + + foreach ($contentsToMove as $item) { + Logging::info("item {$item->getDbId()} to pos {$pos}"); + $item->setDbPosition($pos); + $item->save($this->con); + $pos = $pos + 1; + } + foreach ($otherContent as $item) { + Logging::info("item {$item->getDbId()} to pos {$pos}"); + $item->setDbPosition($pos); + $item->save($this->con); + $pos = $pos + 1; + } + } else { + Logging::info("moving items after {$p_afterItem}"); + + foreach ($otherContent as $item) { + Logging::info("item {$item->getDbId()} to pos {$pos}"); + $item->setDbPosition($pos); + $item->save($this->con); + $pos = $pos + 1; + + if ($item->getDbId() == $p_afterItem) { + foreach ($contentsToMove as $move) { + Logging::info("item {$move->getDbId()} to pos {$pos}"); + $move->setDbPosition($pos); + $move->save($this->con); + $pos = $pos + 1; + } + } + } + } + + $this->con->commit(); + } catch (Exception $e) { + $this->con->rollback(); + throw $e; + } + + $this->block = CcBlockQuery::create()->findPK($this->id); + $this->block->setDbMtime(new DateTime("now", new DateTimeZone("UTC"))); + $this->block->save($this->con); + } + + /** + * Remove audioClip from block + * + * @param array $p_items + * array of unique item ids to remove from the block.. + */ + public function delAudioClips($p_items) + { + + $this->con->beginTransaction(); + + try { + + CcBlockcontentsQuery::create() + ->findPKs($p_items) + ->delete($this->con); + + $contents = CcBlockcontentsQuery::create() + ->filterByDbBlockId($this->id) + ->orderByDbPosition() + ->find($this->con); + + //reset the positions of the remaining items. + for ($i = 0; $i < count($contents); $i++) { + $contents[$i]->setDbPosition($i); + $contents[$i]->save($this->con); + } + + $this->block->setDbMtime(new DateTime("now", new DateTimeZone("UTC"))); + $this->block->save($this->con); + + $this->con->commit(); + + $this->updateBlockLengthInAllPlaylist(); + + } catch (Exception $e) { + $this->con->rollback(); + throw $e; + } + } + + public function getFadeInfo($pos) + { + Logging::info("Getting fade info for pos {$pos}"); + + $row = CcBlockcontentsQuery::create() + ->joinWith(CcFilesPeer::OM_CLASS) + ->filterByDbBlockId($this->id) + ->filterByDbPosition($pos) + ->findOne(); + + + + //Propel returns values in form 00.000000 format which is for only seconds. + //We only want to display 1 decimal + $fadeIn = substr($row->getDbFadein(), 0, 4); + $fadeOut = substr($row->getDbFadeout(), 0, 4); + + return array($fadeIn, $fadeOut); + } + + /** + * Change fadeIn and fadeOut values for block Element + * + * @param int $pos + * position of audioclip in block + * @param string $fadeIn + * new value in ss.ssssss or extent format + * @param string $fadeOut + * new value in ss.ssssss or extent format + * @return boolean + */ + public function changeFadeInfo($id, $fadeIn, $fadeOut) + { + //See issue CC-2065, pad the fadeIn and fadeOut so that it is TIME compatable with the DB schema + //For the top level PlayList either fadeIn or fadeOut will sometimes be Null so need a gaurd against + //setting it to nonNull for checks down below + $fadeIn = $fadeIn?'00:00:'.$fadeIn:$fadeIn; + $fadeOut = $fadeOut?'00:00:'.$fadeOut:$fadeOut; + + $this->con->beginTransaction(); + + try { + $row = CcBlockcontentsQuery::create()->findPK($id); + + if (is_null($row)) { + throw new Exception("Block item does not exist."); + } + + $clipLength = $row->getDbCliplength(); + + if (!is_null($fadeIn)) { + + $sql = "SELECT :fade_in::INTERVAL > :clip_length::INTERVAL"; + $params = array( + ':fade_in' => $fadeIn, + ':clip_length' => $clipLength + ); + + $result = Application_Common_Database::prepareAndExecute($sql, $params, 'column'); + if ($result) { + //"Fade In can't be larger than overall playlength."; + $fadeIn = $clipLength; + } + $row->setDbFadein($fadeIn); + + } + if (!is_null($fadeOut)) { + + $sql = "SELECT :fade_out::INTERVAL > :clip_length::INTERVAL"; + $params = array( + ':fade_out' => $fadeOut, + ':clip_length' => $clipLength + ); + + $result = Application_Common_Database::prepareAndExecute($sql, $params, 'column'); + if ($result) { + //"Fade Out can't be larger than overall playlength."; + $fadeOut = $clipLength; + } + $row->setDbFadeout($fadeOut); + } + + $row->save($this->con); + $this->block->setDbMtime(new DateTime("now", new DateTimeZone("UTC"))); + $this->block->save($this->con); + + $this->con->commit(); + } catch (Exception $e) { + $this->con->rollback(); + throw $e; + } + + return array("fadeIn" => $fadeIn, "fadeOut" => $fadeOut); + } + + public function setfades($fadein, $fadeout) + { + if (isset($fadein)) { + Logging::info("Setting block fade in {$fadein}"); + $row = CcBlockcontentsQuery::create() + ->filterByDbBlockId($this->id) + ->filterByDbPosition(0) + ->findOne($this->con); + + $this->changeFadeInfo($row->getDbId(), $fadein, null); + } + + if (isset($fadeout)) { + Logging::info("Setting block fade out {$fadeout}"); + $row = CcBlockcontentsQuery::create() + ->filterByDbBlockId($this->id) + ->filterByDbPosition($this->getSize()-1) + ->findOne($this->con); + + $this->changeFadeInfo($row->getDbId(), null, $fadeout); + } + } + + /** + * Change cueIn/cueOut values for block element + * + * @param int $pos + * position of audioclip in block + * @param string $cueIn + * new value in ss.ssssss or extent format + * @param string $cueOut + * new value in ss.ssssss or extent format + * @return boolean or pear error object + */ + public function changeClipLength($id, $cueIn, $cueOut) + { + $this->con->beginTransaction(); + + $errArray= array(); + + try { + if (is_null($cueIn) && is_null($cueOut)) { + $errArray["error"] = "Cue in and cue out are null."; + + return $errArray; + } + + $row = CcBlockcontentsQuery::create() + ->joinWith(CcFilesPeer::OM_CLASS) + ->filterByPrimaryKey($id) + ->findOne($this->con); + + if (is_null($row)) { + throw new Exception("Block item does not exist."); + } + + $oldCueIn = $row->getDBCuein(); + $oldCueOut = $row->getDbCueout(); + $fadeIn = $row->getDbFadein(); + $fadeOut = $row->getDbFadeout(); + + $file = $row->getCcFiles($this->con); + $origLength = $file->getDbLength(); + + if (!is_null($cueIn) && !is_null($cueOut)) { + + if ($cueOut === "") { + $cueOut = $origLength; + } + + $sql = "SELECT :cue_out::INTERVAL > :orig_length::INTERVAL"; + $params = array( + ':cue_out' => $cueOut, + ':orig_length' => $origLength + ); + $result = Application_Common_Database::prepareAndExecute($sql, $params, 'column'); + if ($result) { + $errArray["error"] = "Can't set cue out to be greater than file length."; + return $errArray; + } + + $sql = "SELECT :cue_in::INTERVAL > :cue_out::INTERVAL"; + $params = array( + ':cue_in' => $cueIn, + ':cue_out' => $cueOut + ); + $result = Application_Common_Database::prepareAndExecute($sql, $params, 'column'); + if ($result) { + $errArray["error"] = "Can't set cue in to be larger than cue out."; + return $errArray; + } + + $sql = "SELECT :cue_out::INTERVAL - :cue_in::INTERVAL"; + $result = Application_Common_Database::prepareAndExecute($sql, $params, 'column'); + $cliplength = $result; + + $row->setDbCuein($cueIn); + $row->setDbCueout($cueOut); + $row->setDBCliplength($cliplength); + + } elseif (!is_null($cueIn)) { + + $sql = "SELECT :cue_in::INTERVAL > :old_cue_out::INTERVAL"; + $params = array( + ':cue_in' => $cueIn, + ':old_cue_out' => $oldCueOut + ); + $result = Application_Common_Database::prepareAndExecute($sql, $params, 'column'); + if ($result) { + $errArray["error"] = "Can't set cue in to be larger than cue out."; + return $errArray; + } + + $sql = "SELECT :old_cue_out::INTERVAL - :cue_in::INTERVAL"; + $result = Application_Common_Database::prepareAndExecute($sql, $params, 'column'); + $cliplength = $result; + + $row->setDbCuein($cueIn); + $row->setDBCliplength($cliplength); + + } elseif (!is_null($cueOut)) { + + if ($cueOut === "") { + $cueOut = $origLength; + } + + $sql = "SELECT :cue_out::INTERVAL > :orig_length::INTERVAL"; + $params = array( + ':cue_out' => $cueOut, + ':orig_length' => $origLength + ); + $result = Application_Common_Database::prepareAndExecute($sql, $params, 'column'); + if ($result) { + $errArray["error"] = "Can't set cue out to be greater than file length."; + return $errArray; + } + + $sql = "SELECT :cue_out::INTERVAL < :old_cue_in::INTERVAL"; + $params = array( + ':cue_out' => $cueOut, + ':old_cue_in' => $oldCueIn + ); + $result = Application_Common_Database::prepareAndExecute($sql, $params, 'column'); + if ($result) { + $errArray["error"] = "Can't set cue out to be smaller than cue in."; + return $errArray; + } + + $sql = "SELECT :cue_out::INTERVAL - :old_cue_in::INTERVAL"; + $result = Application_Common_Database::prepareAndExecute($sql, $params, 'column'); + $cliplength = $result; + + $row->setDbCueout($cueOut); + $row->setDBCliplength($cliplength); + } + + $cliplength = $row->getDbCliplength(); + + $sql = "SELECT :fade_in::INTERVAL > :clip_length::INTERVAL"; + $params = array( + ':fade_in' => $fadeIn, + ':clip_length' => $cliplength + ); + $result = Application_Common_Database::prepareAndExecute($sql, $params, 'column'); + if ($result) { + $fadeIn = $cliplength; + $row->setDbFadein($fadeIn); + } + + $sql = "SELECT :fade_out::INTERVAL > :clip_length::INTERVAL"; + $params = array( + ':fade_out' => $fadeOut, + ':clip_length' => $cliplength + ); + $result = Application_Common_Database::prepareAndExecute($sql, $params, 'column'); + if ($result) { + $fadeOut = $cliplength; + $row->setDbFadein($fadeOut); + } + + $row->save($this->con); + $this->block->setDbMtime(new DateTime("now", new DateTimeZone("UTC"))); + $this->block->save($this->con); + + $this->con->commit(); + } catch (Exception $e) { + $this->con->rollback(); + throw $e; + } + + return array("cliplength"=> $cliplength, "cueIn"=> $cueIn, "cueOut"=> $cueOut, "length"=> $this->getUnformatedLength(), + "fadeIn"=> $fadeIn, "fadeOut"=> $fadeOut); + } + + public function getAllPLMetaData() + { + $categories = $this->categories; + $md = array(); + + foreach ($categories as $key => $val) { + $method = 'get' . $val; + $md[$key] = $this->$method(); + } + + return $md; + } + + public function getMetaData($category) + { + $cat = $this->categories[$category]; + $method = 'get' . $cat; + + return $this->$method(); + } + + public function setMetadata($category, $value) + { + $cat = $this->categories[$category]; + + $method = 'set' . $cat; + $this->$method($value); + } + + public static function getBlockCount() + { + global $CC_CONFIG; + $con = Propel::getConnection(); + $sql = 'SELECT count(*) as cnt FROM '.$CC_CONFIG["playListTable"]; + + return $con->query($sql)->fetchColumn(0); + } + + /** + * Delete the file from all blocks. + * @param string $p_fileId + */ + public static function DeleteFileFromAllBlocks($p_fileId) + { + CcBlockcontentsQuery::create()->filterByDbFileId($p_fileId)->delete(); + } + + /** + * Delete blocks that match the ids.. + * @param array $p_ids + */ + public static function deleteBlocks($p_ids, $p_userId) + { + $userInfo = Zend_Auth::getInstance()->getStorage()->read(); + $user = new Application_Model_User($userInfo->id); + $isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER)); + + if (!$isAdminOrPM) { + $leftOver = self::blocksNotOwnedByUser($p_ids, $p_userId); + + if (count($leftOver) == 0) { + CcBlockQuery::create()->findPKs($p_ids)->delete(); + } else { + throw new BlockNoPermissionException; + } + } else { + CcBlockQuery::create()->findPKs($p_ids)->delete(); + } + } + + // This function returns that are not owen by $p_user_id among $p_ids + private static function blocksNotOwnedByUser($p_ids, $p_userId) + { + $ownedByUser = CcBlockQuery::create()->filterByDbCreatorId($p_userId)->find()->getData(); + $selectedPls = $p_ids; + $ownedPls = array(); + foreach ($ownedByUser as $pl) { + if (in_array($pl->getDbId(), $selectedPls)) { + $ownedPls[] = $pl->getDbId(); + } + } + + $leftOvers = array_diff($selectedPls, $ownedPls); + + return $leftOvers; + } + + /** + * Delete all files from block + */ + public function deleteAllFilesFromBlock() + { + CcBlockcontentsQuery::create()->findByDbBlockId($this->id)->delete(); + $this->block->reload(); + } + + // smart block functions start + public function shuffleSmartBlock() + { + // if it here that means it's static pl + $this->saveType("static"); + $contents = CcBlockcontentsQuery::create() + ->filterByDbBlockId($this->id) + ->orderByDbPosition() + ->find(); + $shuffledPos = range(0, count($contents)-1); + shuffle($shuffledPos); + foreach ($contents as $item) { + $item->setDbPosition(array_shift($shuffledPos)); + $item->save(); + } + + return array("result"=>0); + } + + public function saveType($p_blockType) + { + // saving dynamic/static flag + CcBlockQuery::create()->findPk($this->id)->setDbType($p_blockType)->save(); + } + + public function setLength($value) + { + $this->block->setDbLength($value); + $this->block->save($this->con); + $this->updateBlockLengthInAllPlaylist(); + } + + + /** + * Saves smart block criteria + * @param array $p_criteria + */ + public function saveSmartBlockCriteria($p_criteria) + { + $data = $this->organizeSmartPlyalistCriteria($p_criteria); + // saving dynamic/static flag + $blockType = $data['etc']['sp_type'] == 0 ? 'static':'dynamic'; + $this->saveType($blockType); + $this->storeCriteriaIntoDb($data); + + // if the block is dynamic, put null to the length + // as it cannot be calculated + if ($blockType == 'dynamic') { + if ($this->hasItemLimit()) { + $this->setLength(null); + } else { + $this->setLength($this->getDynamicBlockLength()); + } + } else { + $length = $this->getStaticLength(); + if (!$length) { + $length = "00:00:00"; + } + $this->setLength($length); + } + + $this->updateBlockLengthInAllPlaylist(); + } + + public function hasItemLimit() + { + list($value, $modifier) = $this->getLimitValueAndModifier(); + return ($modifier == 'items'); + } + + public function storeCriteriaIntoDb($p_criteriaData) + { + // delete criteria under $p_blockId + CcBlockcriteriaQuery::create()->findByDbBlockId($this->id)->delete(); + //Logging::info($p_criteriaData); + //insert modifier rows + if (isset($p_criteriaData['criteria'])) { + $critKeys = array_keys($p_criteriaData['criteria']); + for ($i = 0; $i < count($critKeys); $i++) { + foreach ($p_criteriaData['criteria'][$critKeys[$i]] as $d) { + $qry = new CcBlockcriteria(); + $qry->setDbCriteria($d['sp_criteria_field']) + ->setDbModifier($d['sp_criteria_modifier']) + ->setDbValue($d['sp_criteria_value']) + ->setDbBlockId($this->id); + + if (isset($d['sp_criteria_extra'])) { + $qry->setDbExtra($d['sp_criteria_extra']); + } + $qry->save(); + } + } + } + + // insert limit info + $qry = new CcBlockcriteria(); + $qry->setDbCriteria("limit") + ->setDbModifier($p_criteriaData['etc']['sp_limit_options']) + ->setDbValue($p_criteriaData['etc']['sp_limit_value']) + ->setDbBlockId($this->id) + ->save(); + } + + /** + * generate list of tracks. This function saves creiteria and generate + * tracks. + * @param array $p_criteria + */ + public function generateSmartBlock($p_criteria, $returnList=false) + { + $this->saveSmartBlockCriteria($p_criteria); + $insertList = $this->getListOfFilesUnderLimit(); + $this->deleteAllFilesFromBlock(); + $this->addAudioClips(array_keys($insertList)); + // update length in playlist contents. + $this->updateBlockLengthInAllPlaylist(); + + return array("result"=>0); + } + + public function updateBlockLengthInAllPlaylist() + { + $blocks = CcPlaylistcontentsQuery::create()->filterByDbBlockId($this->id)->find(); + $blocks->getFirst(); + $iterator = $blocks->getIterator(); + while ($iterator->valid()) { + $length = $this->getUnformatedLength(); + if (!preg_match("/^[0-9]{2}:[0-9]{2}:[0-9]{2}/", $length)) { + $iterator->current()->setDbClipLength(null); + } else { + $iterator->current()->setDbClipLength($length); + } + $iterator->current()->save(); + $iterator->next(); + } + } + + public function getListOfFilesUnderLimit() + { + $info = $this->getListofFilesMeetCriteria(); + $files = $info['files']; + $limit = $info['limit']; + + $insertList = array(); + $totalTime = 0; + $totalItems = 0; + + // this moves the pointer to the first element in the collection + $files->getFirst(); + $iterator = $files->getIterator(); + while ($iterator->valid() && $totalTime < $limit['time']) { + $id = $iterator->current()->getDbId(); + $length = Application_Common_DateHelper::calculateLengthInSeconds($iterator->current()->getDbLength()); + $insertList[$id] = $length; + $totalTime += $length; + $totalItems++; + + if ((!is_null($limit['items']) && $limit['items'] == count($insertList)) || $totalItems > 500) { + break; + } + + $iterator->next(); + } + + return $insertList; + } + + public function getCriteria() + { + $criteriaOptions = array( + 0 => "Select criteria", + "album_title" => "Album", + "bit_rate" => "Bit Rate (Kbps)", + "bpm" => "BPM", + "composer" => "Composer", + "conductor" => "Conductor", + "copyright" => "Copyright", + "artist_name" => "Creator", + "encoded_by" => "Encoded By", + "genre" => "Genre", + "isrc_number" => "ISRC", + "label" => "Label", + "language" => "Language", + "mtime" => "Last Modified", + "lptime" => "Last Played", + "length" => "Length", + "mime" => "Mime", + "mood" => "Mood", + "owner_id" => "Owner", + "replay_gain" => "Replay Gain", + "sample_rate" => "Sample Rate (kHz)", + "track_title" => "Title", + "track_number" => "Track Number", + "utime" => "Uploaded", + "info_url" => "Website", + "year" => "Year" + ); + + // Load criteria from db + $out = CcBlockcriteriaQuery::create()->orderByDbCriteria()->findByDbBlockId($this->id); + $storedCrit = array(); + + foreach ($out as $crit) { + $criteria = $crit->getDbCriteria(); + $modifier = $crit->getDbModifier(); + $value = $crit->getDbValue(); + $extra = $crit->getDbExtra(); + + if ($criteria == "limit") { + $storedCrit["limit"] = array("value"=>$value, "modifier"=>$modifier); + } else { + $storedCrit["crit"][$criteria][] = array("criteria"=>$criteria, "value"=>$value, "modifier"=>$modifier, "extra"=>$extra, "display_name"=>$criteriaOptions[$criteria]); + } + } + + return $storedCrit; + + } + + // this function return list of propel object + public function getListofFilesMeetCriteria() + { + $storedCrit = $this->getCriteria(); + + $qry = CcFilesQuery::create(); + $qry->useFkOwnerQuery("subj", "left join"); + + if (isset($storedCrit["crit"])) { + foreach ($storedCrit["crit"] as $crit) { + $i = 0; + foreach ($crit as $criteria) { + //$spCriteriaPhpName = self::$criteria2PeerMap[$criteria['criteria']]; + $spCriteria = $criteria['criteria']; + $spCriteriaModifier = $criteria['modifier']; + + $column = CcFilesPeer::getTableMap()->getColumnByPhpName(self::$criteria2PeerMap[$spCriteria]); + // if the column is timestamp, convert it into UTC + if ($column->getType() == PropelColumnTypes::TIMESTAMP) { + $spCriteriaValue = Application_Common_DateHelper::ConvertToUtcDateTimeString($criteria['value']); + /* Check if only a date was supplied and trim + * the time after it is converted to UTC time + */ + if (strlen($criteria['value']) <= 10) { + //extract date only from timestamp in db + $spCriteria = 'date('.$spCriteria.')'; + $spCriteriaValue = substr($spCriteriaValue, 0, 10); + } + + if (isset($criteria['extra'])) { + $spCriteriaExtra = Application_Common_DateHelper::ConvertToUtcDateTimeString($criteria['extra']); + if (strlen($criteria['extra']) <= 10) { + $spCriteriaExtra = substr($spCriteriaExtra, 0, 10); + } + } + } elseif ($spCriteria == "bit_rate" || $spCriteria == 'sample_rate') { + // multiply 1000 because we store only number value + // e.g 192kps is stored as 192000 + $spCriteriaValue = $criteria['value']*1000; + if (isset($criteria['extra'])) { + $spCriteriaExtra = $criteria['extra']*1000; + } + /* + * If user is searching for an exact match of length we need to + * search as if it starts with the specified length because the + * user only sees the rounded version (i.e. 4:02.7 is 4:02.761625 + * in the database) + */ + } elseif ($spCriteria == 'length' && $spCriteriaModifier == "is") { + $spCriteriaModifier = "starts with"; + $spCriteria = $spCriteria.'::text'; + $spCriteriaValue = $criteria['value']; + } else { + /* Propel does not escape special characters properly when using LIKE/ILIKE + * We have to add extra slashes in these cases + */ + $tempModifier = trim(self::$modifier2CriteriaMap[$spCriteriaModifier]); + if ($tempModifier == 'ILIKE') { + $spCriteriaValue = addslashes($criteria['value']); + // addslashes() does not esapce '%' so we have to do it manually + $spCriteriaValue = str_replace('%', '\%', $spCriteriaValue); + } else { + $spCriteriaValue = ($criteria['value']); + } + + $spCriteriaExtra = $criteria['extra']; + } + + if ($spCriteriaModifier == "starts with") { + $spCriteriaValue = "$spCriteriaValue%"; + } elseif ($spCriteriaModifier == "ends with") { + $spCriteriaValue = "%$spCriteriaValue"; + } elseif ($spCriteriaModifier == "contains" || $spCriteriaModifier == "does not contain") { + $spCriteriaValue = "%$spCriteriaValue%"; + } elseif ($spCriteriaModifier == "is in the range") { + $spCriteriaValue = "$spCriteria >= '$spCriteriaValue' AND $spCriteria <= '$spCriteriaExtra'"; + } + + $spCriteriaModifier = self::$modifier2CriteriaMap[$spCriteriaModifier]; + + try { + if ($spCriteria == "owner_id") { + $spCriteria = "subj.login"; + } + if ($i > 0) { + $qry->addOr($spCriteria, $spCriteriaValue, $spCriteriaModifier); + } else { + $qry->add($spCriteria, $spCriteriaValue, $spCriteriaModifier); + } + + if ($spCriteriaModifier == Criteria::NOT_ILIKE || $spCriteriaModifier == Criteria::NOT_EQUAL) { + $qry->addOr($spCriteria, null, Criteria::ISNULL); + } + } catch (Exception $e) { + Logging::info($e); + } + $i++; + } + } + + // check if file exists + $qry->add("file_exists", "true", Criteria::EQUAL); + $qry->addAscendingOrderByColumn('random()'); + } + // construct limit restriction + $limits = array(); + if (isset($storedCrit['limit'])) { + if ($storedCrit['limit']['modifier'] == "items") { + $limits['time'] = 1440 * 60; + $limits['items'] = $storedCrit['limit']['value']; + } else { + $limits['time'] = $storedCrit['limit']['modifier'] == "hours" ? + intval(floatval($storedCrit['limit']['value']) * 60 * 60) : + intval($storedCrit['limit']['value'] * 60); + $limits['items'] = null; + } + } + try { + $out = $qry->setFormatter(ModelCriteria::FORMAT_ON_DEMAND)->find(); + + return array("files"=>$out, "limit"=>$limits, "count"=>$out->count()); + } catch (Exception $e) { + Logging::info($e); + } + } + + public static function organizeSmartPlyalistCriteria($p_criteria) + { + $fieldNames = array('sp_criteria_field', 'sp_criteria_modifier', 'sp_criteria_value', 'sp_criteria_extra'); + $output = array(); + foreach ($p_criteria as $ele) { + + $index = strrpos($ele['name'], '_'); + + /* Strip field name of modifier index + * Ex: sp_criteria_field_0_0 -> sp_criteria_field_0 + */ + $fieldName = substr($ele['name'], 0, $index); + + // Get criteria row index. + $tempName = $ele['name']; + // Get the last digit in the field name + preg_match('/^\D*(?=\d)/', $tempName, $r); + if (isset($r[0])) { + $critIndexPos = strlen($r[0]); + $critIndex = $tempName[$critIndexPos]; + } + $lastChar = substr($ele['name'], -1); + + // If lastChar is an integer we should strip it off + if (!preg_match("/^[a-zA-Z]$/", $lastChar)) { + /* Strip field name of criteria index + * Ex: sp_criteria_field_0 -> sp_criteria_field + * We do this to check if the field name is a criteria + * or the block type + */ + $n = strrpos($fieldName, '_'); + $fieldName = substr($fieldName, 0, $n); + } + + if (in_array($fieldName, $fieldNames)) { + $output['criteria'][$critIndex][$lastChar][$fieldName] = trim($ele['value']); + } else { + $output['etc'][$ele['name']] = $ele['value']; + } + } + + return $output; + } + // smart block functions end +} + +class BlockNotFoundException extends Exception {} +class BlockNoPermissionException extends Exception {} +class BlockOutDatedException extends Exception {} +class BlockDyanmicException extends Exception {} diff --git a/airtime_mvc/application/models/Dashboard.php b/airtime_mvc/application/models/Dashboard.php index 9236ab2c6..47265a922 100644 --- a/airtime_mvc/application/models/Dashboard.php +++ b/airtime_mvc/application/models/Dashboard.php @@ -3,7 +3,8 @@ class Application_Model_Dashboard { - public static function GetPreviousItem($p_timeNow){ + public static function GetPreviousItem($p_timeNow) + { //get previous show and previous item in the schedule table. //Compare the two and if the last show was recorded and started //after the last item in the schedule table, then return the show's @@ -12,8 +13,8 @@ class Application_Model_Dashboard $showInstance = Application_Model_ShowInstance::GetLastShowInstance($p_timeNow); $row = Application_Model_Schedule::GetLastScheduleItem($p_timeNow); - if (is_null($showInstance)){ - if (count($row) == 0){ + if (is_null($showInstance)) { + if (count($row) == 0) { return null; } else { return array("name"=>$row[0]["artist_name"]." - ".$row[0]["track_title"], @@ -22,8 +23,8 @@ class Application_Model_Dashboard } } else { - if (count($row) == 0){ - if ($showInstance->isRecorded()){ + if (count($row) == 0) { + if ($showInstance->isRecorded()) { //last item is a show instance return array("name"=>$showInstance->getName(), "starts"=>$showInstance->getShowInstanceStart(), @@ -33,7 +34,7 @@ class Application_Model_Dashboard } } else { //return the one that started later. - if ($row[0]["starts"] >= $showInstance->getShowInstanceStart()){ + if ($row[0]["starts"] >= $showInstance->getShowInstanceStart()) { return array("name"=>$row[0]["artist_name"]." - ".$row[0]["track_title"], "starts"=>$row[0]["starts"], "ends"=>$row[0]["ends"]); @@ -46,7 +47,8 @@ class Application_Model_Dashboard } } - public static function GetCurrentItem($p_timeNow){ + public static function GetCurrentItem($p_timeNow) + { //get previous show and previous item in the schedule table. //Compare the two and if the last show was recorded and started //after the last item in the schedule table, then return the show's @@ -54,26 +56,27 @@ class Application_Model_Dashboard $row = array(); $showInstance = Application_Model_ShowInstance::GetCurrentShowInstance($p_timeNow); - if (!is_null($showInstance)){ + if (!is_null($showInstance)) { $instanceId = $showInstance->getShowInstanceId(); $row = Application_Model_Schedule::GetCurrentScheduleItem($p_timeNow, $instanceId); } - if (is_null($showInstance)){ - if (count($row) == 0){ + if (is_null($showInstance)) { + if (count($row) == 0) { return null; } else { /* Should never reach here, but lets return the track information * just in case we allow tracks to be scheduled without a show * in the future. */ + return array("name"=>$row[0]["artist_name"]." - ".$row[0]["track_title"], "starts"=>$row[0]["starts"], "ends"=>$row[0]["ends"]); } } else { - if (count($row) == 0){ + if (count($row) == 0) { //last item is a show instance - if ($showInstance->isRecorded()){ + if ($showInstance->isRecorded()) { return array("name"=>$showInstance->getName(), "starts"=>$showInstance->getShowInstanceStart(), "ends"=>$showInstance->getShowInstanceEnd(), @@ -92,7 +95,8 @@ class Application_Model_Dashboard } } - public static function GetNextItem($p_timeNow){ + public static function GetNextItem($p_timeNow) + { //get previous show and previous item in the schedule table. //Compare the two and if the last show was recorded and started //after the last item in the schedule table, then return the show's @@ -101,8 +105,8 @@ class Application_Model_Dashboard $showInstance = Application_Model_ShowInstance::GetNextShowInstance($p_timeNow); $row = Application_Model_Schedule::GetNextScheduleItem($p_timeNow); - if (is_null($showInstance)){ - if (count($row) == 0){ + if (is_null($showInstance)) { + if (count($row) == 0) { return null; } else { return array("name"=>$row[0]["artist_name"]." - ".$row[0]["track_title"], @@ -110,8 +114,8 @@ class Application_Model_Dashboard "ends"=>$row[0]["ends"]); } } else { - if (count($row) == 0){ - if ($showInstance->isRecorded()){ + if (count($row) == 0) { + if ($showInstance->isRecorded()) { //last item is a show instance return array("name"=>$showInstance->getName(), "starts"=>$showInstance->getShowInstanceStart(), @@ -121,8 +125,8 @@ class Application_Model_Dashboard } } else { //return the one that starts sooner. - - if ($row[0]["starts"] <= $showInstance->getShowInstanceStart()){ + + if ($row[0]["starts"] <= $showInstance->getShowInstanceStart()) { return array("name"=>$row[0]["artist_name"]." - ".$row[0]["track_title"], "starts"=>$row[0]["starts"], "ends"=>$row[0]["ends"]); diff --git a/airtime_mvc/application/models/Datatables.php b/airtime_mvc/application/models/Datatables.php index 84b47ec6b..65e7b1256 100644 --- a/airtime_mvc/application/models/Datatables.php +++ b/airtime_mvc/application/models/Datatables.php @@ -1,104 +1,224 @@ 0) { - $where = join(" AND ", $where); - $sql = $selectorCount." FROM ".$fromTable." WHERE ".$where; - $sqlTotalDisplayRows = $sql; - - $sql = $selectorRows." FROM ".$fromTable." WHERE ".$where." ORDER BY ".$orderby; - - //limit the results returned. - if ($displayLength !== -1) { - $sql .= " OFFSET ".$data["iDisplayStart"]." LIMIT ".$displayLength; - } - } - else { - $sql = $selectorRows." FROM ".$fromTable." ORDER BY ".$orderby; - - //limit the results returned. - if ($displayLength !== -1) { - $sql .= " OFFSET ".$data["iDisplayStart"]." LIMIT ".$displayLength; - } - } - - try { - $r = $con->query($sqlTotalRows); - $totalRows = $r->fetchColumn(0); - - if (isset($sqlTotalDisplayRows)) { - $r = $con->query($sqlTotalDisplayRows); - $totalDisplayRows = $r->fetchColumn(0); - } - else { - $totalDisplayRows = $totalRows; - } - - $r = $con->query($sql); - $r->setFetchMode(PDO::FETCH_ASSOC); - $results = $r->fetchAll(); - } - catch (Exception $e) { - Logging::debug($e->getMessage()); - } - - return array( - "sEcho" => intval($data["sEcho"]), - "iTotalDisplayRecords" => intval($totalDisplayRows), - "iTotalRecords" => intval($totalRows), - $dataProp => $results - ); - } +class Application_Model_Datatables +{ + private static function buildWhereClauseForAdvancedSearch($dbname2searchTerm) + { + $where['clause'] = array(); + $where['params'] = array(); + foreach ($dbname2searchTerm as $dbname=>$term) { + $isRange = false; + if (strstr($term, '~')) { + $info = explode('~', $term); + if ($dbname == 'utime' || $dbname == 'mtime') { + $input1 = isset($info[0])?Application_Common_DateHelper::ConvertToUtcDateTimeString($info[0]):null; + $input2 = isset($info[1])?Application_Common_DateHelper::ConvertToUtcDateTimeString($info[1]):null; + } else if($dbname == 'bit_rate') { + $input1 = isset($info[0])?intval($info[0]) * 1000:null; + $input2 = isset($info[1])?intval($info[1]) * 1000:null; + } else { + $input1 = isset($info[0])?$info[0]:null; + $input2 = isset($info[1])?$info[1]:null; + } + $isRange = true; + } else { + $input1 = $term; + } + + if ($isRange) { + $sub = array(); + if ($input1 != null) { + $sub[] = $dbname." >= :" . $dbname . "1"; + } + if ($input2 != null) { + $sub[] = $dbname." <= :" . $dbname . "2"; + } + if (!empty($sub)) { + $where['clause'][$dbname] = "(".implode(' AND ', $sub).")"; + if ($input1 != null) { + $where['params'][$dbname."1"] = $input1; + } + if ($input2 != null) { + $where['params'][$dbname."2"] = $input2; + } + } + } else { + if (trim($input1) !== "") { + $where['clause'][$dbname] = $dbname." ILIKE :" . $dbname."1"; + $where['params'][$dbname."1"] = "%".$input1."%"; + } + } + } + return $where; + } + /* + * query used to return data for a paginated/searchable datatable. + */ + public static function findEntries($con, $displayColumns, $fromTable, + $data, $dataProp = "aaData") + { + $librarySetting = + Application_Model_Preference::getCurrentLibraryTableColumnMap(); + //$displayColumns[] = 'owner'; + + // map that maps original column position to db name + $current2dbname = array(); + // array of search terms + $orig2searchTerm = array(); + foreach ($data as $key => $d) { + if (strstr($key, "mDataProp_")) { + list($dump, $index) = explode("_", $key); + $current2dbname[$index] = $d; + } elseif (strstr($key, "sSearch_")) { + list($dump, $index) = explode("_", $key); + $orig2searchTerm[$index] = $d; + } + } + + // map that maps dbname to searchTerm + $dbname2searchTerm = array(); + foreach ($current2dbname as $currentPos => $dbname) { + $new_index = $librarySetting($currentPos); + // TODO : Fix this retarded hack later. Just a band aid for + // now at least we print some warnings so that we don't + // forget about this -- cc-4462 + if ( array_key_exists($new_index, $orig2searchTerm) ) { + $dbname2searchTerm[$dbname] = $orig2searchTerm[$new_index]; + } else { + Logging::warn("Trying to reorder to unknown index + printing as much debugging as possible..."); + $debug = array( + '$new_index' => $new_index, + '$currentPos' => $currentPos, + '$orig2searchTerm' => $orig2searchTerm); + Logging::warn($debug); + } + } + + $where = array(); + /* Holds the parameters for binding after the statement has been + prepared */ + $params = array(); + + if (isset($data['advSearch']) && $data['advSearch'] === 'true') { + $advancedWhere = self::buildWhereClauseForAdvancedSearch($dbname2searchTerm); + if (!empty($advancedWhere['clause'])) { + $where[] = join(" AND ", $advancedWhere['clause']); + $params = $advancedWhere['params']; + } + } + + if ($data["sSearch"] !== "") { + $searchTerms = explode(" ", $data["sSearch"]); + } + + $selectorCount = "SELECT COUNT(*) "; + $selectorRows = "SELECT ".join(",", $displayColumns)." "; + + $sql = $selectorCount." FROM ".$fromTable; + $sqlTotalRows = $sql; + + + if (isset($searchTerms)) { + $searchCols = array(); + for ($i = 0; $i < $data["iColumns"]; $i++) { + if ($data["bSearchable_".$i] == "true") { + $searchCols[] = $data["mDataProp_{$i}"]; + } + } + + $outerCond = array(); + $simpleWhere = array(); + + foreach ($searchTerms as $term) { + + foreach ($searchCols as $col) { + $simpleWhere['clause']["simple_".$col] = "{$col}::text ILIKE :simple_".$col; + $simpleWhere['params']["simple_".$col] = "%".$term."%"; + } + $outerCond[] = "(".implode(" OR ", $simpleWhere['clause']).")"; + } + $where[] = "(" .implode(" AND ", $outerCond). ")"; + $params = array_merge($params, $simpleWhere['params']); + } + // End Where clause + + // Order By clause + $orderby = array(); + for ($i = 0; $i < $data["iSortingCols"]; $i++) { + $num = $data["iSortCol_".$i]; + $orderby[] = $data["mDataProp_{$num}"]." ".$data["sSortDir_".$i]; + } + $orderby[] = "id"; + $orderby = join("," , $orderby); + // End Order By clause + + $displayLength = intval($data["iDisplayLength"]); + $needToBind = false; + if (count($where) > 0) { + $needToBind = true; + $where = join(" OR ", $where); + $sql = $selectorCount." FROM ".$fromTable." WHERE ".$where; + $sqlTotalDisplayRows = $sql; + + $sql = $selectorRows." FROM ".$fromTable." WHERE ".$where." ORDER BY ".$orderby; + + //limit the results returned. + if ($displayLength !== -1) { + $sql .= " OFFSET ".$data["iDisplayStart"]." LIMIT ".$displayLength; + } + } else { + $sql = $selectorRows." FROM ".$fromTable." ORDER BY ".$orderby; + + //limit the results returned. + if ($displayLength !== -1) { + $sql .= " OFFSET ".$data["iDisplayStart"]." LIMIT ".$displayLength; + } + } + try { + + $r = $con->query($sqlTotalRows); + $totalRows = $r->fetchColumn(0); + + if (isset($sqlTotalDisplayRows)) { + $totalDisplayRows = Application_Common_Database::prepareAndExecute($sqlTotalDisplayRows, $params, 'column'); + } else { + $totalDisplayRows = $totalRows; + } + + //TODO + if ($needToBind) { + $results = Application_Common_Database::prepareAndExecute($sql, $params); + } else { + $stmt = $con->query($sql); + $stmt->setFetchMode(PDO::FETCH_ASSOC); + $results = $stmt->fetchAll(); + } + + // we need to go over all items and fix length for playlist + // in case the playlist contains dynamic block + foreach ($results as &$r) { + //this function is also called for Manage Users so in + //this case there will be no 'ftype' + if (isset($r['ftype'])) { + if ($r['ftype'] == 'playlist') { + $pl = new Application_Model_Playlist($r['id']); + $r['length'] = $pl->getLength(); + } elseif ($r['ftype'] == "block") { + $bl = new Application_Model_Block($r['id']); + $r['bl_type'] = $bl->isStatic() ? 'static' : 'dynamic'; + $r['length'] = $bl->getLength(); + } + } + } + } catch (Exception $e) { + Logging::debug($e->getMessage()); + } + return array( + "sEcho" => intval($data["sEcho"]), + "iTotalDisplayRecords" => intval($totalDisplayRows), + "iTotalRecords" => intval($totalRows), + $dataProp => $results + ); + } } diff --git a/airtime_mvc/application/models/Email.php b/airtime_mvc/application/models/Email.php index 30b4cc190..234f20397 100644 --- a/airtime_mvc/application/models/Email.php +++ b/airtime_mvc/application/models/Email.php @@ -1,47 +1,55 @@ 'login', - 'ssl' => 'ssl', - 'username' => $username, - 'password' => $password - ); - + + if ($mailServerRequiresAuth) { + $username = Application_Model_Preference::GetMailServerEmailAddress(); + $password = Application_Model_Preference::GetMailServerPassword(); + + $config = array( + 'auth' => 'login', + 'ssl' => 'ssl', + 'username' => $username, + 'password' => $password + ); + } else { + $config = array( + 'ssl' => 'tls' + ); + } + if (isset($port)) { $config['port'] = $port; } - - $transport = new Zend_Mail_Transport_Smtp($mailServer, $config); + + $transport = new Zend_Mail_Transport_Smtp($mailServer, $config); } $mail = new Zend_Mail('utf-8'); $mail->setSubject($subject); $mail->setBodyText($message); - + foreach ((array) $tos as $to) { $mail->addTo($to); } @@ -60,8 +68,8 @@ class Application_Model_Email { } catch (Exception $e) { $success = false; } - } - + } + return $success; } diff --git a/airtime_mvc/application/models/Library.php b/airtime_mvc/application/models/Library.php new file mode 100644 index 000000000..1659f498d --- /dev/null +++ b/airtime_mvc/application/models/Library.php @@ -0,0 +1,36 @@ +id); + unset($obj_sess->type); + } else { + $obj_sess->id = intval($p_id); + $obj_sess->type = $p_type; + } + } + +} diff --git a/airtime_mvc/application/models/LibraryEditable.php b/airtime_mvc/application/models/LibraryEditable.php new file mode 100644 index 000000000..9fb952a71 --- /dev/null +++ b/airtime_mvc/application/models/LibraryEditable.php @@ -0,0 +1,10 @@ +query($sql)->fetchAll(); - + if ($rows != null) { $last_row = self::UpdateLastLogEndTime(array_pop($rows)); array_push($rows, $last_row); @@ -36,7 +37,7 @@ class Application_Model_LiveLog $con->exec($sql_delete); } } - $skip = true; + $skip = true; } $hours = 0; @@ -55,13 +56,13 @@ class Application_Model_LiveLog $intervals[$i] = 0; } } - + // Trim milliseconds (DateInterval does not support) $sec = explode(".", $intervals[2]); if (isset($sec[0])) { $intervals[2] = $sec[0]; } - + $seconds += $intervals[2]; if ($seconds / 60 >= 1) { $minutes += 1; @@ -86,21 +87,21 @@ class Application_Model_LiveLog //Trim milliseconds $seconds = explode(".", $seconds); if (isset($seconds[0])) { - $minutes = (double)(($hours*60)+$minutes . "." . $seconds[0]); - } - else { - $minutes = (double)(($hours*60)+$minutes); + $minutes = (double) (($hours*60)+$minutes . "." . $seconds[0]); + } else { + $minutes = (double) (($hours*60)+$minutes); } } + return $minutes; } catch (Exception $e) { header('HTTP/1.0 503 Service Unavailable'); - Logging::log("GetLiveShowDuration - Could not connect to database."); + Logging::info("GetLiveShowDuration - Could not connect to database."); exit; } } - public static function GetScheduledDuration($p_keepData=false) + public static function GetScheduledDuration($p_keepData=false) { try { $con = Propel::getConnection(); @@ -119,13 +120,12 @@ class Application_Model_LiveLog $last_row = self::UpdateLastLogEndTime(array_pop($rows)); array_push($rows, $last_row); $skip = false; - } - else { + } else { $sql = "SELECT * FROM CC_LIVE_LOG" ." WHERE state = 'S'" ." ORDER BY id"; $rows = $con->query($sql)->fetchAll(); - + if ($rows != null) { $last_row = self::UpdateLastLogEndTime(array_pop($rows)); array_push($rows, $last_row); @@ -135,7 +135,7 @@ class Application_Model_LiveLog $con->exec($sql_delete); } } - $skip = true; + $skip = true; } $hours = 0; @@ -173,7 +173,7 @@ class Application_Model_LiveLog } } $clip_length_seconds = $clip_length_intervals[0]*3600 + $clip_length_intervals[1]*60 + $clip_length_intervals[2]; - + $extra_time = $extra_time->format("%H:%i:%s"); //Convert extra_time into seconds; $extra_time_intervals = explode(":", $extra_time); @@ -185,28 +185,25 @@ class Application_Model_LiveLog $extra_time_seconds = $extra_time_intervals[0]*3600 + $extra_time_intervals[1]*60 + $extra_time_intervals[2]; $clip_length_seconds -= $extra_time_seconds; - + //Convert new clip_length into "H-i-s" format $clip_length_arr = array(); if ($clip_length_seconds / 3600 >= 1) { array_push($clip_length_arr, str_pad(floor($clip_length_seconds / 3600), 2, "0", STR_PAD_LEFT)); $clip_length_seconds -= floor($clip_length_seconds / 3600); - } - else { + } else { array_push($clip_length_arr, "00"); } if ($clip_length_seconds / 60 >= 1) { array_push($clip_length_arr, str_pad(floor($clip_length_seconds / 60), 2, "0", STR_PAD_LEFT)); $clip_length_seconds -= floor($clip_length_seconds / 60); - } - else { + } else { array_push($clip_length_arr, "00"); } array_push($clip_length_arr, str_pad($clip_length_seconds, 2, "0", STR_PAD_LEFT)); $clip_length = implode(":", $clip_length_arr); - } - else { + } else { $clip_length = $track['clip_length']; } @@ -248,21 +245,22 @@ class Application_Model_LiveLog $seconds = explode(".", $seconds); if (isset($seconds[0])) { - $minutes = (double)(($hours*60)+$minutes . "." . $seconds[0]); - } - else { - $minutes = (double)(($hours*60)+$minutes); + $minutes = (double) (($hours*60)+$minutes . "." . $seconds[0]); + } else { + $minutes = (double) (($hours*60)+$minutes); } } + return $minutes; } catch (Exception $e) { header('HTTP/1.0 503 Service Unavailable'); - Logging::log("GetScheduledDuration - Could not connect to database."); + Logging::info("GetScheduledDuration - Could not connect to database."); exit; } } - public static function UpdateLastLogEndTime($log) { + public static function UpdateLastLogEndTime($log) + { if ($log['end_time'] == null) { $current_time = new DateTime("now", new DateTimeZone('UTC')); $log['end_time'] = $current_time; @@ -270,13 +268,15 @@ class Application_Model_LiveLog self::SetEndTime($log['state'], $current_time, true); self::SetNewLogTime($log['state'], $current_time); } + return $log; } - public static function SetNewLogTime($state, $dateTime){ + public static function SetNewLogTime($state, $dateTime) + { try { $con = Propel::getConnection(); - + $scheduled = Application_Model_Preference::GetSourceSwitchStatus('scheduled_play'); if ($state == 'L' && $scheduled == 'on') { self::SetEndTime('S', $dateTime); @@ -293,7 +293,7 @@ class Application_Model_LiveLog $sql_insert = "INSERT INTO CC_LIVE_LOG (state, start_time)" ." VALUES ('$state', '{$dateTime->format("Y-m-d H:i:s")}')"; $con->exec($sql_insert); - if($state == "S"){ + if ($state == "S") { // if scheduled play source is getting broadcasted Application_Model_Schedule::UpdateBrodcastedStatus($dateTime, 1); } @@ -301,12 +301,13 @@ class Application_Model_LiveLog } catch (Exception $e) { header('HTTP/1.0 503 Service Unavailable'); - Logging::log("SetNewLogTime - Could not connect to database."); + Logging::info("SetNewLogTime - Could not connect to database."); exit; } } - public static function SetEndTime($state, $dateTime, $override=false){ + public static function SetEndTime($state, $dateTime, $override=false) + { try { $con = Propel::getConnection(); @@ -337,7 +338,7 @@ class Application_Model_LiveLog } catch (Exception $e) { header('HTTP/1.0 503 Service Unavailable'); - Logging::log("SetEndTime - Could not connect to database."); + Logging::info("SetEndTime - Could not connect to database."); exit; } } diff --git a/airtime_mvc/application/models/LoginAttempts.php b/airtime_mvc/application/models/LoginAttempts.php index 6ebeafff6..63cdce6b5 100644 --- a/airtime_mvc/application/models/LoginAttempts.php +++ b/airtime_mvc/application/models/LoginAttempts.php @@ -1,10 +1,12 @@ query($sql)->fetchColumn(0); @@ -17,14 +19,17 @@ class Application_Model_LoginAttempts { } } - public static function getAttempts($ip){ + public static function getAttempts($ip) + { $con = Propel::getConnection(); $sql = "select attempts from cc_login_attempts WHERE ip='$ip'"; $res = $con->query($sql)->fetchColumn(0); + return $res ? $res : 0; } - public static function resetAttempts($ip){ + public static function resetAttempts($ip) + { $con = Propel::getConnection(); $sql = "select count(*) from cc_login_attempts WHERE ip='$ip'"; $res = $con->query($sql)->fetchColumn(0); @@ -33,4 +38,4 @@ class Application_Model_LoginAttempts { $con->exec($sql); } } -} \ No newline at end of file +} diff --git a/airtime_mvc/application/models/MusicDir.php b/airtime_mvc/application/models/MusicDir.php index 70609fad3..3d28f2e75 100644 --- a/airtime_mvc/application/models/MusicDir.php +++ b/airtime_mvc/application/models/MusicDir.php @@ -2,8 +2,8 @@ class NestedDirectoryException extends Exception { } -class Application_Model_MusicDir { - +class Application_Model_MusicDir +{ /** * @holds propel database object */ @@ -40,52 +40,68 @@ class Application_Model_MusicDir { $this->_dir->save(); } - public function setExistsFlag($flag){ + public function setExistsFlag($flag) + { $this->_dir->setExists($flag); $this->_dir->save(); } - - public function setWatchedFlag($flag){ + + public function setWatchedFlag($flag) + { $this->_dir->setWatched($flag); $this->_dir->save(); } - - public function getWatchedFlag(){ + + public function getWatchedFlag() + { return $this->_dir->getWatched(); } - - public function getExistsFlag(){ + + public function getExistsFlag() + { return $this->_dir->getExists(); } - - /** + + /** * There are 2 cases where this function can be called. * 1. When watched dir was removed * 2. When some dir was watched, but it was unmounted - * + * * In case of 1, $userAddedWatchedDir should be true * In case of 2, $userAddedWatchedDir should be false - * + * * When $userAddedWatchedDir is true, it will set "Watched" flag to false * otherwise, it will set "Exists" flag to true - */ + */ public function remove($userAddedWatchedDir=true) { - $con = Propel::getConnection(); - + $music_dir_id = $this->getId(); - $sql = "SELECT DISTINCT s.instance_id from cc_music_dirs as md " - ." LEFT JOIN cc_files as f on f.directory = md.id" - ." RIGHT JOIN cc_schedule as s on s.file_id = f.id WHERE md.id = $music_dir_id"; + $sql = << $music_dir_id ), 'all' ); - $show_instances = $con->query($sql)->fetchAll(); - // get all the files on this dir - $sql = "UPDATE cc_files SET file_exists = 'f' WHERE id IN (SELECT f.id FROM cc_music_dirs as md " - ." LEFT JOIN cc_files as f on f.directory = md.id WHERE md.id = $music_dir_id)"; - $affected = $con->exec($sql); - + $sql = << $music_dir_id ), 'all'); + // set RemovedFlag to true if ($userAddedWatchedDir) { self::setWatchedFlag(false); @@ -93,7 +109,7 @@ class Application_Model_MusicDir { self::setExistsFlag(false); } //$res = $this->_dir->delete(); - + foreach ($show_instances as $show_instance_row) { $temp_show = new Application_Model_ShowInstance($show_instance_row["instance_id"]); $temp_show->updateScheduledTime(); @@ -113,8 +129,9 @@ class Application_Model_MusicDir { * @return boolean * Returns true if it is the ancestor, false otherwise. */ - private static function isAncestorDir($p_dir1, $p_dir2){ - if (strlen($p_dir1) > strlen($p_dir2)){ + private static function isAncestorDir($p_dir1, $p_dir2) + { + if (strlen($p_dir1) > strlen($p_dir2)) { return false; } @@ -130,23 +147,24 @@ class Application_Model_MusicDir { * The path we want to validate * @return void */ - public static function isPathValid($p_path){ + public static function isPathValid($p_path) + { $dirs = self::getWatchedDirs(); $dirs[] = self::getStorDir(); - - foreach ($dirs as $dirObj){ + + foreach ($dirs as $dirObj) { $dir = $dirObj->getDirectory(); $diff = strlen($dir) - strlen($p_path); - if ($diff == 0){ - if ($dir == $p_path){ + if ($diff == 0) { + if ($dir == $p_path) { throw new NestedDirectoryException("'$p_path' is already watched."); } - } else if ($diff > 0){ - if (self::isAncestorDir($p_path, $dir)){ + } elseif ($diff > 0) { + if (self::isAncestorDir($p_path, $dir)) { throw new NestedDirectoryException("'$p_path' contains nested watched directory: '$dir'"); } } else { /* diff < 0*/ - if (self::isAncestorDir($dir, $p_path)){ + if (self::isAncestorDir($dir, $p_path)) { throw new NestedDirectoryException("'$p_path' is nested within existing watched directory: '$dir'"); } } @@ -156,59 +174,59 @@ class Application_Model_MusicDir { /** There are 2 cases where this function can be called. * 1. When watched dir was added * 2. When some dir was watched, but it was unmounted somehow, but gets mounted again - * + * * In case of 1, $userAddedWatchedDir should be true * In case of 2, $userAddedWatchedDir should be false - * + * * When $userAddedWatchedDir is true, it will set "Removed" flag to false * otherwise, it will set "Exists" flag to true - * + * * @param $nestedWatch - if true, bypass path check, and Watched to false - **/ + **/ public static function addDir($p_path, $p_type, $userAddedWatchedDir=true, $nestedWatch=false) { - if(!is_dir($p_path)){ + if (!is_dir($p_path)) { return array("code"=>2, "error"=>"'$p_path' is not a valid directory."); } $real_path = Application_Common_OsPath::normpath($p_path)."/"; - if($real_path != "/"){ + if ($real_path != "/") { $p_path = $real_path; } - + $exist_dir = self::getDirByPath($p_path); - - if( $exist_dir == NULL ){ + + if ($exist_dir == NULL) { $temp_dir = new CcMusicDirs(); $dir = new Application_Model_MusicDir($temp_dir); - }else{ + } else { $dir = $exist_dir; } - + $dir->setType($p_type); $p_path = Application_Common_OsPath::normpath($p_path)."/"; - try { /* isPathValid() checks if path is a substring or a superstring of an * existing dir and if not, throws NestedDirectoryException */ - if(!$nestedWatch){ + if (!$nestedWatch) { self::isPathValid($p_path); } - if($userAddedWatchedDir){ + if ($userAddedWatchedDir) { $dir->setWatchedFlag(true); - }else{ - if($nestedWatch){ + } else { + if ($nestedWatch) { $dir->setWatchedFlag(false); } $dir->setExistsFlag(true); } $dir->setDirectory($p_path); - + return array("code"=>0); - } catch (NestedDirectoryException $nde){ + } catch (NestedDirectoryException $nde) { $msg = $nde->getMessage(); + return array("code"=>1, "error"=>"$msg"); - } catch(Exception $e){ + } catch (Exception $e) { return array("code"=>1, "error"=>"'$p_path' is already set as the current storage dir or in the watched folders list"); } @@ -217,18 +235,18 @@ class Application_Model_MusicDir { /** There are 2 cases where this function can be called. * 1. When watched dir was added * 2. When some dir was watched, but it was unmounted somehow, but gets mounted again - * + * * In case of 1, $userAddedWatchedDir should be true * In case of 2, $userAddedWatchedDir should be false - * + * * When $userAddedWatchedDir is true, it will set "Watched" flag to true * otherwise, it will set "Exists" flag to true - **/ + **/ public static function addWatchedDir($p_path, $userAddedWatchedDir=true, $nestedWatch=false) { $res = self::addDir($p_path, "watched", $userAddedWatchedDir, $nestedWatch); - - if ($res['code'] == 0){ + + if ($res['code'] == 0) { //convert "linked" files (Airtime <= 1.8.2) to watched files. $propel_link_dir = CcMusicDirsQuery::create() @@ -271,6 +289,7 @@ class Application_Model_MusicDir { $data["directory"] = $p_path; Application_Model_RabbitMq::SendMessageToMediaMonitor("new_watch", $data); } + return $res; } @@ -288,18 +307,18 @@ class Application_Model_MusicDir { $dir = CcMusicDirsQuery::create() ->filterByDirectory($p_path) ->findOne(); - if($dir == NULL){ + if ($dir == NULL) { return null; - } - else{ + } else { $mus_dir = new Application_Model_MusicDir($dir); + return $mus_dir; } } - + /** * Search and returns watched dirs - * + * * @param $exists search condition with exists flag * @param $watched search condition with watched flag */ @@ -309,15 +328,15 @@ class Application_Model_MusicDir { $dirs = CcMusicDirsQuery::create() ->filterByType("watched"); - if($exists !== null){ + if ($exists !== null) { $dirs = $dirs->filterByExists($exists); } - if($watched !== null){ + if ($watched !== null) { $dirs = $dirs->filterByWatched($watched); } $dirs = $dirs->find(); - foreach($dirs as $dir) { + foreach ($dirs as $dir) { $result[] = new Application_Model_MusicDir($dir); } @@ -340,23 +359,24 @@ class Application_Model_MusicDir { // we want to be consistent when storing dir path. // path should always ends with trailing '/' $p_dir = Application_Common_OsPath::normpath($p_dir)."/"; - if(!is_dir($p_dir)){ + if (!is_dir($p_dir)) { return array("code"=>2, "error"=>"'$p_dir' is not a valid directory."); - }else if(Application_Model_Preference::GetImportTimestamp()+10 > time()){ + } elseif (Application_Model_Preference::GetImportTimestamp()+10 > time()) { return array("code"=>3, "error"=>"Airtime is currently importing files. Please wait until this is complete before changing the storage directory."); } $dir = self::getStorDir(); // if $p_dir doesn't exist in DB $exist = $dir->getDirByPath($p_dir); - if($exist == NULL){ + if ($exist == NULL) { $dir->setDirectory($p_dir); $dirId = $dir->getId(); $data = array(); $data["directory"] = $p_dir; $data["dir_id"] = $dirId; Application_Model_RabbitMq::SendMessageToMediaMonitor("change_stor", $data); + return array("code"=>0); - }else{ + } else { return array("code"=>1, "error"=>"'$p_dir' is already set as the current storage dir or in the watched folders list."); } } @@ -369,10 +389,11 @@ class Application_Model_MusicDir { ->filterByWatched(true) ->find(); - foreach($dirs as $dir) { + foreach ($dirs as $dir) { $directory = $dir->getDirectory(); if (substr($p_filepath, 0, strlen($directory)) === $directory) { $mus_dir = new Application_Model_MusicDir($dir); + return $mus_dir; } } @@ -383,18 +404,18 @@ class Application_Model_MusicDir { /** There are 2 cases where this function can be called. * 1. When watched dir was removed * 2. When some dir was watched, but it was unmounted - * + * * In case of 1, $userAddedWatchedDir should be true * In case of 2, $userAddedWatchedDir should be false - * + * * When $userAddedWatchedDir is true, it will set "Watched" flag to false * otherwise, it will set "Exists" flag to true - **/ - public static function removeWatchedDir($p_dir, $userAddedWatchedDir=true){ - - //make sure that $p_dir has a trailing "/" + **/ + public static function removeWatchedDir($p_dir, $userAddedWatchedDir=true) + { + //make sure that $p_dir has a trailing "/" $real_path = Application_Common_OsPath::normpath($p_dir)."/"; - if($real_path != "/"){ + if ($real_path != "/") { $p_dir = $real_path; } $dir = Application_Model_MusicDir::getDirByPath($p_dir); @@ -405,6 +426,7 @@ class Application_Model_MusicDir { $data = array(); $data["directory"] = $p_dir; Application_Model_RabbitMq::SendMessageToMediaMonitor("remove_watch", $data); + return array("code"=>0); } } @@ -412,8 +434,8 @@ class Application_Model_MusicDir { public static function splitFilePath($p_filepath) { $mus_dir = self::getWatchedDirFromFilepath($p_filepath); - - if(is_null($mus_dir)) { + + if (is_null($mus_dir)) { return null; } diff --git a/airtime_mvc/application/models/Playlist.php b/airtime_mvc/application/models/Playlist.php index 70710f567..c99fbb019 100644 --- a/airtime_mvc/application/models/Playlist.php +++ b/airtime_mvc/application/models/Playlist.php @@ -8,8 +8,8 @@ require_once 'formatters/LengthFormatter.php'; * @copyright 2010 Sourcefabric O.P.S. * @license http://www.gnu.org/licenses/gpl.txt */ -class Application_Model_Playlist { - +class Application_Model_Playlist implements Application_Model_LibraryEditable +{ /** * propel connection object. */ @@ -20,17 +20,17 @@ class Application_Model_Playlist { */ private $id; - /** + /** * propel object for this playlist. */ - private $pl; + private $pl; - /** + /** * info needed to insert a new playlist element. */ - private $plItem = array( + private $plItem = array( "id" => "", - "pos" => "", + "pos" => "", "cliplength" => "", "cuein" => "00:00:00", "cueout" => "00:00:00", @@ -38,14 +38,13 @@ class Application_Model_Playlist { "fadeout" => "0.0", ); - //using propel's phpNames. - private $categories = array( - "dc:title" => "Name", - "dc:creator" => "Creator", - "dc:description" => "Description", - "dcterms:extent" => "Length" - ); - + //using propel's phpNames. + private $categories = array( + "dc:title" => "Name", + "dc:creator" => "Creator", + "dc:description" => "Description", + "dcterms:extent" => "Length" + ); public function __construct($id=null, $con=null) { @@ -55,10 +54,9 @@ class Application_Model_Playlist { if (is_null($this->pl)) { throw new PlaylistNotFoundException(); } - } - else { + } else { $this->pl = new CcPlaylist(); - $this->pl->setDbUTime("now", new DateTimeZone("UTC")); + $this->pl->setDbUTime(new DateTime("now", new DateTimeZone("UTC"))); $this->pl->save(); } @@ -79,7 +77,8 @@ class Application_Model_Playlist { * * @return int */ - public function getId() { + public function getId() + { return $this->id; } @@ -90,12 +89,12 @@ class Application_Model_Playlist { */ public function setName($p_newname) { - $this->pl->setDbName($p_newname); - $this->pl->setDbMtime(new DateTime("now", new DateTimeZone("UTC"))); - $this->pl->save($this->con); + $this->pl->setDbName($p_newname); + $this->pl->setDbMtime(new DateTime("now", new DateTimeZone("UTC"))); + $this->pl->save($this->con); } - /** + /** * Get mnemonic playlist name * * @return string @@ -107,9 +106,9 @@ class Application_Model_Playlist { public function setDescription($p_description) { - $this->pl->setDbDescription($p_description); - $this->pl->setDbMtime(new DateTime("now", new DateTimeZone("UTC"))); - $this->pl->save($this->con); + $this->pl->setDbDescription($p_description); + $this->pl->setDbMtime(new DateTime("now", new DateTimeZone("UTC"))); + $this->pl->save($this->con); } public function getDescription() @@ -117,75 +116,148 @@ class Application_Model_Playlist { return $this->pl->getDbDescription(); } - public function getCreator() { - + public function getCreator() + { return $this->pl->getCcSubjs()->getDbLogin(); } - - public function getCreatorId() { + + public function getCreatorId() + { return $this->pl->getCcSubjs()->getDbId(); } - public function setCreator($p_id) { - + public function setCreator($p_id) + { $this->pl->setDbCreatorId($p_id); $this->pl->setDbMtime(new DateTime("now", new DateTimeZone("UTC"))); $this->pl->save($this->con); } - public function getLastModified($format = null) { + public function getLastModified($format = null) + { + //Logging::info($this->pl->getDbMtime($format)); + //Logging::info($this->pl); return $this->pl->getDbMtime($format); } - public function getSize() { - + public function getSize() + { return $this->pl->countCcPlaylistcontentss(); } /** * Get the entire playlist as a two dimentional array, sorted in order of play. * @param boolean $filterFiles if this is true, it will only return files that has - * file_exists flag set to true + * file_exists flag set to true * @return array */ - public function getContents($filterFiles=false) { + public function getContents($filterFiles=false) + { + Logging::info("Getting contents for playlist {$this->id}"); - Logging::log("Getting contents for playlist {$this->id}"); + $sql = <<filterByDbPlaylistId($this->id); - - if($filterFiles){ - $query->useCcFilesQuery() - ->filterByDbFileExists(true) - ->endUse(); - } - $query->orderByDbPosition() - ->leftJoinWith('CcFiles'); - $rows = $query->find($this->con); + $rows = Application_Common_Database::prepareAndExecute($sql, array(':playlist_id1'=>$this->id, ':playlist_id2'=>$this->id, ':playlist_id3'=>$this->id)); - $i = 0; $offset = 0; - foreach ($rows as $row) { - $files[$i] = $row->toArray(BasePeer::TYPE_FIELDNAME, true, true); + foreach ($rows as &$row) { + $clipSec = Application_Common_DateHelper::playlistTimeToSeconds($row['length']); + $offset += $clipSec; + $offset_cliplength = Application_Common_DateHelper::secondsToPlaylistTime($offset); + //format the length for UI. + if ($row['type'] == 2) { + $bl = new Application_Model_Block($row['item_id']); + $formatter = new LengthFormatter($bl->getLength()); + } else { + $formatter = new LengthFormatter($row['length']); + } + $row['length'] = $formatter->format(); - $clipSec = Application_Model_Playlist::playlistTimeToSeconds($files[$i]['cliplength']); - $offset += $clipSec; - $offset_cliplength = Application_Model_Playlist::secondsToPlaylistTime($offset); + $formatter = new LengthFormatter($offset_cliplength); + $row['offset'] = $formatter->format(); - //format the length for UI. - $formatter = new LengthFormatter($files[$i]['cliplength']); - $files[$i]['cliplength'] = $formatter->format(); + //format the fades in format 00(.000000) + $fades = $this->getFadeInfo($row['position']); + $row['fadein'] = $fades[0]; + $row['fadeout'] = $fades[1]; + + // format the cues in format 00:00:00(.0) + // we need to add the '.0' for cues and not fades + // because propel takes care of this for us + // (we use propel to fetch the fades) + $row['cuein'] = str_pad(substr($row['cuein'], 0, 10), 10, '.0'); + $row['cueout'] = str_pad(substr($row['cueout'], 0, 10), 10, '.0'); - $formatter = new LengthFormatter($offset_cliplength); - $files[$i]['offset'] = $formatter->format(); - - $i++; + //format original length + $formatter = new LengthFormatter($row['orig_length']); + $row['orig_length'] = $formatter->format(); } - return $files; + return $rows; } /** @@ -193,42 +265,94 @@ class Application_Model_Playlist { * but this isn't practical since fades shouldn't be very long usuall 1 second or less. This function * will normalize the fade so that it looks like 00.000000 to the user. **/ - public function normalizeFade($fade) { + public function normalizeFade($fade) + { + //First get rid of the first six characters 00:00: which will be added back later for db update + $fade = substr($fade, 6); - //First get rid of the first six characters 00:00: which will be added back later for db update - $fade = substr($fade, 6); + //Second add .000000 if the fade does't have milliseconds format already + $dbFadeStrPos = strpos( $fade, '.' ); + if ($dbFadeStrPos === false) { + $fade .= '.000000'; + } else { + while (strlen($fade) < 9) { + $fade .= '0'; + } + } - //Second add .000000 if the fade does't have milliseconds format already - $dbFadeStrPos = strpos( $fade, '.' ); - if ( $dbFadeStrPos === False ) - $fade .= '.000000'; - else - while( strlen( $fade ) < 9 ) - $fade .= '0'; + //done, just need to set back the formated values + return $fade; + } - //done, just need to set back the formated values - return $fade; + // returns true/false and ids of dynamic blocks + public function hasDynamicBlock() + { + $ids = $this->getIdsOfDynamicBlocks(); + if (count($ids) > 0) { + return true; + } else { + return false; + } + } + + public function getIdsOfDynamicBlocks() + { + $sql = "SELECT bl.id FROM cc_playlistcontents as pc + JOIN cc_block as bl ON pc.type=2 AND pc.block_id=bl.id AND bl.type='dynamic' + WHERE playlist_id=:playlist_id AND pc.type=2"; + + $result = Application_Common_Database::prepareAndExecute($sql, array(':playlist_id'=>$this->id)); + + return $result; } //aggregate column on playlistcontents cliplength column. - public function getLength() { + public function getLength() + { + if ($this->hasDynamicBlock()) { + $ids = $this->getIdsOfDynamicBlocks(); + $length = $this->pl->getDbLength(); + foreach ($ids as $id) { + $bl = new Application_Model_Block($id['id']); + if ($bl->hasItemLimit()) { + return "N/A"; + } + } + $formatter = new LengthFormatter($length); - return $this->pl->getDbLength(); + return "~".$formatter->format(); + } else { + return $this->pl->getDbLength(); + } } - private function insertPlaylistElement($info) { $row = new CcPlaylistcontents(); $row->setDbPlaylistId($this->id); - $row->setDbFileId($info["id"]); $row->setDbPosition($info["pos"]); $row->setDbCliplength($info["cliplength"]); $row->setDbCuein($info["cuein"]); $row->setDbCueout($info["cueout"]); $row->setDbFadein($info["fadein"]); $row->setDbFadeout($info["fadeout"]); + if ($info["ftype"] == "audioclip") { + $row->setDbFileId($info["id"]); + $type = 0; + } elseif ($info["ftype"] == "stream") { + $row->setDbStreamId($info["id"]); + $type = 1; + } elseif ($info["ftype"] == "block") { + $row->setDbBlockId($info["id"]); + $type = 2; + } + $row->setDbType($type); $row->save($this->con); + // above save result update on cc_playlist table on length column. + // but $this->pl doesn't get updated automatically + // so we need to manually grab it again from DB so it has updated values + // It is something to do FORMAT_ON_DEMAND( Lazy Loading ) + $this->pl = CcPlaylistQuery::create()->findPK($this->id); } /* @@ -236,19 +360,31 @@ class Application_Model_Playlist { */ private function buildEntry($p_item, $pos) { - $file = CcFilesQuery::create()->findPK($p_item, $this->con); + $objType = $p_item[1]; + $objId = $p_item[0]; + if ($objType == 'audioclip') { + $obj = CcFilesQuery::create()->findPK($objId, $this->con); + } elseif ($objType == "stream") { + $obj = CcWebstreamQuery::create()->findPK($objId, $this->con); + } elseif ($objType == "block") { + $obj = CcBlockQuery::create()->findPK($objId, $this->con); + } else { + throw new Exception("Unknown file type"); + } - if (isset($file) && $file->getDbFileExists()) { - $entry = $this->plItem; - $entry["id"] = $file->getDbId(); - $entry["pos"] = $pos; - $entry["cliplength"] = $file->getDbLength(); - $entry["cueout"] = $file->getDbLength(); + if (isset($obj)) { + if (($obj instanceof CcFiles && $obj->getDbFileExists()) || $obj instanceof CcWebstream || $obj instanceof CcBlock) { + $entry = $this->plItem; + $entry["id"] = $obj->getDbId(); + $entry["pos"] = $pos; + $entry["cliplength"] = $obj->getDbLength(); + $entry["cueout"] = $obj->getDbLength(); + $entry["ftype"] = $objType; + } return $entry; - } - else { - throw new Exception("trying to add a file that does not exist."); + } else { + throw new Exception("trying to add a object that does not exist."); } } @@ -260,7 +396,7 @@ class Application_Model_Playlist { * @param string (before|after) $addAfter * whether to add the clips before or after the selected item. */ - public function addAudioClips($p_items, $p_afterItem=NULL, $addType = 'after') + public function addAudioClips($p_items, $p_afterItem=null, $addType = 'after') { $this->con->beginTransaction(); $contentsToUpdate = array(); @@ -268,24 +404,20 @@ class Application_Model_Playlist { try { if (is_numeric($p_afterItem)) { - Logging::log("Finding playlist content item {$p_afterItem}"); + Logging::info("Finding playlist content item {$p_afterItem}"); $afterItem = CcPlaylistcontentsQuery::create()->findPK($p_afterItem); $index = $afterItem->getDbPosition(); - Logging::log("index is {$index}"); + Logging::info("index is {$index}"); $pos = ($addType == 'after') ? $index + 1 : $index; - $contentsToUpdate = CcPlaylistcontentsQuery::create() ->filterByDbPlaylistId($this->id) ->filterByDbPosition($pos, Criteria::GREATER_EQUAL) ->orderByDbPosition() ->find($this->con); - Logging::log("Adding to playlist"); - Logging::log("at position {$pos}"); - } - else { + } else { //add to the end of the playlist if ($addType == 'after') { @@ -307,15 +439,16 @@ class Application_Model_Playlist { ->orderByDbPosition() ->find($this->con); - Logging::log("Adding to playlist"); - Logging::log("at position {$pos}"); } - foreach($p_items as $ac) { - Logging::log("Adding audio file {$ac}"); + Logging::info("Adding to playlist"); + Logging::info("at position {$pos}"); + foreach ($p_items as $ac) { $res = $this->insertPlaylistElement($this->buildEntry($ac, $pos)); $pos = $pos + 1; + Logging::info("Adding $ac[1] $ac[0]"); + } //reset the positions of the remaining items. @@ -329,8 +462,7 @@ class Application_Model_Playlist { $this->pl->save($this->con); $this->con->commit(); - } - catch (Exception $e) { + } catch (Exception $e) { $this->con->rollback(); throw $e; } @@ -364,33 +496,32 @@ class Application_Model_Playlist { $pos = 0; //moving items to beginning of the playlist. if (is_null($p_afterItem)) { - Logging::log("moving items to beginning of playlist"); + Logging::info("moving items to beginning of playlist"); foreach ($contentsToMove as $item) { - Logging::log("item {$item->getDbId()} to pos {$pos}"); + Logging::info("item {$item->getDbId()} to pos {$pos}"); $item->setDbPosition($pos); $item->save($this->con); $pos = $pos + 1; } foreach ($otherContent as $item) { - Logging::log("item {$item->getDbId()} to pos {$pos}"); + Logging::info("item {$item->getDbId()} to pos {$pos}"); $item->setDbPosition($pos); $item->save($this->con); $pos = $pos + 1; } - } - else { - Logging::log("moving items after {$p_afterItem}"); + } else { + Logging::info("moving items after {$p_afterItem}"); foreach ($otherContent as $item) { - Logging::log("item {$item->getDbId()} to pos {$pos}"); + Logging::info("item {$item->getDbId()} to pos {$pos}"); $item->setDbPosition($pos); $item->save($this->con); $pos = $pos + 1; if ($item->getDbId() == $p_afterItem) { foreach ($contentsToMove as $move) { - Logging::log("item {$move->getDbId()} to pos {$pos}"); + Logging::info("item {$move->getDbId()} to pos {$pos}"); $move->setDbPosition($pos); $move->save($this->con); $pos = $pos + 1; @@ -400,13 +531,11 @@ class Application_Model_Playlist { } $this->con->commit(); - } - catch (Exception $e) { + } catch (Exception $e) { $this->con->rollback(); throw $e; } - $this->pl = CcPlaylistQuery::create()->findPK($this->id); $this->pl->setDbMtime(new DateTime("now", new DateTimeZone("UTC"))); $this->pl->save($this->con); @@ -416,7 +545,7 @@ class Application_Model_Playlist { * Remove audioClip from playlist * * @param array $p_items - * array of unique item ids to remove from the playlist.. + * array of unique item ids to remove from the playlist.. */ public function delAudioClips($p_items) { @@ -444,53 +573,54 @@ class Application_Model_Playlist { $this->pl->save($this->con); $this->con->commit(); - } - catch (Exception $e) { + } catch (Exception $e) { $this->con->rollback(); throw $e; } } + public function getFadeInfo($pos) + { + Logging::info("Getting fade info for pos {$pos}"); - public function getFadeInfo($pos) { - - Logging::log("Getting fade info for pos {$pos}"); - - $row = CcPlaylistcontentsQuery::create() + $row = CcPlaylistcontentsQuery::create() ->joinWith(CcFilesPeer::OM_CLASS) ->filterByDbPlaylistId($this->id) ->filterByDbPosition($pos) ->findOne(); - #Propel returns values in form 00.000000 format which is for only seconds. - $fadeIn = $row->getDbFadein(); - $fadeOut = $row->getDbFadeout(); - return array($fadeIn, $fadeOut); - } + if (!$row) { + return NULL; + } + //Propel returns values in form 00.000000 format which is for only seconds. + //We only want to display 1 decimal + $fadeIn = substr($row->getDbFadein(), 0, 4); + $fadeOut = substr($row->getDbFadeout(), 0, 4); + + return array($fadeIn, $fadeOut); + } /** * Change fadeIn and fadeOut values for playlist Element * * @param int $pos - * position of audioclip in playlist + * position of audioclip in playlist * @param string $fadeIn - * new value in ss.ssssss or extent format + * new value in ss.ssssss or extent format * @param string $fadeOut - * new value in ss.ssssss or extent format + * new value in ss.ssssss or extent format * @return boolean */ public function changeFadeInfo($id, $fadeIn, $fadeOut) { //See issue CC-2065, pad the fadeIn and fadeOut so that it is TIME compatable with the DB schema //For the top level PlayList either fadeIn or fadeOut will sometimes be Null so need a gaurd against - //setting it to nonNull for checks down below + //setting it to nonNull for checks down below $fadeIn = $fadeIn?'00:00:'.$fadeIn:$fadeIn; $fadeOut = $fadeOut?'00:00:'.$fadeOut:$fadeOut; $this->con->beginTransaction(); - $errArray= array(); - try { $row = CcPlaylistcontentsQuery::create()->findPK($id); @@ -502,19 +632,17 @@ class Application_Model_Playlist { if (!is_null($fadeIn)) { - $sql = "SELECT INTERVAL '{$fadeIn}' > INTERVAL '{$clipLength}'"; - $r = $this->con->query($sql); - if ($r->fetchColumn(0)) { + $sql = "SELECT :fadein::INTERVAL > INTERVAL '{$clipLength}'"; + if (Application_Common_Database::prepareAndExecute($sql, array(':fadein'=>$fadeIn), 'column')) { //"Fade In can't be larger than overall playlength."; $fadeIn = $clipLength; } $row->setDbFadein($fadeIn); } - if (!is_null($fadeOut)){ + if (!is_null($fadeOut)) { - $sql = "SELECT INTERVAL '{$fadeOut}' > INTERVAL '{$clipLength}'"; - $r = $this->con->query($sql); - if ($r->fetchColumn(0)) { + $sql = "SELECT :fadeout::INTERVAL > INTERVAL '{$clipLength}'"; + if (Application_Common_Database::prepareAndExecute($sql, array(':fadeout'=>$fadeOut), 'column')) { //Fade Out can't be larger than overall playlength."; $fadeOut = $clipLength; } @@ -526,8 +654,7 @@ class Application_Model_Playlist { $this->pl->save($this->con); $this->con->commit(); - } - catch (Exception $e) { + } catch (Exception $e) { $this->con->rollback(); throw $e; } @@ -535,10 +662,10 @@ class Application_Model_Playlist { return array("fadeIn" => $fadeIn, "fadeOut" => $fadeOut); } - public function setPlaylistfades($fadein, $fadeout) { - + public function setfades($fadein, $fadeout) + { if (isset($fadein)) { - Logging::log("Setting playlist fade in {$fadein}"); + Logging::info("Setting playlist fade in {$fadein}"); $row = CcPlaylistcontentsQuery::create() ->filterByDbPlaylistId($this->id) ->filterByDbPosition(0) @@ -548,7 +675,7 @@ class Application_Model_Playlist { } if (isset($fadeout)) { - Logging::log("Setting playlist fade out {$fadeout}"); + Logging::info("Setting playlist fade out {$fadeout}"); $row = CcPlaylistcontentsQuery::create() ->filterByDbPlaylistId($this->id) ->filterByDbPosition($this->getSize()-1) @@ -562,11 +689,11 @@ class Application_Model_Playlist { * Change cueIn/cueOut values for playlist element * * @param int $pos - * position of audioclip in playlist + * position of audioclip in playlist * @param string $cueIn - * new value in ss.ssssss or extent format + * new value in ss.ssssss or extent format * @param string $cueOut - * new value in ss.ssssss or extent format + * new value in ss.ssssss or extent format * @return boolean or pear error object */ public function changeClipLength($id, $cueIn, $cueOut) @@ -578,6 +705,7 @@ class Application_Model_Playlist { try { if (is_null($cueIn) && is_null($cueOut)) { $errArray["error"] = "Cue in and cue out are null."; + return $errArray; } @@ -598,74 +726,69 @@ class Application_Model_Playlist { $file = $row->getCcFiles($this->con); $origLength = $file->getDbLength(); - if (!is_null($cueIn) && !is_null($cueOut)){ + if (!is_null($cueIn) && !is_null($cueOut)) { - if ($cueOut === ""){ + if ($cueOut === "") { $cueOut = $origLength; } - $sql = "SELECT INTERVAL '{$cueIn}' > INTERVAL '{$cueOut}'"; - $r = $this->con->query($sql); - if ($r->fetchColumn(0)) { + $sql = "SELECT :cueIn::INTERVAL > :cueOut::INTERVAL"; + if (Application_Common_Database::prepareAndExecute($sql, array(':cueIn'=>$cueIn, ':cueOut'=>$cueOut), 'column')) { $errArray["error"] = "Can't set cue in to be larger than cue out."; + return $errArray; } - $sql = "SELECT INTERVAL '{$cueOut}' > INTERVAL '{$origLength}'"; - $r = $this->con->query($sql); - if ($r->fetchColumn(0)){ + $sql = "SELECT :cueOut::INTERVAL > :origLength::INTERVAL"; + if (Application_Common_Database::prepareAndExecute($sql, array(':cueOut'=>$cueOut, ':origLength'=>$origLength), 'column')) { $errArray["error"] = "Can't set cue out to be greater than file length."; + return $errArray; } - $sql = "SELECT INTERVAL '{$cueOut}' - INTERVAL '{$cueIn}'"; - $r = $this->con->query($sql); - $cliplength = $r->fetchColumn(0); + $sql = "SELECT :cueOut::INTERVAL - :cueIn::INTERVAL"; + $cliplength = Application_Common_Database::prepareAndExecute($sql, array(':cueOut'=>$cueOut, ':cueIn'=>$cueIn), 'column'); $row->setDbCuein($cueIn); $row->setDbCueout($cueOut); $row->setDBCliplength($cliplength); - } - else if (!is_null($cueIn)) { + } elseif (!is_null($cueIn)) { - $sql = "SELECT INTERVAL '{$cueIn}' > INTERVAL '{$oldCueOut}'"; - $r = $this->con->query($sql); - if ($r->fetchColumn(0)) { + $sql = "SELECT :cueIn::INTERVAL > :oldCueOut::INTERVAL"; + if (Application_Common_Database::prepareAndExecute($sql, array(':cueIn'=>$cueIn, ':oldCueOut'=>$oldCueOut), 'column')) { $errArray["error"] = "Can't set cue in to be larger than cue out."; + return $errArray; } - $sql = "SELECT INTERVAL '{$oldCueOut}' - INTERVAL '{$cueIn}'"; - $r = $this->con->query($sql); - $cliplength = $r->fetchColumn(0); + $sql = "SELECT :oldCueOut::INTERVAL - :cueIn::INTERVAL"; + $cliplength = Application_Common_Database::prepareAndExecute($sql, array(':cueIn'=>$cueIn, ':oldCueOut'=>$oldCueOut), 'column'); $row->setDbCuein($cueIn); $row->setDBCliplength($cliplength); - } - else if (!is_null($cueOut)) { + } elseif (!is_null($cueOut)) { - if ($cueOut === ""){ + if ($cueOut === "") { $cueOut = $origLength; } - $sql = "SELECT INTERVAL '{$cueOut}' < INTERVAL '{$oldCueIn}'"; - $r = $this->con->query($sql); - if ($r->fetchColumn(0)) { + $sql = "SELECT :cueOut::INTERVAL < :oldCueIn::INTERVAL"; + if (Application_Common_Database::prepareAndExecute($sql, array(':cueOut'=>$cueOut, ':oldCueIn'=>$oldCueIn), 'column')) { $errArray["error"] = "Can't set cue out to be smaller than cue in."; + return $errArray; } - $sql = "SELECT INTERVAL '{$cueOut}' > INTERVAL '{$origLength}'"; - $r = $this->con->query($sql); - if ($r->fetchColumn(0)){ + $sql = "SELECT :cueOut::INTERVAL > :origLength::INTERVAL"; + if (Application_Common_Database::prepareAndExecute($sql, array(':cueOut'=>$cueOut, ':origLength'=>$origLength), 'column')) { $errArray["error"] = "Can't set cue out to be greater than file length."; + return $errArray; } - $sql = "SELECT INTERVAL '{$cueOut}' - INTERVAL '{$oldCueIn}'"; - $r = $this->con->query($sql); - $cliplength = $r->fetchColumn(0); + $sql = "SELECT :cueOut::INTERVAL - :oldCueIn::INTERVAL"; + $cliplength = Application_Common_Database::prepareAndExecute($sql, array(':cueOut'=>$cueOut, ':oldCueIn'=>$oldCueIn), 'column'); $row->setDbCueout($cueOut); $row->setDBCliplength($cliplength); @@ -673,16 +796,14 @@ class Application_Model_Playlist { $cliplength = $row->getDbCliplength(); - $sql = "SELECT INTERVAL '{$fadeIn}' > INTERVAL '{$cliplength}'"; - $r = $this->con->query($sql); - if ($r->fetchColumn(0)){ + $sql = "SELECT :fadeIn::INTERVAL > :cliplength::INTERVAL"; + if (Application_Common_Database::prepareAndExecute($sql, array(':fadeIn'=>$fadeIn, ':cliplength'=>$cliplength), 'column')) { $fadeIn = $cliplength; $row->setDbFadein($fadeIn); } - $sql = "SELECT INTERVAL '{$fadeOut}' > INTERVAL '{$cliplength}'"; - $r = $this->con->query($sql); - if ($r->fetchColumn(0)){ + $sql = "SELECT :fadeOut::INTERVAL > :cliplength::INTERVAL"; + if (Application_Common_Database::prepareAndExecute($sql, array(':fadeOut'=>$fadeOut, ':cliplength'=>$cliplength), 'column')) { $fadeOut = $cliplength; $row->setDbFadein($fadeOut); } @@ -692,8 +813,7 @@ class Application_Model_Playlist { $this->pl->save($this->con); $this->con->commit(); - } - catch (Exception $e) { + } catch (Exception $e) { $this->con->rollback(); throw $e; } @@ -707,7 +827,7 @@ class Application_Model_Playlist { $categories = $this->categories; $md = array(); - foreach($categories as $key => $val) { + foreach ($categories as $key => $val) { $method = 'get' . $val; $md[$key] = $this->$method(); } @@ -715,14 +835,15 @@ class Application_Model_Playlist { return $md; } - public function getPLMetaData($category) + public function getMetaData($category) { $cat = $this->categories[$category]; $method = 'get' . $cat; + return $this->$method(); } - public function setPLMetaData($category, $value) + public function setMetadata($category, $value) { $cat = $this->categories[$category]; @@ -730,62 +851,12 @@ class Application_Model_Playlist { $this->$method($value); } - /** - * This function is used for calculations! Don't modify for display purposes! - * - * Convert playlist time value to float seconds - * - * @param string $plt - * playlist interval value (HH:mm:ss.dddddd) - * @return int - * seconds - */ - public static function playlistTimeToSeconds($plt) - { - $arr = preg_split('/:/', $plt); - if (isset($arr[2])) { - return (intval($arr[0])*60 + intval($arr[1]))*60 + floatval($arr[2]); - } - if (isset($arr[1])) { - return intval($arr[0])*60 + floatval($arr[1]); - } - return floatval($arr[0]); - } - - - /** - * This function is used for calculations! Don't modify for display purposes! - * - * Convert float seconds value to playlist time format - * - * @param float $seconds - * @return string - * interval in playlist time format (HH:mm:ss.d) - */ - public static function secondsToPlaylistTime($p_seconds) - { - $info = explode('.', $p_seconds); - $seconds = $info[0]; - if(!isset($info[1])){ - $milliStr = 0; - }else{ - $milliStr = $info[1]; - } - $hours = floor($seconds / 3600); - $seconds -= $hours * 3600; - $minutes = floor($seconds / 60); - $seconds -= $minutes * 60; - - $res = sprintf("%02d:%02d:%02d.%s", $hours, $minutes, $seconds, $milliStr); - - return $res; - } - public static function getPlaylistCount() { global $CC_CONFIG; $con = Propel::getConnection(); $sql = 'SELECT count(*) as cnt FROM '.$CC_CONFIG["playListTable"]; + return $con->query($sql)->fetchColumn(0); } @@ -802,12 +873,52 @@ class Application_Model_Playlist { * Delete playlists that match the ids.. * @param array $p_ids */ - public static function DeletePlaylists($p_ids) + public static function deletePlaylists($p_ids, $p_userId) { - CcPlaylistQuery::create()->findPKs($p_ids)->delete(); + $userInfo = Zend_Auth::getInstance()->getStorage()->read(); + $user = new Application_Model_User($userInfo->id); + $isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER)); + + if (!$isAdminOrPM) { + $leftOver = self::playlistsNotOwnedByUser($p_ids, $p_userId); + if (count($leftOver) == 0) { + CcPlaylistQuery::create()->findPKs($p_ids)->delete(); + } else { + throw new PlaylistNoPermissionException; + } + } else { + CcPlaylistQuery::create()->findPKs($p_ids)->delete(); + } + } + + // This function returns that are not owen by $p_user_id among $p_ids + private static function playlistsNotOwnedByUser($p_ids, $p_userId) + { + $ownedByUser = CcPlaylistQuery::create()->filterByDbCreatorId($p_userId)->find()->getData(); + $selectedPls = $p_ids; + $ownedPls = array(); + foreach ($ownedByUser as $pl) { + if (in_array($pl->getDbId(), $selectedPls)) { + $ownedPls[] = $pl->getDbId(); + } + } + + $leftOvers = array_diff($selectedPls, $ownedPls); + + return $leftOvers; + } + + /** + * Delete all files from playlist + * @param int $p_playlistId + */ + public function deleteAllFilesFromPlaylist() + { + CcPlaylistcontentsQuery::create()->findByDbPlaylistId($this->id)->delete(); } } // class Playlist class PlaylistNotFoundException extends Exception {} +class PlaylistNoPermissionException extends Exception {} class PlaylistOutDatedException extends Exception {} diff --git a/airtime_mvc/application/models/PlayoutHistory.php b/airtime_mvc/application/models/PlayoutHistory.php index a5e4b9fb1..7da1ff2c2 100644 --- a/airtime_mvc/application/models/PlayoutHistory.php +++ b/airtime_mvc/application/models/PlayoutHistory.php @@ -2,82 +2,82 @@ require_once 'formatters/LengthFormatter.php'; -class Application_Model_PlayoutHistory { - - private $con; - private $timezone; - - //in UTC timezone - private $startDT; - //in UTC timezone - private $endDT; - - private $epoch_now; - private $opts; - - private $mDataPropMap = array( - "artist" => "file.artist_name", - "title" => "file.track_title", - "played" => "playout.played", - "length" => "file.length", - "composer" => "file.composer", - "copyright" => "file.copyright", - ); - - public function __construct($p_startDT, $p_endDT, $p_opts) { - - $this->con = Propel::getConnection(CcSchedulePeer::DATABASE_NAME); - $this->startDT = $p_startDT; - $this->endDT = $p_endDT; - $this->timezone = date_default_timezone_get(); - $this->epoch_now = time(); - $this->opts = $p_opts; - } - - /* - * map front end mDataProp labels to proper column names for searching etc. - */ - private function translateColumns() { - - for ($i = 0; $i < $this->opts["iColumns"]; $i++){ - - $this->opts["mDataProp_{$i}"] = $this->mDataPropMap[$this->opts["mDataProp_{$i}"]]; - } - } - - public function getItems() { - - $this->translateColumns(); - - $select = array( - "file.track_title as title", - "file.artist_name as artist", - "playout.played", - "playout.file_id", - "file.composer", - "file.copyright", - "file.length" - ); - - $start = $this->startDT->format("Y-m-d H:i:s"); - $end = $this->endDT->format("Y-m-d H:i:s"); - - $historyTable = "( - select count(schedule.file_id) as played, schedule.file_id as file_id - from cc_schedule as schedule - where schedule.starts >= '{$start}' and schedule.starts < '{$end}' - and schedule.playout_status > 0 and schedule.media_item_played != FALSE and schedule.broadcasted = 1 - group by schedule.file_id - ) - AS playout left join cc_files as file on (file.id = playout.file_id)"; +class Application_Model_PlayoutHistory +{ + private $con; + private $timezone; - $results = Application_Model_Datatables::findEntries($this->con, $select, $historyTable, $this->opts, "history"); - - foreach ($results["history"] as &$row) { - $formatter = new LengthFormatter($row['length']); - $row['length'] = $formatter->format(); - } - - return $results; - } -} \ No newline at end of file + //in UTC timezone + private $startDT; + //in UTC timezone + private $endDT; + + private $epoch_now; + private $opts; + + private $mDataPropMap = array( + "artist" => "artist_name", + "title" => "track_title", + "played" => "played", + "length" => "length", + "composer" => "composer", + "copyright" => "copyright", + ); + + public function __construct($p_startDT, $p_endDT, $p_opts) + { + $this->con = Propel::getConnection(CcSchedulePeer::DATABASE_NAME); + $this->startDT = $p_startDT; + $this->endDT = $p_endDT; + $this->timezone = date_default_timezone_get(); + $this->epoch_now = time(); + $this->opts = $p_opts; + } + + /* + * map front end mDataProp labels to proper column names for searching etc. + */ + private function translateColumns() + { + for ($i = 0; $i < $this->opts["iColumns"]; $i++) { + + $this->opts["mDataProp_{$i}"] = $this->mDataPropMap[$this->opts["mDataProp_{$i}"]]; + } + } + + public function getItems() + { + $this->translateColumns(); + + $select = array( + "file.track_title as title", + "file.artist_name as artist", + "playout.played", + "playout.file_id", + "file.composer", + "file.copyright", + "file.length" + ); + + $start = $this->startDT->format("Y-m-d H:i:s"); + $end = $this->endDT->format("Y-m-d H:i:s"); + + $historyTable = "( + select count(schedule.file_id) as played, schedule.file_id as file_id + from cc_schedule as schedule + where schedule.starts >= '{$start}' and schedule.starts < '{$end}' + and schedule.playout_status > 0 and schedule.media_item_played != FALSE and schedule.broadcasted = 1 + group by schedule.file_id + ) + AS playout left join cc_files as file on (file.id = playout.file_id)"; + + $results = Application_Model_Datatables::findEntries($this->con, $select, $historyTable, $this->opts, "history"); + + foreach ($results["history"] as &$row) { + $formatter = new LengthFormatter($row['length']); + $row['length'] = $formatter->format(); + } + + return $results; + } +} diff --git a/airtime_mvc/application/models/Preference.php b/airtime_mvc/application/models/Preference.php index 227966c99..e65151ce4 100644 --- a/airtime_mvc/application/models/Preference.php +++ b/airtime_mvc/application/models/Preference.php @@ -3,126 +3,138 @@ class Application_Model_Preference { - public static function SetValue($key, $value, $isUserValue = false){ + private static function setValue($key, $value, $isUserValue = false) + { try { - $con = Propel::getConnection(); - //called from a daemon process - if(!class_exists("Zend_Auth", false) || !Zend_Auth::getInstance()->hasIdentity()) { + if (!class_exists("Zend_Auth", false) || !Zend_Auth::getInstance()->hasIdentity()) { $id = NULL; - } - else { + } else { $auth = Zend_Auth::getInstance(); $id = $auth->getIdentity()->id; } - $key = pg_escape_string($key); - $value = pg_escape_string($value); - //Check if key already exists $sql = "SELECT COUNT(*) FROM cc_pref" - ." WHERE keystr = '$key'"; - + ." WHERE keystr = :key"; + + $paramMap = array(); + $paramMap[':key'] = $key; + //For user specific preference, check if id matches as well - if($isUserValue) { - $sql .= " AND subjid = '$id'"; + if ($isUserValue) { + $sql .= " AND subjid = :id"; + $paramMap[':id'] = $id; } - - $result = $con->query($sql)->fetchColumn(0); - if($value == "") { - $value = "NULL"; - }else { - $value = "'$value'"; - } - - if($result == 1) { + $result = Application_Common_Database::prepareAndExecute($sql, $paramMap, 'column'); + + $paramMap = array(); + if ($result == 1) { // result found - if(is_null($id) || !$isUserValue) { + if (is_null($id) || !$isUserValue) { // system pref $sql = "UPDATE cc_pref" - ." SET subjid = NULL, valstr = $value" - ." WHERE keystr = '$key'"; + ." SET subjid = NULL, valstr = :value" + ." WHERE keystr = :key"; } else { // user pref $sql = "UPDATE cc_pref" - . " SET valstr = $value" - . " WHERE keystr = '$key' AND subjid = $id"; + . " SET valstr = :value" + . " WHERE keystr = :key AND subjid = :id"; + $paramMap[':id'] = $id; } } else { // result not found - if(is_null($id) || !$isUserValue) { + if (is_null($id) || !$isUserValue) { // system pref $sql = "INSERT INTO cc_pref (keystr, valstr)" - ." VALUES ('$key', $value)"; + ." VALUES (:key, :value)"; } else { // user pref $sql = "INSERT INTO cc_pref (subjid, keystr, valstr)" - ." VALUES ($id, '$key', $value)"; + ." VALUES (:id, :key, :value)"; + $paramMap[':id'] = $id; } } + $paramMap[':key'] = $key; + $paramMap[':value'] = $value; - $con->exec($sql); - - } catch (Exception $e){ + Application_Common_Database::prepareAndExecute($sql, $paramMap, 'execute'); + + } catch (Exception $e) { header('HTTP/1.0 503 Service Unavailable'); - Logging::log("Could not connect to database: ".$e->getMessage()); + Logging::info("Could not connect to database: ".$e->getMessage()); exit; } } - public static function GetValue($key, $isUserValue = false){ + private static function getValue($key, $isUserValue = false) + { try { $con = Propel::getConnection(); //Check if key already exists $sql = "SELECT COUNT(*) FROM cc_pref" ." WHERE keystr = '$key'"; + /*." WHERE keystr = :key"; + $paramMap = array(); + $paramMap[':key'] = $key;*/ //For user specific preference, check if id matches as well if ($isUserValue) { $auth = Zend_Auth::getInstance(); - if($auth->hasIdentity()) { + if ($auth->hasIdentity()) { $id = $auth->getIdentity()->id; $sql .= " AND subjid = '$id'"; + /*$sql .= " AND subjid = :id"; + $paramMap[':id'] = $id;*/ } } $result = $con->query($sql)->fetchColumn(0); - if ($result == 0) + //$result = Application_Common_Database::prepareAndExecute($sql, $paramMap, 'column'); + if ($result == 0) { return ""; - else { + } else { $sql = "SELECT valstr FROM cc_pref" ." WHERE keystr = '$key'"; + /*." WHERE keystr = :key"; + $paramMap = array(); + $paramMap[':key'] = $key;*/ //For user specific preference, check if id matches as well - if($isUserValue && $auth->hasIdentity()) { + if ($isUserValue && $auth->hasIdentity()) { $sql .= " AND subjid = '$id'"; + /*$sql .= " AND subjid = :id"; + $paramMap[':id'] = $id;*/ } - $result = $con->query($sql)->fetchColumn(0); + //$result = Application_Common_Database::prepareAndExecute($sql, $paramMap, 'column'); + return ($result !== false) ? $result : ""; } } catch (Exception $e) { header('HTTP/1.0 503 Service Unavailable'); - Logging::log("Could not connect to database: ".$e->getMessage()); - exit; + Logging::info("Could not connect to database: ".$e->getMessage()); + exit; } } - public static function GetHeadTitle(){ - $title = self::GetValue("station_name"); - $defaultNamespace->title = $title; + public static function GetHeadTitle() + { + $title = self::getValue("station_name"); if (strlen($title) > 0) $title .= " - "; return $title."Airtime"; } - public static function SetHeadTitle($title, $view=null){ - self::SetValue("station_name", $title); + public static function SetHeadTitle($title, $view=null) + { + self::setValue("station_name", $title); // in case this is called from airtime-saas script - if($view !== null){ + if ($view !== null) { //set session variable to new station name so that html title is updated. //should probably do this in a view helper to keep this controller as minimal as possible. $view->headTitle()->exchangeArray(array()); //clear headTitle ArrayObject @@ -142,8 +154,9 @@ class Application_Model_Preference * @param DateTime $dateTime * A row from cc_show_days table */ - public static function SetShowsPopulatedUntil($dateTime) { - self::SetValue("shows_populated_until", $dateTime->format("Y-m-d H:i:s")); + public static function SetShowsPopulatedUntil($dateTime) + { + self::setValue("shows_populated_until", $dateTime->format("Y-m-d H:i:s")); } /** @@ -155,31 +168,34 @@ class Application_Model_Preference * * @return DateTime (in UTC Timezone) */ - public static function GetShowsPopulatedUntil() { - $date = self::GetValue("shows_populated_until"); + public static function GetShowsPopulatedUntil() + { + $date = self::getValue("shows_populated_until"); - if ($date == ""){ + if ($date == "") { return null; } else { return new DateTime($date, new DateTimeZone("UTC")); } } - public static function SetDefaultFade($fade) { - self::SetValue("default_fade", $fade); + public static function SetDefaultFade($fade) + { + self::setValue("default_fade", $fade); } - public static function GetDefaultFade() { - $fade = self::GetValue("default_fade"); - + public static function GetDefaultFade() + { + $fade = self::getValue("default_fade"); + if ($fade === "") { // the default value of the fade is 00.500000 return "00.500000"; } - + // we need this function to work with 2.0 version on default_fade value in cc_pref // it has 00:00:00.000000 format where in 2.1 we have 00.000000 format - if(preg_match("/([0-9]{2}):([0-9]{2}):([0-9]{2}).([0-9]{6})/", $fade, $matches) == 1 && count($matches) == 5){ + if (preg_match("/([0-9]{2}):([0-9]{2}):([0-9]{2}).([0-9]{6})/", $fade, $matches) == 1 && count($matches) == 5) { $out = 0; $out += intval($matches[1] * 3600); $out += intval($matches[2] * 60); @@ -187,31 +203,32 @@ class Application_Model_Preference $out .= ".$matches[4]"; $fade = $out; } - + $fade = number_format($fade, 6); //fades need 2 leading zeros for DateTime conversion $fade = str_pad($fade, 9, "0", STR_PAD_LEFT); + return $fade; } - public static function SetDefaultTransitionFade($fade) { - self::SetValue("default_transition_fade", $fade); + public static function SetDefaultTransitionFade($fade) + { + self::setValue("default_transition_fade", $fade); $eventType = "update_transition_fade"; $md = array("transition_fade"=>$fade); Application_Model_RabbitMq::SendMessageToPypo($eventType, $md); } - public static function GetDefaultTransitionFade() { - $transition_fade = self::GetValue("default_transition_fade"); - if($transition_fade == ""){ - $transition_fade = "00.000000"; - } - return $transition_fade; + public static function GetDefaultTransitionFade() + { + $transition_fade = self::getValue("default_transition_fade"); + return ($transition_fade == "") ? "00.000000" : $transition_fade; } - public static function SetStreamLabelFormat($type){ - self::SetValue("stream_label_format", $type); + public static function SetStreamLabelFormat($type) + { + self::setValue("stream_label_format", $type); $eventType = "update_stream_format"; $md = array("stream_format"=>$type); @@ -219,500 +236,578 @@ class Application_Model_Preference Application_Model_RabbitMq::SendMessageToPypo($eventType, $md); } - public static function GetStreamLabelFormat(){ + public static function GetStreamLabelFormat() + { return self::getValue("stream_label_format"); } - public static function GetStationName(){ + public static function GetStationName() + { return self::getValue("station_name"); } - public static function SetAutoUploadRecordedShowToSoundcloud($upload) { - self::SetValue("soundcloud_auto_upload_recorded_show", $upload); + public static function SetAutoUploadRecordedShowToSoundcloud($upload) + { + self::setValue("soundcloud_auto_upload_recorded_show", $upload); } - public static function GetAutoUploadRecordedShowToSoundcloud() { - return self::GetValue("soundcloud_auto_upload_recorded_show"); + public static function GetAutoUploadRecordedShowToSoundcloud() + { + return self::getValue("soundcloud_auto_upload_recorded_show"); } - public static function SetSoundCloudUser($user) { - self::SetValue("soundcloud_user", $user); + public static function SetSoundCloudUser($user) + { + self::setValue("soundcloud_user", $user); } - public static function GetSoundCloudUser() { - return self::GetValue("soundcloud_user"); + public static function GetSoundCloudUser() + { + return self::getValue("soundcloud_user"); } - public static function SetSoundCloudPassword($password) { + public static function SetSoundCloudPassword($password) + { if (strlen($password) > 0) - self::SetValue("soundcloud_password", $password); + self::setValue("soundcloud_password", $password); } - public static function GetSoundCloudPassword() { - return self::GetValue("soundcloud_password"); + public static function GetSoundCloudPassword() + { + return self::getValue("soundcloud_password"); } - public static function SetSoundCloudTags($tags) { - self::SetValue("soundcloud_tags", $tags); + public static function SetSoundCloudTags($tags) + { + self::setValue("soundcloud_tags", $tags); } - public static function GetSoundCloudTags() { - return self::GetValue("soundcloud_tags"); + public static function GetSoundCloudTags() + { + return self::getValue("soundcloud_tags"); } - public static function SetSoundCloudGenre($genre) { - self::SetValue("soundcloud_genre", $genre); + public static function SetSoundCloudGenre($genre) + { + self::setValue("soundcloud_genre", $genre); } - public static function GetSoundCloudGenre() { - return self::GetValue("soundcloud_genre"); + public static function GetSoundCloudGenre() + { + return self::getValue("soundcloud_genre"); } - public static function SetSoundCloudTrackType($track_type) { - self::SetValue("soundcloud_tracktype", $track_type); + public static function SetSoundCloudTrackType($track_type) + { + self::setValue("soundcloud_tracktype", $track_type); } - public static function GetSoundCloudTrackType() { - return self::GetValue("soundcloud_tracktype"); + public static function GetSoundCloudTrackType() + { + return self::getValue("soundcloud_tracktype"); } - public static function SetSoundCloudLicense($license) { - self::SetValue("soundcloud_license", $license); + public static function SetSoundCloudLicense($license) + { + self::setValue("soundcloud_license", $license); } - public static function GetSoundCloudLicense() { - return self::GetValue("soundcloud_license"); + public static function GetSoundCloudLicense() + { + return self::getValue("soundcloud_license"); } - public static function SetAllow3rdPartyApi($bool) { - self::SetValue("third_party_api", $bool); + public static function SetAllow3rdPartyApi($bool) + { + self::setValue("third_party_api", $bool); } - public static function GetAllow3rdPartyApi() { - $val = self::GetValue("third_party_api"); - if (strlen($val) == 0){ - return "0"; + public static function GetAllow3rdPartyApi() + { + $val = self::getValue("third_party_api"); + return (strlen($val) == 0 ) ? "0" : $val; + } + + public static function SetPhone($phone) + { + self::setValue("phone", $phone); + } + + public static function GetPhone() + { + return self::getValue("phone"); + } + + public static function SetEmail($email) + { + self::setValue("email", $email); + } + + public static function GetEmail() + { + return self::getValue("email"); + } + + public static function SetStationWebSite($site) + { + self::setValue("station_website", $site); + } + + public static function GetStationWebSite() + { + return self::getValue("station_website"); + } + + public static function SetSupportFeedback($feedback) + { + self::setValue("support_feedback", $feedback); + } + + public static function GetSupportFeedback() + { + return self::getValue("support_feedback"); + } + + public static function SetPublicise($publicise) + { + self::setValue("publicise", $publicise); + } + + public static function GetPublicise() + { + return self::getValue("publicise"); + } + + public static function SetRegistered($registered) + { + self::setValue("registered", $registered); + } + + public static function GetRegistered() + { + return self::getValue("registered"); + } + + public static function SetStationCountry($country) + { + self::setValue("country", $country); + } + + public static function GetStationCountry() + { + return self::getValue("country"); + } + + public static function SetStationCity($city) + { + self::setValue("city", $city); + } + + public static function GetStationCity() + { + return self::getValue("city"); + } + + public static function SetStationDescription($description) + { + self::setValue("description", $description); + } + + public static function GetStationDescription() + { + return self::getValue("description"); + } + + public static function SetTimezone($timezone) + { + self::setValue("timezone", $timezone); + date_default_timezone_set($timezone); + } + + public static function GetTimezone() + { + return self::getValue("timezone"); + } + + public static function SetStationLogo($imagePath) + { + if (!empty($imagePath)) { + $image = @file_get_contents($imagePath); + $image = base64_encode($image); + self::setValue("logoImage", $image); } else { - return $val; + Logging::warn("Attempting to set imagePath to empty string"); } } - public static function SetPhone($phone){ - self::SetValue("phone", $phone); + public static function GetStationLogo() + { + return self::getValue("logoImage"); } - public static function GetPhone(){ - return self::GetValue("phone"); - } - - public static function SetEmail($email){ - self::SetValue("email", $email); - } - - public static function GetEmail(){ - return self::GetValue("email"); - } - - public static function SetStationWebSite($site){ - self::SetValue("station_website", $site); - } - - public static function GetStationWebSite(){ - return self::GetValue("station_website"); - } - - public static function SetSupportFeedback($feedback){ - self::SetValue("support_feedback", $feedback); - } - - public static function GetSupportFeedback(){ - return self::GetValue("support_feedback"); - } - - public static function SetPublicise($publicise){ - self::SetValue("publicise", $publicise); - } - - public static function GetPublicise(){ - return self::GetValue("publicise"); - } - - public static function SetRegistered($registered){ - self::SetValue("registered", $registered); - } - - public static function GetRegistered(){ - return self::GetValue("registered"); - } - - public static function SetStationCountry($country){ - self::SetValue("country", $country); - } - - public static function GetStationCountry(){ - return self::GetValue("country"); - } - - public static function SetStationCity($city){ - self::SetValue("city", $city); - } - - public static function GetStationCity(){ - return self::GetValue("city"); - } - - public static function SetStationDescription($description){ - self::SetValue("description", $description); - } - - public static function GetStationDescription(){ - return self::GetValue("description"); - } - - public static function SetTimezone($timezone){ - self::SetValue("timezone", $timezone); - date_default_timezone_set($timezone); - $md = array("timezone" => $timezone); - } - - public static function GetTimezone(){ - return self::GetValue("timezone"); - } - - public static function SetStationLogo($imagePath){ - if(!empty($imagePath)){ - $image = @file_get_contents($imagePath); - $image = base64_encode($image); - self::SetValue("logoImage", $image); - } - } - - public static function GetStationLogo(){ - return self::GetValue("logoImage"); - } - - public static function GetUniqueId(){ - return self::GetValue("uniqueId"); + public static function GetUniqueId() + { + return self::getValue("uniqueId"); } public static function GetCountryList() { - $con = Propel::getConnection(); - $sql = "SELECT * FROM cc_country"; - $res = $con->query($sql)->fetchAll(); - $out = array(); - $out[""] = "Select Country"; - foreach($res as $r){ - $out[$r["isocode"]] = $r["name"]; - } - return $out; + $con = Propel::getConnection(); + $sql = "SELECT * FROM cc_country"; + $res = $con->query($sql)->fetchAll(); + $out = array(); + $out[""] = "Select Country"; + foreach ($res as $r) { + $out[$r["isocode"]] = $r["name"]; + } + + return $out; } public static function GetSystemInfo($returnArray=false, $p_testing=false) { - exec('/usr/bin/airtime-check-system --no-color', $output); - $output = preg_replace('/\s+/', ' ', $output); + exec('/usr/bin/airtime-check-system --no-color', $output); + $output = preg_replace('/\s+/', ' ', $output); - $systemInfoArray = array(); - foreach( $output as $key => &$out){ - $info = explode('=', $out); - if(isset($info[1])){ - $key = str_replace(' ', '_', trim($info[0])); - $key = strtoupper($key); - if ($key == 'WEB_SERVER' || $key == 'CPU' || $key == 'OS' || $key == 'TOTAL_RAM' || - $key == 'FREE_RAM' || $key == 'AIRTIME_VERSION' || $key == 'KERNAL_VERSION' || - $key == 'MACHINE_ARCHITECTURE' || $key == 'TOTAL_MEMORY_MBYTES' || $key == 'TOTAL_SWAP_MBYTES' || - $key == 'PLAYOUT_ENGINE_CPU_PERC' ) { - if($key == 'AIRTIME_VERSION'){ - // remove hash tag on the version string - $version = explode('+', $info[1]); - $systemInfoArray[$key] = $version[0]; - }else{ - $systemInfoArray[$key] = $info[1]; - } - } - } - } - - $outputArray = array(); + $systemInfoArray = array(); + foreach ($output as $key => &$out) { + $info = explode('=', $out); + if (isset($info[1])) { + $key = str_replace(' ', '_', trim($info[0])); + $key = strtoupper($key); + if ($key == 'WEB_SERVER' || $key == 'CPU' || $key == 'OS' || $key == 'TOTAL_RAM' || + $key == 'FREE_RAM' || $key == 'AIRTIME_VERSION' || $key == 'KERNAL_VERSION' || + $key == 'MACHINE_ARCHITECTURE' || $key == 'TOTAL_MEMORY_MBYTES' || $key == 'TOTAL_SWAP_MBYTES' || + $key == 'PLAYOUT_ENGINE_CPU_PERC') { + if ($key == 'AIRTIME_VERSION') { + // remove hash tag on the version string + $version = explode('+', $info[1]); + $systemInfoArray[$key] = $version[0]; + } else { + $systemInfoArray[$key] = $info[1]; + } + } + } + } - $outputArray['LIVE_DURATION'] = Application_Model_LiveLog::GetLiveShowDuration($p_testing); - $outputArray['SCHEDULED_DURATION'] = Application_Model_LiveLog::GetScheduledDuration($p_testing); - $outputArray['SOUNDCLOUD_ENABLED'] = self::GetUploadToSoundcloudOption(); + $outputArray = array(); + + $outputArray['LIVE_DURATION'] = Application_Model_LiveLog::GetLiveShowDuration($p_testing); + $outputArray['SCHEDULED_DURATION'] = Application_Model_LiveLog::GetScheduledDuration($p_testing); + $outputArray['SOUNDCLOUD_ENABLED'] = self::GetUploadToSoundcloudOption(); if ($outputArray['SOUNDCLOUD_ENABLED']) { - $outputArray['NUM_SOUNDCLOUD_TRACKS_UPLOADED'] = Application_Model_StoredFile::getSoundCloudUploads(); + $outputArray['NUM_SOUNDCLOUD_TRACKS_UPLOADED'] = Application_Model_StoredFile::getSoundCloudUploads(); } else { $outputArray['NUM_SOUNDCLOUD_TRACKS_UPLOADED'] = NULL; } - $outputArray['STATION_NAME'] = self::GetStationName(); - $outputArray['PHONE'] = self::GetPhone(); - $outputArray['EMAIL'] = self::GetEmail(); - $outputArray['STATION_WEB_SITE'] = self::GetStationWebSite(); - $outputArray['STATION_COUNTRY'] = self::GetStationCountry(); - $outputArray['STATION_CITY'] = self::GetStationCity(); - $outputArray['STATION_DESCRIPTION'] = self::GetStationDescription(); + $outputArray['STATION_NAME'] = self::GetStationName(); + $outputArray['PHONE'] = self::GetPhone(); + $outputArray['EMAIL'] = self::GetEmail(); + $outputArray['STATION_WEB_SITE'] = self::GetStationWebSite(); + $outputArray['STATION_COUNTRY'] = self::GetStationCountry(); + $outputArray['STATION_CITY'] = self::GetStationCity(); + $outputArray['STATION_DESCRIPTION'] = self::GetStationDescription(); - // get web server info - if(isset($systemInfoArray["AIRTIME_VERSION_URL"])){ - $url = $systemInfoArray["AIRTIME_VERSION_URL"]; + // get web server info + if (isset($systemInfoArray["AIRTIME_VERSION_URL"])) { + $url = $systemInfoArray["AIRTIME_VERSION_URL"]; $index = strpos($url,'/api/'); $url = substr($url, 0, $index); $headerInfo = get_headers(trim($url),1); $outputArray['WEB_SERVER'] = $headerInfo['Server'][0]; - } + } - $outputArray['NUM_OF_USERS'] = Application_Model_User::getUserCount(); - $outputArray['NUM_OF_SONGS'] = Application_Model_StoredFile::getFileCount(); - $outputArray['NUM_OF_PLAYLISTS'] = Application_Model_Playlist::getPlaylistCount(); - $outputArray['NUM_OF_SCHEDULED_PLAYLISTS'] = Application_Model_Schedule::getSchduledPlaylistCount(); - $outputArray['NUM_OF_PAST_SHOWS'] = Application_Model_ShowInstance::GetShowInstanceCount(gmdate("Y-m-d H:i:s")); - $outputArray['UNIQUE_ID'] = self::GetUniqueId(); - $outputArray['SAAS'] = self::GetPlanLevel(); - if ($outputArray['SAAS'] != 'disabled') { - $outputArray['TRIAL_END_DATE'] = self::GetTrialEndingDate(); - } else { + $outputArray['NUM_OF_USERS'] = Application_Model_User::getUserCount(); + $outputArray['NUM_OF_SONGS'] = Application_Model_StoredFile::getFileCount(); + $outputArray['NUM_OF_PLAYLISTS'] = Application_Model_Playlist::getPlaylistCount(); + $outputArray['NUM_OF_SCHEDULED_PLAYLISTS'] = Application_Model_Schedule::getSchduledPlaylistCount(); + $outputArray['NUM_OF_PAST_SHOWS'] = Application_Model_ShowInstance::GetShowInstanceCount(gmdate("Y-m-d H:i:s")); + $outputArray['UNIQUE_ID'] = self::GetUniqueId(); + $outputArray['SAAS'] = self::GetPlanLevel(); + if ($outputArray['SAAS'] != 'disabled') { + $outputArray['TRIAL_END_DATE'] = self::GetTrialEndingDate(); + } else { $outputArray['TRIAL_END_DATE'] = NULL; } - $outputArray['INSTALL_METHOD'] = self::GetInstallMethod(); - $outputArray['NUM_OF_STREAMS'] = self::GetNumOfStreams(); - $outputArray['STREAM_INFO'] = Application_Model_StreamSetting::getStreamInfoForDataCollection(); + $outputArray['INSTALL_METHOD'] = self::GetInstallMethod(); + $outputArray['NUM_OF_STREAMS'] = self::GetNumOfStreams(); + $outputArray['STREAM_INFO'] = Application_Model_StreamSetting::getStreamInfoForDataCollection(); - $outputArray = array_merge($systemInfoArray, $outputArray); + $outputArray = array_merge($systemInfoArray, $outputArray); - $outputString = "\n"; - foreach($outputArray as $key => $out){ - if($key == 'TRIAL_END_DATE' && ($out != '' || $out != 'NULL')){ - continue; - } - if($key == "STREAM_INFO"){ - $outputString .= $key." :\n"; - foreach($out as $s_info){ - foreach($s_info as $k => $v){ - $outputString .= "\t".strtoupper($k)." : ".$v."\n"; - } - } - }else if ($key == "SOUNDCLOUD_ENABLED") { - if ($out) { - $outputString .= $key." : TRUE\n"; - } else if (!$out) { - $outputString .= $key." : FALSE\n"; - } - }else if ($key == "SAAS") { + $outputString = "\n"; + foreach ($outputArray as $key => $out) { + if ($key == 'TRIAL_END_DATE' && ($out != '' || $out != 'NULL')) { + continue; + } + if ($key == "STREAM_INFO") { + $outputString .= $key." :\n"; + foreach ($out as $s_info) { + foreach ($s_info as $k => $v) { + $outputString .= "\t".strtoupper($k)." : ".$v."\n"; + } + } + } elseif ($key == "SOUNDCLOUD_ENABLED") { + if ($out) { + $outputString .= $key." : TRUE\n"; + } elseif (!$out) { + $outputString .= $key." : FALSE\n"; + } + } elseif ($key == "SAAS") { if (strcmp($out, 'disabled')!=0) { $outputString .= $key.' : '.$out."\n"; } - }else{ - $outputString .= $key.' : '.$out."\n"; - } - } - if($returnArray){ - $outputArray['PROMOTE'] = self::GetPublicise(); - $outputArray['LOGOIMG'] = self::GetStationLogo(); - return $outputArray; - }else{ - return $outputString; - } + } else { + $outputString .= $key.' : '.$out."\n"; + } + } + if ($returnArray) { + $outputArray['PROMOTE'] = self::GetPublicise(); + $outputArray['LOGOIMG'] = self::GetStationLogo(); + + return $outputArray; + } else { + return $outputString; + } } - public static function GetInstallMethod(){ + public static function GetInstallMethod() + { $easy_install = file_exists('/usr/bin/airtime-easy-setup'); $debian_install = file_exists('/var/lib/dpkg/info/airtime.config'); - if($debian_install){ - if($easy_install){ + if ($debian_install) { + if ($easy_install) { return "easy_install"; - }else{ + } else { return "debian_install"; } - }else{ + } else { return "manual_install"; } } - public static function SetRemindMeDate(){ - $weekAfter = mktime(0, 0, 0, gmdate("m"), gmdate("d")+7, gmdate("Y")); - self::SetValue("remindme", $weekAfter); - } - - public static function GetRemindMeDate(){ - return self::GetValue("remindme"); - } - - public static function SetImportTimestamp(){ - $now = time(); - if(self::GetImportTimestamp()+5 < $now){ - self::SetValue("import_timestamp", $now); + public static function SetRemindMeDate($p_never = false) + { + if ($p_never) { + self::setValue("remindme", -1); + } else { + $weekAfter = mktime(0, 0, 0, gmdate("m"), gmdate("d")+7, gmdate("Y")); + self::setValue("remindme", $weekAfter); } } - public static function GetImportTimestamp(){ - return self::GetValue("import_timestamp"); + public static function GetRemindMeDate() + { + return self::getValue("remindme"); } - public static function GetStreamType(){ - $st = self::GetValue("stream_type"); + public static function SetImportTimestamp() + { + $now = time(); + if (self::GetImportTimestamp()+5 < $now) { + self::setValue("import_timestamp", $now); + } + } + + public static function GetImportTimestamp() + { + return self::getValue("import_timestamp"); + } + + public static function GetStreamType() + { + $st = self::getValue("stream_type"); + return explode(',', $st); } - public static function GetStreamBitrate(){ - $sb = self::GetValue("stream_bitrate"); + public static function GetStreamBitrate() + { + $sb = self::getValue("stream_bitrate"); + return explode(',', $sb); } - public static function SetPrivacyPolicyCheck($flag){ - self::SetValue("privacy_policy", $flag); + public static function SetPrivacyPolicyCheck($flag) + { + self::setValue("privacy_policy", $flag); } - public static function GetPrivacyPolicyCheck(){ - return self::GetValue("privacy_policy"); + public static function GetPrivacyPolicyCheck() + { + return self::getValue("privacy_policy"); } - public static function SetNumOfStreams($num){ - self::SetValue("num_of_streams", intval($num)); + public static function SetNumOfStreams($num) + { + self::setValue("num_of_streams", intval($num)); } - public static function GetNumOfStreams(){ - return self::GetValue("num_of_streams"); + public static function GetNumOfStreams() + { + return self::getValue("num_of_streams"); } - public static function SetMaxBitrate($bitrate){ - self::SetValue("max_bitrate", intval($bitrate)); + public static function SetMaxBitrate($bitrate) + { + self::setValue("max_bitrate", intval($bitrate)); } - public static function GetMaxBitrate(){ - return self::GetValue("max_bitrate"); + public static function GetMaxBitrate() + { + return self::getValue("max_bitrate"); } - public static function SetPlanLevel($plan){ - self::SetValue("plan_level", $plan); + public static function SetPlanLevel($plan) + { + self::setValue("plan_level", $plan); } - public static function GetPlanLevel(){ - $plan = self::GetValue("plan_level"); - if(trim($plan) == ''){ + public static function GetPlanLevel() + { + $plan = self::getValue("plan_level"); + if (trim($plan) == '') { $plan = 'disabled'; } + return $plan; } - public static function SetTrialEndingDate($date){ - self::SetValue("trial_end_date", $date); + public static function SetTrialEndingDate($date) + { + self::setValue("trial_end_date", $date); } - public static function GetTrialEndingDate(){ - return self::GetValue("trial_end_date"); + public static function GetTrialEndingDate() + { + return self::getValue("trial_end_date"); } - public static function SetEnableStreamConf($bool){ - self::SetValue("enable_stream_conf", $bool); + public static function SetEnableStreamConf($bool) + { + self::setValue("enable_stream_conf", $bool); } - public static function GetEnableStreamConf(){ - if(self::GetValue("enable_stream_conf") == Null){ + public static function GetEnableStreamConf() + { + if (self::getValue("enable_stream_conf") == Null) { return "true"; } - return self::GetValue("enable_stream_conf"); + + return self::getValue("enable_stream_conf"); } - public static function GetAirtimeVersion(){ - if (defined('APPLICATION_ENV') && APPLICATION_ENV == "development" && function_exists('exec')){ + public static function GetAirtimeVersion() + { + if (defined('APPLICATION_ENV') && APPLICATION_ENV == "development" && function_exists('exec')) { $version = exec("git rev-parse --short HEAD 2>/dev/null", $out, $return_code); - if ($return_code == 0){ - return self::GetValue("system_version")."+".$version.":".time(); + if ($return_code == 0) { + return self::getValue("system_version")."+".$version.":".time(); } } - return self::GetValue("system_version"); + + return self::getValue("system_version"); } - public static function GetLatestVersion(){ - $latest = self::GetValue("latest_version"); - if($latest == null || strlen($latest) == 0) { + public static function GetLatestVersion() + { + $latest = self::getValue("latest_version"); + if ($latest == null || strlen($latest) == 0) { return self::GetAirtimeVersion(); } else { return $latest; } } - public static function SetLatestVersion($version){ + public static function SetLatestVersion($version) + { $pattern = "/^[0-9]+\.[0-9]+\.[0-9]+/"; - if(preg_match($pattern, $version)) { - self::SetValue("latest_version", $version); + if (preg_match($pattern, $version)) { + self::setValue("latest_version", $version); } } - public static function GetLatestLink(){ - $link = self::GetValue("latest_link"); - if($link == null || strlen($link) == 0) { + public static function GetLatestLink() + { + $link = self::getValue("latest_link"); + if ($link == null || strlen($link) == 0) { return 'http://airtime.sourcefabric.org'; } else { return $link; } } - public static function SetLatestLink($link){ + public static function SetLatestLink($link) + { $pattern = "#^(http|https|ftp)://" . "([a-zA-Z0-9]+\.)*[a-zA-Z0-9]+" . "(/[a-zA-Z0-9\-\.\_\~\:\?\#\[\]\@\!\$\&\'\(\)\*\+\,\;\=]+)*/?$#"; - if(preg_match($pattern, $link)) { - self::SetValue("latest_link", $link); + if (preg_match($pattern, $link)) { + self::setValue("latest_link", $link); } } - public static function SetUploadToSoundcloudOption($upload) { - self::SetValue("soundcloud_upload_option", $upload); + public static function SetUploadToSoundcloudOption($upload) + { + self::setValue("soundcloud_upload_option", $upload); } - public static function GetUploadToSoundcloudOption() { - return self::GetValue("soundcloud_upload_option"); + public static function GetUploadToSoundcloudOption() + { + return self::getValue("soundcloud_upload_option"); } - public static function SetSoundCloudDownloadbleOption($upload) { - self::SetValue("soundcloud_downloadable", $upload); + public static function SetSoundCloudDownloadbleOption($upload) + { + self::setValue("soundcloud_downloadable", $upload); } - public static function GetSoundCloudDownloadbleOption() { - return self::GetValue("soundcloud_downloadable"); + public static function GetSoundCloudDownloadbleOption() + { + return self::getValue("soundcloud_downloadable"); } - public static function SetWeekStartDay($day) { - self::SetValue("week_start_day", $day); + public static function SetWeekStartDay($day) + { + self::setValue("week_start_day", $day); } - public static function GetWeekStartDay() { - $val = self::GetValue("week_start_day"); - if (strlen($val) == 0){ - return "0"; - } else { - return $val; - } + public static function GetWeekStartDay() + { + $val = self::getValue("week_start_day"); + return (strlen($val) == 0) ? "0" : $val; } /** * Stores the last timestamp of user updating stream setting */ - public static function SetStreamUpdateTimestamp() { + public static function SetStreamUpdateTimestamp() + { $now = time(); - self::SetValue("stream_update_timestamp", $now); + self::setValue("stream_update_timestamp", $now); } /** * Gets the last timestamp of user updating stream setting */ - public static function GetStreamUpdateTimestemp() { - $update_time = self::GetValue("stream_update_timestamp"); - if($update_time == null){ - $update_time = 0; - } - return $update_time; + public static function GetStreamUpdateTimestemp() + { + $update_time = self::getValue("stream_update_timestamp"); + return ($update_time == null) ? 0 : $update_time; } - public static function GetClientId() { - return self::GetValue("client_id"); + public static function GetClientId() + { + return self::getValue("client_id"); } - public static function SetClientId($id) { + public static function SetClientId($id) + { if (is_numeric($id)) { - self::SetValue("client_id", $id); + self::setValue("client_id", $id); + } else { + Logging::warn("Attempting to set client_id to invalid value: $id"); } } @@ -721,239 +816,361 @@ class Application_Model_Preference /** * Sets the time scale preference (agendaDay/agendaWeek/month) in Calendar. * - * @param $timeScale new time scale + * @param $timeScale new time scale */ - public static function SetCalendarTimeScale($timeScale) { - self::SetValue("calendar_time_scale", $timeScale, true /* user specific */); + public static function SetCalendarTimeScale($timeScale) + { + self::setValue("calendar_time_scale", $timeScale, true /* user specific */); } /** * Retrieves the time scale preference for the current user. * Defaults to month if no entry exists */ - public static function GetCalendarTimeScale() { - $val = self::GetValue("calendar_time_scale", true /* user specific */); - if(strlen($val) == 0) { + public static function GetCalendarTimeScale() + { + $val = self::getValue("calendar_time_scale", true /* user specific */); + if (strlen($val) == 0) { $val = "month"; } - return $val; + + return $val; } /** * Sets the number of entries to show preference in library under Playlist Builder. * - * @param $numEntries new number of entries to show + * @param $numEntries new number of entries to show */ - public static function SetLibraryNumEntries($numEntries) { - self::SetValue("library_num_entries", $numEntries, true /* user specific */); + public static function SetLibraryNumEntries($numEntries) + { + self::setValue("library_num_entries", $numEntries, true /* user specific */); } /** * Retrieves the number of entries to show preference in library under Playlist Builder. * Defaults to 10 if no entry exists */ - public static function GetLibraryNumEntries() { - $val = self::GetValue("library_num_entries", true /* user specific */); - if(strlen($val) == 0) { + public static function GetLibraryNumEntries() + { + $val = self::getValue("library_num_entries", true /* user specific */); + if (strlen($val) == 0) { $val = "10"; } + return $val; } /** * Sets the time interval preference in Calendar. * - * @param $timeInterval new time interval + * @param $timeInterval new time interval */ - public static function SetCalendarTimeInterval($timeInterval) { - self::SetValue("calendar_time_interval", $timeInterval, true /* user specific */); + public static function SetCalendarTimeInterval($timeInterval) + { + self::setValue("calendar_time_interval", $timeInterval, true /* user specific */); } /** * Retrieves the time interval preference for the current user. * Defaults to 30 min if no entry exists */ - public static function GetCalendarTimeInterval() { - $val = self::GetValue("calendar_time_interval", true /* user specific */); - if(strlen($val) == 0) { - $val = "30"; - } - return $val; + public static function GetCalendarTimeInterval() + { + $val = self::getValue("calendar_time_interval", true /* user specific */); + return (strlen($val) == 0) ? "30" : $val; } - public static function SetDiskQuota($value){ - self::SetValue("disk_quota", $value, false); + public static function SetDiskQuota($value) + { + self::setValue("disk_quota", $value, false); } - public static function GetDiskQuota(){ - $val = self::GetValue("disk_quota"); - if(strlen($val) == 0) { - $val = "0"; - } - return $val; + public static function GetDiskQuota() + { + $val = self::getValue("disk_quota"); + return (strlen($val) == 0) ? 0 : $val; } - public static function SetLiveSteamMasterUsername($value){ - self::SetValue("live_stream_master_username", $value, false); + public static function SetLiveStreamMasterUsername($value) + { + self::setValue("live_stream_master_username", $value, false); } - public static function GetLiveSteamMasterUsername(){ - return self::GetValue("live_stream_master_username"); + public static function GetLiveStreamMasterUsername() + { + return self::getValue("live_stream_master_username"); } - public static function SetLiveSteamMasterPassword($value){ - self::SetValue("live_stream_master_password", $value, false); + public static function SetLiveStreamMasterPassword($value) + { + self::setValue("live_stream_master_password", $value, false); } - public static function GetLiveSteamMasterPassword(){ - return self::GetValue("live_stream_master_password"); + public static function GetLiveStreamMasterPassword() + { + return self::getValue("live_stream_master_password"); } - public static function SetSourceStatus($sourcename, $status){ - self::SetValue($sourcename, $status, false); + public static function SetSourceStatus($sourcename, $status) + { + self::setValue($sourcename, $status, false); } - public static function GetSourceStatus($sourcename){ - $value = self::GetValue($sourcename); - if($value == null || $value == "false"){ - return false; - }else{ - return true; - } + public static function GetSourceStatus($sourcename) + { + $value = self::getValue($sourcename); + return !($value == null || $value == "false"); } - public static function SetSourceSwitchStatus($sourcename, $status){ - self::SetValue($sourcename."_switch", $status, false); + public static function SetSourceSwitchStatus($sourcename, $status) + { + self::setValue($sourcename."_switch", $status, false); } - public static function GetSourceSwitchStatus($sourcename){ - $value = self::GetValue($sourcename."_switch"); - if($value == null || $value == "off"){ - return "off"; - }else{ - return "on"; - } + public static function GetSourceSwitchStatus($sourcename) + { + $value = self::getValue($sourcename."_switch"); + return ($value == null || $value == "off") ? 'off' : 'on'; } - public static function SetMasterDJSourceConnectionURL($value){ - self::SetValue("master_dj_source_connection_url", $value, false); + public static function SetMasterDJSourceConnectionURL($value) + { + self::setValue("master_dj_source_connection_url", $value, false); } - public static function GetMasterDJSourceConnectionURL(){ - return self::GetValue("master_dj_source_connection_url"); - } - - public static function SetLiveDJSourceConnectionURL($value){ - self::SetValue("live_dj_source_connection_url", $value, false); + public static function GetMasterDJSourceConnectionURL() + { + return self::getValue("master_dj_source_connection_url"); } - public static function GetLiveDJSourceConnectionURL(){ - return self::GetValue("live_dj_source_connection_url"); + public static function SetLiveDJSourceConnectionURL($value) + { + self::setValue("live_dj_source_connection_url", $value, false); } - + + public static function GetLiveDJSourceConnectionURL() + { + return self::getValue("live_dj_source_connection_url"); + } + /* Source Connection URL override status starts */ - public static function GetLiveDjConnectionUrlOverride(){ - return self::GetValue("live_dj_connection_url_override"); + public static function GetLiveDjConnectionUrlOverride() + { + return self::getValue("live_dj_connection_url_override"); } - - public static function SetLiveDjConnectionUrlOverride($value){ - self::SetValue("live_dj_connection_url_override", $value, false); + + public static function SetLiveDjConnectionUrlOverride($value) + { + self::setValue("live_dj_connection_url_override", $value, false); } - - public static function GetMasterDjConnectionUrlOverride(){ - return self::GetValue("master_dj_connection_url_override"); + + public static function GetMasterDjConnectionUrlOverride() + { + return self::getValue("master_dj_connection_url_override"); } - - public static function SetMasterDjConnectionUrlOverride($value){ - self::SetValue("master_dj_connection_url_override", $value, false); + + public static function SetMasterDjConnectionUrlOverride($value) + { + self::setValue("master_dj_connection_url_override", $value, false); } /* Source Connection URL override status ends */ - - public static function SetAutoTransition($value){ - self::SetValue("auto_transition", $value, false); + + public static function SetAutoTransition($value) + { + self::setValue("auto_transition", $value, false); } - - public static function GetAutoTransition(){ - return self::GetValue("auto_transition"); + + public static function GetAutoTransition() + { + return self::getValue("auto_transition"); } - - public static function SetAutoSwitch($value){ - self::SetValue("auto_switch", $value, false); + + public static function SetAutoSwitch($value) + { + self::setValue("auto_switch", $value, false); } - - public static function GetAutoSwitch(){ - return self::GetValue("auto_switch"); + + public static function GetAutoSwitch() + { + return self::getValue("auto_switch"); } - - public static function SetEnableSystemEmail($upload) { - self::SetValue("enable_system_email", $upload); - } - - public static function GetEnableSystemEmail() { - $v = self::GetValue("enable_system_email"); - - if ($v === "") { - return 0; - } - - return $v; + + public static function SetEnableSystemEmail($upload) + { + self::setValue("enable_system_email", $upload); } - - public static function SetSystemEmail($value) { - self::SetValue("system_email", $value, false); - } - - public static function GetSystemEmail() { - return self::GetValue("system_email"); + + public static function GetEnableSystemEmail() + { + $v = self::getValue("enable_system_email"); + return ($v === "") ? 0 : $v; + } + + public static function SetSystemEmail($value) + { + self::setValue("system_email", $value, false); + } + + public static function GetSystemEmail() + { + return self::getValue("system_email"); + } + + public static function SetMailServerConfigured($value) + { + self::setValue("mail_server_configured", $value, false); + } + + public static function GetMailServerConfigured() + { + return self::getValue("mail_server_configured"); + } + + public static function SetMailServer($value) + { + self::setValue("mail_server", $value, false); + } + + public static function GetMailServer() + { + return self::getValue("mail_server"); + } + + public static function SetMailServerEmailAddress($value) + { + self::setValue("mail_server_email_address", $value, false); + } + + public static function GetMailServerEmailAddress() + { + return self::getValue("mail_server_email_address"); + } + + public static function SetMailServerPassword($value) + { + self::setValue("mail_server_password", $value, false); + } + + public static function GetMailServerPassword() + { + return self::getValue("mail_server_password"); + } + + public static function SetMailServerPort($value) + { + self::setValue("mail_server_port", $value, false); + } + + public static function GetMailServerPort() + { + return self::getValue("mail_server_port"); + } + + public static function SetMailServerRequiresAuth($value) + { + self::setValue("mail_server_requires_auth", $value, false); + } + + public static function GetMailServerRequiresAuth() + { + return self::getValue("mail_server_requires_auth"); } - - public static function SetMailServerConfigured($value) { - self::SetValue("mail_server_configured", $value, false); - } - - public static function GetMailServerConfigured() { - return self::GetValue("mail_server_configured"); - } - - public static function SetMailServer($value) { - self::SetValue("mail_server", $value, false); - } - - public static function GetMailServer() { - return self::GetValue("mail_server"); - } - - public static function SetMailServerEmailAddress($value) { - self::SetValue("mail_server_email_address", $value, false); - } - - public static function GetMailServerEmailAddress() { - return self::GetValue("mail_server_email_address"); - } - - public static function SetMailServerPassword($value) { - self::SetValue("mail_server_password", $value, false); - } - - public static function GetMailServerPassword() { - return self::GetValue("mail_server_password"); - } - - public static function SetMailServerPort($value) { - self::SetValue("mail_server_port", $value, false); - } - - public static function GetMailServerPort() { - return self::GetValue("mail_server_port"); - } /* User specific preferences end */ - public static function ShouldShowPopUp(){ - $today = mktime(0, 0, 0, gmdate("m"), gmdate("d"), gmdate("Y")); - $remindDate = Application_Model_Preference::GetRemindMeDate(); - if($remindDate == NULL || $today >= $remindDate){ - return true; - } + public static function ShouldShowPopUp() + { + $today = mktime(0, 0, 0, gmdate("m"), gmdate("d"), gmdate("Y")); + $remindDate = Application_Model_Preference::GetRemindMeDate(); + $retVal = false; + + if (is_null($remindDate) || ($remindDate != -1 && $today >= $remindDate)) { + $retVal = true; + } + + return $retVal; + } + + + + public static function getOrderingMap($pref_param) + { + $v = self::getValue($pref_param, true); + + $id = function ($x) { return $x; }; + + if ($v === '') { + return $id; + } + + $ds = unserialize($v); + + if (!array_key_exists('ColReorder', $ds)) { + return $id; + } + + return function ($x) use ($ds) { + if (array_key_exists($x, $ds['ColReorder'])) { + return $ds['ColReorder'][$x]; + } else { + /*For now we just have this hack for debugging. We should not + rely on this crappy behaviour in case of failure*/ + Logging::info("Pref: $pref_param"); + Logging::warn("Index $x does not exist preferences"); + Logging::warn("Defaulting to identity and printing preferences"); + Logging::warn($ds); + return $x; + } + }; + } + + public static function getCurrentLibraryTableColumnMap() + { + return self::getOrderingMap("library_datatable"); + } + + public static function setCurrentLibraryTableSetting($settings) + { + $num_columns = count(Application_Model_StoredFile::getLibraryColumns()); + $new_columns_num = count($settings['abVisCols']); + + if ($num_columns != $new_columns_num) { + throw new Exception("Trying to write a user column preference with incorrect number of columns!"); + } + + $data = serialize($settings); + $v = self::setValue("library_datatable", $data, true); + } + + public static function getCurrentLibraryTableSetting() + { + $data = self::getValue("library_datatable", true); + return ($data != "") ? unserialize($data) : null; + } + + + public static function setTimelineDatatableSetting($settings) + { + $data = serialize($settings); + self::setValue("timeline_datatable", $data, true); + } + + public static function getTimelineDatatableSetting() + { + $data = self::getValue("timeline_datatable", true); + return ($data != "") ? unserialize($data) : null; + } + + + public static function setNowPlayingScreenSettings($settings) + { + $data = serialize($settings); + self::setValue("nowplaying_screen", $data, true); + } + + public static function getNowPlayingScreenSettings() + { + $data = self::getValue("nowplaying_screen", true); + return ($data != "") ? unserialize($data) : null; } } - diff --git a/airtime_mvc/application/models/RabbitMq.php b/airtime_mvc/application/models/RabbitMq.php index 4e00da379..d92975413 100644 --- a/airtime_mvc/application/models/RabbitMq.php +++ b/airtime_mvc/application/models/RabbitMq.php @@ -3,94 +3,72 @@ require_once 'php-amqplib/amqp.inc'; class Application_Model_RabbitMq { - static public $doPush = FALSE; + public static $doPush = false; /** * Sets a flag to push the schedule at the end of the request. */ - public static function PushSchedule() { - Application_Model_RabbitMq::$doPush = TRUE; + public static function PushSchedule() + { + self::$doPush = true; + } + + private static function sendMessage($exchange, $data) + { + global $CC_CONFIG; + + $conn = new AMQPConnection($CC_CONFIG["rabbitmq"]["host"], + $CC_CONFIG["rabbitmq"]["port"], + $CC_CONFIG["rabbitmq"]["user"], + $CC_CONFIG["rabbitmq"]["password"], + $CC_CONFIG["rabbitmq"]["vhost"]); + $channel = $conn->channel(); + $channel->access_request($CC_CONFIG["rabbitmq"]["vhost"], false, false, + true, true); + + $channel->exchange_declare($exchange, 'direct', false, true); + + $msg = new AMQPMessage($data, array('content_type' => 'text/plain')); + + $channel->basic_publish($msg, $exchange); + $channel->close(); + $conn->close(); } public static function SendMessageToPypo($event_type, $md) { - global $CC_CONFIG; - $md["event_type"] = $event_type; - $conn = new AMQPConnection($CC_CONFIG["rabbitmq"]["host"], - $CC_CONFIG["rabbitmq"]["port"], - $CC_CONFIG["rabbitmq"]["user"], - $CC_CONFIG["rabbitmq"]["password"], - $CC_CONFIG["rabbitmq"]["vhost"]); - $channel = $conn->channel(); - $channel->access_request($CC_CONFIG["rabbitmq"]["vhost"], false, false, true, true); - - $EXCHANGE = 'airtime-pypo'; - $channel->exchange_declare($EXCHANGE, 'direct', false, true); - + $exchange = 'airtime-pypo'; $data = json_encode($md, JSON_FORCE_OBJECT); - $msg = new AMQPMessage($data, array('content_type' => 'text/plain')); - - $channel->basic_publish($msg, $EXCHANGE); - $channel->close(); - $conn->close(); + self::sendMessage($exchange, $data); } public static function SendMessageToMediaMonitor($event_type, $md) { - global $CC_CONFIG; - $md["event_type"] = $event_type; - $conn = new AMQPConnection($CC_CONFIG["rabbitmq"]["host"], - $CC_CONFIG["rabbitmq"]["port"], - $CC_CONFIG["rabbitmq"]["user"], - $CC_CONFIG["rabbitmq"]["password"], - $CC_CONFIG["rabbitmq"]["vhost"]); - $channel = $conn->channel(); - $channel->access_request($CC_CONFIG["rabbitmq"]["vhost"], false, false, true, true); - - $EXCHANGE = 'airtime-media-monitor'; - $channel->exchange_declare($EXCHANGE, 'direct', false, true); - + $exchange = 'airtime-media-monitor'; $data = json_encode($md); - $msg = new AMQPMessage($data, array('content_type' => 'text/plain')); - - $channel->basic_publish($msg, $EXCHANGE); - $channel->close(); - $conn->close(); + self::sendMessage($exchange, $data); } - + public static function SendMessageToShowRecorder($event_type) { - global $CC_CONFIG; + $exchange = 'airtime-pypo'; - $conn = new AMQPConnection($CC_CONFIG["rabbitmq"]["host"], - $CC_CONFIG["rabbitmq"]["port"], - $CC_CONFIG["rabbitmq"]["user"], - $CC_CONFIG["rabbitmq"]["password"], - $CC_CONFIG["rabbitmq"]["vhost"]); - $channel = $conn->channel(); - $channel->access_request($CC_CONFIG["rabbitmq"]["vhost"], false, false, true, true); - - $EXCHANGE = 'airtime-pypo'; - $channel->exchange_declare($EXCHANGE, 'direct', false, true); - $now = new DateTime("@".time()); //in UTC timezone $end_timestamp = new DateTime("@".(time() + 3600*2)); //in UTC timezone + $temp = array(); $temp['event_type'] = $event_type; $temp['server_timezone'] = Application_Model_Preference::GetTimezone(); - if($event_type == "update_recorder_schedule"){ - $temp['shows'] = Application_Model_Show::getShows($now, $end_timestamp, $excludeInstance=NULL, $onlyRecord=TRUE); + if ($event_type == "update_recorder_schedule") { + $temp['shows'] = Application_Model_Show::getShows($now, + $end_timestamp, $onlyRecord=true); } $data = json_encode($temp); - $msg = new AMQPMessage($data, array('content_type' => 'text/plain')); - - $channel->basic_publish($msg, $EXCHANGE); - $channel->close(); - $conn->close(); + + self::sendMessage($exchange, $data); } } - diff --git a/airtime_mvc/application/models/Schedule.php b/airtime_mvc/application/models/Schedule.php index 5c80013ef..b668f13e5 100644 --- a/airtime_mvc/application/models/Schedule.php +++ b/airtime_mvc/application/models/Schedule.php @@ -1,37 +1,38 @@ NOW() AT TIME ZONE 'UTC'"; - $count = $con->query($sql)->fetchColumn(0); - if (is_numeric($count) && ($count != '0')) { - return TRUE; - } else { - return FALSE; - } + $sql = << NOW() AT TIME ZONE 'UTC' +SQL; + $count = Application_Common_Database::prepareAndExecute( $sql, array( + ':file_id'=>$p_fileId), 'column'); + return (is_numeric($count) && ($count != '0')); } /** * Returns data related to the scheduled items. * - * @param int $p_prev - * @param int $p_next + * @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)){ + 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(); } @@ -43,99 +44,112 @@ class Application_Model_Schedule { $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 = Application_Model_Schedule::GetPrevCurrentNext($previousShowID, $currentShowID, $nextShowID, $utcTimeNow); + $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), - //"current"=>$results['current'] !=null?$results['current']:(count($shows['currentShow'])>0?$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")); + "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 + * 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) + if ($p_previousShowID == null && $p_currentShowID == null && $p_nextShowID == null) { return; - - - global $CC_CONFIG; - $con = Propel::getConnection(); - $sql = 'Select ft.artist_name, ft.track_title, st.starts as starts, st.ends as ends, st.media_item_played as media_item_played, si.ends as show_ends - FROM cc_schedule st LEFT JOIN cc_files ft ON st.file_id = ft.id LEFT JOIN cc_show_instances si on st.instance_id = si.id - WHERE '; - - /* Alternate SQL...merge conflict and I'm not sure which on is right.... -MK - $sql = 'Select ft.artist_name, ft.track_title, st.starts as starts, st.ends as ends, st.media_item_played as media_item_played, si.ends as show_ends - FROM cc_schedule st LEFT JOIN cc_files ft ON st.file_id = ft.id - WHERE '; - */ - - if (isset($p_previousShowID)){ - if (isset($p_nextShowID) || isset($p_currentShowID)) - $sql .= '('; - $sql .= 'st.instance_id = '.$p_previousShowID; } - if ($p_currentShowID != null){ - if ($p_previousShowID != null) - $sql .= ' OR '; - else if($p_nextShowID != null) - $sql .= '('; - $sql .= 'st.instance_id = '.$p_currentShowID; - } - if ($p_nextShowID != null) { - if ($p_previousShowID != null || $p_currentShowID != null) - $sql .= ' OR '; - $sql .= 'st.instance_id = '.$p_nextShowID; - if($p_previousShowID != null || $p_currentShowID != null) - $sql .= ')'; - } else if($p_previousShowID != null && $p_currentShowID != null) - $sql .= ')'; + $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 = <<query($sql)->fetchAll(); + $streamSql = str_replace("%%columns%%", $streamColumns, $sql); + $streamSql = str_replace("%%tables%%", $streamJoin, $streamSql); + + $sql = "SELECT * FROM (($filesSql) UNION ($streamSql)) AS unioned ORDER BY starts"; + + $rows = Application_Common_Database::prepareAndExecute($sql, $paramMap); $numberOfRows = count($rows); $results['previous'] = null; - $results['current'] = null; - $results['next'] = null; + $results['current'] = null; + $results['next'] = null; $timeNowAsMillis = strtotime($p_timeNow); - for( $i = 0; $i < $numberOfRows; ++$i ){ + for ($i = 0; $i < $numberOfRows; ++$i) { // if the show is overbooked, then update the track end time to the end of the show time. - if($rows[$i]['ends'] > $rows[$i]["show_ends"]){ + if ($rows[$i]['ends'] > $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){ + + 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"], + $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])){ + 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"], @@ -161,34 +175,36 @@ class Application_Model_Schedule { "starts"=>$rows[$previousIndex]["starts"], "ends"=>$rows[$previousIndex]["ends"]);; } + return $results; } - public static function GetLastScheduleItem($p_timeNow){ + public static function GetLastScheduleItem($p_timeNow) + { global $CC_CONFIG; - $con = Propel::getConnection(); - $sql = "SELECT" - ." ft.artist_name, ft.track_title," - ." st.starts as starts, st.ends as ends" - ." FROM $CC_CONFIG[scheduleTable] st" - ." LEFT JOIN $CC_CONFIG[filesTable] ft" - ." ON st.file_id = ft.id" - ." LEFT JOIN $CC_CONFIG[showInstances] sit" - ." ON st.instance_id = sit.id" - ." WHERE st.ends < TIMESTAMP '$p_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.ends DESC" - ." LIMIT 1"; + $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)); - $row = $con->query($sql)->fetchAll(); return $row; } - - public static function GetCurrentScheduleItem($p_timeNow, $p_instanceId){ + public static function GetCurrentScheduleItem($p_timeNow, $p_instanceId) + { global $CC_CONFIG; - $con = Propel::getConnection(); /* 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 @@ -200,19 +216,20 @@ class Application_Model_Schedule { ." FROM $CC_CONFIG[scheduleTable] st" ." LEFT JOIN $CC_CONFIG[filesTable] ft" ." ON st.file_id = ft.id" - ." WHERE st.starts <= TIMESTAMP '$p_timeNow'" - ." AND st.instance_id = $p_instanceId" - ." AND st.ends > TIMESTAMP '$p_timeNow'" + ." WHERE st.starts <= TIMESTAMP :timeNow1" + ." AND st.instance_id = :instanceId" + ." AND st.ends > TIMESTAMP :timeNow2" ." ORDER BY st.starts DESC" ." LIMIT 1"; - $row = $con->query($sql)->fetchAll(); + $row = Application_Common_Database::prepareAndExecute($sql, array(':timeNow1'=>$p_timeNow, ':instanceId'=>$p_instanceId, ':timeNow2'=>$p_timeNow,)); + return $row; } - public static function GetNextScheduleItem($p_timeNow){ + public static function GetNextScheduleItem($p_timeNow) + { global $CC_CONFIG; - $con = Propel::getConnection(); $sql = "SELECT" ." ft.artist_name, ft.track_title," ." st.starts as starts, st.ends as ends" @@ -221,68 +238,147 @@ class Application_Model_Schedule { ." ON st.file_id = ft.id" ." LEFT JOIN $CC_CONFIG[showInstances] sit" ." ON st.instance_id = sit.id" - ." WHERE st.starts > TIMESTAMP '$p_timeNow'" + ." 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 = $con->query($sql)->fetchAll(); + $row = Application_Common_Database::prepareAndExecute($sql, array(':timeNow'=>$p_timeNow)); + return $row; } - /* - * - * @param DateTime $p_startDateTime - * - * @param DateTime $p_endDateTime - * - * @return array $scheduledItems - * - */ + /* + * + * @param DateTime $p_startDateTime + * + * @param DateTime $p_endDateTime + * + * @return array $scheduledItems + * + */ public static function GetScheduleDetailItems($p_start, $p_end, $p_shows) { global $CC_CONFIG; $con = Propel::getConnection(); - $sql = "SELECT DISTINCT - showt.name AS show_name, showt.color AS show_color, - showt.background_color AS show_background_color, showt.id AS show_id, + $p_start_str = $p_start->format("Y-m-d H:i:s"); + $p_end_str = $p_end->format("Y-m-d H:i:s"); - si.starts AS si_starts, si.ends AS si_ends, si.time_filled AS si_time_filled, - si.record AS si_record, si.rebroadcast AS si_rebroadcast, si.instance_id AS parent_show, - si.id AS si_id, si.last_scheduled AS si_last_scheduled, si.file_id AS si_file_id, - sched.starts AS sched_starts, sched.ends AS sched_ends, sched.id AS sched_id, - sched.cue_in AS cue_in, sched.cue_out AS cue_out, - sched.fade_in AS fade_in, sched.fade_out AS fade_out, - sched.playout_status AS playout_status, + //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"); - ft.track_title AS file_track_title, ft.artist_name AS file_artist_name, - ft.album_title AS file_album_title, ft.length AS file_length, ft.file_exists AS file_exists + $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}')) ) - - WHERE si.modified_instance = false AND - - ((si.starts >= '{$p_start}' AND si.starts < '{$p_end}') - OR (si.ends > '{$p_start}' AND si.ends <= '{$p_end}') - OR (si.starts <= '{$p_start}' AND si.ends >= '{$p_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) { - $sql .= " AND show_id IN (".implode(",", $p_shows).")"; + $showPredicate = " AND show_id IN (".implode(",", $p_shows).")"; } - $sql .= " ORDER BY si.starts, sched.starts;"; - - Logging::debug($sql); + $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); - $rows = $con->query($sql)->fetchAll(); return $rows; } @@ -294,28 +390,36 @@ class Application_Model_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'?true:false; - $master_dj = Application_Model_Preference::GetSourceSwitchStatus('master_dj') == 'on'?true:false; - $scheduled_play = Application_Model_Preference::GetSourceSwitchStatus('scheduled_play') == 'on'?true:false; - - if(!$live_dj && !$master_dj && $scheduled_play){ + $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){ - global $CC_CONFIG; - $con = Propel::getConnection(); + + public static function UpdateBrodcastedStatus($dateTime, $value) + { $now = $dateTime->format("Y-m-d H:i:s"); - $sql = "UPDATE ".$CC_CONFIG['scheduleTable'] - ." SET broadcasted=$value" - ." WHERE starts <= '$now' AND ends >= '$now'"; - $retVal = $con->exec($sql); + + $sql = <<= :ends::TIMESTAMP +SQL; + + $retVal = Application_Common_Database::prepareAndExecute($sql, array( + ':broadcastedValue' => $value, + ':starts' => $now, + ':ends' => $now), 'execute'); return $retVal; } @@ -324,15 +428,15 @@ class Application_Model_Schedule { global $CC_CONFIG; $con = Propel::getConnection(); $sql = "SELECT count(*) as cnt FROM ".$CC_CONFIG['scheduleTable']; + 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 + * @param string $p_time * @return string */ private static function AirtimeTimeToPypoTime($p_time) @@ -340,6 +444,7 @@ class Application_Model_Schedule { $p_time = substr($p_time, 0, 19); $p_time = str_replace(" ", "-", $p_time); $p_time = str_replace(":", "-", $p_time); + return $p_time; } @@ -347,19 +452,20 @@ class Application_Model_Schedule { * Convert a time string in the format "YYYY-MM-DD-HH-mm-SS" to * "YYYY-MM-DD HH:mm:SS". * - * @param string $p_time + * @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 + * @param string $p_time * @return boolean */ public static function ValidPypoTimeFormat($p_time) @@ -373,6 +479,7 @@ class Application_Model_Schedule { return false; } } + return true; } @@ -380,7 +487,7 @@ class Application_Model_Schedule { * Converts a time value as a string (with format HH:MM:SS.mmmmmm) to * millisecs. * - * @param string $p_time + * @param string $p_time * @return int */ public static function WallTimeToMillisecs($p_time) @@ -397,16 +504,17 @@ class Application_Model_Schedule { $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. + * 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 + * @param string $p_time1 + * @param string $p_time2 * @return double */ private static function TimeDiff($p_time1, $p_time2) @@ -423,6 +531,7 @@ class Application_Model_Schedule { $millisec2 = intval($millisec2); $diff = abs($millisec1 - $millisec2)/1000; } + return $diff; } @@ -442,63 +551,212 @@ class Application_Model_Schedule { * Returns null if nothing found, else an array of associative * arrays representing each row. */ - public static function GetItems($p_startTime, $p_endTime) { - global $CC_CONFIG; - $con = Propel::getConnection(); + 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; - $baseQuery = "SELECT st.file_id AS file_id," - ." st.id as id," - ." st.instance_id as instance_id," - ." st.starts AS start," - ." st.ends AS end," - ." st.cue_in AS cue_in," - ." st.cue_out AS cue_out," - ." st.fade_in AS fade_in," - ." st.fade_out AS fade_out," - ." si.starts as show_start," - ." si.ends as show_end" - ." FROM $CC_CONFIG[scheduleTable] as st" - ." LEFT JOIN $CC_CONFIG[showInstances] as si" - ." ON st.instance_id = si.id"; + $sql = $baseQuery." ".$predicates; + $rows = Application_Common_Database::prepareAndExecute($sql, array( + ':startTime1' => $p_startTime, + ':endTime' => $p_endTime, + ':startTime2' => $p_startTime)); - $predicates = " WHERE st.ends > '$p_startTime'" - ." AND st.starts < '$p_endTime'" - ." AND st.playout_status > 0" - ." AND si.ends > '$p_startTime'" - ." ORDER BY st.starts"; - - $sql = $baseQuery.$predicates; - - $rows = $con->query($sql)->fetchAll(); - - if (count($rows) < 3){ - Logging::debug("Get Schedule: Less than 3 results returned. Doing another query since we need a minimum of 3 results."); - + if (count($rows) < 3) { $dt = new DateTime("@".time()); $dt->add(new DateInterval("PT24H")); $range_end = $dt->format("Y-m-d H:i:s"); - $predicates = " WHERE st.ends > '$p_startTime'" - ." AND st.starts < '$range_end'" - ." AND st.playout_status > 0" - ." AND si.ends > '$p_startTime'" - ." ORDER BY st.starts" - ." LIMIT 3"; + $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 = $con->query($sql)->fetchAll(); + $sql = $baseQuery." ".$predicates." "; + $rows = Application_Common_Database::prepareAndExecute($sql, + array( + ':startTime1' => $p_startTime, + ':rangeEnd' => $range_end, + ':startTime2' => $p_startTime)); } return $rows; } - public static function GetScheduledPlaylists($p_fromDateTime = null, $p_toDateTime = null){ + /** + * 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]['independent_event'] = true; + } + } + } + + private static function createFileScheduleEvent(&$data, $item, $media_id, $uri) + { + $start = self::AirtimeTimeToPypoTime($item["start"]); + $end = self::AirtimeTimeToPypoTime($item["end"]); + + $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' => is_null($item["replay_gain"]) ? "0": $item["replay_gain"], + 'independent_event' => true + ); + 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) + { global $CC_CONFIG; - /* if $p_fromDateTime and $p_toDateTime function parameters are null, then set range - * from "now" to "now + 24 hours". */ + /* 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"); @@ -510,7 +768,7 @@ class Application_Model_Schedule { $cache_ahead_hours = $CC_CONFIG["cache_ahead_hours"]; - if (is_numeric($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 { @@ -523,83 +781,85 @@ class Application_Model_Schedule { $range_end = Application_Model_Schedule::PypoTimeToAirtimeTime($p_toDateTime); } - // Scheduler wants everything in a playlist - $items = Application_Model_Schedule::GetItems($range_start, $range_end); + return array($range_start, $range_end); + } - $data = array(); + + private static function createScheduledEvents(&$data, $range_start, $range_end) + { $utcTimeZone = new DateTimeZone("UTC"); - - $data["status"] = array(); - $data["media"] = array(); - - $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 = Application_Model_Schedule::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"; - - if($kick_time !== $switch_off_time){ - $switch_start = Application_Model_Schedule::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"; - } - } - - foreach ($items as $item){ - - $showInstance = CcShowInstancesQuery::create()->findPK($item["instance_id"]); - $showId = $showInstance->getDbShowId(); - $show = CcShowQuery::create()->findPK($showId); - $showName = $show->getDbName(); - + $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()){ + + if ($trackStartDateTime->getTimestamp() > $showEndDateTime->getTimestamp()) { + //do not send any tracks that start past their show's end time continue; } - /* Note: cue_out and end are always the same. */ - /* TODO: Not all tracks will have "show_end" */ - if ($trackEndDateTime->getTimestamp() > $showEndDateTime->getTimestamp()){ + 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"); } - - $storedFile = Application_Model_StoredFile::Recall($item["file_id"]); - $uri = $storedFile->getFilePath(); - - $start = Application_Model_Schedule::AirtimeTimeToPypoTime($item["start"]); - $data["media"][$start] = array( - 'id' => $storedFile->getGunid(), - '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' => Application_Model_Schedule::AirtimeTimeToPypoTime($item["end"]), - 'show_name' => $showName - ); + + 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)); + } + } + } + + /** + * Purpose of this function is to iterate through the entire + * schedule array that was just built and fix the data up a bit. For + * example, if we have two consecutive webstreams, we don't need the + * first webstream to shutdown the output, when the second one will + * just switch it back on. Preventing this behaviour stops hiccups + * in output sound. + */ + private static function filterData(&$data) + { + $previous_key = null; + $previous_val = null; + foreach ($data as $k => $v) { + if ($v["type"] == "stream_buffer_start" + && !is_null($previous_val) + && $previous_val["type"] == "stream_output_end") { + + unset($data[$previous_key]); + } + $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(); + + self::createInputHarborKickTimes($data, $range_start, $range_end); + self::createScheduledEvents($data, $range_start, $range_end); + + self::filterData($data["media"]); return $data; } @@ -610,30 +870,31 @@ class Application_Model_Schedule { $con = Propel::getConnection(); $con->exec("TRUNCATE TABLE ".$CC_CONFIG["scheduleTable"]); } - - public static function deleteWithFileId($fileId){ + + public static function deleteWithFileId($fileId) + { global $CC_CONFIG; - $con = Propel::getConnection(); - $sql = "DELETE FROM ".$CC_CONFIG["scheduleTable"]." WHERE file_id=$fileId"; - $res = $con->query($sql); + $sql = "DELETE FROM ".$CC_CONFIG["scheduleTable"]." WHERE file_id=:file_id"; + Application_Common_Database::prepareAndExecute($sql, array(':file_id'=>$fileId), 'execute'); } - public static function createNewFormSections($p_view){ + public static function createNewFormSections($p_view) + { $isSaas = Application_Model_Preference::GetPlanLevel() == 'disabled'?false:true; - $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 = 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'); + $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; @@ -642,7 +903,7 @@ class Application_Model_Schedule { $p_view->style = $formStyle; $p_view->live = $formLive; - $formWhat->populate(array('add_show_id' => '-1', + $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', @@ -652,7 +913,7 @@ class Application_Model_Schedule { $formRepeats->populate(array('add_show_end_date' => date("Y-m-d"))); - if(!$isSaas){ + if (!$isSaas) { $formRecord = new Application_Form_AddShowRR(); $formAbsoluteRebroadcast = new Application_Form_AddShowAbsoluteRebroadcastDates(); $formRebroadcast = new Application_Form_AddShowRebroadcastDates(); @@ -667,30 +928,31 @@ class Application_Model_Schedule { } $p_view->addNewShow = true; } - - /* This function is responsible for handling the case where an individual + + /* 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){ + public static function updateShowInstance($data, $controller) + { $isSaas = (Application_Model_Preference::GetPlanLevel() != 'disabled'); - - $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'); - - if(!$isSaas){ + $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'); + + if (!$isSaas) { $formRecord = new Application_Form_AddShowRR(); $formAbsoluteRebroadcast = new Application_Form_AddShowAbsoluteRebroadcastDates(); $formRebroadcast = new Application_Form_AddShowRebroadcastDates(); @@ -700,21 +962,23 @@ class Application_Model_Schedule { $formRebroadcast->removeDecorator('DtDdWrapper'); } $when = $formWhen->isValid($data); - - if($when && $formWhen->checkReliantFields($data, true)) { - $start_dt = new DateTime($data['add_show_start_date']." ".$data['add_show_start_time'], new DateTimeZone(date_default_timezone_get())); + + 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 = 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(); - + $ccShowInstance->save(); + Application_Model_Schedule::createNewFormSections($controller->view); - + return true; } else { $formWhat->disable(); @@ -723,36 +987,38 @@ class Application_Model_Schedule { $formWho->disable(); $formStyle->disable(); //$formLive->disable(); - - $controller->view->what = $formWhat; - $controller->view->when = $formWhen; + + $controller->view->what = $formWhat; + $controller->view->when = $formWhen; $controller->view->repeats = $formRepeats; - $controller->view->who = $formWho; - $controller->view->style = $formStyle; - $controller->view->live = $formLive; - if(!$isSaas){ + $controller->view->who = $formWho; + $controller->view->style = $formStyle; + $controller->view->live = $formLive; + if (!$isSaas) { $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) + + /* 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 + * -Martin */ - public static function addUpdateShow($data, $controller, $validateStartDate, $originalStartDate=null){ - + 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)); @@ -760,25 +1026,25 @@ class Application_Model_Schedule { $isSaas = (Application_Model_Preference::GetPlanLevel() != 'disabled'); $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 = 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'); + $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); + $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 @@ -793,17 +1059,17 @@ class Application_Model_Schedule { $hValue = 0; $mValue = 0; - if($hPos !== false){ - $hValue = trim(substr($data["add_show_duration"], 0, $hPos)); + 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 )); + if ($mPos !== false) { + $hPos = $hPos === false ? 0 : $hPos+1; + $mValue = trim(substr($data["add_show_duration"], $hPos, -1 )); } $data["add_show_duration"] = $hValue.":".$mValue; - if(!$isSaas){ + if (!$isSaas) { $formRecord = new Application_Form_AddShowRR(); $formAbsoluteRebroadcast = new Application_Form_AddShowAbsoluteRebroadcastDates(); $formRebroadcast = new Application_Form_AddShowRebroadcastDates(); @@ -816,19 +1082,19 @@ class Application_Model_Schedule { $record = $formRecord->isValid($data); } - if($data["add_show_repeats"]) { - $repeats = $formRepeats->isValid($data); - if($repeats) { + if ($data["add_show_repeats"]) { + $repeats = $formRepeats->isValid($data); + if ($repeats) { $repeats = $formRepeats->checkReliantFields($data); } - if(!$isSaas){ + if (!$isSaas) { $formAbsoluteRebroadcast->reset(); //make it valid, results don't matter anyways. $rebroadAb = 1; if ($data["add_show_rebroadcast"]) { $rebroad = $formRebroadcast->isValid($data); - if($rebroad) { + if ($rebroad) { $rebroad = $formRebroadcast->checkReliantFields($data); } } else { @@ -837,14 +1103,14 @@ class Application_Model_Schedule { } } else { $repeats = 1; - if(!$isSaas){ + if (!$isSaas) { $formRebroadcast->reset(); //make it valid, results don't matter anyways. $rebroad = 1; if ($data["add_show_rebroadcast"]) { $rebroadAb = $formAbsoluteRebroadcast->isValid($data); - if($rebroadAb) { + if ($rebroadAb) { $rebroadAb = $formAbsoluteRebroadcast->checkReliantFields($data); } } else { @@ -853,11 +1119,11 @@ class Application_Model_Schedule { } } - $who = $formWho->isValid($data); - $style = $formStyle->isValid($data); + $who = $formWho->isValid($data); + $style = $formStyle->isValid($data); if ($what && $when && $repeats && $who && $style && $live) { - if(!$isSaas){ - if($record && $rebroadAb && $rebroad){ + if (!$isSaas) { + if ($record && $rebroadAb && $rebroad) { if ($isAdminOrPM) { Application_Model_Show::create($data); } @@ -878,7 +1144,7 @@ class Application_Model_Schedule { $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; @@ -894,15 +1160,15 @@ class Application_Model_Schedule { //$controller->view->newForm = $controller->view->render('schedule/add-show-form.phtml'); return true; } - } else { - $controller->view->what = $formWhat; - $controller->view->when = $formWhen; + } 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; - - if(!$isSaas){ + $controller->view->who = $formWho; + $controller->view->style = $formStyle; + $controller->view->live = $formLive; + + if (!$isSaas) { $controller->view->rr = $formRecord; $controller->view->absoluteRebroadcast = $formAbsoluteRebroadcast; $controller->view->rebroadcast = $formRebroadcast; @@ -912,4 +1178,101 @@ class Application_Model_Schedule { 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/Scheduler.php b/airtime_mvc/application/models/Scheduler.php index 3e7a39aa7..664c40504 100644 --- a/airtime_mvc/application/models/Scheduler.php +++ b/airtime_mvc/application/models/Scheduler.php @@ -1,7 +1,7 @@ "", @@ -11,59 +11,64 @@ class Application_Model_Scheduler { "fadein" => "00:00:00", "fadeout" => "00:00:00", "sched_id" => null, + "type" => 0 //default type of '0' to represent files. type '1' represents a webstream ); - + private $epochNow; private $nowDT; private $user; - + private $checkUserPermissions = true; - public function __construct() { - + public function __construct() + { $this->con = Propel::getConnection(CcSchedulePeer::DATABASE_NAME); - - $this->epochNow = microtime(true); + + //subtracting one because sometimes when we cancel a track, we set its end time + //to epochNow and then send the new schedule to pypo. Sometimes the currently cancelled + //track can still be included in the new schedule because it may have a few ms left to play. + //subtracting 1 second from epochNow resolves this issue. + $this->epochNow = microtime(true)-1; $this->nowDT = DateTime::createFromFormat("U.u", $this->epochNow, new DateTimeZone("UTC")); - - if ($this->nowDT === false){ + + if ($this->nowDT === false) { // DateTime::createFromFormat does not support millisecond string formatting in PHP 5.3.2 (Ubuntu 10.04). // In PHP 5.3.3 (Ubuntu 10.10), this has been fixed. $this->nowDT = DateTime::createFromFormat("U", time(), new DateTimeZone("UTC")); - } - - $this->user = Application_Model_User::GetCurrentUser(); + } + + $this->user = Application_Model_User::getCurrentUser(); } - - public function setCheckUserPermissions($value) { + + public function setCheckUserPermissions($value) + { $this->checkUserPermissions = $value; } - - - /* - * make sure any incoming requests for scheduling are ligit. - * - * @param array $items, an array containing pks of cc_schedule items. - */ - private function validateRequest($items) { - + + /* + * make sure any incoming requests for scheduling are ligit. + * + * @param array $items, an array containing pks of cc_schedule items. + */ + 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) { $schedInfo[$id] = $items[$i]["instance"]; } - $instanceInfo[$items[$i]["instance"]] = $items[$i]["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); @@ -71,48 +76,48 @@ class Application_Model_Scheduler { $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)"); + 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)"); + + //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!"); + + 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("You are not allowed to schedule show {$show->getDbName()}."); + + if ($this->checkUserPermissions && $this->user->canSchedule($show->getDbId()) === false) { + throw new Exception("You are not allowed to schedule show {$show->getDbName()}."); } - - $showEndEpoch = floatval($instance->getDbEnds("U.u")); - - if ($showEndEpoch < $nowEpoch) { - throw new OutDatedScheduleException("The show {$show->getDbName()} is over and cannot be scheduled."); + + $showEndEpoch = floatval($instance->getDbEnds("U.u")); + + if ($showEndEpoch < $nowEpoch) { + throw new OutDatedScheduleException("The show {$show->getDbName()} is over and cannot be scheduled."); } - + $ts = intval($instanceInfo[$id]); - $lastSchedTs = intval($instance->getDbLastScheduled("U")) ? : 0; + $lastSchedTs = intval($instance->getDbLastScheduled("U")) ? : 0; if ($ts < $lastSchedTs) { - Logging::log("ts {$ts} last sched {$lastSchedTs}"); - throw new OutDatedScheduleException("The show {$show->getDbName()} has been previously updated!"); + Logging::info("ts {$ts} last sched {$lastSchedTs}"); + throw new OutDatedScheduleException("The show {$show->getDbName()} has been previously updated!"); } - } + } } /* @@ -121,8 +126,8 @@ class Application_Model_Scheduler { * * @return $files */ - private function retrieveMediaFiles($id, $type) { - + private function retrieveMediaFiles($id, $type) + { $files = array(); if ($type === "audioclip") { @@ -130,8 +135,7 @@ class Application_Model_Scheduler { if (is_null($file) || !$file->getDbFileExists()) { throw new Exception("A selected File does not exist!"); - } - else { + } else { $data = $this->fileInfo; $data["id"] = $id; $data["cliplength"] = $file->getDbLength(); @@ -146,32 +150,118 @@ class Application_Model_Scheduler { $files[] = $data; } - } - else if ($type === "playlist") { - - $contents = CcPlaylistcontentsQuery::create() - ->orderByDbPosition() - ->filterByDbPlaylistId($id) - ->find($this->con); - - if (is_null($contents)) { - throw new Exception("A selected Playlist does not exist!"); - } + } elseif ($type === "playlist") { + $pl = new Application_Model_Playlist($id); + $contents = $pl->getContents(); foreach ($contents as $plItem) { - - $file = $plItem->getCcFiles($this->con); - if (isset($file) && $file->getDbFileExists()) { - - $data = $this->fileInfo; - $data["id"] = $plItem->getDbFileId(); - $data["cliplength"] = $plItem->getDbCliplength(); - $data["cuein"] = $plItem->getDbCuein(); - $data["cueout"] = $plItem->getDbCueout(); - $data["fadein"] = $plItem->getDbFadein(); - $data["fadeout"] = $plItem->getDbFadeout(); - + if ($plItem['type'] == 0) { + $data["id"] = $plItem['item_id']; + $data["cliplength"] = $plItem['length']; + $data["cuein"] = $plItem['cuein']; + $data["cueout"] = $plItem['cueout']; + $data["fadein"] = $plItem['fadein']; + $data["fadeout"] = $plItem['fadeout']; + $data["type"] = 0; $files[] = $data; + } elseif ($plItem['type'] == 1) { + $data["id"] = $plItem['item_id']; + $data["cliplength"] = $plItem['length']; + $data["cuein"] = $plItem['cuein']; + $data["cueout"] = $plItem['cueout']; + $data["fadein"] = "00.500000";//$plItem['fadein']; + $data["fadeout"] = "00.500000";//$plItem['fadeout']; + $data["type"] = 1; + $files[] = $data; + } elseif ($plItem['type'] == 2) { + // if it's a block + $bl = new Application_Model_Block($plItem['item_id']); + if ($bl->isStatic()) { + foreach ($bl->getContents() as $track) { + $data["id"] = $track['item_id']; + $data["cliplength"] = $track['length']; + $data["cuein"] = $track['cuein']; + $data["cueout"] = $track['cueout']; + $data["fadein"] = $track['fadein']; + $data["fadeout"] = $track['fadeout']; + $data["type"] = 0; + $files[] = $data; + } + } else { + $dynamicFiles = $bl->getListOfFilesUnderLimit(); + foreach ($dynamicFiles as $fileId=>$f) { + $file = CcFilesQuery::create()->findPk($fileId); + if (isset($file) && $file->getDbFileExists()) { + $data["id"] = $file->getDbId(); + $data["cliplength"] = $file->getDbLength(); + $data["cuein"] = "00:00:00"; + $data["cueout"] = $file->getDbLength(); + $defaultFade = Application_Model_Preference::GetDefaultFade(); + if (isset($defaultFade)) { + //fade is in format SS.uuuuuu + $data["fadein"] = $defaultFade; + $data["fadeout"] = $defaultFade; + } + $data["type"] = 0; + $files[] = $data; + } + } + } + } + } + } elseif ($type == "stream") { + //need to return + $stream = CcWebstreamQuery::create()->findPK($id, $this->con); + + if (is_null($stream) /* || !$file->getDbFileExists() */) { + throw new Exception("A selected File does not exist!"); + } else { + $data = $this->fileInfo; + $data["id"] = $id; + $data["cliplength"] = $stream->getDbLength(); + $data["cueout"] = $stream->getDbLength(); + $data["type"] = 1; + + $defaultFade = Application_Model_Preference::GetDefaultFade(); + if (isset($defaultFade)) { + //fade is in format SS.uuuuuu + $data["fadein"] = $defaultFade; + $data["fadeout"] = $defaultFade; + } + + $files[] = $data; + } + } elseif ($type == "block") { + $bl = new Application_Model_Block($id); + if ($bl->isStatic()) { + foreach ($bl->getContents() as $track) { + $data["id"] = $track['item_id']; + $data["cliplength"] = $track['length']; + $data["cuein"] = $track['cuein']; + $data["cueout"] = $track['cueout']; + $data["fadein"] = $track['fadein']; + $data["fadeout"] = $track['fadeout']; + $data["type"] = 0; + $files[] = $data; + } + } else { + $dynamicFiles = $bl->getListOfFilesUnderLimit(); + foreach ($dynamicFiles as $fileId=>$f) { + $file = CcFilesQuery::create()->findPk($fileId); + if (isset($file) && $file->getDbFileExists()) { + $data["id"] = $file->getDbId(); + $data["cliplength"] = $file->getDbLength(); + $data["cuein"] = "00:00:00"; + $data["cueout"] = $file->getDbLength(); + $defaultFade = Application_Model_Preference::GetDefaultFade(); + if (isset($defaultFade)) { + //fade is in format SS.uuuuuu + $data["fadein"] = $defaultFade; + $data["fadeout"] = $defaultFade; + } + $data["type"] = 0; + $files[] = $data; + } } } } @@ -186,89 +276,89 @@ class Application_Model_Scheduler { * * @return DateTime endDT in UTC */ - private function findEndTime($p_startDT, $p_duration) { - + private function findEndTime($p_startDT, $p_duration) + { $startEpoch = $p_startDT->format("U.u"); - $durationSeconds = Application_Model_Playlist::playlistTimeToSeconds($p_duration); + $durationSeconds = Application_Common_DateHelper::playlistTimeToSeconds($p_duration); //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; } - - private function findNextStartTime($DT, $instance) { - - $sEpoch = $DT->format("U.u"); + + private function findNextStartTime($DT, $instance) + { + $sEpoch = $DT->format("U.u"); $nEpoch = $this->epochNow; - - //check for if the show has started. - if (bccomp( $nEpoch , $sEpoch , 6) === 1) { - //need some kind of placeholder for cc_schedule. - //playout_status will be -1. + + //check for if the show has started. + if (bccomp( $nEpoch , $sEpoch , 6) === 1) { + //need some kind of placeholder for cc_schedule. + //playout_status will be -1. $nextDT = $this->nowDT; - - $length = bcsub($nEpoch , $sEpoch , 6); - $cliplength = Application_Model_Playlist::secondsToPlaylistTime($length); - - //fillers are for only storing a chunk of time space that has already passed. - $filler = new CcSchedule(); - $filler->setDbStarts($DT) - ->setDbEnds($this->nowDT) - ->setDbClipLength($cliplength) - ->setDbPlayoutStatus(-1) - ->setDbInstanceId($instance->getDbId()) - ->save($this->con); - } - else { - $nextDT = $DT; + + $length = bcsub($nEpoch , $sEpoch , 6); + $cliplength = Application_Common_DateHelper::secondsToPlaylistTime($length); + + //fillers are for only storing a chunk of time space that has already passed. + $filler = new CcSchedule(); + $filler->setDbStarts($DT) + ->setDbEnds($this->nowDT) + ->setDbClipLength($cliplength) + ->setDbPlayoutStatus(-1) + ->setDbInstanceId($instance->getDbId()) + ->save($this->con); + } else { + $nextDT = $DT; } - + return $nextDT; } - - /* - * @param int $showInstance - * @param array $exclude - * ids of sched items to remove from the calulation. - */ - private function removeGaps($showInstance, $exclude=null) { - - Logging::log("removing gaps from show instance #".$showInstance); - - $instance = CcShowInstancesQuery::create()->findPK($showInstance, $this->con); - if (is_null($instance)) { - throw new OutDatedScheduleException("The schedule you're viewing is out of date!"); - } - - $itemStartDT = $instance->getDbStarts(null); - - $schedule = CcScheduleQuery::create() - ->filterByDbInstanceId($showInstance) - ->filterByDbId($exclude, Criteria::NOT_IN) - ->orderByDbStarts() - ->find($this->con); - - - foreach ($schedule as $item) { - - $itemEndDT = $this->findEndTime($itemStartDT, $item->getDbClipLength()); - - $item->setDbStarts($itemStartDT) - ->setDbEnds($itemEndDT); - - $itemStartDT = $itemEndDT; + + /* + * @param int $showInstance + * @param array $exclude + * ids of sched items to remove from the calulation. + * This function squeezes all items of a show together so that + * there are no gaps between them. + */ + public function removeGaps($showInstance, $exclude=null) + { + Logging::info("removing gaps from show instance #".$showInstance); + + $instance = CcShowInstancesQuery::create()->findPK($showInstance, $this->con); + if (is_null($instance)) { + throw new OutDatedScheduleException("The schedule you're viewing is out of date!"); } - - $schedule->save($this->con); + + $itemStartDT = $instance->getDbStarts(null); + + $schedule = CcScheduleQuery::create() + ->filterByDbInstanceId($showInstance) + ->filterByDbId($exclude, Criteria::NOT_IN) + ->orderByDbStarts() + ->find($this->con); + + foreach ($schedule as $item) { + + $itemEndDT = $this->findEndTime($itemStartDT, $item->getDbClipLength()); + + $item->setDbStarts($itemStartDT) + ->setDbEnds($itemEndDT); + + $itemStartDT = $itemEndDT; + } + + $schedule->save($this->con); } /* @@ -276,8 +366,8 @@ class Application_Model_Scheduler { * @param array $fileIds * @param array $playlistIds */ - private function insertAfter($scheduleItems, $schedFiles, $adjustSched = true) { - + private function insertAfter($scheduleItems, $schedFiles, $adjustSched = true) + { try { $affectedShowInstances = array(); @@ -291,20 +381,20 @@ class Application_Model_Scheduler { } $startProfile = microtime(true); - + foreach ($scheduleItems as $schedule) { $id = intval($schedule["id"]); - + if ($id !== 0) { $schedItem = CcScheduleQuery::create()->findPK($id, $this->con); $instance = $schedItem->getCcShowInstances($this->con); - + $schedItemEndDT = $schedItem->getDbEnds(null); $nextStartDT = $this->findNextStartTime($schedItemEndDT, $instance); } //selected empty row to add after else { - + $instance = CcShowInstancesQuery::create()->findPK($schedule["instance"], $this->con); $showStartDT = $instance->getDbStarts(null); @@ -316,22 +406,22 @@ class Application_Model_Scheduler { } 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."); + + $pend = microtime(true); + Logging::debug("finding all following items."); Logging::debug(floatval($pend) - floatval($pstart)); } - foreach($schedFiles as $file) { + foreach ($schedFiles as $file) { $endTimeDT = $this->findEndTime($nextStartDT, $file['cliplength']); @@ -339,48 +429,57 @@ class Application_Model_Scheduler { //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 { + } else { $sched = new CcSchedule(); } - Logging::log(print_r($file,true)); + Logging::info($file); $sched->setDbStarts($nextStartDT) ->setDbEnds($endTimeDT) - ->setDbFileId($file['id']) ->setDbCueIn($file['cuein']) ->setDbCueOut($file['cueout']) ->setDbFadeIn($file['fadein']) ->setDbFadeOut($file['fadeout']) ->setDbClipLength($file['cliplength']) - ->setDbInstanceId($instance->getDbId()) - ->save($this->con); + ->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; } 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->save($this->con); - $nextStartDT = $endTimeDT; + $nextStartDT = $endTimeDT; } - + $pend = microtime(true); - Logging::debug("adjusting all following items."); + Logging::debug("adjusting all following items."); Logging::debug(floatval($pend) - floatval($pstart)); } } - - $endProfile = microtime(true); - Logging::debug("finished adding scheduled items."); + + $endProfile = microtime(true); + Logging::debug("finished adding scheduled items."); Logging::debug(floatval($endProfile) - floatval($startProfile)); //update the status flag in cc_schedule. @@ -389,27 +488,26 @@ class Application_Model_Scheduler { ->find($this->con); $startProfile = microtime(true); - + foreach ($instances as $instance) { $instance->updateScheduleStatus($this->con); } - - $endProfile = microtime(true); - Logging::debug("updating show instances status."); + + $endProfile = microtime(true); + Logging::debug("updating show instances status."); Logging::debug(floatval($endProfile) - floatval($startProfile)); $startProfile = microtime(true); - + //update the last scheduled timestamp. CcShowInstancesQuery::create() ->filterByPrimaryKeys($affectedShowInstances) ->update(array('DbLastScheduled' => new DateTime("now", new DateTimeZone("UTC"))), $this->con); - - $endProfile = microtime(true); - Logging::debug("updating last scheduled timestamp."); + + $endProfile = microtime(true); + Logging::debug("updating last scheduled timestamp."); Logging::debug(floatval($endProfile) - floatval($startProfile)); - } - catch (Exception $e) { + } catch (Exception $e) { Logging::debug($e->getMessage()); throw $e; } @@ -419,14 +517,14 @@ class Application_Model_Scheduler { * @param array $scheduleItems * @param array $mediaItems */ - public function scheduleAfter($scheduleItems, $mediaItems, $adjustSched = true) { - + public function scheduleAfter($scheduleItems, $mediaItems, $adjustSched = true) + { $this->con->beginTransaction(); $schedFiles = array(); try { - + $this->validateRequest($scheduleItems); foreach ($mediaItems as $media) { @@ -437,8 +535,7 @@ class Application_Model_Scheduler { $this->con->commit(); Application_Model_RabbitMq::PushSchedule(); - } - catch (Exception $e) { + } catch (Exception $e) { $this->con->rollback(); throw $e; } @@ -448,104 +545,101 @@ class Application_Model_Scheduler { * @param array $selectedItem * @param array $afterItem */ - public function moveItem($selectedItems, $afterItems, $adjustSched = true) { - + public function moveItem($selectedItems, $afterItems, $adjustSched = true) + { $startProfile = microtime(true); - + $this->con->beginTransaction(); $this->con->useDebug(true); - + try { - + $this->validateRequest($selectedItems); $this->validateRequest($afterItems); - - $endProfile = microtime(true); - Logging::debug("validating move request took:"); + + $endProfile = microtime(true); + Logging::debug("validating move request took:"); Logging::debug(floatval($endProfile) - floatval($startProfile)); - - $afterInstance = CcShowInstancesQuery::create()->findPK($afterItems[0]["instance"], $this->con); - + + $afterInstance = CcShowInstancesQuery::create()->findPK($afterItems[0]["instance"], $this->con); + //map show instances to cc_schedule primary keys. $modifiedMap = array(); $movedData = array(); - + //prepare each of the selected items. for ($i = 0; $i < count($selectedItems); $i++) { - - $selected = CcScheduleQuery::create()->findPk($selectedItems[$i]["id"], $this->con); - $selectedInstance = $selected->getCcShowInstances($this->con); - - $data = $this->fileInfo; - $data["id"] = $selected->getDbFileId(); - $data["cliplength"] = $selected->getDbClipLength(); - $data["cuein"] = $selected->getDbCueIn(); - $data["cueout"] = $selected->getDbCueOut(); - $data["fadein"] = $selected->getDbFadeIn(); - $data["fadeout"] = $selected->getDbFadeOut(); + + $selected = CcScheduleQuery::create()->findPk($selectedItems[$i]["id"], $this->con); + $selectedInstance = $selected->getCcShowInstances($this->con); + + $data = $this->fileInfo; + $data["id"] = $selected->getDbFileId(); + $data["cliplength"] = $selected->getDbClipLength(); + $data["cuein"] = $selected->getDbCueIn(); + $data["cueout"] = $selected->getDbCueOut(); + $data["fadein"] = $selected->getDbFadeIn(); + $data["fadeout"] = $selected->getDbFadeOut(); $data["sched_id"] = $selected->getDbId(); - + $movedData[] = $data; - + //figure out which items must be removed from calculated show times. $showInstanceId = $selectedInstance->getDbId(); $schedId = $selected->getDbId(); if (isset($modifiedMap[$showInstanceId])) { - array_push($modifiedMap[$showInstanceId], $schedId); - } - else { + array_push($modifiedMap[$showInstanceId], $schedId); + } else { $modifiedMap[$showInstanceId] = array($schedId); } - } + } //calculate times excluding the to be moved items. foreach ($modifiedMap as $instance => $schedIds) { $startProfile = microtime(true); - + $this->removeGaps($instance, $schedIds); - - $endProfile = microtime(true); - Logging::debug("removing gaps from instance $instance:"); + + $endProfile = microtime(true); + Logging::debug("removing gaps from instance $instance:"); Logging::debug(floatval($endProfile) - floatval($startProfile)); } - + $startProfile = microtime(true); - + $this->insertAfter($afterItems, $movedData, $adjustSched); - - $endProfile = microtime(true); - Logging::debug("inserting after removing gaps."); + + $endProfile = microtime(true); + Logging::debug("inserting after removing gaps."); Logging::debug(floatval($endProfile) - floatval($startProfile)); - - $afterInstanceId = $afterInstance->getDbId(); + $modified = array_keys($modifiedMap); //need to adjust shows we have moved items from. - foreach($modified as $instanceId) { - + foreach ($modified as $instanceId) { + $instance = CcShowInstancesQuery::create()->findPK($instanceId, $this->con); $instance->updateScheduleStatus($this->con); } - + $this->con->useDebug(false); $this->con->commit(); Application_Model_RabbitMq::PushSchedule(); - } - catch (Exception $e) { + } catch (Exception $e) { $this->con->rollback(); throw $e; } } - public function removeItems($scheduledItems, $adjustSched = true) { - + public function removeItems($scheduledItems, $adjustSched = true) + { $showInstances = array(); $this->con->beginTransaction(); try { - + $this->validateRequest($scheduledItems); - + $scheduledIds = array(); foreach ($scheduledItems as $item) { $scheduledIds[] = $item["id"]; @@ -555,28 +649,30 @@ class Application_Model_Scheduler { //check to make sure all items selected are up to date foreach ($removedItems as $removedItem) { - + $instance = $removedItem->getCcShowInstances($this->con); - + //check to truncate the currently playing item instead of deleting it. if ($removedItem->isCurrentItem($this->epochNow)) { - + $nEpoch = $this->epochNow; $sEpoch = $removedItem->getDbStarts('U.u'); - - $length = bcsub($nEpoch , $sEpoch , 6); - $cliplength = Application_Model_Playlist::secondsToPlaylistTime($length); - - $cueinSec = Application_Model_Playlist::playlistTimeToSeconds($removedItem->getDbCueIn()); + + $length = bcsub($nEpoch , $sEpoch , 6); + $cliplength = Application_Common_DateHelper::secondsToPlaylistTime($length); + + $cueinSec = Application_Common_DateHelper::playlistTimeToSeconds($removedItem->getDbCueIn()); $cueOutSec = bcadd($cueinSec , $length, 6); - $cueout = Application_Model_Playlist::secondsToPlaylistTime($cueOutSec); - + $cueout = Application_Common_DateHelper::secondsToPlaylistTime($cueOutSec); + + //Set DbEnds - 1 second because otherwise there can be a timing issue + //when sending the new schedule to Pypo where Pypo thinks the track is still + //playing. $removedItem->setDbCueOut($cueout) ->setDbClipLength($cliplength) - ->setDbEnds($this->nowDT) + ->setDbEnds($this->nowDT) ->save($this->con); - } - else { + } else { $removedItem->delete($this->con); } } @@ -613,64 +709,61 @@ class Application_Model_Scheduler { $this->con->commit(); Application_Model_RabbitMq::PushSchedule(); - } - catch (Exception $e) { + } catch (Exception $e) { $this->con->rollback(); throw $e; } } - + /* * Used for cancelling the current show instance. - * + * * @param $p_id id of the show instance to cancel. */ - public function cancelShow($p_id) { - + public function cancelShow($p_id) + { $this->con->beginTransaction(); - + try { - + $instance = CcShowInstancesQuery::create()->findPK($p_id); - + if (!$instance->getDbRecord()) { - - $items = CcScheduleQuery::create() - ->filterByDbInstanceId($p_id) - ->filterByDbEnds($this->nowDT, Criteria::GREATER_THAN) - ->find($this->con); - + + $items = CcScheduleQuery::create() + ->filterByDbInstanceId($p_id) + ->filterByDbEnds($this->nowDT, Criteria::GREATER_THAN) + ->find($this->con); + if (count($items) > 0) { - $remove = array(); - $ts = $this->nowDT->format('U'); - - for($i = 0; $i < count($items); $i++) { - $remove[$i]["instance"] = $p_id; - $remove[$i]["timestamp"] = $ts; - $remove[$i]["id"] = $items[$i]->getDbId(); - } - + $remove = array(); + $ts = $this->nowDT->format('U'); + + for ($i = 0; $i < count($items); $i++) { + $remove[$i]["instance"] = $p_id; + $remove[$i]["timestamp"] = $ts; + $remove[$i]["id"] = $items[$i]->getDbId(); + } + $this->removeItems($remove, false); } - } - else { + } else { $rebroadcasts = $instance->getCcShowInstancessRelatedByDbId(null, $this->con); $rebroadcasts->delete($this->con); - } - + } + $instance->setDbEnds($this->nowDT); $instance->save($this->con); - + $this->con->commit(); - + if ($instance->getDbRecord()) { Application_Model_RabbitMq::SendMessageToShowRecorder("cancel_recording"); } + } catch (Exception $e) { + $this->con->rollback(); + throw $e; } - catch (Exception $e) { - $this->con->rollback(); - throw $e; - } } } diff --git a/airtime_mvc/application/models/ServiceRegister.php b/airtime_mvc/application/models/ServiceRegister.php index 47c647829..543bfb24b 100644 --- a/airtime_mvc/application/models/ServiceRegister.php +++ b/airtime_mvc/application/models/ServiceRegister.php @@ -1,11 +1,26 @@ findOneByDbName($p_componentName); - if ($component == NULL){ + if (is_null($component)) { $component = new CcServiceRegister(); $component->setDbName($p_componentName); } @@ -14,10 +29,10 @@ class Application_Model_ServiceRegister { // to allow access via an ipv6 address. // http://[::1]:2812 does not respond. // Bug: http://savannah.nongnu.org/bugs/?27608 - if ($p_ipAddress == "::1"){ + if ($p_ipAddress == "::1") { $p_ipAddress = "127.0.0.1"; } - + $component->setDbIp($p_ipAddress); $component->save(); } diff --git a/airtime_mvc/application/models/Show.php b/airtime_mvc/application/models/Show.php index e7cf6967b..41ffbeefd 100644 --- a/airtime_mvc/application/models/Show.php +++ b/airtime_mvc/application/models/Show.php @@ -1,7 +1,7 @@ findPK($this->_showId); + return $show->getDbName(); } @@ -21,26 +22,30 @@ class Application_Model_Show { $show->setDbName($name); Application_Model_RabbitMq::PushSchedule(); } - - public function setAirtimeAuthFlag($flag){ + + public function setAirtimeAuthFlag($flag) + { $show = CcShowQuery::create()->findPK($this->_showId); $show->setDbLiveStreamUsingAirtimeAuth($flag); $show->save(); } - - public function setCustomAuthFlag($flag){ + + public function setCustomAuthFlag($flag) + { $show = CcShowQuery::create()->findPK($this->_showId); $show->setDbLiveStreamUsingCustomAuth($flag); $show->save(); } - - public function setCustomUsername($username){ + + public function setCustomUsername($username) + { $show = CcShowQuery::create()->findPK($this->_showId); $show->setDbLiveStreamUser($username); $show->save(); } - - public function setCustomPassword($password){ + + public function setCustomPassword($password) + { $show = CcShowQuery::create()->findPK($this->_showId); $show->setDbLiveStreamPass($password); $show->save(); @@ -49,6 +54,7 @@ class Application_Model_Show { public function getDescription() { $show = CcShowQuery::create()->findPK($this->_showId); + return $show->getDbDescription(); } @@ -61,6 +67,7 @@ class Application_Model_Show { public function getColor() { $show = CcShowQuery::create()->findPK($this->_showId); + return $show->getDbColor(); } @@ -73,9 +80,14 @@ class Application_Model_Show { 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); @@ -85,6 +97,7 @@ class Application_Model_Show { public function getGenre() { $show = CcShowQuery::create()->findPK($this->_showId); + return $show->getDbGenre(); } @@ -97,6 +110,7 @@ class Application_Model_Show { public function getBackgroundColor() { $show = CcShowQuery::create()->findPK($this->_showId); + return $show->getDbBackgroundColor(); } @@ -113,31 +127,34 @@ class Application_Model_Show { public function getHosts() { - $con = Propel::getConnection(); + $sql = <<query($sql)->fetchAll(); + $hosts = Application_Common_Database::prepareAndExecute( $sql, + array( ':show_id' => $this->getId() ), 'all'); $res = array(); foreach ($hosts as $host) { $res[] = $host['first_name']." ".$host['last_name']; } - return $res; } public function getHostsIds() { - $con = Propel::getConnection(); + $sql = <<query($sql)->fetchAll(); + $hosts = Application_Common_Database::prepareAndExecute( + $sql, array( ':show_id' => $this->getId() ), 'all'); return $hosts; } @@ -157,38 +174,96 @@ class Application_Model_Show { public function resizeShow($deltaDay, $deltaMin) { - $con = Propel::getConnection(); + $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; - if ($hours > 0) { - $hours = floor($hours); - } - else { - $hours = ceil($hours); - } - - $mins = abs($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"); - //update all cc_show_instances that are in the future. - $sql = "UPDATE cc_show_instances SET ends = (ends + interval '{$deltaDay} days' + interval '{$hours}:{$mins}') - WHERE (show_id = {$this->_showId} AND ends > '$current_timestamp') - AND ((ends + interval '{$deltaDay} days' + interval '{$hours}:{$mins}' - starts) <= interval '24:00');"; + $sql_gen = << :current_timestamp1) + AND ((ends + :deltaDay2::INTERVAL + :interval2::INTERVAL - starts) <= interval '24:00') +SQL; - //update cc_show_days so future shows can be created with the new duration. - //only setting new duration if it is less than or equal to 24 hours. - $sql = $sql . " UPDATE cc_show_days SET duration = (CAST(duration AS interval) + interval '{$deltaDay} days' + interval '{$hours}:{$mins}') - WHERE show_id = {$this->_showId} - AND ((CAST(duration AS interval) + interval '{$deltaDay} days' + interval '{$hours}:{$mins}') <= interval '24:00')"; + 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"); - //do both the queries at once. - $con->exec($sql); + $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(); @@ -205,11 +280,10 @@ class Application_Model_Show { } $con->commit(); - } - catch (Exception $e) { + } catch (Exception $e) { $con->rollback(); - Logging::log("Couldn't update schedule status."); - Logging::log($e->getMessage()); + Logging::info("Couldn't update schedule status."); + Logging::info($e->getMessage()); } Application_Model_RabbitMq::PushSchedule(); @@ -217,30 +291,30 @@ class Application_Model_Show { public function cancelShow($day_timestamp) { - $con = Propel::getConnection(); - $timeinfo = explode(" ", $day_timestamp); CcShowDaysQuery::create() ->filterByDbShowId($this->_showId) ->update(array('DbLastShow' => $timeinfo[0])); - $sql = "UPDATE cc_show_instances - SET modified_instance = TRUE - WHERE starts >= '{$day_timestamp}' AND show_id = {$this->_showId}"; + $sql = <<= :dayTimestamp::TIMESTAMP + AND show_id = :showId +SQL; + + $rows = Application_Common_Database::prepareAndExecute( $sql, array( + ':dayTimestamp' => $day_timestamp, + ':showId' => $this->getId()), 'all'); - $con->exec($sql); - - // check if we can safely delete the show - $showInstancesRow = CcShowInstancesQuery::create() - ->filterByDbShowId($this->_showId) - ->filterByDbModifiedInstance(false) - ->findOne(); - - if(is_null($showInstancesRow)){ - $sql = "DELETE FROM cc_show WHERE id = {$this->_showId}"; - $con->exec($sql); - } + 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(); } @@ -260,8 +334,6 @@ class Application_Model_Show { */ public function removeUncheckedDaysInstances($p_uncheckedDays) { - $con = Propel::getConnection(); - //need to convert local doftw to UTC doftw (change made for 2.0 since shows are stored in UTC) $daysRemovedUTC = array(); @@ -269,43 +341,49 @@ class Application_Model_Show { ->filterByDbShowId($this->getId()) ->find(); - Logging::log("Unchecked days:"); - foreach($p_uncheckedDays as $day) { - Logging::log($day); + Logging::info("Unchecked days:"); + foreach ($p_uncheckedDays as $day) { + Logging::info($day); } - foreach($showDays as $showDay) { - //Logging::log("Local show day is: {$showDay->getDbDay()}"); - //Logging::log("First show day is: {$showDay->getDbFirstShow()}"); - //Logging::log("Id show days is: {$showDay->getDbId()}"); + 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::log("Local show day is: {$showDay->getDbDay()}"); - //Logging::log("First show day is: {$showDay->getDbFirstShow()}"); - //Logging::log("Id show days is: {$showDay->getDbId()}"); + //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::log("Show start day: {$startDay->format('Y-m-d H:i:s')}"); + //Logging::info("Show start day: {$startDay->format('Y-m-d H:i:s')}"); $startDay->setTimezone(new DateTimeZone("UTC")); - //Logging::log("Show start day UTC: {$startDay->format('Y-m-d H:i:s')}"); + //Logging::info("Show start day UTC: {$startDay->format('Y-m-d H:i:s')}"); $daysRemovedUTC[] = $startDay->format('w'); - //Logging::log("UTC show day is: {$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 = "DELETE FROM cc_show_instances" - ." WHERE EXTRACT(DOW FROM starts) IN ($uncheckedDaysImploded)" - ." AND starts > TIMESTAMP '$timestamp'" - ." AND show_id = $showId"; + $sql = << :timestamp::TIMESTAMP + AND show_id = :showId +SQL; - //Logging::log($sql); - - $con->exec($sql); + Application_Common_Database::prepareAndExecute( $sql, + array( + ":timestamp" => $timestamp, + ":showId" => $showId, + ), "execute"); } /** @@ -315,7 +393,8 @@ class Application_Model_Show { * @return boolean * true if originated from recording, otherwise false. */ - public function isRecorded(){ + public function isRecorded() + { $showInstancesRow = CcShowInstancesQuery::create() ->filterByDbShowId($this->getId()) ->filterByDbRecord(1) @@ -353,27 +432,38 @@ class Application_Model_Show { */ public function getRebroadcastsAbsolute() { - $con = Propel::getConnection(); + $sql = <<getId(); - - $sql = "SELECT starts FROM cc_show_instances " - ."WHERE instance_id = (SELECT id FROM cc_show_instances WHERE show_id = $showId ORDER BY starts LIMIT 1) AND rebroadcast = 1 " - ."ORDER BY starts"; - - //Logging::log($sql); - - $rebroadcasts = $con->query($sql)->fetchAll(); + $rebroadcasts = Application_Common_Database::prepareAndExecute( $sql, + array( 'showId' => $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; - foreach ($rebroadcasts as $show) { - $startDateTime = new DateTime($show["starts"], new DateTimeZone("UTC")); - $startDateTime->setTimezone(new DateTimeZone(date_default_timezone_get())); - $rebroadcastsLocal[$i]["start_date"] = $startDateTime->format("Y-m-d"); - $rebroadcastsLocal[$i]["start_time"] = $startDateTime->format("H:i"); + $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; } @@ -391,14 +481,15 @@ class Application_Model_Show { */ public function getRebroadcastsRelative() { - $con = Propel::getConnection(); - - $showId = $this->getId(); - $sql = "SELECT day_offset, start_time FROM cc_show_rebroadcast " - ."WHERE show_id = $showId " - ."ORDER BY day_offset"; - - return $con->query($sql)->fetchAll(); + $sql = << $this->getId() ), 'all' ); } /** @@ -414,10 +505,9 @@ class Application_Model_Show { ->filterByDbShowId($this->_showId) ->findOne(); - if (!is_null($showDaysRow)){ + if (!is_null($showDaysRow)) { return ($showDaysRow->getDbRepeatType() != -1); - } - else { + } else { return false; } } @@ -436,9 +526,9 @@ class Application_Model_Show { ->filterByDbShowId($this->_showId) ->findOne(); - if (!is_null($showDaysRow)){ + if (!is_null($showDaysRow)) return $showDaysRow->getDbRepeatType(); - } else + else return -1; } @@ -451,14 +541,18 @@ class Application_Model_Show { */ public function getRepeatingEndDate() { - $con = Propel::getConnection(); + $sql = <<getId(); - $sql = "SELECT last_show FROM cc_show_days" - ." WHERE show_id = $showId" - ." ORDER BY last_show DESC"; + $query = Application_Common_Database::prepareAndExecute( $sql, + array( 'showId' => $this->getId() ), 'column' ); - $query = $con->query($sql)->fetchColumn(0); + /* TODO: Why return empty string instead of false? very confusing --RG + */ return ($query !== false) ? $query : ""; } @@ -472,33 +566,35 @@ class Application_Model_Show { * it cause any scheduled playlists within those show instances to * be gone for good. */ - public function deleteAllInstances(){ - $con = Propel::getConnection(); - - $timestamp = gmdate("Y-m-d H:i:s"); - - $showId = $this->getId(); - $sql = "DELETE FROM cc_show_instances" - ." WHERE starts > TIMESTAMP '$timestamp'" - ." AND show_id = $showId"; - - $con->exec($sql); + 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(){ - $con = Propel::getConnection(); - - $timestamp = gmdate("Y-m-d H:i:s"); - - $showId = $this->getId(); - $sql = "DELETE FROM cc_show_instances" - ." WHERE starts > TIMESTAMP '$timestamp'" - ." AND show_id = $showId" - ." AND rebroadcast = 1"; + 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); } @@ -512,12 +608,13 @@ class Application_Model_Show { * @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(); + public function removeAllInstancesFromDate($p_date=null) + { + $con = Propel::getConnection(); $timestamp = gmdate("Y-m-d H:i:s"); - if(is_null($p_date)) { + if (is_null($p_date)) { $date = new Application_Common_DateHelper; $p_date = $date->getDate(); } @@ -544,8 +641,9 @@ class Application_Model_Show { * @param string $p_date * The date which to delete before */ - public function removeAllInstancesBeforeDate($p_date){ - $con = Propel::getConnection(); + public function removeAllInstancesBeforeDate($p_date) + { + $con = Propel::getConnection(); $timestamp = gmdate("Y-m-d H:i:s"); @@ -557,34 +655,39 @@ class Application_Model_Show { $con->exec($sql); } - + /** * Get the start date of the current show in UTC timezone. * * @return string - * The start date in the format YYYY-MM-DD + * The start date in the format YYYY-MM-DD or empty string in case + * start date could not be found */ - public function getStartDateAndTime(){ + public function getStartDateAndTime() + { $con = Propel::getConnection(); $showId = $this->getId(); - $sql = "SELECT first_show, start_time, timezone FROM cc_show_days" - ." WHERE show_id = $showId" + $stmt = $con->prepare( + "SELECT first_show, start_time, timezone FROM cc_show_days" + ." WHERE show_id = :showId" ." ORDER BY first_show" - ." LIMIT 1"; + ." LIMIT 1"); - $query = $con->query($sql); + $stmt->bindParam(':showId', $showId); + $stmt->execute(); - if ($query->rowCount() == 0){ + if (!$stmt) { return ""; - } else { - $rows = $query->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"); } + + $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"); } /** @@ -593,9 +696,11 @@ class Application_Model_Show { * @return string * The start date in the format YYYY-MM-DD */ - public function getStartDate(){ - list($date,) = explode(" ", $this->getStartDateAndTime()); - return $date; + public function getStartDate() + { + list($date,) = explode(" ", $this->getStartDateAndTime()); + + return $date; } /** @@ -605,9 +710,11 @@ class Application_Model_Show { * The start time in the format HH:MM */ - public function getStartTime(){ - list(,$time) = explode(" ", $this->getStartDateAndTime()); - return $time; + public function getStartTime() + { + list(,$time) = explode(" ", $this->getStartDateAndTime()); + + return $time; } /** @@ -617,13 +724,14 @@ class Application_Model_Show { * @return string * The end date in the format YYYY-MM-DD */ - public function getEndDate(){ - $startDate = $this->getStartDate(); - $startTime = $this->getStartTime(); - $duration = $this->getDuration(); + public function getEndDate() + { + $startDate = $this->getStartDate(); + $startTime = $this->getStartTime(); + $duration = $this->getDuration(); $startDateTime = new DateTime($startDate.' '.$startTime); - $duration = explode(":", $duration); + $duration = explode(":", $duration); $endDate = $startDateTime->add(new DateInterval('PT'.$duration[0].'H'.$duration[1].'M')); @@ -636,7 +744,8 @@ class Application_Model_Show { * @return string * The start time in the format HH:MM:SS */ - public function getEndTime(){ + public function getEndTime() + { $startDate = $this->getStartDate(); $startTime = $this->getStartTime(); $duration = $this->getDuration(); @@ -656,9 +765,11 @@ class Application_Model_Show { * @return boolean * true if the StartDate is in the past, false otherwise */ - public function isStartDateTimeInPast(){ + public function isStartDateTimeInPast() + { $date = new Application_Common_DateHelper; $current_timestamp = $date->getUtcTimestamp(); + return ($current_timestamp > ($this->getStartDate()." ".$this->getStartTime())); } @@ -669,25 +780,24 @@ class Application_Model_Show { * A simple array containing all ID's of show instance * scheduled in the future. */ - public function getAllFutureInstanceIds(){ - $con = Propel::getConnection(); + 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"); - $date = new Application_Common_DateHelper; - $timestamp = $date->getTimestamp(); - - $showId = $this->getId(); - $sql = "SELECT id from cc_show_instances" - ." WHERE show_id = $showId" - ." AND starts > TIMESTAMP '$timestamp'" - ." AND modified_instance != TRUE"; - - $rows = $con->query($sql)->fetchAll(); - - $instance_ids = array(); - foreach ($rows as $row) { - $instance_ids[] = $row["id"]; + $res = array(); + foreach ($rows as $r) { + $res[] = $r['id']; } - return $instance_ids; + return $res; } /* Called when a show's duration is changed (edited). @@ -697,30 +807,40 @@ class Application_Model_Show { * browser. * */ - private function updateDurationTime($p_data){ + private function updateDurationTime($p_data) + { //need to update cc_show_instances, cc_show_days - $con = Propel::getConnection(); + $con = Propel::getConnection(); $date = new Application_Common_DateHelper; $timestamp = $date->getUtcTimestamp(); - $sql = "UPDATE cc_show_days " - ."SET duration = '$p_data[add_show_duration]' " - ."WHERE show_id = $p_data[add_show_id]"; - $con->exec($sql); - - $sql = "UPDATE cc_show_instances " - ."SET ends = starts + INTERVAL '$p_data[add_show_duration]' " - ."WHERE show_id = $p_data[add_show_id] " - ."AND ends > TIMESTAMP '$timestamp'"; - $con->exec($sql); + $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){ + private function updateStartDateTime($p_data, $p_endDate) + { //need to update cc_schedule, cc_show_instances, cc_show_days - $con = Propel::getConnection(); + $con = Propel::getConnection(); $date = new Application_Common_DateHelper; $timestamp = $date->getTimestamp(); @@ -729,7 +849,7 @@ class Application_Model_Show { $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){ + if (strlen ($p_endDate) == 0) { $sql .= "last_show = NULL "; } else { $sql .= "last_show = DATE '$p_endDate' "; @@ -749,7 +869,7 @@ class Application_Model_Show { $con->exec($sql); $showInstanceIds = $this->getAllFutureInstanceIds(); - if (count($showInstanceIds) > 0 && $diff != 0){ + if (count($showInstanceIds) > 0 && $diff != 0) { $showIdsImploded = implode(",", $showInstanceIds); $sql = "UPDATE cc_schedule " ."SET starts = starts + INTERVAL '$diff sec', " @@ -759,31 +879,34 @@ class Application_Model_Show { } } - public function getDuration($format=false){ + public function getDuration($format=false) + { $showDay = CcShowDaysQuery::create()->filterByDbShowId($this->getId())->findOne(); - if(!$format){ + if (!$format) { return $showDay->getDbDuration(); - }else{ + } 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(); - - $days = array(); - foreach ($showDays as $showDay){ - array_push($days, $showDay->getDbDay()); + public function getShowDays() + { + $showDays = CcShowDaysQuery::create()->filterByDbShowId( + $this->getId())->find(); + $res = array(); + foreach ($showDays as $showDay) { + $res[] = $showDay->getDbDay(); } - - return $days; + return $res; } /* Only used for shows that aren't repeating. * * @return Boolean: true if show has an instance, otherwise false. */ - public function hasInstance(){ + public function hasInstance() + { return (!is_null($this->getInstance())); } @@ -791,7 +914,8 @@ class Application_Model_Show { * * @return CcShowInstancesQuery: An propel object representing a * row in the cc_show_instances table. */ - public function getInstance(){ + public function getInstance() + { $showInstance = CcShowInstancesQuery::create() ->filterByDbShowId($this->getId()) ->findOne(); @@ -802,15 +926,16 @@ class Application_Model_Show { /** * returns info about live stream override info */ - public function getLiveStreamInfo(){ + public function getLiveStreamInfo() + { $info = array(); - if($this->_showId == null){ + if ($this->getId() == null) { return $info; - }else{ + } 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['cb_custom_auth'] = $ccShow->getDbLiveStreamUsingCustomAuth(); $info['custom_username'] = $ccShow->getDbLiveStreamUser(); $info['custom_password'] = $ccShow->getDbLiveStreamPass(); return $info; @@ -827,11 +952,11 @@ class Application_Model_Show { * * @return Boolean: true if show has an instance on $p_dateTime, * otherwise false. */ - public function hasInstanceOnDate($p_dateTime){ + 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. @@ -840,35 +965,41 @@ class Application_Model_Show { * * @return CcShowInstancesQuery: An propel object representing a * row in the cc_show_instances table. */ - public function getInstanceOnDate($p_dateTime){ - $con = Propel::getConnection(); - + public function getInstanceOnDate($p_dateTime) + { $timestamp = $p_dateTime->format("Y-m-d H:i:s"); - - $showId = $this->getId(); - $sql = "SELECT id FROM cc_show_instances" - ." WHERE date(starts) = date(TIMESTAMP '$timestamp') " - ." AND show_id = $showId AND rebroadcast = 0"; - - $query = $con->query($sql); - $row = ($query !== false) ? $query->fetchColumn(0) : null; - return CcShowInstancesQuery::create() - ->findPk($row); + $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()){ + if ($p_data['add_show_repeats'] != $this->isRepeating()) { //repeat option was toggled $this->deleteAllInstances(); } - if ($p_data['add_show_duration'] != $this->getDuration()){ + if ($p_data['add_show_duration'] != $this->getDuration()) { //duration has changed $this->updateDurationTime($p_data); } - if ($p_data['add_show_repeats']){ + if ($p_data['add_show_repeats']) { if (($repeatType == 1 || $repeatType == 2) && $p_data['add_show_start_date'] != $this->getStartDate()){ @@ -879,28 +1010,27 @@ class Application_Model_Show { $this->deleteAllInstances(); } - if ($repeatType != $this->getRepeatType()){ + 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)){ + 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'])){ + if (count($intersect) != count($p_data['add_show_day_check'])) { $repeatingDaysChanged = true; } - } - else { + } else { $repeatingDaysChanged = true; } - if ($repeatingDaysChanged){ + if ($repeatingDaysChanged) { $daysRemoved = array_diff($showDaysArray, $p_data['add_show_day_check']); - if (count($daysRemoved) > 0){ + if (count($daysRemoved) > 0) { $this->removeUncheckedDaysInstances($daysRemoved); } @@ -912,7 +1042,7 @@ class Application_Model_Show { $newDate = strtotime($p_data['add_show_start_date']); $oldDate = strtotime($this->getStartDate()); - if ($newDate > $oldDate){ + if ($newDate > $oldDate) { $this->removeAllInstancesBeforeDate($p_data['add_show_start_date']); } @@ -922,20 +1052,19 @@ class Application_Model_Show { //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']){ + 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 { + if ($p_data['add_show_no_end']) { + } else { $this->removeAllInstancesFromDate($p_endDate); } } - if ($this->getRepeatingEndDate() != $p_data['add_show_end_date']){ + 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){ + if ($newDate < $oldDate) { $this->removeAllInstancesFromDate($p_endDate); } } @@ -947,7 +1076,7 @@ class Application_Model_Show { * * Note: end dates are non inclusive. * - * @param array $data + * @param array $data * @return int * Show ID */ @@ -959,14 +1088,12 @@ class Application_Model_Show { if ($data['add_show_no_end']) { $endDate = NULL; - } - else if ($data['add_show_repeats']) { + } 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 { + } else { $endDateTime = new DateTime($data['add_show_start_date']); //$endDateTime->setTimezone(new DateTimeZone('UTC')); $endDateTime->add(new DateInterval("P1D")); @@ -980,14 +1107,14 @@ class Application_Model_Show { $startDow = date("w", $startDateTime->getTimestamp()); if (!$data['add_show_repeats']) { $data['add_show_day_check'] = array($startDow); - } else if ($data['add_show_repeats'] && $data['add_show_day_check'] == "") { + } 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){ + if ($data['add_show_id'] == -1) { $ccShow = new CcShow(); } else { $ccShow = CcShowQuery::create()->findPK($data['add_show_id']); @@ -998,8 +1125,8 @@ class Application_Model_Show { $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?true:false); - $ccShow->setDbLiveStreamUsingCustomAuth($data['cb_custom_auth'] == 1?true:false); + $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(); @@ -1008,19 +1135,19 @@ class Application_Model_Show { $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); $show->deletePossiblyInvalidInstances($data, $endDate, $isRecorded, $repeatType); } //check if we are adding or updating a show, and if updating //erase all the show's show_days information first. - if ($data['add_show_id'] != -1){ + if ($data['add_show_id'] != -1) { CcShowDaysQuery::create()->filterByDbShowId($data['add_show_id'])->delete(); } //don't set day for monthly repeat type, it's invalid. - if ($data['add_show_repeats'] && $data['add_show_repeat_type'] == 2){ + if ($data['add_show_repeats'] && $data['add_show_repeat_type'] == 2) { $showDay = new CcShowDays(); $showDay->setDbFirstShow($startDateTime->format("Y-m-d")); $showDay->setDbLastShow($endDate); @@ -1035,7 +1162,7 @@ class Application_Model_Show { foreach ($data['add_show_day_check'] as $day) { $daysAdd=0; $startDateTimeClone = clone $startDateTime; - if ($startDow !== $day){ + if ($startDow !== $day) { if ($startDow > $day) $daysAdd = 6 - $startDow + 1 + $day; else @@ -1061,12 +1188,14 @@ class Application_Model_Show { //check if we are adding or updating a show, and if updating //erase all the show's future show_rebroadcast information first. - if (($data['add_show_id'] != -1) && isset($data['add_show_rebroadcast']) && $data['add_show_rebroadcast']){ + if (($data['add_show_id'] != -1) && isset($data['add_show_rebroadcast']) && $data['add_show_rebroadcast']) { CcShowRebroadcastQuery::create() ->filterByDbShowId($data['add_show_id']) ->delete(); } //adding rows to cc_show_rebroadcast + /* TODO: Document magic constant 10 and define it properly somewhere + --RG */ if (($isRecorded && $data['add_show_rebroadcast']) && ($repeatType != -1)) { for ($i=1; $i<=10; $i++) { if ($data['add_show_rebroadcast_date_'.$i]) { @@ -1077,14 +1206,25 @@ class Application_Model_Show { $showRebroad->save(); } } - } - else if ($isRecorded && $data['add_show_rebroadcast'] && ($repeatType == -1)){ + } 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']}' "; - $r = $con->query($sql); - $offset_days = $r->fetchColumn(0); + //$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"); @@ -1097,7 +1237,7 @@ class Application_Model_Show { //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'])) { @@ -1129,16 +1269,16 @@ class Application_Model_Show { } $con->commit(); - } - catch (Exception $e) { + } catch (Exception $e) { $con->rollback(); - Logging::log("Couldn't update schedule status."); - Logging::log($e->getMessage()); + Logging::info("Couldn't update schedule status."); + Logging::info($e->getMessage()); } } Application_Model_Show::populateShowUntil($showId); Application_Model_RabbitMq::PushSchedule(); + return $showId; } @@ -1161,8 +1301,11 @@ class Application_Model_Show { $p_populateUntilDateTime = $date; } - $sql = "SELECT * FROM cc_show_days WHERE show_id = $p_showId"; - $res = $con->query($sql)->fetchAll(); + $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); @@ -1180,17 +1323,17 @@ class Application_Model_Show { * @param DateTime $p_populateUntilDateTime * DateTime object in UTC time. */ - private static function populateShow($p_showDaysRow, $p_populateUntilDateTime) { - if($p_showDaysRow["repeat_type"] == -1) { + 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); - } - else if($p_showDaysRow["repeat_type"] == 0) { + } elseif ($p_showDaysRow["repeat_type"] == 0) { Application_Model_Show::populateRepeatingShow($p_showDaysRow, $p_populateUntilDateTime, 'P7D'); - } - else if($p_showDaysRow["repeat_type"] == 1) { + } elseif ($p_showDaysRow["repeat_type"] == 1) { Application_Model_Show::populateRepeatingShow($p_showDaysRow, $p_populateUntilDateTime, 'P14D'); - } - else if($p_showDaysRow["repeat_type"] == 2) { + } elseif ($p_showDaysRow["repeat_type"] == 2) { Application_Model_Show::populateRepeatingShow($p_showDaysRow, $p_populateUntilDateTime, 'P1M'); } Application_Model_RabbitMq::PushSchedule(); @@ -1207,16 +1350,13 @@ class Application_Model_Show { */ private static function populateNonRepeatingShow($p_showRow, $p_populateUntilDateTime) { - $con = Propel::getConnection(); - - $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"]; - $day = $p_showRow["day"]; - $record = $p_showRow["record"]; - $timezone = $p_showRow["timezone"]; - $start = $first_show." ".$start_time; + $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); @@ -1224,7 +1364,7 @@ class Application_Model_Show { $currentUtcTimestamp = gmdate("Y-m-d H:i:s"); $show = new Application_Model_Show($show_id); - if ($show->hasInstance()){ + if ($show->hasInstance()) { $ccShowInstance = $show->getInstance(); $newInstance = false; } else { @@ -1232,7 +1372,7 @@ class Application_Model_Show { $newInstance = true; } - if ($newInstance || $ccShowInstance->getDbStarts() > $currentUtcTimestamp){ + if ($newInstance || $ccShowInstance->getDbStarts() > $currentUtcTimestamp) { $ccShowInstance->setDbShowId($show_id); $ccShowInstance->setDbStarts($utcStartDateTime); $ccShowInstance->setDbEnds($utcEndDateTime); @@ -1243,16 +1383,17 @@ class Application_Model_Show { $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 = $con->query($sql)->fetchAll(); + $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); + if ($showInstance->isRecorded()) { + $showInstance->deleteRebroadcasts(); + self::createRebroadcastInstances($rebroadcasts, $currentUtcTimestamp, $show_id, $show_instance_id, $start, $duration, $timezone); } } } @@ -1271,21 +1412,19 @@ class Application_Model_Show { */ private static function populateRepeatingShow($p_showDaysRow, $p_populateUntilDateTime, $p_interval) { - $con = Propel::getConnection(); - - $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 - $start_time = $p_showDaysRow["start_time"]; //non-UTC - $duration = $p_showDaysRow["duration"]; - $day = $p_showDaysRow["day"]; - $record = $p_showDaysRow["record"]; - $timezone = $p_showDaysRow["timezone"]; + $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)) { + if (isset($next_pop_date)) { $start = $next_pop_date." ".$start_time; } else { $start = $first_show." ".$start_time; @@ -1295,8 +1434,10 @@ class Application_Model_Show { //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 = $con->query($sql)->fetchAll(); + $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); @@ -1305,15 +1446,15 @@ class Application_Model_Show { list($utcStartDateTime, $utcEndDateTime) = self::createUTCStartEndDateTime($start, $duration, $timezone); - if ($show->hasInstanceOnDate($utcStartDateTime)){ + if ($show->hasInstanceOnDate($utcStartDateTime)) { $ccShowInstance = $show->getInstanceOnDate($utcStartDateTime); - - if ($ccShowInstance->getDbModifiedInstance()){ + + 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(); @@ -1323,7 +1464,7 @@ class Application_Model_Show { /* 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); @@ -1337,7 +1478,7 @@ class Application_Model_Show { /* If we are updating a show then make sure that the scheduled content within * the show is updated to the correct time. */ - if (!$newInstance){ + if (!$newInstance) { $showInstance->correctScheduleStartTimes(); } @@ -1349,10 +1490,11 @@ class Application_Model_Show { Application_Model_Show::setNextPop($start, $show_id, $day); } - - private static function advanceRepeatingDate($p_interval, $start, $timezone){ + + private static function advanceRepeatingDate($p_interval, $start, $timezone) + { $startDt = new DateTime($start, new DateTimeZone($timezone)); - if ($p_interval == 'P1M'){ + 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 @@ -1368,20 +1510,20 @@ class Application_Model_Show { * 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"))); - + } 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); } @@ -1413,6 +1555,7 @@ class Application_Model_Show { $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); } @@ -1435,14 +1578,14 @@ class Application_Model_Show { * 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){ - + 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) { + foreach ($p_rebroadcasts as $rebroadcast) { $days = explode(" ", $rebroadcast["day_offset"]); $time = explode(":", $rebroadcast["start_time"]); @@ -1450,7 +1593,7 @@ class Application_Model_Show { 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){ + if ($utcStartDateTime->format("Y-m-d H:i:s") > $p_currentUtcTimestamp) { $newRebroadcastInstance = new CcShowInstances(); $newRebroadcastInstance->setDbShowId($p_showId); @@ -1471,14 +1614,12 @@ class Application_Model_Show { * In UTC time. * @param DateTime $end_timestamp * In UTC time. - * @param unknown_type $excludeInstance - * @param boolean $onlyRecord + * @param unknown_type $excludeInstance + * @param boolean $onlyRecord * @return array */ - public static function getShows($start_timestamp, $end_timestamp, $excludeInstance=NULL, $onlyRecord=FALSE) + public static function getShows($start_timestamp, $end_timestamp, $onlyRecord=FALSE) { - $con = Propel::getConnection(); - //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. @@ -1487,42 +1628,56 @@ class Application_Model_Show { Application_Model_Preference::SetShowsPopulatedUntil($end_timestamp); } - $sql = "SELECT si1.starts AS starts, si1.ends AS ends, si1.record AS record, si1.rebroadcast AS rebroadcast, si2.starts AS parent_starts, - si1.instance_id AS record_id, si1.show_id AS show_id, show.name AS name, - show.color AS color, show.background_color AS background_color, si1.file_id AS file_id, si1.id AS instance_id, - si1.created AS created, si1.last_scheduled AS last_scheduled, si1.time_filled AS time_filled - FROM cc_show_instances AS si1 - LEFT JOIN cc_show_instances AS si2 ON si1.instance_id = si2.id - LEFT JOIN cc_show AS show ON show.id = si1.show_id - WHERE si1.modified_instance = FALSE"; + $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)"; - $sql = $sql." AND (si1.starts >= '{$start_string}' AND si1.starts < timestamp '{$end_string}')"; - $sql = $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'); } - else { - - $sql = $sql." AND ((si1.starts >= '{$start_string}' AND si1.starts < '{$end_string}') - OR (si1.ends > '{$start_string}' AND si1.ends <= '{$end_string}') - OR (si1.starts <= '{$start_string}' AND si1.ends >= '{$end_string}'))"; - } - - - if (isset($excludeInstance)) { - foreach($excludeInstance as $instance) { - $sql_exclude[] = "si1.id != {$instance}"; - } - - $exclude = join(" OR ", $sql_exclude); - - $sql = $sql." AND ({$exclude})"; - } - - $result = $con->query($sql)->fetchAll(); - return $result; } private static function setNextPop($next_date, $show_id, $day) @@ -1548,23 +1703,26 @@ class Application_Model_Show { */ public static function populateAllShowsInRange($p_startTimestamp, $p_endTimestamp) { - $con = Propel::getConnection(); + $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 { + } else { $today_timestamp = new DateTime("now", new DateTimeZone("UTC")); $startTimeString = $today_timestamp->format("Y-m-d H:i:s"); } - $sql = "SELECT * FROM cc_show_days - WHERE last_show IS NULL - OR first_show < '{$endTimeString}' AND last_show > '{$startTimeString}'"; + $stmt = $con->prepare(" + SELECT * FROM cc_show_days + WHERE last_show IS NULL + OR first_show < :endTimeString AND last_show > :startTimeString"); - //Logging::log($sql); - $res = $con->query($sql)->fetchAll(); + $stmt->bindParam(':endTimeString', $endTimeString); + $stmt->bindParam(':startTimeString', $startTimeString); + $stmt->execute(); + + $res = $stmt->fetchAll(); foreach ($res as $row) { Application_Model_Show::populateShow($row, $p_endTimestamp); } @@ -1578,43 +1736,66 @@ class Application_Model_Show { * -in UTC time * @param boolean $editable */ - public static function getFullCalendarEvents($p_start, $p_end, $p_editable=false) + public static function &getFullCalendarEvents($p_start, $p_end, $p_editable=false) { - $events = array(); + $events = array(); $interval = $p_start->diff($p_end); - $days = $interval->format('%a'); - $shows = Application_Model_Show::getShows($p_start, $p_end); + $days = $interval->format('%a'); + $shows = Application_Model_Show::getShows($p_start, $p_end); $nowEpoch = time(); - + $content_count = Application_Model_ShowInstance::getContentCount( + $p_start, $p_end); + $timezone = date_default_timezone_get(); + 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"]); } - + + $utc = new DateTimeZone("UTC"); + if (isset($show["parent_starts"])) { - $parentStartsDT = new DateTime($show["parent_starts"], new DateTimeZone("UTC")); + $parentStartsDT = new DateTime($show["parent_starts"], $utc); $parentStartsEpoch = intval($parentStartsDT->format("U")); } - $startsDT = new DateTime($show["starts"], new DateTimeZone("UTC")); - $endsDT = new DateTime($show["ends"], new DateTimeZone("UTC")); - - $startsEpoch = intval($startsDT->format("U")); - $endsEpoch = intval($endsDT->format("U")); - if ($p_editable && $show["record"] && $nowEpoch > $startsEpoch) { - $options["editable"] = false; + $startsDT = DateTime::createFromFormat("Y-m-d G:i:s", + $show["starts"],$utc); + $endsDT = DateTime::createFromFormat("Y-m-d G:i:s", + $show["ends"], $utc); + + $startsEpochStr = $startsDT->format("U"); + $endsEpochStr = $endsDT->format("U"); + + $startsEpoch = intval($startsEpochStr); + $endsEpoch = intval($endsEpochStr); + + $startsDT->setTimezone(new DateTimeZone($timezone)); + $endsDT->setTimezone(new DateTimeZone($timezone)); + + if( $p_editable ) { + if ($show["record"] && $nowEpoch > $startsEpoch) { + $options["editable"] = false; + } elseif ($show["rebroadcast"] && + $nowEpoch > $parentStartsEpoch) { + $options["editable"] = false; + } elseif ($nowEpoch < $endsEpoch) { + $options["editable"] = true; + } } - else if ($p_editable && $show["rebroadcast"] && $nowEpoch > $parentStartsEpoch) { - $options["editable"] = false; - } - else if ($p_editable && $nowEpoch < $endsEpoch) { - $options["editable"] = true; - } - $events[] = Application_Model_Show::makeFullCalendarEvent($show, $options); + + + $showInstance = new Application_Model_ShowInstance( + $show["instance_id"]); + + $options["show_empty"] = (array_key_exists($show['instance_id'], + $content_count)) ? 0 : 1; + + $events[] = &self::makeFullCalendarEvent($show, $options, + $startsDT, $endsDT, $startsEpochStr, $endsEpochStr); } return $events; @@ -1624,7 +1805,8 @@ class Application_Model_Show { * 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){ + 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); @@ -1632,39 +1814,28 @@ class Application_Model_Show { return $percent; } - private static function makeFullCalendarEvent($show, $options=array()) + private static function &makeFullCalendarEvent(&$show, $options=array(), $startDateTime, $endDateTime, $startsEpoch, $endsEpoch) { $event = array(); - $startDateTime = new DateTime($show["starts"], new DateTimeZone("UTC")); - $startDateTime->setTimezone(new DateTimeZone(date_default_timezone_get())); - - $endDateTime = new DateTime($show["ends"], new DateTimeZone("UTC")); - $endDateTime->setTimezone(new DateTimeZone(date_default_timezone_get())); - - $event["id"] = intval($show["instance_id"]); - $event["title"] = $show["name"]; - $event["start"] = $startDateTime->format("Y-m-d H:i:s"); - $event["startUnix"] = $startDateTime->format("U"); - $event["end"] = $endDateTime->format("Y-m-d H:i:s"); - $event["endUnix"] = $endDateTime->format("U"); - $event["allDay"] = false; - $event["showId"] = intval($show["show_id"]); - $event["record"] = intval($show["record"]); - $event["rebroadcast"] = intval($show["rebroadcast"]); - - // get soundcloud_id - if (!is_null($show["file_id"])){ - $file = Application_Model_StoredFile::Recall($show["file_id"]); - $soundcloud_id = $file->getSoundCloudId(); - } - - $event["soundcloud_id"] = isset($soundcloud_id) ? $soundcloud_id : -1; + $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"]; } @@ -1679,8 +1850,8 @@ class Application_Model_Show { /* Takes in a UTC DateTime object. * Converts this to local time, since cc_show days * requires local time. */ - public function setShowFirstShow($p_dt){ - + public function setShowFirstShow($p_dt) + { //clone object since we are modifying it and it was passed by reference. $dt = clone $p_dt; @@ -1689,18 +1860,18 @@ class Application_Model_Show { $showDay = CcShowDaysQuery::create() ->filterByDbShowId($this->_showId) ->findOne(); - + $showDay->setDbFirstShow($dt)->setDbStartTime($dt) ->save(); - //Logging::log("setting show's first show."); + //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){ - + public function setShowLastShow($p_dt) + { //clone object since we are modifying it and it was passed by reference. $dt = clone $p_dt; @@ -1721,87 +1892,133 @@ class Application_Model_Show { * 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 + * @param String $timeNow - current time (in UTC) + * @return array - show being played right now */ - public static function GetCurrentShow($timeNow=null) + public static function getCurrentShow($timeNow=null) { global $CC_CONFIG; $con = Propel::getConnection(); - if($timeNow == null){ + if ($timeNow == null) { $date = new Application_Common_DateHelper; - $timeNow = $date->getUtcTimestamp(); + $timeNow = $date->getUtcTimestamp(); } //TODO, returning starts + ends twice (once with an alias). Unify this after the 2.0 release. --Martin - $sql = "SELECT si.starts as start_timestamp, si.ends as end_timestamp, s.name, s.id, si.id as instance_id, si.record, s.url, starts, ends" - ." FROM $CC_CONFIG[showInstances] si, $CC_CONFIG[showTable] s" - ." WHERE si.show_id = s.id" - ." AND si.starts <= TIMESTAMP '$timeNow'" - ." AND si.ends > TIMESTAMP '$timeNow'" - ." AND modified_instance != TRUE"; + $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"); + } - // Convert back to local timezone - $rows = $con->query($sql)->fetchAll(); return $rows; } /** - * Gets the current show, previous and next with an 2day window from the given timeNow, so timeNow-2days and timeNow+2days. + * 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) { global $CC_CONFIG; $con = Propel::getConnection(); + // //TODO, returning starts + ends twice (once with an alias). Unify this after the 2.0 release. --Martin - $sql = "SELECT si.starts as start_timestamp, si.ends as end_timestamp, s.name, s.id, si.id as instance_id, si.record, s.url, starts, ends" - ." FROM $CC_CONFIG[showInstances] si, $CC_CONFIG[showTable] s" - ." WHERE si.show_id = s.id" - ." AND si.starts > TIMESTAMP '$p_timeNow' - INTERVAL '2 days'" - ." AND si.ends < TIMESTAMP '$p_timeNow' + INTERVAL '2 days'" - ." AND modified_instance != TRUE" - ." ORDER BY si.starts"; - - $rows = $con->query($sql)->fetchAll(PDO::FETCH_ASSOC); + $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(); + $results['currentShow'] = array(); + $results['nextShow'] = array(); $timeNowAsMillis = strtotime($p_timeNow); - for( $i = 0; $i < $numberOfRows; ++$i ){ + 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){ + 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"); + "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])){ + 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"); - + "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; } @@ -1812,16 +2029,16 @@ class Application_Model_Show { //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"); + "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; } } @@ -1829,97 +2046,110 @@ class Application_Model_Show { //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"); + "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 returns; + * 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 + * @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 = "0", $timeEnd = "") + public static function getNextShows($timeStart, $limit = "ALL", $timeEnd = "") { - global $CC_CONFIG; - $con = Propel::getConnection(); - // defaults to retrieving shows from next 2 days if no end time has // been specified if ($timeEnd == "") { $timeEnd = "'$timeStart' + INTERVAL '2 days'"; - } else { - $timeEnd = "'$timeEnd'"; } //TODO, returning starts + ends twice (once with an alias). Unify this after the 2.0 release. --Martin - $sql = "SELECT *, si.starts as start_timestamp, si.ends as end_timestamp FROM " - ." $CC_CONFIG[showInstances] si, $CC_CONFIG[showTable] s" - ." WHERE si.show_id = s.id" - ." AND si.starts >= TIMESTAMP '$timeStart'" - ." AND si.starts < TIMESTAMP $timeEnd" - ." AND modified_instance != TRUE" - ." ORDER BY si.starts"; + $sql = <<= :timeStart::timestamp + AND si.starts < :timeEnd::timestamp + AND modified_instance != TRUE +ORDER BY si.starts +SQL; - // defaults to retrieve all shows within the interval if $limit not set - if($limit != "0") { - $sql = $sql . " LIMIT $limit"; + //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); } - $rows = $con->query($sql)->fetchAll(); - return $rows; + 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 + * @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) { - $timezone = date_default_timezone_get(); - + public static function convertToLocalTimeZone(&$rows, $columnsToConvert) + { if (!is_array($rows)) { return; } - foreach($rows as &$row) { - foreach($columnsToConvert as $column) { + foreach ($rows as &$row) { + foreach ($columnsToConvert as $column) { $row[$column] = Application_Common_DateHelper::ConvertToLocalDateTimeString($row[$column]); } } } - public static function GetMaxLengths() { - global $CC_CONFIG; + public static function getMaxLengths() + { $con = Propel::getConnection(); - - $sql = "SELECT column_name, character_maximum_length FROM information_schema.columns" - ." WHERE table_name = 'cc_show' AND character_maximum_length > 0"; - $result = $con->query($sql)->fetchAll(); - - // store result into assoc array + $sql = << 0 +SQL; + $result = $con->query($sql)->fetchAll(); $assocArray = array(); foreach ($result as $row) { $assocArray[$row['column_name']] = $row['character_maximum_length']; } - return $assocArray; } } diff --git a/airtime_mvc/application/models/ShowBuilder.php b/airtime_mvc/application/models/ShowBuilder.php index 650734e2d..8436c3011 100644 --- a/airtime_mvc/application/models/ShowBuilder.php +++ b/airtime_mvc/application/models/ShowBuilder.php @@ -3,8 +3,8 @@ require_once 'formatters/LengthFormatter.php'; require_once 'formatters/TimeFilledFormatter.php'; -class Application_Model_ShowBuilder { - +class Application_Model_ShowBuilder +{ private $timezone; //in UTC timezone @@ -14,85 +14,86 @@ class Application_Model_ShowBuilder { private $user; private $opts; - + private $pos; private $contentDT; private $epoch_now; private $currentShow; - + private $showInstances = array(); - + private $defaultRowArray = array( - "header" => false, - "footer" => false, - "empty" => false, - "allowed" => false, - "id" => 0, - "instance" => "", - "starts" => "", - "ends" => "", - "runtime" => "", - "title" => "", - "creator" => "", - "album" => "", - "timestamp" => null, - "cuein" => "", - "cueout" => "", - "fadein" => "", - "fadeout" => "", - "image" => false, - "color" => "", //in hex without the '#' sign. - "backgroundColor"=> "", //in hex without the '#' sign. + "header" => false, + "footer" => false, + "empty" => false, + "allowed" => false, + "id" => 0, + "instance" => "", + "starts" => "", + "ends" => "", + "runtime" => "", + "title" => "", + "creator" => "", + "album" => "", + "timestamp" => null, + "cuein" => "", + "cueout" => "", + "fadein" => "", + "fadeout" => "", + "image" => false, + "color" => "", //in hex without the '#' sign. + "backgroundColor" => "", //in hex without the '#' sign. ); /* * @param DateTime $p_startsDT * @param DateTime $p_endsDT */ - public function __construct($p_startDT, $p_endDT, $p_opts) { - - $this->startDT = $p_startDT; - $this->endDT = $p_endDT; - $this->timezone = date_default_timezone_get(); - $this->user = Application_Model_User::GetCurrentUser(); - $this->opts = $p_opts; - $this->epoch_now = floatval(microtime(true)); + public function __construct($p_startDT, $p_endDT, $p_opts) + { + $this->startDT = $p_startDT; + $this->endDT = $p_endDT; + $this->timezone = date_default_timezone_get(); + $this->user = Application_Model_User::getCurrentUser(); + $this->opts = $p_opts; + $this->epoch_now = floatval(microtime(true)); $this->currentShow = false; } - - private function getUsersShows() { - + + private function getUsersShows() + { $shows = array(); - - $host_shows = CcShowHostsQuery::create() - ->setFormatter(ModelCriteria::FORMAT_ON_DEMAND) - ->filterByDbHost($this->user->getId()) - ->find(); - - foreach ($host_shows as $host_show) { - $shows[] = $host_show->getDbShow(); + + $host_shows = CcShowHostsQuery::create() + ->setFormatter(ModelCriteria::FORMAT_ON_DEMAND) + ->filterByDbHost($this->user->getId()) + ->find(); + + foreach ($host_shows as $host_show) { + $shows[] = $host_show->getDbShow(); } - + return $shows; } //check to see if this row should be editable by the user. - private function isAllowed($p_item, &$row) { - + private function isAllowed($p_item, &$row) + { //cannot schedule in a recorded show. if (intval($p_item["si_record"]) === 1) { return; } - if ($this->user->canSchedule($p_item["show_id"]) == true) { + if ($this->user->canSchedule($p_item["show_id"]) == true) { $row["allowed"] = true; - } + } } - - private function getItemColor($p_item, &$row) { - $defaultColor = "ffffff"; + + private function getItemColor($p_item, &$row) + { + $defaultColor = "ffffff"; $defaultBackground = "3366cc"; - + $color = $p_item["show_color"]; if ($color === '') { $color = $defaultColor; @@ -101,70 +102,76 @@ class Application_Model_ShowBuilder { if ($backgroundColor === '') { $backgroundColor = $defaultBackground; } - - $row["color"] = $color; + + $row["color"] = $color; $row["backgroundColor"] = $backgroundColor; } //information about whether a track is inside|boundary|outside a show. - private function getItemStatus($p_item, &$row) { - + private function getItemStatus($p_item, &$row) + { $row["status"] = intval($p_item["playout_status"]); } - private function getRowTimestamp($p_item, &$row) { - + private function getRowTimestamp($p_item, &$row) + { if (is_null($p_item["si_last_scheduled"])) { $ts = 0; - } - else { + } else { $dt = new DateTime($p_item["si_last_scheduled"], new DateTimeZone("UTC")); $ts = intval($dt->format("U")); } $row["timestamp"] = $ts; } - + /* * marks a row's status. * 0 = past * 1 = current * 2 = future + * TODO : change all of the above to real constants -- RG */ - private function getScheduledStatus($p_epochItemStart, $p_epochItemEnd, &$row) { - - if ($row["footer"] === true && $this->epoch_now > $p_epochItemStart && $this->epoch_now > $p_epochItemEnd) { + private function getScheduledStatus($p_epochItemStart, $p_epochItemEnd, &$row) + { + if ($row["footer"] === true && $this->epoch_now > $p_epochItemStart && + $this->epoch_now > $p_epochItemEnd) { $row["scheduled"] = 0; - } - else if ($row["footer"] === true && $this->epoch_now < $p_epochItemEnd) { - $row["scheduled"] = 2; - } - else if ($row["header"] === true && $this->epoch_now >= $p_epochItemStart) { + } elseif ($row["footer"] === true && $this->epoch_now < $p_epochItemEnd) { + $row["scheduled"] = 2; + } elseif ($row["header"] === true && $this->epoch_now >= $p_epochItemStart) { $row["scheduled"] = 0; + } elseif ($row["header"] === true && $this->epoch_now < $p_epochItemEnd) { + $row["scheduled"] = 2; } - else if ($row["header"] === true && $this->epoch_now < $p_epochItemEnd) { - $row["scheduled"] = 2; - } - + //item is in the past. - else if ($this->epoch_now > $p_epochItemEnd) { - $row["scheduled"] = 0; + else if ($this->epoch_now > $p_epochItemEnd) { + $row["scheduled"] = 0; } - - //item is the currently scheduled item. - else if ($this->epoch_now >= $p_epochItemStart && $this->epoch_now < $p_epochItemEnd) { - $row["scheduled"] = 1; - //how many seconds the view should wait to redraw itself. - $row["refresh"] = $p_epochItemEnd - $this->epoch_now; + + //item is the currently scheduled item. + else if ($this->epoch_now >= $p_epochItemStart && $this->epoch_now < $p_epochItemEnd) { + $row["scheduled"] = 1; + //how many seconds the view should wait to redraw itself. + $row["refresh"] = $p_epochItemEnd - $this->epoch_now; + } + + //item is in the future. + else if ($this->epoch_now < $p_epochItemStart) { + $row["scheduled"] = 2; + } else { + Logging::warn("No-op? is this what should happen...printing + debug just in case"); + $d = array( + '$p_epochItemStart' => $p_epochItemStart, + '$p_epochItemEnd' => $p_epochItemEnd, + '$row' => $row); + Logging::warn($d); } - - //item is in the future. - else if ($this->epoch_now < $p_epochItemStart) { - $row["scheduled"] = 2; - } } - private function makeHeaderRow($p_item) { - + private function makeHeaderRow($p_item) + { $row = $this->defaultRowArray; $this->isAllowed($p_item, $row); $this->getRowTimestamp($p_item, $row); @@ -173,55 +180,56 @@ class Application_Model_ShowBuilder { $showStartDT = new DateTime($p_item["si_starts"], new DateTimeZone("UTC")); $showStartDT->setTimezone(new DateTimeZone($this->timezone)); $startsEpoch = floatval($showStartDT->format("U.u")); - $showEndDT = new DateTime($p_item["si_ends"], new DateTimeZone("UTC")); + $showEndDT = new DateTime($p_item["si_ends"], new DateTimeZone("UTC")); $showEndDT->setTimezone(new DateTimeZone($this->timezone)); $endsEpoch = floatval($showEndDT->format("U.u")); - - //is a rebroadcast show - if (intval($p_item["si_rebroadcast"]) === 1) { + + //is a rebroadcast show + if (intval($p_item["si_rebroadcast"]) === 1) { $row["rebroadcast"] = true; - + $parentInstance = CcShowInstancesQuery::create()->findPk($p_item["parent_show"]); - $name = $parentInstance->getCcShow()->getDbName(); - $dt = $parentInstance->getDbStarts(null); + $name = $parentInstance->getCcShow()->getDbName(); + $dt = $parentInstance->getDbStarts(null); $dt->setTimezone(new DateTimeZone($this->timezone)); $time = $dt->format("Y-m-d H:i"); - - $row["rebroadcast_title"] = "Rebroadcast of {$name} from {$time}"; - } - else if (intval($p_item["si_record"]) === 1) { + + $row["rebroadcast_title"] = "Rebroadcast of {$name} from {$time}"; + } elseif (intval($p_item["si_record"]) === 1) { $row["record"] = true; - - if (Application_Model_Preference::GetUploadToSoundcloudOption()) { - $file = Application_Model_StoredFile::Recall($p_item["si_file_id"]); + + // at the time of creating on show, the recorded file is not in the DB yet. + // therefore, 'si_file_id' is null. So we need to check it. + if (Application_Model_Preference::GetUploadToSoundcloudOption() && isset($p_item['si_file_id'])) { + $file = Application_Model_StoredFile::Recall( + $p_item['si_file_id']); if (isset($file)) { - $sid = $file->getSoundCloudId(); - $row["soundcloud_id"] = $sid; - } + $sid = $file->getSoundCloudId(); + $row['soundcloud_id'] = $sid; + } } } - + if ($startsEpoch < $this->epoch_now && $endsEpoch > $this->epoch_now) { $row["currentShow"] = true; $this->currentShow = true; - } - else { + } else { $this->currentShow = false; } - $row["header"] = true; - $row["starts"] = $showStartDT->format("Y-m-d H:i"); + $row["header"] = true; + $row["starts"] = $showStartDT->format("Y-m-d H:i"); $row["startDate"] = $showStartDT->format("Y-m-d"); $row["startTime"] = $showStartDT->format("H:i"); - $row["refresh"] = floatval($showStartDT->format("U.u")) - $this->epoch_now; - $row["ends"] = $showEndDT->format("Y-m-d H:i"); - $row["endDate"] = $showEndDT->format("Y-m-d"); - $row["endTime"] = $showEndDT->format("H:i"); - $row["duration"] = floatval($showEndDT->format("U.u")) - floatval($showStartDT->format("U.u")); - $row["title"] = $p_item["show_name"]; - $row["instance"] = intval($p_item["si_id"]); - $row["image"] = ''; - + $row["refresh"] = floatval($showStartDT->format("U.u")) - $this->epoch_now; + $row["ends"] = $showEndDT->format("Y-m-d H:i"); + $row["endDate"] = $showEndDT->format("Y-m-d"); + $row["endTime"] = $showEndDT->format("H:i"); + $row["duration"] = floatval($showEndDT->format("U.u")) - floatval($showStartDT->format("U.u")); + $row["title"] = $p_item["show_name"]; + $row["instance"] = intval($p_item["si_id"]); + $row["image"] = ''; + $this->getScheduledStatus($startsEpoch, $endsEpoch, $row); $this->contentDT = $showStartDT; @@ -229,162 +237,171 @@ class Application_Model_ShowBuilder { return $row; } - private function makeScheduledItemRow($p_item) { + private function makeScheduledItemRow($p_item) + { $row = $this->defaultRowArray; if (isset($p_item["sched_starts"])) { - $schedStartDT = new DateTime($p_item["sched_starts"], new DateTimeZone("UTC")); + $schedStartDT = new DateTime($p_item["sched_starts"], + new DateTimeZone("UTC")); $schedStartDT->setTimezone(new DateTimeZone($this->timezone)); - $schedEndDT = new DateTime($p_item["sched_ends"], new DateTimeZone("UTC")); + $schedEndDT = new DateTime($p_item["sched_ends"], + new DateTimeZone("UTC")); $schedEndDT->setTimezone(new DateTimeZone($this->timezone)); $showEndDT = new DateTime($p_item["si_ends"], new DateTimeZone("UTC")); $this->getItemStatus($p_item, $row); - $startsEpoch = floatval($schedStartDT->format("U.u")); - $endsEpoch = floatval($schedEndDT->format("U.u")); + $startsEpoch = floatval($schedStartDT->format("U.u")); + $endsEpoch = floatval($schedEndDT->format("U.u")); $showEndEpoch = floatval($showEndDT->format("U.u")); //don't want an overbooked item to stay marked as current. $this->getScheduledStatus($startsEpoch, min($endsEpoch, $showEndEpoch), $row); - $row["id"] = intval($p_item["sched_id"]); - $row["image"] = $p_item["file_exists"]; + $row["id"] = intval($p_item["sched_id"]); + $row["image"] = $p_item["file_exists"]; $row["instance"] = intval($p_item["si_id"]); - $row["starts"] = $schedStartDT->format("H:i:s"); - $row["ends"] = $schedEndDT->format("H:i:s"); - - $formatter = new LengthFormatter($p_item['file_length']); - $row['runtime'] = $formatter->format(); + $row["starts"] = $schedStartDT->format("H:i:s"); + $row["ends"] = $schedEndDT->format("H:i:s"); - $row["title"] = $p_item["file_track_title"]; - $row["creator"] = $p_item["file_artist_name"]; - $row["album"] = $p_item["file_album_title"]; + $formatter = new LengthFormatter($p_item['file_length']); + $row['runtime'] = $formatter->format(); - $row["cuein"] = $p_item["cue_in"]; - $row["cueout"] = $p_item["cue_out"]; - $row["fadein"] = round(substr($p_item["fade_in"], 6), 6); - $row["fadeout"] = round(substr($p_item["fade_out"], 6), 6); - - $row["pos"] = $this->pos++; + $row["title"] = $p_item["file_track_title"]; + $row["creator"] = $p_item["file_artist_name"]; + $row["album"] = $p_item["file_album_title"]; + + $row["cuein"] = $p_item["cue_in"]; + $row["cueout"] = $p_item["cue_out"]; + $row["fadein"] = round(substr($p_item["fade_in"], 6), 6); + $row["fadeout"] = round(substr($p_item["fade_out"], 6), 6); + + $row["pos"] = $this->pos++; $this->contentDT = $schedEndDT; } //show is empty or is a special kind of show (recording etc) else if (intval($p_item["si_record"]) === 1) { - $row["record"] = true; + $row["record"] = true; $row["instance"] = intval($p_item["si_id"]); - - $showStartDT = new DateTime($p_item["si_starts"], new DateTimeZone("UTC")); - $showEndDT = new DateTime($p_item["si_ends"], new DateTimeZone("UTC")); - - $startsEpoch = floatval($showStartDT->format("U.u")); - $endsEpoch = floatval($showEndDT->format("U.u")); - + + $showStartDT = new DateTime($p_item["si_starts"], new DateTimeZone("UTC")); + $showEndDT = new DateTime($p_item["si_ends"], new DateTimeZone("UTC")); + + $startsEpoch = floatval($showStartDT->format("U.u")); + $endsEpoch = floatval($showEndDT->format("U.u")); + $this->getScheduledStatus($startsEpoch, $endsEpoch, $row); - } - else { - $row["empty"] = true; - $row["id"] = 0 ; + } else { + $row["empty"] = true; + $row["id"] = 0 ; $row["instance"] = intval($p_item["si_id"]); } - - if (intval($p_item["si_rebroadcast"]) === 1) { - $row["rebroadcast"] = true; + + if (intval($p_item["si_rebroadcast"]) === 1) { + $row["rebroadcast"] = true; } - + if ($this->currentShow === true) { $row["currentShow"] = true; } - - $this->getItemColor($p_item, $row); - $this->getRowTimestamp($p_item, $row); + + $this->getItemColor($p_item, $row); + $this->getRowTimestamp($p_item, $row); $this->isAllowed($p_item, $row); return $row; } - private function makeFooterRow($p_item) { - - $row = $this->defaultRowArray; - $row["footer"] = true; + private function makeFooterRow($p_item) + { + $row = $this->defaultRowArray; + $row["footer"] = true; $row["instance"] = intval($p_item["si_id"]); $this->getRowTimestamp($p_item, $row); - $showEndDT = new DateTime($p_item["si_ends"], new DateTimeZone("UTC")); - $contentDT = $this->contentDT; + $showEndDT = new DateTime($p_item["si_ends"], new DateTimeZone("UTC")); + $contentDT = $this->contentDT; - $runtime = bcsub($contentDT->format("U.u"), $showEndDT->format("U.u"), 6); - $row["runtime"] = $runtime; + $runtime = bcsub($contentDT->format("U.u"), $showEndDT->format("U.u"), 6); + $row["runtime"] = $runtime; - $timeFilled = new TimeFilledFormatter($runtime); + $timeFilled = new TimeFilledFormatter($runtime); $row["fRuntime"] = $timeFilled->format(); - - $showStartDT = new DateTime($p_item["si_starts"], new DateTimeZone("UTC")); - $showStartDT->setTimezone(new DateTimeZone($this->timezone)); - $startsEpoch = floatval($showStartDT->format("U.u")); - $showEndDT = new DateTime($p_item["si_ends"], new DateTimeZone("UTC")); - $showEndDT->setTimezone(new DateTimeZone($this->timezone)); + + $showStartDT = new DateTime($p_item["si_starts"], new DateTimeZone("UTC")); + $showStartDT->setTimezone(new DateTimeZone($this->timezone)); + $startsEpoch = floatval($showStartDT->format("U.u")); + $showEndDT = new DateTime($p_item["si_ends"], new DateTimeZone("UTC")); + $showEndDT->setTimezone(new DateTimeZone($this->timezone)); $endsEpoch = floatval($showEndDT->format("U.u")); - - $row["refresh"] = floatval($showEndDT->format("U.u")) - $this->epoch_now; - - if ($this->currentShow === true) { - $row["currentShow"] = true; + + $row["refresh"] = floatval($showEndDT->format("U.u")) - $this->epoch_now; + + if ($this->currentShow === true) { + $row["currentShow"] = true; } - + $this->getScheduledStatus($startsEpoch, $endsEpoch, $row); - $this->isAllowed($p_item, $row); - + $this->isAllowed($p_item, $row); + + if (intval($p_item["si_record"]) === 1) { + $row["record"] = true; + } + return $row; } /* * @param int $timestamp Unix timestamp in seconds. * - * @return boolean whether the schedule in the show builder's range has been updated. + * @return boolean whether the schedule in the show builder's range has + * been updated. * */ - public function hasBeenUpdatedSince($timestamp, $instances) { + public function hasBeenUpdatedSince($timestamp, $instances) + { $outdated = false; $shows = Application_Model_Show::getShows($this->startDT, $this->endDT); - + if ($this->opts["showFilter"] !== 0) { $include[] = $this->opts["showFilter"]; - } - else if ($this->opts["myShows"] === 1) { + } elseif ($this->opts["myShows"] === 1) { $include = $this->getUsersShows(); } - - + + $currentInstances = array(); foreach ($shows as $show) { - + if (empty($include) || in_array($show["show_id"], $include)) { $currentInstances[] = $show["instance_id"]; - + if (isset($show["last_scheduled"])) { - $dt = new DateTime($show["last_scheduled"], new DateTimeZone("UTC")); + $dt = new DateTime($show["last_scheduled"], + new DateTimeZone("UTC")); + } else { + $dt = new DateTime($show["created"], + new DateTimeZone("UTC")); } - else { - $dt = new DateTime($show["created"], new DateTimeZone("UTC")); - } - + //check if any of the shows have a more recent timestamp. - $showTimeStamp = intval($dt->format("U")); + $showTimeStamp = intval($dt->format("U")); if ($timestamp < $showTimeStamp) { - Logging::debug("timestamp is {$timestamp} show timestamp is {$showTimeStamp}"); - $outdated = true; - break; + $outdated = true; + break; } } } - //see if the displayed show instances have changed. (deleted, empty schedule etc) - if ($outdated === false && count($instances) !== count($currentInstances)) { + //see if the displayed show instances have changed. (deleted, + //empty schedule etc) + if ($outdated === false && count($instances) + !== count($currentInstances)) { Logging::debug("show instances have changed."); $outdated = true; } @@ -392,8 +409,8 @@ class Application_Model_ShowBuilder { return $outdated; } - public function GetItems() { - + public function getItems() + { $current_id = -1; $display_items = array(); @@ -401,19 +418,20 @@ class Application_Model_ShowBuilder { if ($this->opts["myShows"] === 1) { $shows = $this->getUsersShows(); - } - else if ($this->opts["showFilter"] !== 0) { + } elseif ($this->opts["showFilter"] !== 0) { $shows[] = $this->opts["showFilter"]; } - $scheduled_items = Application_Model_Schedule::GetScheduleDetailItems($this->startDT->format("Y-m-d H:i:s"), $this->endDT->format("Y-m-d H:i:s"), $shows); + $scheduled_items = Application_Model_Schedule::GetScheduleDetailItems( + $this->startDT, $this->endDT, $shows); for ($i = 0, $rows = count($scheduled_items); $i < $rows; $i++) { $item = $scheduled_items[$i]; - + //don't send back data for filler rows. - if (isset($item["playout_status"]) && $item["playout_status"] < 0) { + if (isset($item["playout_status"]) && + $item["playout_status"] < 0) { continue; } @@ -422,14 +440,16 @@ class Application_Model_ShowBuilder { //make a footer row. if ($current_id !== -1) { - //pass in the previous row as it's the last row for the previous show. - $display_items[] = $this->makeFooterRow($scheduled_items[$i-1]); + // pass in the previous row as it's the last row for + // the previous show. + $display_items[] = $this->makeFooterRow( + $scheduled_items[$i-1]); } - + $display_items[] = $this->makeHeaderRow($item); $current_id = $item["si_id"]; - + $this->pos = 1; } @@ -439,17 +459,21 @@ class Application_Model_ShowBuilder { if (isset($row)) { $display_items[] = $row; } - - if ($current_id !== -1 && !in_array($current_id, $this->showInstances)) { - $this->showInstances[] = $current_id; + + if ($current_id !== -1 && + !in_array($current_id, $this->showInstances)) { + $this->showInstances[] = $current_id; } } //make the last footer if there were any scheduled items. if (count($scheduled_items) > 0) { - $display_items[] = $this->makeFooterRow($scheduled_items[count($scheduled_items)-1]); + $display_items[] = $this->makeFooterRow($scheduled_items[ + count($scheduled_items)-1]); } - - return array("schedule" => $display_items, "showInstances" => $this->showInstances); + + return array( + "schedule" => $display_items, + "showInstances" => $this->showInstances); } } diff --git a/airtime_mvc/application/models/ShowInstance.php b/airtime_mvc/application/models/ShowInstance.php index 9e7c82327..533118c29 100644 --- a/airtime_mvc/application/models/ShowInstance.php +++ b/airtime_mvc/application/models/ShowInstance.php @@ -2,8 +2,8 @@ require_once 'formatters/LengthFormatter.php'; -class Application_Model_ShowInstance { - +class Application_Model_ShowInstance +{ private $_instanceId; private $_showInstance; @@ -12,7 +12,7 @@ class Application_Model_ShowInstance { $this->_instanceId = $instanceId; $this->_showInstance = CcShowInstancesQuery::create()->findPK($instanceId); - if (is_null($this->_showInstance)){ + if (is_null($this->_showInstance)) { throw new Exception(); } } @@ -22,27 +22,31 @@ class Application_Model_ShowInstance { return $this->_showInstance->getDbShowId(); } + /* TODO: A little inconsistent because other models have a getId() method + to get PK --RG */ public function getShowInstanceId() { return $this->_instanceId; } - public function getShow(){ + public function getShow() + { return new Application_Model_Show($this->getShowId()); } - - public function deleteRebroadcasts(){ - $con = Propel::getConnection(); + public function deleteRebroadcasts() + { $timestamp = gmdate("Y-m-d H:i:s"); $instance_id = $this->getShowInstanceId(); - - $sql = "DELETE FROM cc_show_instances" - ." WHERE starts > TIMESTAMP '$timestamp'" - ." AND instance_id = $instance_id" - ." AND rebroadcast = 1"; - - $con->exec($sql); + $sql = << :timestamp::TIMESTAMP +AND instance_id = :instanceId +AND rebroadcast = 1; +SQL; + Application_Common_Database::prepareAndExecute( $sql, array( + ':instanceId' => $instance_id, + ':timestamp' => $timestamp), 'execute'); } /* This function is weird. It should return a boolean, but instead returns @@ -62,12 +66,14 @@ class Application_Model_ShowInstance { public function getName() { $show = CcShowQuery::create()->findPK($this->getShowId()); + return $show->getDbName(); } public function getGenre() { $show = CcShowQuery::create()->findPK($this->getShowId()); + return $show->getDbGenre(); } @@ -93,6 +99,7 @@ class Application_Model_ShowInstance { { $showStart = $this->getShowInstanceStart(); $showStartExplode = explode(" ", $showStart); + return $showStartExplode[0]; } @@ -113,6 +120,7 @@ class Application_Model_ShowInstance { public function getSoundCloudFileId() { $file = Application_Model_StoredFile::Recall($this->_showInstance->getDbRecordedFile()); + return $file->getSoundCloudId(); } @@ -161,26 +169,33 @@ class Application_Model_ShowInstance { $con = Propel::getConnection(); $instance_id = $this->getShowInstanceId(); - $sql = "SELECT starts from cc_schedule" - ." WHERE instance_id = $instance_id" - ." ORDER BY starts" - ." LIMIT 1"; - - $scheduleStarts = $con->query($sql)->fetchColumn(0); + $sql = << $instance_id ), 'column' ); if ($scheduleStarts) { $scheduleStartsEpoch = strtotime($scheduleStarts); - $showStartsEpoch = strtotime($this->getShowInstanceStart()); + $showStartsEpoch = strtotime($this->getShowInstanceStart()); $diff = $showStartsEpoch - $scheduleStartsEpoch; - if ($diff != 0){ - $sql = "UPDATE cc_schedule" - ." SET starts = starts + INTERVAL '$diff' second," - ." ends = ends + INTERVAL '$diff' second" - ." WHERE instance_id = $instance_id"; - - $con->exec($sql); + if ($diff != 0) { + $sql = << $diff, + ':diff2' => $diff, + ':instanceId' => $instance_id ), 'execute'); } } Application_Model_RabbitMq::PushSchedule(); @@ -199,8 +214,8 @@ class Application_Model_ShowInstance { * @return $newDateTime * php DateTime, $dateTime with the added time deltas. */ - private static function addDeltas($dateTime, $deltaDay, $deltaMin) { - + public static function addDeltas($dateTime, $deltaDay, $deltaMin) + { $newDateTime = clone $dateTime; $days = abs($deltaDay); @@ -211,15 +226,13 @@ class Application_Model_ShowInstance { if ($deltaDay > 0) { $newDateTime->add($dayInterval); - } - else if ($deltaDay < 0){ + } elseif ($deltaDay < 0) { $newDateTime->sub($dayInterval); } if ($deltaMin > 0) { $newDateTime->add($minInterval); - } - else if ($deltaMin < 0) { + } elseif ($deltaMin < 0) { $newDateTime->sub($minInterval); } @@ -228,7 +241,7 @@ class Application_Model_ShowInstance { public function moveShow($deltaDay, $deltaMin) { - if ($this->getShow()->isRepeating()){ + if ($this->getShow()->isRepeating()) { return "Can't drag and drop repeating shows"; } @@ -257,6 +270,12 @@ class Application_Model_ShowInstance { return "Can't move show into past"; } + //check if show is overlapping + $overlapping = Application_Model_Schedule::checkOverlappingShows($newStartsDateTime, $newEndsDateTime, true, $this->getShowInstanceId()); + if ($overlapping) { + return "Cannot schedule overlapping shows"; + } + if ($this->isRecorded()) { //rebroadcasts should start at max 1 hour after a recorded show has ended. @@ -280,6 +299,7 @@ class Application_Model_ShowInstance { //recorded show doesn't exist. catch (Exception $e) { $this->_showInstance->delete(); + return "Show was deleted because recorded show does not exist!"; } @@ -296,7 +316,7 @@ class Application_Model_ShowInstance { $this->correctScheduleStartTimes(); $show = new Application_Model_Show($this->getShowId()); - if(!$show->isRepeating() && is_null($this->isRebroadcast())){ + if (!$show->isRepeating() && is_null($this->isRebroadcast())) { $show->setShowFirstShow($newStartsDateTime); $show->setShowLastShow($newEndsDateTime); } @@ -304,33 +324,32 @@ class Application_Model_ShowInstance { Application_Model_RabbitMq::PushSchedule(); } - /* - * FUNCTION SHOULD NOT BE CALLED - * - we are removing ability to resize just a single show instance - * -please use the resize method on the Show.php class. - */ public function resizeShow($deltaDay, $deltaMin) { - $con = Propel::getConnection(); + $con = Propel::getConnection(); - $hours = $deltaMin/60; - if($hours > 0) - $hours = floor($hours); - else - $hours = ceil($hours); + $hours = $deltaMin / 60; - $mins = abs($deltaMin%60); + $hours = ($hours > 0) ? floor($hours) : ceil($hours); + + $mins = abs($deltaMin % 60); $today_timestamp = gmdate("Y-m-d H:i:s"); - $starts = $this->getShowInstanceStart(); - $ends = $this->getShowInstanceEnd(); + $starts = $this->getShowInstanceStart(); + $ends = $this->getShowInstanceEnd(); - if(strtotime($today_timestamp) > strtotime($starts)) { + if (strtotime($today_timestamp) > strtotime($starts)) { return "can't resize a past show"; } - $sql = "SELECT timestamp '{$ends}' + interval '{$deltaDay} days' + interval '{$hours}:{$mins}'"; - $new_ends = $con->query($sql)->fetchColumn(0); + //$sql = "SELECT timestamp '{$ends}' + interval '{$deltaDay} days' + interval '{$hours}:{$mins}'"; + $sql = "SELECT timestamp :ends + interval :deltaDays + interval :deltaTime"; + + $now_ends = Application_Common_Database::prepareAndExecute($sql, + array(':ends' => $ends, + ':deltaDays' => "$deltaDay days", + ':deltaTime' => "{$hours}:{$mins}"), 'column' + ); //only need to check overlap if show increased in size. if (strtotime($new_ends) > strtotime($ends)) { @@ -340,17 +359,26 @@ class Application_Model_ShowInstance { $overlap = Application_Model_Show::getShows($utcStartDateTime, $utcEndDateTime); - if(count($overlap) > 0) { + if (count($overlap) > 0) { + // TODO : fix ghetto error handling -- RG return "Should not overlap shows"; } } //with overbooking no longer need to check already scheduled content still fits. //must update length of all rebroadcast instances. - if($this->isRecorded()) { - $sql = "UPDATE cc_show_instances SET ends = (ends + interval '{$deltaDay} days' + interval '{$hours}:{$mins}') - WHERE rebroadcast = 1 AND instance_id = {$this->_instanceId}"; - $con->exec($sql); + if ($this->isRecorded()) { + $sql = << "$deltaDay days", + ':interval' => "$hours:$mins", + ':instanceId' => $this->_instanceId ), 'execute'); + } $this->setShowEnd($new_ends); @@ -370,7 +398,7 @@ class Application_Model_ShowInstance { $scheduler = new Application_Model_Scheduler(); $scheduler->scheduleAfter( - array(array("id" => 0, "instance" => $id, "timestamp" => $ts)), + array(array("id" => 0, "instance" => $id, "timestamp" => $ts)), array(array("id" => $pl_id, "type" => "playlist")) ); } @@ -447,7 +475,7 @@ class Application_Model_ShowInstance { ->filterByDbRebroadcast(0) ->find(); - if (is_null($showInstances)){ + if (is_null($showInstances)) { return true; } //only 1 show instance left of the show, make it non repeating. @@ -490,7 +518,7 @@ class Application_Model_ShowInstance { return false; } - public function delete() + public function delete($rabbitmqPush = true) { // see if it was recording show $recording = $this->isRecorded(); @@ -526,23 +554,23 @@ class Application_Model_ShowInstance { ->delete(); - if ($this->checkToDeleteShow($showId)){ + if ($this->checkToDeleteShow($showId)) { CcShowQuery::create() ->filterByDbId($showId) ->delete(); } - } - else { + } else { if ($this->isRebroadcast()) { $this->_showInstance->delete(); - } - else { + } else { $show->delete(); } } } - Application_Model_RabbitMq::PushSchedule(); + if ($rabbitmqPush) { + Application_Model_RabbitMq::PushSchedule(); + } } public function setRecordedFile($file_id) @@ -561,11 +589,8 @@ class Application_Model_ShowInstance { try { $rebroad = new Application_Model_ShowInstance($rebroadcast->getDbId()); $rebroad->addFileToShow($file_id, false); - } - catch (Exception $e) { - Logging::log("{$e->getFile()}"); - Logging::log("{$e->getLine()}"); - Logging::log("{$e->getMessage()}"); + } catch (Exception $e) { + Logging::info($e->getMessage()); } } } @@ -573,21 +598,20 @@ class Application_Model_ShowInstance { public function getTimeScheduled() { $time = $this->_showInstance->getDbTimeFilled(); - + if ($time != "00:00:00" && !empty($time)) { $time_arr = explode(".", $time); if (count($time_arr) > 1) { $time_arr[1] = "." . $time_arr[1]; $milliseconds = number_format(round($time_arr[1], 2), 2); $time = $time_arr[0] . substr($milliseconds, 1); - } - else { + } else { $time = $time_arr[0] . ".00"; } } else { $time = "00:00:00.00"; } - + return $time; } @@ -595,13 +619,15 @@ class Application_Model_ShowInstance { public function getTimeScheduledSecs() { $time_filled = $this->getTimeScheduled(); - return Application_Model_Playlist::playlistTimeToSeconds($time_filled); + + return Application_Common_DateHelper::playlistTimeToSeconds($time_filled); } public function getDurationSecs() { $ends = $this->getShowInstanceEnd(null); $starts = $this->getShowInstanceStart(null); + return intval($ends->format('U')) - intval($starts->format('U')); } @@ -631,22 +657,107 @@ class Application_Model_ShowInstance { } else { $returnStr = $hours . ":" . $interval->format("%I:%S") . ".00"; } - + return $returnStr; } + + + public static function getContentCount($p_start, $p_end) + { + $sql = << :p_start::TIMESTAMP + AND starts < :p_end::TIMESTAMP +GROUP BY instance_id +SQL; + + $counts = Application_Common_Database::prepareAndExecute($sql, array( + ':p_start' => $p_start->format("Y-m-d G:i:s"), + ':p_end' => $p_end->format("Y-m-d G:i:s")) + , 'all'); + + $real_counts = array(); + foreach ($counts as $c) { + $real_counts[$c['instance_id']] = $c['instance_count']; + } + return $real_counts; + + } + + public function showEmpty() + { + $sql = <<= 0 + AND ((s.stream_id IS NOT NULL) + OR (s.file_id IS NOT NULL)) LIMIT 1 +SQL; + # TODO : use prepareAndExecute properly + $res = Application_Common_Database::prepareAndExecute($sql, + array( ':instance_id' => $this->_instanceId ), 'all' ); + # TODO : A bit retarded. fix this later + foreach ($res as $r) { + return false; + } + return true; + + } + public function getShowListContent() { - $con = Propel::getConnection(); + $con = Propel::getConnection(); - $sql = "SELECT * - FROM (cc_schedule AS s LEFT JOIN cc_files AS f ON f.id = s.file_id) - WHERE s.instance_id = '{$this->_instanceId}' AND s.playout_status >= 0 - ORDER BY starts"; + $sql = <<= 0 + AND s.file_id IS NOT NULL) + UNION + (SELECT s.starts, + 1::INTEGER as type, + ws.id AS item_id, + (ws.name || ': ' || ws.url) AS title, + null AS album, + null AS genre, + ws.length AS length, + sub.login AS creator, + 't'::boolean AS EXISTS, + ws.url AS filepath, + ws.mime as mime + FROM cc_schedule AS s + LEFT JOIN cc_webstream AS ws ON ws.id = s.stream_id + LEFT JOIN cc_subjs AS sub ON ws.creator_id = sub.id + WHERE s.instance_id = :instance_id2 + AND s.playout_status >= 0 + AND s.stream_id IS NOT NULL)) AS temp +ORDER BY starts; +SQL; - //Logging::log($sql); - - $results = $con->query($sql)->fetchAll(); + $stmt = $con->prepare($sql); + $stmt->execute(array( + ':instance_id1' => $this->_instanceId, + ':instance_id2' => $this->_instanceId + )); + $results = $stmt->fetchAll(PDO::FETCH_ASSOC); foreach ($results as &$row) { @@ -654,8 +765,10 @@ class Application_Model_ShowInstance { $dt->setTimezone(new DateTimeZone(date_default_timezone_get())); $row["starts"] = $dt->format("Y-m-d H:i:s"); - $formatter = new LengthFormatter($row["clip_length"]); - $row["clip_length"] = $formatter->format(); + if (isset($row['length'])) { + $formatter = new LengthFormatter($row["length"]); + $row["length"] = $formatter->format(); + } } @@ -664,126 +777,120 @@ class Application_Model_ShowInstance { public function getLastAudioItemEnd() { - $con = Propel::getConnection(); + $con = Propel::getConnection(); - $sql = "SELECT ends FROM cc_schedule " - ."WHERE instance_id = {$this->_instanceId} " - ."ORDER BY ends DESC " - ."LIMIT 1"; + $sql = "SELECT ends FROM cc_schedule " + ."WHERE instance_id = :instanceId" + ."ORDER BY ends DESC " + ."LIMIT 1"; - $query = $con->query($sql)->fetchColumn(0); - return ($query !== false) ? $query : NULL; - } + $query = Application_Common_Database::prepareAndExecute( $sql, + array(':instanceId' => $this->_instanceId), 'column'); - public function getShowEndGapTime(){ - $showEnd = $this->getShowInstanceEnd(); - $lastItemEnd = $this->getLastAudioItemEnd(); + return ($query !== false) ? $query : null; + } - if (is_null($lastItemEnd)){ - $lastItemEnd = $this->getShowInstanceStart(); - } + public function getShowEndGapTime() + { + $showEnd = $this->getShowInstanceEnd(); + $lastItemEnd = $this->getLastAudioItemEnd(); - - $diff = strtotime($showEnd) - strtotime($lastItemEnd); - - return ($diff < 0) ? 0 : $diff; - } - - public static function GetLastShowInstance($p_timeNow){ - global $CC_CONFIG; - $con = Propel::getConnection(); - - $sql = "SELECT si.id" - ." FROM $CC_CONFIG[showInstances] si" - ." WHERE si.ends < TIMESTAMP '$p_timeNow'" - ." AND si.modified_instance = 'f'" - ." ORDER BY si.ends DESC" - ." LIMIT 1"; - - $id = $con->query($sql)->fetchColumn(0); - if ($id) { - return new Application_Model_ShowInstance($id); - } else { - return null; + if (is_null($lastItemEnd)) { + $lastItemEnd = $this->getShowInstanceStart(); } + + + $diff = strtotime($showEnd) - strtotime($lastItemEnd); + + return ($diff < 0) ? 0 : $diff; + } + + public static function GetLastShowInstance($p_timeNow) + { + $sql = << $p_timeNow ), 'column' ); + + return ($id ? new Application_Model_ShowInstance($id) : null ); } public static function GetCurrentShowInstance($p_timeNow) { - global $CC_CONFIG; - $con = Propel::getConnection(); - /* Orderby si.starts descending, because in some cases * we can have multiple shows overlapping each other. In * this case, the show that started later is the one that * is actually playing, and so this is the one we want. */ - $sql = "SELECT si.id" - ." FROM $CC_CONFIG[showInstances] si" - ." WHERE si.starts <= TIMESTAMP '$p_timeNow'" - ." AND si.ends > TIMESTAMP '$p_timeNow'" - ." AND si.modified_instance = 'f'" - ." ORDER BY si.starts DESC" - ." LIMIT 1"; + $sql = << :timeNow2::TIMESTAMP + AND si.modified_instance = 'f' +ORDER BY si.starts DESC LIMIT 1 +SQL; - $id = $con->query($sql)->fetchColumn(0); - if ($id) { - return new Application_Model_ShowInstance($id); - } else { - return null; - } + $id = Application_Common_Database( $sql, array( + ':timeNow1' => $p_timeNow, + ':timeNow2' => $p_timeNow ), 'column'); + + return ( $id ? new Application_Model_ShowInstance($id) : null ); } public static function GetNextShowInstance($p_timeNow) { - global $CC_CONFIG; - $con = Propel::getConnection(); - - $sql = "SELECT si.id" - ." FROM $CC_CONFIG[showInstances] si" - ." WHERE si.starts > TIMESTAMP '$p_timeNow'" - ." AND si.modified_instance = 'f'" - ." ORDER BY si.starts" - ." LIMIT 1"; - - $id = $con->query($sql)->fetchColumn(0); - if ($id) { - return new Application_Model_ShowInstance($id); - } else { - return null; - } + $sql = << :timeNow::TIMESTAMP +AND si.modified_instance = 'f' +ORDER BY si.starts +LIMIT 1 +SQL; + $id = Application_Common_Database::prepareAndExecute( $sql, + array( 'timeNow' => $p_timeNow ), 'column' ); + return ( $id ? new Application_Model_ShowInstance($id) : null ); } // returns number of show instances that ends later than $day public static function GetShowInstanceCount($day) { - global $CC_CONFIG; - $con = Propel::getConnection(); - $sql = "SELECT count(*) as cnt FROM $CC_CONFIG[showInstances] WHERE ends < '$day'"; - return $con->query($sql)->fetchColumn(0); + $sql = << $day ), 'column' ); } // this returns end timestamp of all shows that are in the range and has live DJ set up public static function GetEndTimeOfNextShowWithLiveDJ($p_startTime, $p_endTime) { - global $CC_CONFIG; - $con = Propel::getConnection(); - - $sql = "SELECT ends - FROM cc_show_instances as si - JOIN cc_show as sh ON si.show_id = sh.id - WHERE si.ends > '$p_startTime' and si.ends < '$p_endTime' and (sh.live_stream_using_airtime_auth or live_stream_using_custom_auth) - ORDER BY si.ends"; - - return $con->query($sql)->fetchAll(); + $sql = << :startTime::TIMESTAMP + AND si.ends < :endTime::TIMESTAMP + AND (sh.live_stream_using_airtime_auth + OR live_stream_using_custom_auth) +ORDER BY si.ends +SQL; + return Application_Common_Database::prepareAndExecute( $sql, array( + ':startTime' => $p_startTime, + ':endTime' => $p_endTime), 'all'); } - - function isRepeating(){ - if ($this->getShow()->isRepeating()){ - return true; - }else{ - return false; - } + + public function isRepeating() + { + return $this->getShow()->isRepeating(); } } diff --git a/airtime_mvc/application/models/Soundcloud.php b/airtime_mvc/application/models/Soundcloud.php index d8286988f..2b1068e57 100644 --- a/airtime_mvc/application/models/Soundcloud.php +++ b/airtime_mvc/application/models/Soundcloud.php @@ -1,15 +1,16 @@ _soundcloud = new Services_Soundcloud($CC_CONFIG['soundcloud-client-id'], $CC_CONFIG['soundcloud-client-secret']); + $this->_soundcloud = new Services_Soundcloud( + $CC_CONFIG['soundcloud-client-id'], + $CC_CONFIG['soundcloud-client-secret']); } private function getToken() @@ -22,46 +23,43 @@ class Application_Model_Soundcloud { return $token; } - public function uploadTrack($filepath, $filename, $description, $tags=array(), $release=null, $genre=null) + public function uploadTrack($filepath, $filename, $description, + $tags=array(), $release=null, $genre=null) { - if($this->getToken()) - { - if(count($tags)) { + if ($this->getToken()) { + if (count($tags)) { $tags = join(" ", $tags); $tags = $tags." ".Application_Model_Preference::GetSoundCloudTags(); - } - else { + } else { $tags = Application_Model_Preference::GetSoundCloudTags(); } - $downloadable = Application_Model_Preference::GetSoundCloudDownloadbleOption() == '1'?true:false; - + $downloadable = Application_Model_Preference::GetSoundCloudDownloadbleOption() == '1'; + $track_data = array( - 'track[sharing]' => 'private', - 'track[title]' => $filename, - 'track[asset_data]' => '@' . $filepath, - 'track[tag_list]' => $tags, - 'track[description]' => $description, + 'track[sharing]' => 'private', + 'track[title]' => $filename, + 'track[asset_data]' => '@' . $filepath, + 'track[tag_list]' => $tags, + 'track[description]' => $description, 'track[downloadable]' => $downloadable, ); - if(isset($release)) { + if (isset($release)) { $release = str_replace(" ", "-", $release); $release = str_replace(":", "-", $release); //YYYY-MM-DD-HH-mm-SS $release = explode("-", $release); - - $track_data['track[release_year]'] = $release[0]; + $track_data['track[release_year]'] = $release[0]; $track_data['track[release_month]'] = $release[1]; - $track_data['track[release_day]'] = $release[2]; + $track_data['track[release_day]'] = $release[2]; } if (isset($genre) && $genre != "") { $track_data['track[genre]'] = $genre; - } - else { + } else { $default_genre = Application_Model_Preference::GetSoundCloudGenre(); if ($default_genre != "") { $track_data['track[genre]'] = $default_genre; @@ -77,14 +75,24 @@ class Application_Model_Soundcloud { if ($license != "") { $track_data['track[license]'] = $license; } - + $response = json_decode( $this->_soundcloud->post('tracks', $track_data), true ); return $response; + } else { + throw new NoSoundCloundToken(); } } + public static function uploadSoundcloud($id) + { + $cmd = "/usr/lib/airtime/utils/soundcloud-uploader $id > /dev/null &"; + Logging::info("Uploading soundcloud with command: $cmd"); + exec($cmd); + } } + +class NoSoundCloundToken extends Exception {} diff --git a/airtime_mvc/application/models/StoredFile.php b/airtime_mvc/application/models/StoredFile.php index b7b0eadd4..2300f4eb7 100644 --- a/airtime_mvc/application/models/StoredFile.php +++ b/airtime_mvc/application/models/StoredFile.php @@ -13,8 +13,8 @@ require_once 'formatters/BitrateFormatter.php'; * @license http://www.gnu.org/licenses/gpl.txt * @see MetaData */ -class Application_Model_StoredFile { - +class Application_Model_StoredFile +{ /** * @holds propel database object */ @@ -24,52 +24,45 @@ class Application_Model_StoredFile { * array of db metadata -> propel */ private $_dbMD = array ( - "track_title" => "DbTrackTitle", - "artist_name" => "DbArtistName", - "album_title" => "DbAlbumTitle", - "genre" => "DbGenre", - "mood" => "DbMood", + "track_title" => "DbTrackTitle", + "artist_name" => "DbArtistName", + "album_title" => "DbAlbumTitle", + "genre" => "DbGenre", + "mood" => "DbMood", "track_number" => "DbTrackNumber", - "bpm" => "DbBpm", - "label" => "DbLabel", - "composer" => "DbComposer", - "encoded_by" => "DbEncodedBy", - "conductor" => "DbConductor", - "year" => "DbYear", - "info_url" => "DbInfoUrl", - "isrc_number" => "DbIsrcNumber", - "copyright" => "DbCopyright", - "length" => "DbLength", - "bit_rate" => "DbBitRate", - "sample_rate" => "DbSampleRate", - "mime" => "DbMime", - "md5" => "DbMd5", - "ftype" => "DbFtype", - "language" => "DbLanguage", - //"filepath" => "DbFilepath", - "directory" => "DbDirectory" + "bpm" => "DbBpm", + "label" => "DbLabel", + "composer" => "DbComposer", + "encoded_by" => "DbEncodedBy", + "conductor" => "DbConductor", + "year" => "DbYear", + "info_url" => "DbInfoUrl", + "isrc_number" => "DbIsrcNumber", + "copyright" => "DbCopyright", + "length" => "DbLength", + "bit_rate" => "DbBitRate", + "sample_rate" => "DbSampleRate", + "mime" => "DbMime", + //"md5" => "DbMd5", + "ftype" => "DbFtype", + "language" => "DbLanguage", + "replay_gain" => "DbReplayGain", + "directory" => "DbDirectory", + "owner_id" => "DbOwnerId" ); - public function __construct() - { - - } - public function getId() { return $this->_file->getDbId(); } - public function getGunId() { - return $this->_file->getDbGunid(); - } - public function getFormat() { return $this->_file->getDbFtype(); } - public function getPropelOrm(){ + public function getPropelOrm() + { return $this->_file; } @@ -78,6 +71,25 @@ class Application_Model_StoredFile { $this->_file->setDbFtype($p_format); } + /* This function is only called after liquidsoap + * has notified that a track has started playing. + */ + public function setLastPlayedTime($p_now) + { + $this->_file->setDbLPtime($p_now); + /* Normally we would only call save after all columns have been set + * like in setDbColMetadata(). But since we are only setting one + * column in this case it is OK. + */ + $this->_file->save(); + } + + public static function createWithFile($f) { + $storedFile = new Application_Model_StoredFile(); + $storedFile->_file = $f; + return $storedFile; + } + /** * Set multiple metadata values using defined metadata constants. * @@ -88,40 +100,43 @@ class Application_Model_StoredFile { { if (is_null($p_md)) { $this->setDbColMetadata(); - } - else { + } else { $dbMd = array(); - - if (isset($p_md["MDATA_KEY_YEAR"])){ - // We need to make sure to clean this value before inserting into database. - // If value is outside of range [-2^31, 2^31-1] then postgresl will throw error - // when trying to retrieve this value. We could make sure number is within these bounds, - // but simplest is to do substring to 4 digits (both values are garbage, but at least our - // new garbage value won't cause errors). If the value is 2012-01-01, then substring to - // 4 digits is an OK result. - // CC-3771 - + + if (isset($p_md["MDATA_KEY_YEAR"])) { + // We need to make sure to clean this value before + // inserting into database. If value is outside of range + // [-2^31, 2^31-1] then postgresl will throw error when + // trying to retrieve this value. We could make sure + // number is within these bounds, but simplest is to do + // substring to 4 digits (both values are garbage, but + // at least our new garbage value won't cause errors). + // If the value is 2012-01-01, then substring to first 4 + // digits is an OK result. CC-3771 + $year = $p_md["MDATA_KEY_YEAR"]; - - if (strlen($year) > 4){ + + if (strlen($year) > 4) { $year = substr($year, 0, 4); } - if (!is_numeric($year)){ + if (!is_numeric($year)) { $year = 0; } $p_md["MDATA_KEY_YEAR"] = $year; } - + + # Translate metadata attributes from media monitor (MDATA_KEY_*) + # to their counterparts in constants.php (usually the column names) foreach ($p_md as $mdConst => $mdValue) { - if (defined($mdConst)){ + if (defined($mdConst)) { $dbMd[constant($mdConst)] = $mdValue; + } else { + Logging::warn("using metadata that is not defined. + [$mdConst] => [$mdValue]"); } } $this->setDbColMetadata($dbMd); } - - $this->_file->setDbMtime(new DateTime("now"), new DateTimeZone("UTC")); - $this->_file->save(); } /** @@ -137,22 +152,60 @@ class Application_Model_StoredFile { $method = "set$propelColumn"; $this->_file->$method(null); } - } - else { + } else { + $owner = $this->_file->getFkOwner(); + // if owner_id is already set we don't want to set it again. + if (!$owner) { // no owner detected, we try to assign one. + // if MDATA_OWNER_ID is not set then we default to the + // first admin user we find + if (!array_key_exists('owner_id', $p_md)) { + //$admins = Application_Model_User::getUsers(array('A')); + $admins = Application_Model_User::getUsersOfType('A'); + if (count($admins) > 0) { // found admin => pick first one + $owner = $admins[0]; + } + } + // get the user by id and set it like that + else { + $user = CcSubjsQuery::create() + ->findPk($p_md['owner_id']); + if ($user) { + $owner = $user; + } + } + if ($owner) { + $this->_file->setDbOwnerId( $owner->getDbId() ); + } else { + Logging::info("Could not find suitable owner for file + '".$p_md['MDATA_KEY_FILEPATH']."'"); + } + } + # We don't want to process owner_id in bulk because we already + # processed it in the code above. This is done because owner_id + # needs special handling + if (array_key_exists('owner_id', $p_md)) { + unset($p_md['owner_id']); + } foreach ($p_md as $dbColumn => $mdValue) { - //don't blank out name, defaults to original filename on first insertion to database. - if($dbColumn == "track_title" && (is_null($mdValue) || $mdValue == "")) { + // don't blank out name, defaults to original filename on first + // insertion to database. + if ($dbColumn == "track_title" && (is_null($mdValue) || $mdValue == "")) { continue; } + # TODO : refactor string evals if (isset($this->_dbMD[$dbColumn])) { $propelColumn = $this->_dbMD[$dbColumn]; - $method = "set$propelColumn"; + $method = "set$propelColumn"; + + /* We need to set track_number to null if it is an empty string + * because propel defaults empty strings to zeros */ + if ($dbColumn == "track_number" && empty($mdValue)) $mdValue = null; $this->_file->$method($mdValue); } } } - $this->_file->setDbMtime(new DateTime("now"), new DateTimeZone("UTC")); + $this->_file->setDbMtime(new DateTime("now", new DateTimeZone("UTC"))); $this->_file->save(); } @@ -160,9 +213,9 @@ class Application_Model_StoredFile { * Set metadata element value * * @param string $category - * Metadata element by metadata constant + * Metadata element by metadata constant * @param string $value - * value to store, if NULL then delete record + * value to store, if NULL then delete record */ public function setMetadataValue($p_category, $p_value) { @@ -175,17 +228,18 @@ class Application_Model_StoredFile { * Set metadata element value * * @param string $category - * Metadata element by db column + * Metadata element by db column * @param string $value - * value to store, if NULL then delete record + * value to store, if NULL then delete record */ public function setDbColMetadataValue($p_category, $p_value) { //don't blank out name, defaults to original filename on first insertion to database. - if($p_category == "track_title" && (is_null($p_value) || $p_value == "")) { + if ($p_category == "track_title" && (is_null($p_value) || $p_value == "")) { return; } if (isset($this->_dbMD[$p_category])) { + // TODO : fix this crust -- RG $propelColumn = $this->_dbMD[$p_category]; $method = "set$propelColumn"; $this->_file->$method($p_value); @@ -193,32 +247,6 @@ class Application_Model_StoredFile { } } - /** - * Get one metadata value. - * - * @param string $p_category (MDATA_KEY_URL) - * @return string - */ - public function getMetadataValue($p_category) - { - // constant() was used because it gets quoted constant name value from - // api_client.py. This is the wrapper funtion - return $this->getDbColMetadataValue(constant($p_category)); - } - - /** - * Get one metadata value. - * - * @param string $p_category (url) - * @return string - */ - public function getDbColMetadataValue($p_category) - { - $propelColumn = $this->_dbMD[$p_category]; - $method = "get$propelColumn"; - return $this->_file->$method(); - } - /** * Get metadata as array, indexed by the column names in the database. * @@ -244,12 +272,12 @@ class Application_Model_StoredFile { { $c = get_defined_constants(true); $md = array(); - - /* Create a copy of dbMD here and create a "filepath" key inside of + + /* Create a copy of dbMD here and create a "filepath" key inside of * it. The reason we do this here, instead of creating this key inside - * dbMD is because "filepath" isn't really metadata, and we don't want + * dbMD is because "filepath" isn't really metadata, and we don't want * filepath updated everytime the metadata changes. Also it needs extra - * processing before we can write it to the database (needs to be split + * processing before we can write it to the database (needs to be split * into base and relative path) * */ $dbmd_copy = $this->_dbMD; @@ -258,8 +286,8 @@ class Application_Model_StoredFile { foreach ($c['user'] as $constant => $value) { if (preg_match('/^MDATA_KEY/', $constant)) { if (isset($dbmd_copy[$value])) { - $propelColumn = $dbmd_copy[$value]; - $method = "get$propelColumn"; + $propelColumn = $dbmd_copy[$value]; + $method = "get$propelColumn"; $md[$constant] = $this->_file->$method(); } } @@ -268,48 +296,37 @@ class Application_Model_StoredFile { return $md; } - /** - * Set state of virtual file - * - * @param string $p_state - * 'empty'|'incomplete'|'ready'|'edited' - * @param int $p_editedby - * user id | 'NULL' for clear editedBy field - * @return TRUE - */ - public function setState($p_state, $p_editedby=NULL) - { - global $CC_CONFIG; - $con = Propel::getConnection(); - $escapedState = pg_escape_string($p_state); - $eb = (!is_null($p_editedby) ? ", editedBy=$p_editedby" : ''); - $sql = "UPDATE ".$CC_CONFIG['filesTable'] - ." SET state='$escapedState'$eb, mtime=now()" - ." WHERE gunid='{$this->gunid}'"; - $res = $con->exec($sql); - $this->state = $p_state; - $this->editedby = $p_editedby; - return TRUE; - } - /** * Returns an array of playlist objects that this file is a part of. * @return array */ - public function getPlaylists() { - global $CC_CONFIG; + public function getPlaylists() + { $con = Propel::getConnection(); - $sql = "SELECT playlist_id " - ." FROM ".$CC_CONFIG['playistTable'] - ." WHERE file_id='{$this->id}'"; - $ids = $con->query($sql)->fetchAll(); - $playlists = array(); - if (is_array($ids) && count($ids) > 0) { - foreach ($ids as $id) { - $playlists[] = Application_Model_Playlist::Recall($id); - } + + $sql = <<prepare($sql); + $stmt->bindParam(':file_id', $this->id, PDO::PARAM_INT); + + if ($stmt->execute()) { + $ids = $stmt->fetchAll(); + } else { + $msg = implode(',', $stmt->errorInfo()); + throw new Exception("Error: $msg"); + } + + if (is_array($ids) && count($ids) > 0) { + return array_map( function ($id) { + return Application_Model_Playlist::Recall($id); + }, $ids); + } else { + return array(); } - return $playlists; } /** @@ -329,20 +346,20 @@ class Application_Model_StoredFile { $music_dir = Application_Model_MusicDir::getDirByPK($this->_file->getDbDirectory()); $type = $music_dir->getType(); - + if (file_exists($filepath) && $type == "stor") { $data = array("filepath" => $filepath, "delete" => 1); Application_Model_RabbitMq::SendMessageToMediaMonitor("file_delete", $data); } - if ($deleteFromPlaylist){ + if ($deleteFromPlaylist) { Application_Model_Playlist::DeleteFileFromAllPlaylists($this->getId()); } // set file_exists falg to false $this->_file->setDbFileExists(false); $this->_file->save(); } - + /** * This function is for when media monitor detects deletion of file * and trying to update airtime side @@ -354,29 +371,53 @@ class Application_Model_StoredFile { { $filepath = $this->getFilePath(); - if ($deleteFromPlaylist){ + if ($deleteFromPlaylist) { Application_Model_Playlist::DeleteFileFromAllPlaylists($this->getId()); } - // set file_exists falg to false + // set file_exists flag to false $this->_file->setDbFileExists(false); $this->_file->save(); } + + public function getRealFileExtension() { + $path = $this->_file->getDbFilepath(); + $path_elements = explode('.', $path); + if (count($path_elements) < 2) { + return ""; + } else { + return $path_elements[count($path_elements) - 1]; + } + } + /** * Return suitable extension. * * @return string - * file extension without a dot + * file extension without a dot */ public function getFileExtension() { + $possible_ext = $this->getRealFileExtension(); + if ($possible_ext !== "") { + return $possible_ext; + } + + // We fallback to guessing the extension from the mimetype if we + // cannot extract it from the file name + $mime = $this->_file->getDbMime(); - if ($mime == "audio/vorbis" || $mime == "application/ogg") { + if ($mime == "audio/ogg" || $mime == "application/ogg") { return "ogg"; - } - else if ($mime == "audio/mp3" || $mime == "audio/mpeg") { + } elseif ($mime == "audio/mp3" || $mime == "audio/mpeg") { return "mp3"; + } elseif ($mime == "audio/x-flac") { + return "flac"; + } elseif ($mime == "audio/mp4") { + return "mp4"; + } else { + throw new Exception("Unknown $mime"); } } @@ -387,14 +428,14 @@ class Application_Model_StoredFile { */ public function getFilePath() { - $music_dir = Application_Model_MusicDir::getDirByPK($this->_file->getDbDirectory()); + $music_dir = Application_Model_MusicDir::getDirByPK($this-> + _file->getDbDirectory()); $directory = $music_dir->getDirectory(); + $filepath = $this->_file->getDbFilepath(); - $filepath = $this->_file->getDbFilepath(); - - return $directory.$filepath; + return Application_Common_OsPath::join($directory, $filepath); } - + /** * Set real filename of raw media data * @@ -431,16 +472,17 @@ class Application_Model_StoredFile { * is specified in the airtime.conf config file. If either of these is * not specified, then use values provided by the $_SERVER global variable. */ - public function getFileUrlUsingConfigAddress(){ + public function getFileUrlUsingConfigAddress() + { global $CC_CONFIG; - if (isset($CC_CONFIG['baseUrl'])){ + if (isset($CC_CONFIG['baseUrl'])) { $serverName = $CC_CONFIG['baseUrl']; } else { $serverName = $_SERVER['SERVER_NAME']; } - if (isset($CC_CONFIG['basePort'])){ + if (isset($CC_CONFIG['basePort'])) { $serverPort = $CC_CONFIG['basePort']; } else { $serverPort = $_SERVER['SERVER_PORT']; @@ -449,9 +491,9 @@ class Application_Model_StoredFile { return $this->constructGetFileUrl($serverName, $serverPort); } - private function constructGetFileUrl($p_serverName, $p_serverPort){ -Logging::log("getting media! - 2"); - return "http://$p_serverName:$p_serverPort/api/get-media/file/".$this->getGunId().".".$this->getFileExtension(); + private function constructGetFileUrl($p_serverName, $p_serverPort) + { + return "http://$p_serverName:$p_serverPort/api/get-media/file/".$this->getId().".".$this->getFileExtension(); } /** @@ -460,147 +502,86 @@ Logging::log("getting media! - 2"); */ public function getRelativeFileUrl($baseUrl) { - Logging::log("getting media!"); - return $baseUrl."/api/get-media/file/".$this->getGunId().".".$this->getFileExtension(); + return $baseUrl."/api/get-media/file/".$this->getId().".".$this->getFileExtension(); } - public static function Insert($md=null) + public static function Insert($md) { + // save some work by checking if filepath is given right away + if ( !isset($md['MDATA_KEY_FILEPATH']) ) { + return null; + } + $file = new CcFiles(); - $file->setDbGunid(md5(uniqid("", true))); - $file->setDbUtime(new DateTime("now"), new DateTimeZone("UTC")); - $file->setDbMtime(new DateTime("now"), new DateTimeZone("UTC")); + $now = new DateTime("now", new DateTimeZone("UTC")); + $file->setDbUtime($now); + $file->setDbMtime($now); $storedFile = new Application_Model_StoredFile(); $storedFile->_file = $file; - if(isset($md['MDATA_KEY_FILEPATH'])) { - // removed "//" in the path. Always use '/' for path separator - $filepath = str_replace("//", "/", $md['MDATA_KEY_FILEPATH']); - $res = $storedFile->setFilePath($filepath); - if ($res === -1) { - return null; - } - } - else { + // removed "//" in the path. Always use '/' for path separator + // TODO : it might be better to just call OsPath::normpath on the file + // path. Also note that mediamonitor normalizes the paths anyway + // before passing them to php so it's not necessary to do this at all + + $filepath = str_replace("//", "/", $md['MDATA_KEY_FILEPATH']); + $res = $storedFile->setFilePath($filepath); + if ($res === -1) { return null; } + $storedFile->setMetadata($md); - if(isset($md)) { - $storedFile->setMetadata($md); - } - - return $storedFile; + return $storedFile; } - /** - * Fetch instance of StoreFile object.
- * Should be supplied with only ONE parameter, all the rest should - * be NULL. - * - * @param int $p_id - * local id - * @param string $p_gunid - * global unique id of file - * @param string $p_md5sum - * MD5 sum of the file - * @param boolean $exist - * When this is true, it check against only files with file_exist is 'true' - * @return Application_Model_StoredFile|NULL - * Return NULL if the object doesnt exist in the DB. - */ - public static function Recall($p_id=null, $p_gunid=null, $p_md5sum=null, $p_filepath=null, $exist=false) + public static function Recall($p_id=null, $p_gunid=null, $p_md5sum=null, + $p_filepath=null) { + if( isset($p_id ) ) { + $f = CcFilesQuery::create()->findPK(intval($p_id)); + return is_null($f) ? null : self::createWithFile($f); + } elseif ( isset($p_gunid) ) { + throw new Exception("You should never use gunid ($gunid) anymore"); + } elseif ( isset($p_md5sum) ) { + throw new Exception("Searching by md5($p_md5sum) is disabled"); + } elseif ( isset($p_filepath) ) { + return is_null($f) ? null : self::createWithFile( + Application_Model_StoredFile::RecallByFilepath($p_filepath)); + } else { + throw new Exception("No arguments passsed to Recall"); + } + } + + public function getName() { - if (isset($p_id)) { - $file = CcFilesQuery::create()->findPK(intval($p_id)); - } - else if (isset($p_gunid)) { - $file = CcFilesQuery::create() - ->filterByDbGunid($p_gunid) - ->findOne(); - } - else if (isset($p_md5sum)) { - if($exist){ - $file = CcFilesQuery::create() - ->filterByDbMd5($p_md5sum) - ->filterByDbFileExists(true) - ->findOne(); - }else{ - $file = CcFilesQuery::create() - ->filterByDbMd5($p_md5sum) - ->findOne(); - } - } - else if (isset($p_filepath)) { - $path_info = Application_Model_MusicDir::splitFilePath($p_filepath); - - if (is_null($path_info)) { - return null; - } - $music_dir = Application_Model_MusicDir::getDirByPath($path_info[0]); - - $file = CcFilesQuery::create() - ->filterByDbDirectory($music_dir->getId()) - ->filterByDbFilepath($path_info[1]) - ->findOne(); - } - else { - return null; - } - - if (isset($file)) { - $storedFile = new Application_Model_StoredFile(); - $storedFile->_file = $file; - - return $storedFile; - } - else { - return null; - } - } - - public function getName(){ $info = pathinfo($this->getFilePath()); return $info['filename']; } - /** - * Create instance of StoreFile object and recall existing file - * by gunid. - * - * @param string $p_gunid - * global unique id of file - * @return Application_Model_StoredFile|NULL - */ - public static function RecallByGunid($p_gunid) - { - return Application_Model_StoredFile::Recall(null, $p_gunid); - } - - - /** - * Fetch the Application_Model_StoredFile by looking up the MD5 value. - * - * @param string $p_md5sum - * @return Application_Model_StoredFile|NULL - */ - public static function RecallByMd5($p_md5sum, $exist=false) - { - return Application_Model_StoredFile::Recall(null, null, $p_md5sum, null, $exist); - } - /** * Fetch the Application_Model_StoredFile by looking up its filepath. * - * @param string $p_filepath path of file stored in Airtime. + * @param string $p_filepath path of file stored in Airtime. * @return Application_Model_StoredFile|NULL */ public static function RecallByFilepath($p_filepath) { - return Application_Model_StoredFile::Recall(null, null, null, $p_filepath); + $path_info = Application_Model_MusicDir::splitFilePath($p_filepath); + + if (is_null($path_info)) { + return null; + } + + $music_dir = Application_Model_MusicDir::getDirByPath($path_info[0]); + $file = CcFilesQuery::create() + ->filterByDbDirectory($music_dir->getId()) + ->filterByDbFilepath($path_info[1]) + ->findOne(); + return is_null($file) ? null : self::createWithFile($file); } - public static function RecallByPartialFilepath($partial_path){ + public static function RecallByPartialFilepath($partial_path) + { $path_info = Application_Model_MusicDir::splitFilePath($partial_path); if (is_null($path_info)) { @@ -613,75 +594,121 @@ Logging::log("getting media! - 2"); ->filterByDbFilepath("$path_info[1]%") ->find(); $res = array(); - foreach ($files as $file){ - $storedFile = new Application_Model_StoredFile(); + foreach ($files as $file) { + $storedFile = new Application_Model_StoredFile(); $storedFile->_file = $file; - $res[] = $storedFile; + $res[] = $storedFile; } + return $res; } - public static function searchLibraryFiles($datatables) { + public static function getLibraryColumns() + { + return array("id", "track_title", "artist_name", "album_title", + "genre", "length", "year", "utime", "mtime", "ftype", + "track_number", "mood", "bpm", "composer", "info_url", + "bit_rate", "sample_rate", "isrc_number", "encoded_by", "label", + "copyright", "mime", "language", "filepath", "owner_id", + "conductor", "replay_gain", "lptime" ); + } - $con = Propel::getConnection(CcFilesPeer::DATABASE_NAME); - $displayColumns = array("id", "track_title", "artist_name", "album_title", "genre", "length", - "year", "utime", "mtime", "ftype", "track_number", "mood", "bpm", "composer", "info_url", - "bit_rate", "sample_rate", "isrc_number", "encoded_by", "label", "copyright", "mime", - "language", "gunid", "filepath" - ); + public static function searchLibraryFiles($datatables) + { + $con = Propel::getConnection(CcFilesPeer::DATABASE_NAME); - $plSelect = array(); - $fileSelect = array(); + $displayColumns = self::getLibraryColumns(); + + $plSelect = array(); + $blSelect = array(); + $fileSelect = array(); + $streamSelect = array(); foreach ($displayColumns as $key) { if ($key === "id") { - $plSelect[] = "PL.id AS ".$key; - $fileSelect[] = $key; - } - else if ($key === "track_title") { - $plSelect[] = "name AS ".$key; - $fileSelect[] = $key; - } - else if ($key === "ftype") { - $plSelect[] = "'playlist'::varchar AS ".$key; - $fileSelect[] = $key; - } - else if ($key === "artist_name") { - $plSelect[] = "login AS ".$key; - $fileSelect[] = $key; + $plSelect[] = "PL.id AS ".$key; + $blSelect[] = "BL.id AS ".$key; + $fileSelect[] = "FILES.id AS $key"; + $streamSelect[] = "ws.id AS ".$key; + } elseif ($key === "track_title") { + $plSelect[] = "name AS ".$key; + $blSelect[] = "name AS ".$key; + $fileSelect[] = $key; + $streamSelect[] = "name AS ".$key; + } elseif ($key === "ftype") { + $plSelect[] = "'playlist'::varchar AS ".$key; + $blSelect[] = "'block'::varchar AS ".$key; + $fileSelect[] = $key; + $streamSelect[] = "'stream'::varchar AS ".$key; + } elseif ($key === "artist_name") { + $plSelect[] = "login AS ".$key; + $blSelect[] = "login AS ".$key; + $fileSelect[] = $key; + $streamSelect[] = "login AS ".$key; + } elseif ($key === "owner_id") { + $plSelect[] = "login AS ".$key; + $blSelect[] = "login AS ".$key; + $fileSelect[] = "sub.login AS $key"; + $streamSelect[] = "login AS ".$key; + } elseif ($key === "replay_gain") { + $plSelect[] = "NULL::NUMERIC AS ".$key; + $blSelect[] = "NULL::NUMERIC AS ".$key; + $fileSelect[] = $key; + $streamSelect[] = "NULL::NUMERIC AS ".$key; + } elseif ($key === "lptime") { + $plSelect[] = "NULL::TIMESTAMP AS ".$key; + $blSelect[] = "NULL::TIMESTAMP AS ".$key; + $fileSelect[] = $key; + $streamSelect[] = $key; } //same columns in each table. - else if(in_array($key, array("length", "utime", "mtime"))) { - $plSelect[] = $key; - $fileSelect[] = $key; - } - else if ($key === "year") { - - $plSelect[] = "EXTRACT(YEAR FROM utime)::varchar AS ".$key; - $fileSelect[] = "year AS ".$key; + else if (in_array($key, array("length", "utime", "mtime"))) { + $plSelect[] = $key; + $blSelect[] = $key; + $fileSelect[] = $key; + $streamSelect[] = $key; + } elseif ($key === "year") { + $plSelect[] = "EXTRACT(YEAR FROM utime)::varchar AS ".$key; + $blSelect[] = "EXTRACT(YEAR FROM utime)::varchar AS ".$key; + $fileSelect[] = "year AS ".$key; + $streamSelect[] = "EXTRACT(YEAR FROM utime)::varchar AS ".$key; } //need to cast certain data as ints for the union to search on. - else if (in_array($key, array("track_number", "bit_rate", "sample_rate"))){ - $plSelect[] = "NULL::int AS ".$key; - $fileSelect[] = $key; - } - else { - $plSelect[] = "NULL::text AS ".$key; - $fileSelect[] = $key; + else if (in_array($key, array("track_number", "bit_rate", "sample_rate", "bpm"))) { + $plSelect[] = "NULL::int AS ".$key; + $blSelect[] = "NULL::int AS ".$key; + $fileSelect[] = $key; + $streamSelect[] = "NULL::int AS ".$key; + } elseif ($key === "filepath") { + $plSelect[] = "NULL::VARCHAR AS ".$key; + $blSelect[] = "NULL::VARCHAR AS ".$key; + $fileSelect[] = $key; + $streamSelect[] = "url AS ".$key; + } else { + $plSelect[] = "NULL::text AS ".$key; + $blSelect[] = "NULL::text AS ".$key; + $fileSelect[] = $key; + $streamSelect[] = "NULL::text AS ".$key; } } - $plSelect = "SELECT ". join(",", $plSelect); - $fileSelect = "SELECT ". join(",", $fileSelect); + $plSelect = "SELECT ". join(",", $plSelect); + $blSelect = "SELECT ". join(",", $blSelect); + $fileSelect = "SELECT ". join(",", $fileSelect); + $streamSelect = "SELECT ". join(",", $streamSelect); $type = intval($datatables["type"]); $plTable = "({$plSelect} FROM cc_playlist AS PL LEFT JOIN cc_subjs AS sub ON (sub.id = PL.creator_id))"; - $fileTable = "({$fileSelect} FROM cc_files AS FILES WHERE file_exists = 'TRUE')"; - $unionTable = "({$plTable} UNION {$fileTable} ) AS RESULTS"; + $blTable = "({$blSelect} FROM cc_block AS BL LEFT JOIN cc_subjs AS sub ON (sub.id = BL.creator_id))"; + $fileTable = "({$fileSelect} FROM cc_files AS FILES LEFT JOIN cc_subjs AS sub ON (sub.id = FILES.owner_id) WHERE file_exists = 'TRUE')"; + //$fileTable = "({$fileSelect} FROM cc_files AS FILES WHERE file_exists = 'TRUE')"; + $streamTable = "({$streamSelect} FROM cc_webstream AS ws LEFT JOIN cc_subjs AS sub ON (sub.id = ws.creator_id))"; + $unionTable = "({$plTable} UNION {$blTable} UNION {$fileTable} UNION {$streamTable}) AS RESULTS"; //choose which table we need to select data from. + // TODO : use constants instead of numbers -- RG switch ($type) { case 0: $fromTable = $unionTable; @@ -692,6 +719,12 @@ Logging::log("getting media! - 2"); case 2: $fromTable = $plTable." AS Playlist"; //need an alias for the table if it's standalone. break; + case 3: + $fromTable = $blTable." AS Block"; //need an alias for the table if it's standalone. + break; + case 4: + $fromTable = $streamTable." AS StreamTable"; //need an alias for the table if it's standalone. + break; default: $fromTable = $unionTable; } @@ -713,6 +746,14 @@ Logging::log("getting media! - 2"); $row['bit_rate'] = $formatter->format(); } + //convert mtime and utime to localtime + $row['mtime'] = new DateTime($row['mtime'], new DateTimeZone('UTC')); + $row['mtime']->setTimeZone(new DateTimeZone(date_default_timezone_get())); + $row['mtime'] = $row['mtime']->format('Y-m-d H:i:s'); + $row['utime'] = new DateTime($row['utime'], new DateTimeZone('UTC')); + $row['utime']->setTimeZone(new DateTimeZone(date_default_timezone_get())); + $row['utime'] = $row['utime']->format('Y-m-d H:i:s'); + // add checkbox row $row['checkbox'] = ""; @@ -720,16 +761,23 @@ Logging::log("getting media! - 2"); $row['tr_id'] = "{$type}_{$row['id']}"; - //TODO url like this to work on both playlist/showbuilder screens. - //datatable stuff really needs to be pulled out and generalized within the project - //access to zend view methods to access url helpers is needed. + //TODO url like this to work on both playlist/showbuilder + //screens. datatable stuff really needs to be pulled out and + //generalized within the project access to zend view methods + //to access url helpers is needed. - if($type == "au"){//&& isset( $audioResults )) { - $row['audioFile'] = $row['gunid'].".".pathinfo($row['filepath'], PATHINFO_EXTENSION); + // TODO : why is there inline html here? breaks abstraction and is + // ugly + if ($type == "au") { + $row['audioFile'] = $row['id'].".".pathinfo($row['filepath'], PATHINFO_EXTENSION); $row['image'] = ''; - } - else { + } elseif ($type == "pl") { $row['image'] = ''; + } elseif ($type == "st") { + $row['audioFile'] = $row['id']; + $row['image'] = ''; + } elseif ($type == "bl") { + $row['image'] = ''; } } @@ -748,7 +796,7 @@ Logging::log("getting media! - 2"); // Settings $cleanupTargetDir = false; // Remove old files - $maxFileAge = 60 * 60; // Temp file age in seconds + $maxFileAge = 60 * 60; // Temp file age in seconds // 5 minutes execution time @set_time_limit(5 * 60); @@ -758,7 +806,9 @@ Logging::log("getting media! - 2"); $chunk = isset($_REQUEST["chunk"]) ? $_REQUEST["chunk"] : 0; $chunks = isset($_REQUEST["chunks"]) ? $_REQUEST["chunks"] : 0; $fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : ''; - Logging::log(__FILE__.":uploadFile(): filename=$fileName to $p_targetDir"); + # TODO : should not log __FILE__ itself. there is general logging for + # this + Logging::info(__FILE__.":uploadFile(): filename=$fileName to $p_targetDir"); // Clean the fileName for security reasons //this needs fixing for songs not in ascii. //$fileName = preg_replace('/[^\w\._]+/', '', $fileName); @@ -793,6 +843,7 @@ Logging::log("getting media! - 2"); // plupload support unique_name feature. $tempFilePath= $p_targetDir . DIRECTORY_SEPARATOR . $fileName; + // Old IBM code... if (strpos($contentType, "multipart") !== false) { if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) { // Open temp file @@ -838,143 +889,211 @@ Logging::log("getting media! - 2"); * Check, using disk_free_space, the space available in the $destination_folder folder to see if it has * enough space to move the $audio_file into and report back to the user if not. **/ - public static function checkForEnoughDiskSpaceToCopy($destination_folder, $audio_file){ + public static function isEnoughDiskSpaceToCopy($destination_folder, $audio_file) + { //check to see if we have enough space in the /organize directory to copy the file $freeSpace = disk_free_space($destination_folder); $fileSize = filesize($audio_file); - if ( $freeSpace < $fileSize){ - $freeSpace = ceil($freeSpace/1024/1024); - $fileSize = ceil($fileSize/1024/1024); - return array("code" => 107, "message" => "The file was not uploaded, there is ".$freeSpace."MB of disk space left and the file you are uploading has a size of ".$fileSize."MB."); - return false; - } else { - return true; - } + return $freeSpace >= $fileSize; } - public static function copyFileToStor($p_targetDir, $fileName, $tempname){ + public static function copyFileToStor($p_targetDir, $fileName, $tempname) + { $audio_file = $p_targetDir . DIRECTORY_SEPARATOR . $tempname; - Logging::log('copyFileToStor: moving file '.$audio_file); - $md5 = md5_file($audio_file); - $duplicate = Application_Model_StoredFile::RecallByMd5($md5, true); + Logging::info('copyFileToStor: moving file '.$audio_file); - $result = null; - if ($duplicate) { - if (file_exists($duplicate->getFilePath())) { - $duplicateName = $duplicate->getMetadataValue('MDATA_KEY_TITLE'); - $result = array( "code" => 106, "message" => "An identical audioclip named '$duplicateName' already exists on the server."); + $storDir = Application_Model_MusicDir::getStorDir(); + $stor = $storDir->getDirectory(); + // check if "organize" dir exists and if not create one + if (!file_exists($stor."/organize")) { + if (!mkdir($stor."/organize", 0777)) { + return array( + "code" => 109, + "message" => "Failed to create 'organize' directory."); } } - if (!isset($result)){//The file has no duplicate, so proceed to copy. - $storDir = Application_Model_MusicDir::getStorDir(); - $stor = $storDir->getDirectory(); - // check if "organize" dir exists and if not create one - if(!file_exists($stor."/organize")){ - if(!mkdir($stor."/organize", 0777)){ - $result = array("code" => 109, "message" => "Failed to create 'organize' directory."); - return $result; - } - } - //check to see if there is enough space in $stor to continue. - $enough_space = Application_Model_StoredFile::checkForEnoughDiskSpaceToCopy($stor, $audio_file); - if ($enough_space){ - $audio_stor = Application_Common_OsPath::join($stor, "organize", $fileName); - - Logging::log("copyFileToStor: moving file $audio_file to $audio_stor"); - - if (chmod($audio_file, 0644) === false){ - Logging::log("Warning: couldn't change permissions of $audio_file to 0644"); - } - - // Check if file is playable - $command = sprintf("/usr/bin/airtime-liquidsoap -c 'output.dummy(audio_to_stereo(single(\"%s\")))' 2>&1", $audio_file); - - exec($command, $output, $rv); - if ($rv != 0 || (!empty($output) && $output[0] == 'TagLib: MPEG::Properties::read() -- Could not find a valid last MPEG frame in the stream.')) { - $result = array("code" => 110, "message" => "This file appears to be corrupted and will not be added to media library."); - } else { - //Martin K.: changed to rename: Much less load + quicker since this is an atomic operation - $r = @rename($audio_file, $audio_stor); - - if ($r === false) { - #something went wrong likely there wasn't enough space in the audio_stor to move the file too. - #warn the user that the file wasn't uploaded and they should check if there is enough disk space. - unlink($audio_file);//remove the file from the organize after failed rename - $result = array("code" => 108, "message" => "The file was not uploaded, this error will occur if the computer hard drive does not have enough disk space."); - } - } - } + if (chmod($audio_file, 0644) === false) { + Logging::info("Warning: couldn't change permissions of $audio_file to 0644"); } - return $result; + + // Check if we have enough space before copying + if (!self::isEnoughDiskSpaceToCopy($stor, $audio_file)) { + $freeSpace = disk_free_space($stor); + + return array("code" => 107, + "message" => "The file was not uploaded, there is + ".$freeSpace."MB of disk space left and the file you are + uploading has a size of ".$fileSize."MB."); + } + + // Check if liquidsoap can play this file + if (!self::liquidsoapFilePlayabilityTest($audio_file)) { + return array( + "code" => 110, + "message" => "This file appears to be corrupted and will not + be added to media library."); + } + + // Did all the checks for real, now trying to copy + $audio_stor = Application_Common_OsPath::join($stor, "organize", + $fileName); + $user = Application_Model_User::getCurrentUser(); + if (is_null($user)) { + $uid = Application_Model_User::getFirstAdminId(); + } else { + $uid = $user->getId(); + } + $id_file = "$audio_stor.identifier"; + if (file_put_contents($id_file, $uid) === false) { + Logging::info("Could not write file to identify user: '$uid'"); + Logging::info("Id file path: '$id_file'"); + Logging::info("Defaulting to admin (no identification file was + written)"); + } else { + Logging::info("Successfully written identification file for + uploaded '$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 + if (@rename($audio_file, $audio_stor) === false) { + //something went wrong likely there wasn't enough space in . + //the audio_stor to move the file too warn the user that . + //the file wasn't uploaded and they should check if there . + //is enough disk space . + unlink($audio_file); //remove the file after failed rename + unlink($id_file); // Also remove the identifier file + + return array( + "code" => 108, + "message" => " + The file was not uploaded, this error can occur if the computer + hard drive does not have enough disk space or the stor + directory does not have correct write permissions."); + } + // Now that we successfully added this file, we will add another tag + // file that will identify the user that owns it + return null; } + /* + * Pass the file through Liquidsoap and test if it is readable. Return True if readable, and False otherwise. + */ + public static function liquidsoapFilePlayabilityTest($audio_file) + { + $LIQUIDSOAP_ERRORS = array('TagLib: MPEG::Properties::read() -- Could not find a valid last MPEG frame in the stream.'); + + // Ask Liquidsoap if file is playable + $command = sprintf("/usr/bin/airtime-liquidsoap -c 'output.dummy(audio_to_stereo(single(\"%s\")))' 2>&1", $audio_file); + + exec($command, $output, $rv); + + $isError = count($output) > 0 && in_array($output[0], $LIQUIDSOAP_ERRORS); + + return ($rv == 0 && !$isError); + } public static function getFileCount() { - global $CC_CONFIG; - $con = Propel::getConnection(); - - $sql = "SELECT count(*) as cnt FROM ".$CC_CONFIG["filesTable"]." WHERE file_exists"; + $con = Propel::getConnection(); + $sql = "SELECT count(*) as cnt FROM cc_files WHERE file_exists"; return $con->query($sql)->fetchColumn(0); } /** * * Enter description here ... - * @param $dir_id - if this is not provided, it returns all files with full path constructed. - * @param $propelObj - if this is true, it returns array of proepl obj + * @param $dir_id - if this is not provided, it returns all files with full + * path constructed. */ - public static function listAllFiles($dir_id=null, $propelObj=false) + public static function listAllFiles($dir_id=null, $all) { - $con = Propel::getConnection(); + $con = Propel::getConnection(); - if ($propelObj) { - $sql = "SELECT m.directory || f.filepath as fp" - ." FROM CC_MUSIC_DIRS m" - ." LEFT JOIN CC_FILES f" - ." ON m.id = f.directory WHERE m.id = $dir_id and f.file_exists = 'TRUE'"; - } else { - $sql = "SELECT filepath as fp" - ." FROM CC_FILES" - ." WHERE directory = $dir_id and file_exists = 'TRUE'"; + $sql = <<query($sql)->fetchAll(); + $stmt = $con->prepare($sql); + $stmt->bindParam(':dir_id', $dir_id); + + if ($stmt->execute()) { + $rows = $stmt->fetchAll(); + } else { + $msg = implode(',', $stmt->errorInfo()); + throw new Exception("Error: $msg"); + } + $results = array(); foreach ($rows as $row) { - if ($propelObj) { - $results[] = Application_Model_StoredFile::RecallByFilepath($row["fp"]); - } else { - $results[] = $row["fp"]; - } + $results[] = $row["fp"]; } return $results; } - + + //TODO: MERGE THIS FUNCTION AND "listAllFiles" -MK + public static function listAllFiles2($dir_id=null, $limit="ALL") + { + $con = Propel::getConnection(); + + $sql = <<prepare($sql); + $stmt->bindParam(':dir_id', $dir_id); + $stmt->bindParam(':lim', $limit); + + if ($stmt->execute()) { + $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); + } else { + $msg = implode(',', $stmt->errorInfo()); + throw new Exception("Error: $msg"); + } + + return $rows; + } + /* Gets number of tracks uploaded to * Soundcloud in the last 24 hours */ public static function getSoundCloudUploads() { try { - $con = Propel::getConnection(); - - $sql = "SELECT soundcloud_id as id, soundcloud_upload_time" - ." FROM CC_FILES" - ." WHERE (id != -2 and id != -3) and" - ." (soundcloud_upload_time >= (now() - (INTERVAL '1 day')))"; - + $con = Propel::getConnection(); + + $sql = <<= (now() - (INTERVAL '1 day'))) +SQL; + $rows = $con->query($sql)->fetchAll(); + return count($rows); } catch (Exception $e) { header('HTTP/1.0 503 Service Unavailable'); - Logging::log("Could not connect to database."); - exit; + Logging::info("Could not connect to database."); + exit; } - + } public function setSoundCloudLinkToFile($link_to_file) @@ -983,7 +1102,8 @@ Logging::log("getting media! - 2"); ->save(); } - public function getSoundCloudLinkToFile(){ + public function getSoundCloudLinkToFile() + { return $this->_file->getDbSoundCloudLinkToFile(); } @@ -993,78 +1113,90 @@ Logging::log("getting media! - 2"); ->save(); } - public function getSoundCloudId(){ + public function getSoundCloudId() + { return $this->_file->getDbSoundCloudId(); } - public function setSoundCloudErrorCode($code){ + public function setSoundCloudErrorCode($code) + { $this->_file->setDbSoundCloudErrorCode($code) ->save(); } - public function getSoundCloudErrorCode(){ + public function getSoundCloudErrorCode() + { return $this->_file->getDbSoundCloudErrorCode(); } - public function setSoundCloudErrorMsg($msg){ + public function setSoundCloudErrorMsg($msg) + { $this->_file->setDbSoundCloudErrorMsg($msg) ->save(); } - public function getSoundCloudErrorMsg(){ + public function getSoundCloudErrorMsg() + { return $this->_file->getDbSoundCloudErrorMsg(); } - - public function getDirectory(){ - return $this->_file->getDbDirectory(); - } - public function setFileExistsFlag($flag){ + public function getDirectory() + { + return $this->_file->getDbDirectory(); + } + + public function setFileExistsFlag($flag) + { $this->_file->setDbFileExists($flag) ->save(); } - public function setSoundCloudUploadTime($time){ + public function setSoundCloudUploadTime($time) + { $this->_file->setDbSoundCloundUploadTime($time) - ->save(); + ->save(); } - public function getFileExistsFlag(){ + public function getFileExistsFlag() + { return $this->_file->getDbFileExists(); } + + // note: never call this method from controllers because it does a sleep public function uploadToSoundCloud() { global $CC_CONFIG; $file = $this->_file; - if(is_null($file)) { + if (is_null($file)) { return "File does not exist"; } - if(Application_Model_Preference::GetUploadToSoundcloudOption()) - { - for($i=0; $i<$CC_CONFIG['soundcloud-connection-retries']; $i++) { + if (Application_Model_Preference::GetUploadToSoundcloudOption()) { + for ($i=0; $i<$CC_CONFIG['soundcloud-connection-retries']; $i++) { $description = $file->getDbTrackTitle(); - $tag = array(); - $genre = $file->getDbGenre(); - $release = $file->getDbYear(); + $tag = array(); + $genre = $file->getDbGenre(); + $release = $file->getDbYear(); try { - $soundcloud = new Application_Model_Soundcloud(); - $soundcloud_res = $soundcloud->uploadTrack($this->getFilePath(), $this->getName(), $description, $tag, $release, $genre); + $soundcloud = new Application_Model_Soundcloud(); + $soundcloud_res = $soundcloud->uploadTrack( + $this->getFilePath(), $this->getName(), $description, + $tag, $release, $genre); $this->setSoundCloudFileId($soundcloud_res['id']); $this->setSoundCloudLinkToFile($soundcloud_res['permalink_url']); $this->setSoundCloudUploadTime(new DateTime("now"), new DateTimeZone("UTC")); break; - } - catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) { + } catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) { $code = $e->getHttpCode(); - $msg = $e->getHttpBody(); + $msg = $e->getHttpBody(); + // TODO : Do not parse JSON by hand $temp = explode('"error":',$msg); - $msg = trim($temp[1], '"}'); + $msg = trim($temp[1], '"}'); $this->setSoundCloudErrorCode($code); $this->setSoundCloudErrorMsg($msg); // setting sc id to -3 which indicates error $this->setSoundCloudFileId(SOUNDCLOUD_ERROR); - if(!in_array($code, array(0, 100))) { + if (!in_array($code, array(0, 100))) { break; } } diff --git a/airtime_mvc/application/models/StreamSetting.php b/airtime_mvc/application/models/StreamSetting.php index b9dd16ac7..cdd7747b7 100644 --- a/airtime_mvc/application/models/StreamSetting.php +++ b/airtime_mvc/application/models/StreamSetting.php @@ -1,51 +1,65 @@ query($sql)->fetchColumn(0); + $stmt = $con->prepare($sql); + $stmt->bindParam(':key', $key); + + if ($stmt->execute()) { + $result = $stmt->fetchColumn(0); + } else { + $msg = implode(',', $stmt->errorInfo()); + throw new Exception("Error: $msg"); + } if ($result == 1) { $sql = "UPDATE cc_stream_setting" - ." SET value = '$value', type='$type'" - ." WHERE keyname = '$key'"; + ." SET value = :value, type = :type" + ." WHERE keyname = :key"; } else { $sql = "INSERT INTO cc_stream_setting (keyname, value, type)" - ." VALUES ('$key', '$value', '$type')"; + ." VALUES (:key, :value, :type)"; } - return $con->exec($sql); + $stmt = $con->prepare($sql); + $stmt->bindParam(':key', $key); + $stmt->bindParam(':value', $value); + $stmt->bindParam(':type', $type); + + if ($stmt->execute()) { + //do nothing + } else { + $msg = implode(',', $stmt->errorInfo()); + throw new Exception("Error: $msg"); + } } - public static function GetValue($key) + public static function getValue($key) { - global $CC_CONFIG; - $con = Propel::getConnection(); - + $con = Propel::getConnection(); + //Check if key already exists - $sql = "SELECT COUNT(*) FROM cc_stream_setting" - ." WHERE keyname = '$key'"; - $result = $con->query($sql)->fetchColumn(0); + $sql = "SELECT value FROM cc_stream_setting" + ." WHERE keyname = :key"; - if ($result == 0) - return ""; - else { - $sql = "SELECT value FROM cc_stream_setting" - ." WHERE keyname = '$key'"; - - $result = $con->query($sql)->fetchColumn(0); - return ($result !== false) ? $result : NULL; + $stmt = $con->prepare($sql); + $stmt->bindParam(':key', $key); + + if ($stmt->execute()) { + $result = $stmt->fetchColumn(0); + } else { + $msg = implode(',', $stmt->errorInfo()); + throw new Exception("Error: $msg"); } + + return $result ? $result : ""; } /* Returns the id's of all streams that are enabled in an array. An @@ -65,7 +79,7 @@ class Application_Model_StreamSetting { $ids[] = substr($row["keyname"], 0, strpos($row["keyname"], "_")); } - //Logging::log(print_r($ids, true)); + //Logging::info(print_r($ids, true)); return $ids; } @@ -92,11 +106,20 @@ class Application_Model_StreamSetting { public static function getStreamData($p_streamId) { $con = Propel::getConnection(); + $streamId = pg_escape_string($p_streamId); $sql = "SELECT * " ."FROM cc_stream_setting " - ."WHERE keyname LIKE '${p_streamId}_%'"; + ."WHERE keyname LIKE '{$streamId}_%'"; + + $stmt = $con->prepare($sql); + + if ($stmt->execute()) { + $rows = $stmt->fetchAll(); + } else { + $msg = implode(',', $stmt->errorInfo()); + throw new Exception("Error: $msg"); + } - $rows = $con->query($sql)->fetchAll(); $data = array(); foreach ($rows as $row) { @@ -120,30 +143,51 @@ class Application_Model_StreamSetting { foreach ($rows as $r) { if ($r['keyname'] == 'master_live_stream_port') { $exists['master_live_stream_port'] = true; - } elseif($r['keyname'] == 'master_live_stream_mp') { + } elseif ($r['keyname'] == 'master_live_stream_mp') { $exists['master_live_stream_mp'] = true; - } elseif($r['keyname'] == 'dj_live_stream_port') { + } elseif ($r['keyname'] == 'dj_live_stream_port') { $exists['dj_live_stream_port'] = true; - } elseif($r['keyname'] == 'dj_live_stream_mp') { + } elseif ($r['keyname'] == 'dj_live_stream_mp') { $exists['dj_live_stream_mp'] = true; } } if (!isset($exists["master_live_stream_port"])) { - $rows[] = (array("keyname" =>"master_live_stream_port", "value"=>self::GetMasterLiveSteamPort(), "type"=>"integer")); + $rows[] = array("keyname" =>"master_live_stream_port", + "value"=>self::getMasterLiveStreamPort(), + "type"=>"integer"); } if (!isset($exists["master_live_stream_mp"])) { - $rows[] = (array("keyname" =>"master_live_stream_mp", "value"=>self::GetMasterLiveSteamMountPoint(), "type"=>"string")); + $rows[] = array("keyname" =>"master_live_stream_mp", + "value"=>self::getMasterLiveStreamMountPoint(), + "type"=>"string"); } if (!isset($exists["dj_live_stream_port"])) { - $rows[] = (array("keyname" =>"dj_live_stream_port", "value"=>self::GetDJLiveSteamPort(), "type"=>"integer")); + $rows[] = array("keyname" =>"dj_live_stream_port", + "value"=>self::getDjLiveStreamPort(), + "type"=>"integer"); } if (!isset($exists["dj_live_stream_mp"])) { - $rows[] = (array("keyname" =>"dj_live_stream_mp", "value"=>self::GetDJLiveSteamMountPoint(), "type"=>"string")); + $rows[] = array("keyname" =>"dj_live_stream_mp", + "value"=>self::getDjLiveStreamMountPoint(), + "type"=>"string"); } + return $rows; } + + private static function saveStreamSetting($key, $value) + { + $stream_setting = CcStreamSettingQuery::create()->filterByDbKeyName($key)->findOne(); + if (is_null($stream_setting)) { + throw new Exception("Keyname $key does not exist!"); + } + + $stream_setting->setDbValue($value); + $stream_setting->save(); + } + /* * function that take all the information of stream and sets them. * This is used by stream setting via UI. @@ -153,31 +197,23 @@ class Application_Model_StreamSetting { */ public static function setStreamSetting($data) { - $con = Propel::getConnection(); - - foreach ($data as $key=>$d) { + foreach ($data as $key => $d) { if ($key == "output_sound_device" || $key == "icecast_vorbis_metadata") { - $v = $d == 1?"true":"false"; - $sql = "UPDATE cc_stream_setting SET value='$v' WHERE keyname='$key'"; - $con->exec($sql); - } else if ($key == "output_sound_device_type") { - $sql = "UPDATE cc_stream_setting SET value='$d' WHERE keyname='$key'"; - $con->exec($sql); - } else if (is_array($d)) { + $v = ($d == 1) ? "true" : "false"; + + self::saveStreamSetting($key, $v); + } elseif ($key == "output_sound_device_type") { + self::saveStreamSetting($key, $d); + } elseif (is_array($d)) { $temp = explode('_', $key); $prefix = $temp[0]; - foreach ($d as $k=>$v) { + foreach ($d as $k => $v) { $keyname = $prefix . "_" . $k; if ($k == 'enable') { $v = $d['enable'] == 1 ? 'true' : 'false'; } $v = trim($v); - - #escape double single quotes CC-3926 - $v = str_replace("'", "''", $v); - $sql = "UPDATE cc_stream_setting SET value='$v' WHERE keyname='$keyname'"; - - $con->exec($sql); + self::saveStreamSetting($keyname, $v); } } } @@ -187,10 +223,13 @@ class Application_Model_StreamSetting { * Sets indivisual stream setting. * * $data - data array. $data is []. + * TODO: Make this SQL a prepared statement! + * + * Do not remove this function. It is called by airtime-system.php */ - public static function setIndivisualStreamSetting($data) + public static function setIndividualStreamSetting($data) { - $con = Propel::getConnection(); + $con = Propel::getConnection(); foreach ($data as $keyname => $v) { $sql = "UPDATE cc_stream_setting SET value='$v' WHERE keyname='$keyname'"; @@ -198,58 +237,93 @@ class Application_Model_StreamSetting { } } + /* * Stores liquidsoap status if $boot_time > save time. * save time is the time that user clicked save on stream setting page */ public static function setLiquidsoapError($stream_id, $msg, $boot_time=null) { - $con = Propel::getConnection(); + $con = Propel::getConnection(); $update_time = Application_Model_Preference::GetStreamUpdateTimestemp(); if ($boot_time == null || $boot_time > $update_time) { $keyname = "s".$stream_id."_liquidsoap_error"; $sql = "SELECT COUNT(*) FROM cc_stream_setting" - ." WHERE keyname = '$keyname'"; - $result = $con->query($sql)->fetchColumn(0); + ." WHERE keyname = :keyname"; + + $stmt = $con->prepare($sql); + $stmt->bindParam(':keyname', $keyname); + + if ($stmt->execute()) { + $result= $stmt->fetchColumn(0); + } else { + $msg = implode(',', $stmt->errorInfo()); + throw new Exception("Error: $msg"); + } + if ($result == 1) { $sql = "UPDATE cc_stream_setting" - ." SET value = '$msg'" - ." WHERE keyname = '$keyname'"; + ." SET value = :msg" + ." WHERE keyname = :keyname"; } else { $sql = "INSERT INTO cc_stream_setting (keyname, value, type)" - ." VALUES ('$keyname', '$msg', 'string')"; + ." VALUES (:keyname, :msg, 'string')"; + } + + $stmt = $con->prepare($sql); + $stmt->bindParam(':keyname', $keyname); + $stmt->bindParam(':msg', $msg); + + if ($stmt->execute()) { + //do nothing + } else { + $msg = implode(',', $stmt->errorInfo()); + throw new Exception("Error: $msg"); } - $res = $con->exec($sql); } } public static function getLiquidsoapError($stream_id) { - $con = Propel::getConnection(); + $con = Propel::getConnection(); $keyname = "s".$stream_id."_liquidsoap_error"; $sql = "SELECT value FROM cc_stream_setting" - ." WHERE keyname = '$keyname'"; - $result = $con->query($sql)->fetchColumn(0); + ." WHERE keyname = :keyname"; - return ($result !== false) ? $result : NULL; + $stmt = $con->prepare($sql); + $stmt->bindParam(':keyname', $keyname); + + if ($stmt->execute()) { + $result= $stmt->fetchColumn(0); + } else { + $msg = implode(',', $stmt->errorInfo()); + throw new Exception("Error: $msg"); + } + + return ($result !== false) ? $result : null; } public static function getStreamEnabled($stream_id) { - $con = Propel::getConnection(); + $con = Propel::getConnection(); $keyname = "s" . $stream_id . "_enable"; $sql = "SELECT value FROM cc_stream_setting" - ." WHERE keyname = '$keyname'"; - $result = $con->query($sql)->fetchColumn(0); - if ($result == 'false') { - $result = false; + ." WHERE keyname = :keyname"; + + $stmt = $con->prepare($sql); + $stmt->bindParam(':keyname', $keyname); + + if ($stmt->execute()) { + $result= $stmt->fetchColumn(0); } else { - $result = true; + $msg = implode(',', $stmt->errorInfo()); + throw new Exception("Error: $msg"); } - return $result; + + return ($result != 'false'); } /* @@ -258,18 +332,28 @@ class Application_Model_StreamSetting { */ public static function getStreamInfoForDataCollection() { - $con = Propel::getConnection(); + $con = Propel::getConnection(); $out = array(); $enabled_stream = self::getEnabledStreamIds(); foreach ($enabled_stream as $stream) { - $keys = "'".$stream."_output', "."'".$stream."_type', "."'".$stream."_bitrate', "."'".$stream."_host'"; + $keys = array("{$stream}_output", "{$stream}_type", "{$stream}_bitrate", "{$stream}_host"); + $key_csv = implode(',', $keys); $sql = "SELECT keyname, value FROM cc_stream_setting" - ." WHERE keyname IN ($keys)"; + ." WHERE keyname IN (:key_csv)"; + + $stmt = $con->prepare($sql); + $stmt->bindParam(':key_csv', $key_csv); + + if ($stmt->execute()) { + $rows = $stmt->fetchAll(); + } else { + $msg = implode(',', $stmt->errorInfo()); + throw new Exception("Error: $msg"); + } - $rows = $con->query($sql)->fetchAll(); $info = array(); foreach ($rows as $r) { $temp = explode("_", $r['keyname']); @@ -277,38 +361,47 @@ class Application_Model_StreamSetting { $out[$stream] = $info; } } + return $out; } - public static function SetMasterLiveSteamPort($value){ - self::SetValue("master_live_stream_port", $value, "integer"); + public static function setMasterLiveStreamPort($value) + { + self::setValue("master_live_stream_port", $value, "integer"); } - public static function GetMasterLiveSteamPort(){ - return self::GetValue("master_live_stream_port"); + public static function getMasterLiveStreamPort() + { + return self::getValue("master_live_stream_port"); } - public static function SetMasterLiveSteamMountPoint($value){ - self::SetValue("master_live_stream_mp", $value, "string"); + public static function setMasterLiveStreamMountPoint($value) + { + self::setValue("master_live_stream_mp", $value, "string"); } - public static function GetMasterLiveSteamMountPoint(){ - return self::GetValue("master_live_stream_mp"); + public static function getMasterLiveStreamMountPoint() + { + return self::getValue("master_live_stream_mp"); } - public static function SetDJLiveSteamPort($value){ - self::SetValue("dj_live_stream_port", $value, "integer"); + public static function setDjLiveStreamPort($value) + { + self::setValue("dj_live_stream_port", $value, "integer"); } - public static function GetDJLiveSteamPort(){ - return self::GetValue("dj_live_stream_port"); + public static function getDjLiveStreamPort() + { + return self::getValue("dj_live_stream_port"); } - public static function SetDJLiveSteamMountPoint($value){ - self::SetValue("dj_live_stream_mp", $value, "string"); + public static function setDjLiveStreamMountPoint($value) + { + self::setValue("dj_live_stream_mp", $value, "string"); } - public static function GetDJLiveSteamMountPoint(){ - return self::GetValue("dj_live_stream_mp"); + public static function getDjLiveStreamMountPoint() + { + return self::getValue("dj_live_stream_mp"); } } diff --git a/airtime_mvc/application/models/Subjects.php b/airtime_mvc/application/models/Subjects.php index e66bbaa8a..6aa2708a2 100644 --- a/airtime_mvc/application/models/Subjects.php +++ b/airtime_mvc/application/models/Subjects.php @@ -14,106 +14,10 @@ define('ALIBERR_BADSMEMB', 21); * @copyright 2010 Sourcefabric O.P.S. * @license http://www.gnu.org/licenses/gpl.txt */ -class Application_Model_Subjects { - +class Application_Model_Subjects +{ /* ======================================================= public methods */ - /** - * Check login and password - * - * @param string $login - * @param string $pass - * optional - * @return boolean|int|PEAR_Error - */ - public static function Authenticate($login, $pass='') - { - global $CC_CONFIG; - $con = Propel::getConnection(); - $cpass = md5($pass); - $sql = "SELECT id FROM ".$CC_CONFIG['subjTable'] - ." WHERE login='$login' AND pass='$cpass' AND type='U'" - ." LIMIT 1"; - $query = $con->query($sql)->fetchColumn(0); - return $query; - } - - - /** - * Change user password - * - * @param string $login - * @param string $oldpass - * old password (optional for 'superuser mode') - * @param string $pass - * optional - * @param boolean $passenc - * optional, password already encrypted if true - * @return boolean|PEAR_Error - */ - public static function Passwd($login, $oldpass=null, $pass='', $passenc=FALSE) - { - global $CC_CONFIG; - $con = Propel::getConnection(); - if (!$passenc) { - $cpass = md5($pass); - } else { - $cpass = $pass; - } - if (!is_null($oldpass)) { - $oldcpass = md5($oldpass); - $oldpCond = "AND pass='$oldcpass'"; - } else { - $oldpCond = ''; - } - $sql = "UPDATE ".$CC_CONFIG['subjTable']." SET pass='$cpass'" - ." WHERE login='$login' $oldpCond AND type='U'"; - $con->exec($sql); - return TRUE; - } - - - /* --------------------------------------------------------------- groups */ - - /* --------------------------------------------------------- info methods */ - - /** - * Get subject id from login - * - * @param string $login - * @return int|false - */ - public static function GetSubjId($login) - { - global $CC_CONFIG; - $con = Propel::getConnection(); - $sql = "SELECT id FROM ".$CC_CONFIG['subjTable'] - ." WHERE login='$login'"; - $query = $con->query($sql)->fetchColumn(0); - return ($query !== false) ? $query : NULL; - } - - - /** - * Return true if uid is direct member of gid - * - * @param int $uid - * local user id - * @param int $gid - * local group id - * @return boolean - */ - public static function IsMemberOf($uid, $gid) - { - global $CC_CONFIG; - $con = Propel::getConnection(); - $sql = "SELECT count(*) as cnt" - ." FROM ".$CC_CONFIG['smembTable'] - ." WHERE uid='$uid' AND gid='$gid'"; - $res = $con->query($sql)->fetchColumn(0); - return (intval($res) > 0); - } - public static function increaseLoginAttempts($login) { global $CC_CONFIG; @@ -121,6 +25,7 @@ class Application_Model_Subjects { $sql = "UPDATE ".$CC_CONFIG['subjTable']." SET login_attempts = login_attempts+1" ." WHERE login='$login'"; $res = $con->exec($sql); + return (intval($res) > 0); } @@ -131,7 +36,8 @@ class Application_Model_Subjects { $sql = "UPDATE ".$CC_CONFIG['subjTable']." SET login_attempts = '0'" ." WHERE login='$login'"; $res = $con->exec($sql); - return TRUE; + + return true; } public static function getLoginAttempts($login) @@ -140,8 +46,8 @@ class Application_Model_Subjects { $con = Propel::getConnection(); $sql = "SELECT login_attempts FROM ".$CC_CONFIG['subjTable']." WHERE login='$login'"; $res = $con->query($sql)->fetchColumn(0); + return ($res !== false) ? $res : 0; } } // class Subjects - diff --git a/airtime_mvc/application/models/Systemstatus.php b/airtime_mvc/application/models/Systemstatus.php index fd798bc57..d62ad7110 100644 --- a/airtime_mvc/application/models/Systemstatus.php +++ b/airtime_mvc/application/models/Systemstatus.php @@ -3,27 +3,28 @@ class Application_Model_Systemstatus { - public static function GetMonitStatus($p_ip){ + public static function GetMonitStatus($p_ip) + { global $CC_CONFIG; $monit_user = $CC_CONFIG['monit_user']; $monit_password = $CC_CONFIG['monit_password']; $url = "http://$p_ip:2812/_status?format=xml"; - - $ch = curl_init(); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($ch, CURLOPT_URL, $url); + + $ch = curl_init(); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_USERPWD, "$monit_user:$monit_password"); //wait a max of 3 seconds before aborting connection attempt curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3); $result = curl_exec($ch); - + $info = curl_getinfo($ch); curl_close($ch); $docRoot = null; - if ($result !== FALSE && $info["http_code"] === 200){ - if ($result != ""){ + if ($result !== FALSE && $info["http_code"] === 200) { + if ($result != "") { $xmlDoc = new DOMDocument(); $xmlDoc->loadXML($result); $docRoot = $xmlDoc->documentElement; @@ -32,9 +33,9 @@ class Application_Model_Systemstatus return $docRoot; } - - public static function ExtractServiceInformation($p_docRoot, $p_serviceName){ + public static function ExtractServiceInformation($p_docRoot, $p_serviceName) + { $starting = array( "name"=>"", "process_id"=>"STARTING...", @@ -43,7 +44,7 @@ class Application_Model_Systemstatus "memory_perc"=>"0%", "memory_kb"=>"0", "cpu_perc"=>"0%"); - + $notMonitored = array( "name"=>$p_serviceName, "process_id"=>"NOT MONITORED", @@ -53,7 +54,7 @@ class Application_Model_Systemstatus "memory_kb"=>"0", "cpu_perc"=>"0%" ); - + $notRunning = array( "name"=>$p_serviceName, "process_id"=>"FAILED", @@ -65,140 +66,140 @@ class Application_Model_Systemstatus ); $data = $notRunning; - - if (!is_null($p_docRoot)){ - foreach ($p_docRoot->getElementsByTagName("service") AS $item) - { - if ($item->getElementsByTagName("name")->item(0)->nodeValue == $p_serviceName){ + if (!is_null($p_docRoot)) { + foreach ($p_docRoot->getElementsByTagName("service") AS $item) { + if ($item->getElementsByTagName("name")->item(0)->nodeValue == $p_serviceName) { $monitor = $item->getElementsByTagName("monitor"); - if ($monitor->length > 0){ + if ($monitor->length > 0) { $status = $monitor->item(0)->nodeValue; - if ($status == "2"){ + if ($status == "2") { $data = $starting; - } else if ($status == 1){ + } elseif ($status == 1) { //is monitored, but is it running? $pid = $item->getElementsByTagName("pid"); - if ($pid->length == 0){ + if ($pid->length == 0) { $data = $notRunning; } else { //running! } - } else if ($status == 0){ + } elseif ($status == 0) { $data = $notMonitored; } } $process_id = $item->getElementsByTagName("name"); - if ($process_id->length > 0){ + if ($process_id->length > 0) { $data["name"] = $process_id->item(0)->nodeValue; } - + $process_id = $item->getElementsByTagName("pid"); - if ($process_id->length > 0){ + if ($process_id->length > 0) { $data["process_id"] = $process_id->item(0)->nodeValue; $data["status"] = 0; } $uptime = $item->getElementsByTagName("uptime"); - if ($uptime->length > 0){ + if ($uptime->length > 0) { $data["uptime_seconds"] = $uptime->item(0)->nodeValue; } - + $memory = $item->getElementsByTagName("memory"); - if ($memory->length > 0){ + if ($memory->length > 0) { $data["memory_perc"] = $memory->item(0)->getElementsByTagName("percenttotal")->item(0)->nodeValue."%"; $data["memory_kb"] = $memory->item(0)->getElementsByTagName("kilobytetotal")->item(0)->nodeValue; } - + $cpu = $item->getElementsByTagName("cpu"); - if ($cpu->length > 0){ + if ($cpu->length > 0) { $data["cpu_perc"] = $cpu->item(0)->getElementsByTagName("percent")->item(0)->nodeValue."%"; } break; } } } + return $data; } - public static function GetPlatformInfo(){ + public static function GetPlatformInfo() + { $keys = array("release", "machine", "memory", "swap"); - foreach($keys as $key) { + foreach ($keys as $key) { $data[$key] = "UNKNOWN"; } - + $docRoot = self::GetMonitStatus("localhost"); - if (!is_null($docRoot)){ - foreach ($docRoot->getElementsByTagName("platform") AS $item) - { - foreach($keys as $key) { + if (!is_null($docRoot)) { + foreach ($docRoot->getElementsByTagName("platform") AS $item) { + foreach ($keys as $key) { $keyElement = $item->getElementsByTagName($key); - if($keyElement->length > 0) { + if ($keyElement->length > 0) { $data[$key] = $keyElement->item(0)->nodeValue; } } } } - + return $data; } - public static function GetPypoStatus(){ - + public static function GetPypoStatus() + { $component = CcServiceRegisterQuery::create()->findOneByDbName("pypo"); - if (is_null($component)){ + if (is_null($component)) { return null; } else { $ip = $component->getDbIp(); - + $docRoot = self::GetMonitStatus($ip); $data = self::ExtractServiceInformation($docRoot, "airtime-playout"); return $data; } } - - public static function GetLiquidsoapStatus(){ + public static function GetLiquidsoapStatus() + { $component = CcServiceRegisterQuery::create()->findOneByDbName("pypo"); - if (is_null($component)){ + if (is_null($component)) { return null; } else { $ip = $component->getDbIp(); - + $docRoot = self::GetMonitStatus($ip); $data = self::ExtractServiceInformation($docRoot, "airtime-liquidsoap"); return $data; } } - - public static function GetMediaMonitorStatus(){ + public static function GetMediaMonitorStatus() + { $component = CcServiceRegisterQuery::create()->findOneByDbName("media-monitor"); - if (is_null($component)){ + if (is_null($component)) { return null; } else { $ip = $component->getDbIp(); - + $docRoot = self::GetMonitStatus($ip); $data = self::ExtractServiceInformation($docRoot, "airtime-media-monitor"); return $data; } } - - public static function GetIcecastStatus(){ + + public static function GetIcecastStatus() + { $docRoot = self::GetMonitStatus("localhost"); $data = self::ExtractServiceInformation($docRoot, "icecast2"); return $data; } - public static function GetRabbitMqStatus(){ - - if (isset($_SERVER["RABBITMQ_HOST"])){ + public static function GetRabbitMqStatus() + { + if (isset($_SERVER["RABBITMQ_HOST"])) { $rabbitmq_host = $_SERVER["RABBITMQ_HOST"]; } else { $rabbitmq_host = "localhost"; @@ -208,37 +209,38 @@ class Application_Model_Systemstatus return $data; } - - public static function GetDiskInfo(){ + + public static function GetDiskInfo() + { $partions = array(); - - if (isset($_SERVER['AIRTIME_SRV'])){ + + if (isset($_SERVER['AIRTIME_SRV'])) { //connect to DB and find how much total space user has allocated. $totalSpace = Application_Model_Preference::GetDiskQuota(); - + $storPath = Application_Model_MusicDir::getStorDir()->getDirectory(); - + list($usedSpace,) = preg_split("/[\s]+/", exec("du -bs $storPath")); - + $partitions[$totalSpace]->totalSpace = $totalSpace; $partitions[$totalSpace]->totalFreeSpace = $totalSpace - $usedSpace; - Logging::log($partitions[$totalSpace]->totalFreeSpace); + Logging::info($partitions[$totalSpace]->totalFreeSpace); } else { /* First lets get all the watched directories. Then we can group them * into the same partitions by comparing the partition sizes. */ $musicDirs = Application_Model_MusicDir::getWatchedDirs(); $musicDirs[] = Application_Model_MusicDir::getStorDir(); - - foreach($musicDirs as $md){ + + foreach ($musicDirs as $md) { $totalSpace = disk_total_space($md->getDirectory()); - if (!isset($partitions[$totalSpace])){ + if (!isset($partitions[$totalSpace])) { $partitions[$totalSpace] = new StdClass; $partitions[$totalSpace]->totalSpace = $totalSpace; $partitions[$totalSpace]->totalFreeSpace = disk_free_space($md->getDirectory()); } - + $partitions[$totalSpace]->dirs[] = $md->getDirectory(); } } diff --git a/airtime_mvc/application/models/User.php b/airtime_mvc/application/models/User.php index cb0e8fa00..63b82820a 100644 --- a/airtime_mvc/application/models/User.php +++ b/airtime_mvc/application/models/User.php @@ -1,263 +1,319 @@ _userInstance = $this->createUser(); - } - else { + } else { $this->_userInstance = CcSubjsQuery::create()->findPK($userId); - if (is_null($this->_userInstance)){ + if (is_null($this->_userInstance)) { throw new Exception(); } } } - public function getId() { + public function getId() + { return $this->_userInstance->getDbId(); } - public function isGuest() { - return $this->getType() == UTYPE_GUEST; + public function isGuest() + { + return $this->getType() == UTYPE_GUEST; } - public function isHost($showId) { - return $this->isUserType(UTYPE_HOST, $showId); + public function isHostOfShow($showId) + { + $userId = $this->_userInstance->getDbId(); + return CcShowHostsQuery::create() + ->filterByDbShow($showId) + ->filterByDbHost($userId)->count() > 0; } - public function isPM() { + public function isHost() + { + return $this->isUserType(UTYPE_HOST); + } + + public function isPM() + { return $this->isUserType(UTYPE_PROGRAM_MANAGER); } - public function isAdmin() { + public function isAdmin() + { return $this->isUserType(UTYPE_ADMIN); } - public function canSchedule($p_showId) { - $type = $this->getType(); - $result = false; + public function canSchedule($p_showId) + { + $type = $this->getType(); + $result = false; - if ( $type === UTYPE_ADMIN || + if ($type === UTYPE_ADMIN || $type === UTYPE_PROGRAM_MANAGER || - CcShowHostsQuery::create()->filterByDbShow($p_showId)->filterByDbHost($this->getId())->count() > 0 ) - { - $result = true; - } - - return $result; + self::isHostOfShow($p_showId)) { + $result = true; + } + return $result; } - public function isUserType($type, $showId=''){ - if(is_array($type)){ - $result = false; - foreach($type as $t){ - switch($t){ - case UTYPE_ADMIN: - $result = $this->_userInstance->getDbType() === 'A'; - break; - case UTYPE_HOST: - $userId = $this->_userInstance->getDbId(); - $result = CcShowHostsQuery::create()->filterByDbShow($showId)->filterByDbHost($userId)->count() > 0; - break; - case UTYPE_PROGRAM_MANAGER: - $result = $this->_userInstance->getDbType() === 'P'; - break; - } - if($result){ - return $result; - } - } - }else{ - switch($type){ - case UTYPE_ADMIN: - return $this->_userInstance->getDbType() === 'A'; - case UTYPE_HOST: - $userId = $this->_userInstance->getDbId(); - return CcShowHostsQuery::create()->filterByDbShow($showId)->filterByDbHost($userId)->count() > 0; - case UTYPE_PROGRAM_MANAGER: - return $this->_userInstance->getDbType() === 'P'; - } - } + // TODO : refactor code to only accept arrays for isUserType and + // simplify code even further + public function isUserType($type) + { + if (!is_array($type)) { + $type = array($type); + } + $real_type = $this->_userInstance->getDbType(); + return in_array($real_type, $type); } - public function setLogin($login){ + public function setLogin($login) + { $user = $this->_userInstance; $user->setDbLogin($login); } - public function setPassword($password){ + public function setPassword($password) + { $user = $this->_userInstance; $user->setDbPass(md5($password)); } - public function setFirstName($firstName){ + public function setFirstName($firstName) + { $user = $this->_userInstance; $user->setDbFirstName($firstName); } - public function setLastName($lastName){ + public function setLastName($lastName) + { $user = $this->_userInstance; $user->setDbLastName($lastName); } - public function setType($type){ + public function setType($type) + { $user = $this->_userInstance; $user->setDbType($type); } - public function setEmail($email){ + public function setEmail($email) + { $user = $this->_userInstance; $user->setDbEmail(strtolower($email)); } - - public function setCellPhone($cellPhone){ + + public function setCellPhone($cellPhone) + { $user = $this->_userInstance; $user->setDbCellPhone($cellPhone); } - public function setSkype($skype){ + public function setSkype($skype) + { $user = $this->_userInstance; $user->setDbSkypeContact($skype); } - public function setJabber($jabber){ + public function setJabber($jabber) + { $user = $this->_userInstance; $user->setDbJabberContact($jabber); } - public function getLogin(){ + public function getLogin() + { $user = $this->_userInstance; + return $user->getDbLogin(); } - public function getPassword(){ + public function getPassword() + { $user = $this->_userInstance; + return $user->getDbPass(); } - public function getFirstName(){ + public function getFirstName() + { $user = $this->_userInstance; + return $user->getDbFirstName(); } - public function getLastName(){ + public function getLastName() + { $user = $this->_userInstance; + return $user->getDbLastName(); } - public function getType(){ + public function getType() + { $user = $this->_userInstance; + return $user->getDbType(); } - public function getEmail(){ + public function getEmail() + { $user = $this->_userInstance; + return $user->getDbEmail(); } - - public function getCellPhone(){ + + public function getCellPhone() + { $user = $this->_userInstance; + return $user->getDbCellPhone(); } - public function getSkype(){ + public function getSkype() + { $user = $this->_userInstance; + return $user->getDbSkypeContact(); } - public function getJabber(){ + public function getJabber() + { $user = $this->_userInstance; + return $user->getDbJabberContact(); } - public function save(){ + public function save() + { $this->_userInstance->save(); } - public function delete(){ - if (!$this->_userInstance->isDeleted()) + public function delete() + { + if (!$this->_userInstance->isDeleted()) { $this->_userInstance->delete(); + } + } + public function getOwnedFiles() + { + $user = $this->_userInstance; + // do we need a find call at the end here? + return $user->getCcFilessRelatedByDbOwnerId(); } - private function createUser() { + public function donateFilesTo($user) // $user is object not user id + { + $my_files = $this->getOwnedFiles(); + foreach ($my_files as $file) { + $file->reassignTo($user); + } + } + + public function deleteAllFiles() + { + $my_files = $this->getOwnedFiles(); + foreach ($files as $file) { + $file->delete(); + } + } + + private function createUser() + { $user = new CcSubjs(); + return $user; } - public static function getUsers($type, $search=NULL) + public static function getUsersOfType($type) { - $con = Propel::getConnection(); + return CcSubjsQuery::create()->filterByDbType($type)->find(); + } + + public static function getFirstAdmin() { + $admins = Application_Model_User::getUsersOfType('A'); + if (count($admins) > 0) { // found admin => pick first one + return $admins[0]; + } else { + Logging::warn("Warning. no admins found in database"); + return null; + } + } + + public static function getFirstAdminId() + { + $admin = self::getFirstAdmin(); + if ($admin) { + return $admin->getDbId(); + } else { + return null; + } + } + + public static function getUsers(array $type, $search=null) + { + $con = Propel::getConnection(); $sql_gen = "SELECT login AS value, login AS label, id as index FROM cc_subjs "; - $sql = $sql_gen; + $sql = $sql_gen; - if (is_array($type)) { - for($i=0; $iquery($sql)->fetchAll();; + return Application_Common_Database::prepareAndExecute($sql, $params, "all"); } - public static function getUserCount($type=NULL){ + public static function getUserCount() + { $con = Propel::getConnection(); - $sql = ''; - $sql_gen = "SELECT count(*) AS cnt FROM cc_subjs "; + $sql_gen = "SELECT count(*) AS cnt FROM cc_subjs"; - if (!isset($type)) { - $sql = $sql_gen; - } - else{ - if (is_array($type)) { - for ($i=0; $iquery($sql_gen)->fetchColumn(0); - $sql = $sql_gen ." WHERE (". $sql_type.") "; - } - - $query = $con->query($sql)->fetchColumn(0); - return ($query !== false) ? $query : NULL; + return ($query !== false) ? $query : null; } - public static function getHosts($search=NULL) { + public static function getHosts($search=null) + { return Application_Model_User::getUsers(array('H'), $search); } - public static function getUsersDataTablesInfo($datatables) { + public static function getUsersDataTablesInfo($datatables) + { - $con = Propel::getConnection(CcSubjsPeer::DATABASE_NAME); + $con = Propel::getConnection(CcSubjsPeer::DATABASE_NAME); $displayColumns = array("id", "login", "first_name", "last_name", "type"); $fromTable = "cc_subjs"; @@ -273,8 +329,8 @@ class Application_Model_User { $res = Application_Model_Datatables::findEntries($con, $displayColumns, $fromTable, $datatables); // mark record which is for the current user - foreach($res['aaData'] as &$record){ - if($record['login'] == $username){ + foreach ($res['aaData'] as &$record) { + if ($record['login'] == $username) { $record['delete'] = "self"; } else { $record['delete'] = ""; @@ -284,39 +340,32 @@ class Application_Model_User { return $res; } - public static function getUserData($id){ - $con = Propel::getConnection(); - - $sql = "SELECT login, first_name, last_name, type, id, email, cell_phone, skype_contact, jabber_contact" - ." FROM cc_subjs" - ." WHERE id = $id"; - - return $con->query($sql)->fetch(); + public static function getUserData($id) + { + $sql = << $id), 'single'); } - public static function GetUserID($login){ - $user = CcSubjsQuery::create()->findOneByDbLogin($login); - if (is_null($user)){ - return -1; - } else { - return $user->getDbId(); - } - } - - public static function GetCurrentUser() { + public static function getCurrentUser() + { $userinfo = Zend_Auth::getInstance()->getStorage()->read(); - - if (is_null($userinfo)){ + if (is_null($userinfo)) { + return null; + } + try { + return new self($userinfo->id); + } catch (Exception $e) { + //we get here if $userinfo->id is defined, but doesn't exist + //in the database anymore. + Zend_Auth::getInstance()->clearIdentity(); + return null; - } else { - try { - return new self($userinfo->id); - } catch (Exception $e){ - //we get here if $userinfo->id is defined, but doesn't exist - //in the database anymore. - Zend_Auth::getInstance()->clearIdentity(); - return null; - } } } } diff --git a/airtime_mvc/application/models/Webstream.php b/airtime_mvc/application/models/Webstream.php new file mode 100644 index 000000000..45d3caf9a --- /dev/null +++ b/airtime_mvc/application/models/Webstream.php @@ -0,0 +1,372 @@ +webstream = CcWebstreamQuery::create()->findPK($webstream); + if (is_null($this->webstream)) { + throw new Exception(); + } + } else { + $this->webstream = $webstream; + } + } + + public function getOrm() + { + return $this->webstream; + } + + public function getName() + { + return $this->webstream->getDbName(); + } + + public function getId() + { + return $this->webstream->getDbId(); + } + + public function getCreatorId() + { + return $this->Webstream->getCcSubjs()->getDbId(); + } + + public function getLastModified($p_type) + { + return $this->webstream->getDbMtime(); + } + + public function getDefaultLength() + { + $dateString = $this->webstream->getDbLength(); + $arr = explode(":", $dateString); + if (count($arr) == 3) { + list($hours, $min, $sec) = $arr; + $di = new DateInterval("PT{$hours}H{$min}M{$sec}S"); + + return $di->format("%Hh %Im"); + } + + return ""; + } + + public function getLength() + { + return $this->getDefaultLength(); + } + + public function getDescription() + { + return $this->webstream->getDbDescription(); + } + + public function getUrl() + { + return $this->webstream->getDbUrl(); + } + + public function getMetadata() + { + $subjs = CcSubjsQuery::create()->findPK($this->webstream->getDbCreatorId()); + + $username = $subjs->getDbLogin(); + + return array( + "name" => $this->webstream->getDbName(), + "length" => $this->webstream->getDbLength(), + "description" => $this->webstream->getDbDescription(), + "login" => $username, + "url" => $this->webstream->getDbUrl(), + ); + } + + public static function deleteStreams($p_ids, $p_userId) + { + $leftOver = self::streamsNotOwnedByUser($p_ids, $p_userId); + if (count($leftOver) == 0) { + CcWebstreamQuery::create()->findPKs($p_ids)->delete(); + } else { + throw new Exception("Invalid user permissions"); + } + } + + // This function returns that are not owen by $p_user_id among $p_ids + private static function streamsNotOwnedByUser($p_ids, $p_userId) + { + $ownedByUser = CcWebstreamQuery::create()->filterByDbCreatorId($p_userId)->find()->getData(); + $ownedStreams = array(); + foreach ($ownedByUser as $pl) { + if (in_array($pl->getDbId(), $p_ids)) { + $ownedStreams[] = $pl->getDbId(); + } + } + + $leftOvers = array_diff($p_ids, $ownedStreams); + + return $leftOvers; + } + + public static function analyzeFormData($parameters) + { + $valid = array("length" => array(true, ''), + "url" => array(true, ''), + "name" => array(true, '')); + + $di = null; + $length = $parameters["length"]; + $result = preg_match("/^(?:([0-9]{1,2})h)?\s*(?:([0-9]{1,2})m)?$/", $length, $matches); + + $invalid_date_interval = false; + if ($result == 1 && count($matches) == 2) { + $hours = $matches[1]; + $minutes = 0; + } elseif ($result == 1 && count($matches) == 3) { + $hours = $matches[1]; + $minutes = $matches[2]; + } else { + $invalid_date_interval = true; + } + + if (!$invalid_date_interval) { + + //Due to the way our Regular Expression is set up, we could have $minutes or $hours + //not set. Do simple test here + if (!is_numeric($hours)) { + $hours = 0; + } + if (!is_numeric($minutes)) { + $minutes = 0; + } + + //minutes cannot be over 59. Need to convert anything > 59 minutes into hours. + $hours += intval($minutes/60); + $minutes = $minutes%60; + + $di = new DateInterval("PT{$hours}H{$minutes}M"); + + $totalMinutes = $di->h * 60 + $di->i; + + if ($totalMinutes == 0) { + $valid['length'][0] = false; + $valid['length'][1] = 'Length needs to be greater than 0 minutes'; + } + + } else { + $valid['length'][0] = false; + $valid['length'][1] = 'Length should be of form "00h 00m"'; + } + + $url = $parameters["url"]; + //simple validator that checks to make sure that the url starts with + //http(s), + //and that the domain is at least 1 letter long + $result = preg_match("/^(http|https):\/\/.+/", $url, $matches); + + $mime = null; + $mediaUrl = null; + if ($result == 0) { + $valid['url'][0] = false; + $valid['url'][1] = 'URL should be of form "http://domain"'; + } elseif (strlen($url) > 512) { + $valid['url'][0] = false; + $valid['url'][1] = 'URL should be 512 characters or less'; + } else { + + try { + list($mime, $content_length_found) = self::discoverStreamMime($url); + if (is_null($mime)) { + throw new Exception("No MIME type found for webstream."); + } + $mediaUrl = self::getMediaUrl($url, $mime, $content_length_found); + + if (preg_match("/(x-mpegurl)|(xspf\+xml)|(pls\+xml)/", $mime)) { + list($mime, $content_length_found) = self::discoverStreamMime($mediaUrl); + } + } catch (Exception $e) { + $valid['url'][0] = false; + $valid['url'][1] = $e->getMessage(); + } + } + + $name = $parameters["name"]; + if (strlen($name) == 0) { + $valid['name'][0] = false; + $valid['name'][1] = 'Webstream name cannot be empty'; + } + + $id = $parameters["id"]; + + return array($valid, $mime, $mediaUrl, $di); + } + + public static function isValid($analysis) + { + foreach ($analysis as $k => $v) { + if ($v[0] === false) { + return false; + } + } + return true; + } + + // TODO : Fix this interface + //This function should not be defined in the interface. + public function setMetadata($key, $val) + { + throw new Exception("Not implemented."); + } + + public function setName($name) + { + $this->webstream->setDbName($name); + } + + public function setLastPlayed($timestamp) + { + $this->webstream->setDbLPtime($timestamp); + $this->webstream->save(); + } + + private static function getUrlData($url) + { + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_HEADER, 0); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + + // grab URL and pass it to the browser + //TODO: What if invalid url? + $content = curl_exec($ch); + + // close cURL resource, and free up system resources + curl_close($ch); + + return $content; + } + + private static function getXspfUrl($url) + { + $content = self::getUrlData($url); + + $dom = new DOMDocument; + //TODO: What if invalid xml? + $dom->loadXML($content); + $tracks = $dom->getElementsByTagName('track'); + + foreach ($tracks as $track) { + $locations = $track->getElementsByTagName('location'); + foreach ($locations as $loc) { + return $loc->nodeValue; + } + } + + throw new Exception("Could not parse XSPF playlist"); + } + + private static function getPlsUrl($url) + { + $content = self::getUrlData($url); + $ini = parse_ini_string($content, true); + + if ($ini !== false && isset($ini["playlist"]) && isset($ini["playlist"]["File1"])) { + return $ini["playlist"]["File1"]; + } + + throw new Exception("Could not parse PLS playlist"); + } + + private static function getM3uUrl($url) + { + $content = self::getUrlData($url); + + //split into lines: + $delim = "\n"; + if (strpos($content, "\r\n") !== false) { + $delim = "\r\n"; + } + $lines = explode("$delim", $content); + #$lines = preg_split('/$\R?^/m', $content); + + if (count($lines) > 0) { + return $lines[0]; + } + + throw new Exception("Could not parse M3U playlist"); + } + + private static function getMediaUrl($url, $mime, $content_length_found) + { + + if (preg_match("/x-mpegurl/", $mime)) { + $media_url = self::getM3uUrl($url); + } elseif (preg_match("/xspf\+xml/", $mime)) { + $media_url = self::getXspfUrl($url); + } elseif (preg_match("/pls\+xml/", $mime)) { + $media_url = self::getPlsUrl($url); + } elseif (preg_match("/(mpeg|ogg)/", $mime)) { + if ($content_length_found) { + throw new Exception("Invalid webstream - This appears to be a file download."); + } + $media_url = $url; + } else { + throw new Exception("Unrecognized stream type: $mime"); + } + + return $media_url; + + } + + private static function discoverStreamMime($url) + { + //TODO: What if invalid URL? + $headers = get_headers($url); + $mime = null; + $content_length_found = false; + foreach ($headers as $h) { + if (preg_match("/^content-type:/i", $h)) { + list(, $value) = explode(":", $h, 2); + $mime = trim($value); + } + if (preg_match("/^content-length:/i", $h)) { + $content_length_found = true; + } + } + + return array($mime, $content_length_found); + } + + public static function save($parameters, $mime, $mediaUrl, $di) + { + $userInfo = Zend_Auth::getInstance()->getStorage()->read(); + + $id = $parameters['id']; + if ($id != -1) { + $webstream = CcWebstreamQuery::create()->findPK($id); + } else { + $webstream = new CcWebstream(); + } + + $webstream->setDbName($parameters["name"]); + $webstream->setDbDescription($parameters["description"]); + $webstream->setDbUrl($mediaUrl); + + $dblength = $di->format("%H:%I"); + $webstream->setDbLength($dblength); + $webstream->setDbCreatorId($userInfo->id); + $webstream->setDbUtime(new DateTime("now", new DateTimeZone('UTC'))); + $webstream->setDbMtime(new DateTime("now", new DateTimeZone('UTC'))); + + $ws = new Application_Model_Webstream($webstream); + + $webstream->setDbMime($mime); + $webstream->save(); + + return $webstream->getDbId(); + } +} diff --git a/airtime_mvc/application/models/airtime/CcBlock.php b/airtime_mvc/application/models/airtime/CcBlock.php new file mode 100644 index 000000000..da43e76f0 --- /dev/null +++ b/airtime_mvc/application/models/airtime/CcBlock.php @@ -0,0 +1,100 @@ +utime === null) { + return null; + } + + try { + $dt = new DateTime($this->utime, new DateTimeZone("UTC")); + } catch (Exception $x) { + throw new PropelException("Internally stored date/time/timestamp value could not be converted to DateTime: " . var_export($this->utime, true), $x); + } + + if ($format === null) { + // Because propel.useDateTimeClass is TRUE, we return a DateTime object. + return $dt; + } elseif (strpos($format, '%') !== false) { + return strftime($format, $dt->format('U')); + } else { + return $dt->format($format); + } + } + + /** + * Get the [optionally formatted] temporal [mtime] column value. + * + * + * @param string $format The date/time format string (either date()-style or strftime()-style). + * If format is NULL, then the raw DateTime object will be returned. + * @return mixed Formatted date/time value as string or DateTime object (if format is NULL), NULL if column is NULL + * @throws PropelException - if unable to parse/validate the date/time value. + */ + public function getDbMtime($format = 'Y-m-d H:i:s') + { + if ($this->mtime === null) { + return null; + } + + try { + $dt = new DateTime($this->mtime, new DateTimeZone("UTC")); + } catch (Exception $x) { + throw new PropelException("Internally stored date/time/timestamp value could not be converted to DateTime: " . var_export($this->mtime, true), $x); + } + + if ($format === null) { + // Because propel.useDateTimeClass is TRUE, we return a DateTime object. + return $dt; + } elseif (strpos($format, '%') !== false) { + return strftime($format, $dt->format('U')); + } else { + return $dt->format($format); + } + } + + /** + * Computes the value of the aggregate column length + * Overridden to provide a default of 00:00:00 if the block is empty. + * + * @param PropelPDO $con A connection object + * + * @return mixed The scalar result from the aggregate query + */ + public function computeDbLength(PropelPDO $con) + { + $stmt = $con->prepare('SELECT SUM(cliplength) FROM "cc_blockcontents" WHERE cc_blockcontents.BLOCK_ID = :p1'); + $stmt->bindValue(':p1', $this->getDbId()); + $stmt->execute(); + $length = $stmt->fetchColumn(); + + if (is_null($length)) { + $length = "00:00:00"; + } + + return $length; + } +} // CcBlock diff --git a/install_minimal/upgrades/airtime-1.9.0/propel/airtime/CcPermsPeer.php b/airtime_mvc/application/models/airtime/CcBlockPeer.php similarity index 79% rename from install_minimal/upgrades/airtime-1.9.0/propel/airtime/CcPermsPeer.php rename to airtime_mvc/application/models/airtime/CcBlockPeer.php index 9b5b51837..491ea67ee 100644 --- a/install_minimal/upgrades/airtime-1.9.0/propel/airtime/CcPermsPeer.php +++ b/airtime_mvc/application/models/airtime/CcBlockPeer.php @@ -3,7 +3,7 @@ /** - * Skeleton subclass for performing query and update operations on the 'cc_perms' table. + * Skeleton subclass for performing query and update operations on the 'cc_block' table. * * * @@ -13,6 +13,6 @@ * * @package propel.generator.airtime */ -class CcPermsPeer extends BaseCcPermsPeer { +class CcBlockPeer extends BaseCcBlockPeer { -} // CcPermsPeer +} // CcBlockPeer diff --git a/install_minimal/upgrades/airtime-1.9.0/propel/airtime/CcPermsQuery.php b/airtime_mvc/application/models/airtime/CcBlockQuery.php similarity index 78% rename from install_minimal/upgrades/airtime-1.9.0/propel/airtime/CcPermsQuery.php rename to airtime_mvc/application/models/airtime/CcBlockQuery.php index 96cf4e4de..7c3b1ece5 100644 --- a/install_minimal/upgrades/airtime-1.9.0/propel/airtime/CcPermsQuery.php +++ b/airtime_mvc/application/models/airtime/CcBlockQuery.php @@ -3,7 +3,7 @@ /** - * Skeleton subclass for performing query and update operations on the 'cc_perms' table. + * Skeleton subclass for performing query and update operations on the 'cc_block' table. * * * @@ -13,6 +13,6 @@ * * @package propel.generator.airtime */ -class CcPermsQuery extends BaseCcPermsQuery { +class CcBlockQuery extends BaseCcBlockQuery { -} // CcPermsQuery +} // CcBlockQuery diff --git a/airtime_mvc/application/models/airtime/CcBlockcontents.php b/airtime_mvc/application/models/airtime/CcBlockcontents.php new file mode 100644 index 000000000..caae46f6a --- /dev/null +++ b/airtime_mvc/application/models/airtime/CcBlockcontents.php @@ -0,0 +1,113 @@ +fadein = $dt->format('H:i:s.u'); + } else { + $this->fadein = $dt->format('H:i:s').".".$microsecond; + } + $this->modifiedColumns[] = CcBlockcontentsPeer::FADEIN; + + return $this; + } // setDbFadein() + + /** + * + * @param String in format SS.uuuuuu, Datetime, or DateTime accepted string. + * + * @return CcBlockcontents The current object (for fluent API support) + */ + public function setDbFadeout($v) + { + $microsecond = 0; + if ($v instanceof DateTime) { + $dt = $v; + } + else if (preg_match('/^[0-9]{1,2}(\.\d{1,6})?$/', $v)) { + // in php 5.3.2 createFromFormat() with "u" is not supported(bug) + // Hence we need to do parsing. + $info = explode('.', $v); + $microsecond = $info[1]; + $dt = DateTime::createFromFormat("s", $info[0]); + } + else { + try { + $dt = new DateTime($v); + } catch (Exception $x) { + throw new PropelException('Error parsing date/time value: ' . var_export($v, true), $x); + } + } + + if ($microsecond == 0) { + $this->fadeout = $dt->format('H:i:s.u'); + } else { + $this->fadeout = $dt->format('H:i:s').".".$microsecond; + } + $this->modifiedColumns[] = CcBlockcontentsPeer::FADEOUT; + + return $this; + } // setDbFadeout() + +} // CcBlockcontents diff --git a/install_minimal/upgrades/airtime-1.9.0/propel/airtime/CcAccessPeer.php b/airtime_mvc/application/models/airtime/CcBlockcontentsPeer.php similarity index 73% rename from install_minimal/upgrades/airtime-1.9.0/propel/airtime/CcAccessPeer.php rename to airtime_mvc/application/models/airtime/CcBlockcontentsPeer.php index ee70081ba..024cb0523 100644 --- a/install_minimal/upgrades/airtime-1.9.0/propel/airtime/CcAccessPeer.php +++ b/airtime_mvc/application/models/airtime/CcBlockcontentsPeer.php @@ -3,7 +3,7 @@ /** - * Skeleton subclass for performing query and update operations on the 'cc_access' table. + * Skeleton subclass for performing query and update operations on the 'cc_blockcontents' table. * * * @@ -13,6 +13,6 @@ * * @package propel.generator.airtime */ -class CcAccessPeer extends BaseCcAccessPeer { +class CcBlockcontentsPeer extends BaseCcBlockcontentsPeer { -} // CcAccessPeer +} // CcBlockcontentsPeer diff --git a/airtime_mvc/application/models/airtime/CcBlockcontentsQuery.php b/airtime_mvc/application/models/airtime/CcBlockcontentsQuery.php new file mode 100644 index 000000000..72746d075 --- /dev/null +++ b/airtime_mvc/application/models/airtime/CcBlockcontentsQuery.php @@ -0,0 +1,18 @@ +setDbOwnerId( $user->getDbId() ); + $this->save(); + } } // CcFiles diff --git a/airtime_mvc/application/models/airtime/CcPlaylistcontents.php b/airtime_mvc/application/models/airtime/CcPlaylistcontents.php index b5125de32..ab0aa6d56 100644 --- a/airtime_mvc/application/models/airtime/CcPlaylistcontents.php +++ b/airtime_mvc/application/models/airtime/CcPlaylistcontents.php @@ -43,11 +43,16 @@ class CcPlaylistcontents extends BaseCcPlaylistcontents { */ public function setDbFadein($v) { + $microsecond = 0; if ($v instanceof DateTime) { $dt = $v; } else if (preg_match('/^[0-9]{1,2}(\.\d{1,6})?$/', $v)) { - $dt = DateTime::createFromFormat("s.u", $v); + // in php 5.3.2 createFromFormat() with "u" is not supported(bug) + // Hence we need to do parsing. + $info = explode('.', $v); + $microsecond = $info[1]; + $dt = DateTime::createFromFormat("s", $info[0]); } else { try { @@ -57,7 +62,11 @@ class CcPlaylistcontents extends BaseCcPlaylistcontents { } } - $this->fadein = $dt->format('H:i:s.u'); + if ($microsecond == 0) { + $this->fadein = $dt->format('H:i:s.u'); + } else { + $this->fadein = $dt->format('H:i:s').".".$microsecond; + } $this->modifiedColumns[] = CcPlaylistcontentsPeer::FADEIN; return $this; @@ -71,11 +80,16 @@ class CcPlaylistcontents extends BaseCcPlaylistcontents { */ public function setDbFadeout($v) { + $microsecond = 0; if ($v instanceof DateTime) { $dt = $v; } else if (preg_match('/^[0-9]{1,2}(\.\d{1,6})?$/', $v)) { - $dt = DateTime::createFromFormat("s.u", $v); + // in php 5.3.2 createFromFormat() with "u" is not supported(bug) + // Hence we need to do parsing. + $info = explode('.', $v); + $microsecond = $info[1]; + $dt = DateTime::createFromFormat("s", $info[0]); } else { try { @@ -85,7 +99,11 @@ class CcPlaylistcontents extends BaseCcPlaylistcontents { } } - $this->fadeout = $dt->format('H:i:s.u'); + if ($microsecond == 0) { + $this->fadeout = $dt->format('H:i:s.u'); + } else { + $this->fadeout = $dt->format('H:i:s').".".$microsecond; + } $this->modifiedColumns[] = CcPlaylistcontentsPeer::FADEOUT; return $this; diff --git a/install_minimal/upgrades/airtime-1.9.0/propel/airtime/CcAccess.php b/airtime_mvc/application/models/airtime/CcPlaylistcriteria.php similarity index 61% rename from install_minimal/upgrades/airtime-1.9.0/propel/airtime/CcAccess.php rename to airtime_mvc/application/models/airtime/CcPlaylistcriteria.php index 2b3d4443d..ae4232cdb 100644 --- a/install_minimal/upgrades/airtime-1.9.0/propel/airtime/CcAccess.php +++ b/airtime_mvc/application/models/airtime/CcPlaylistcriteria.php @@ -3,7 +3,7 @@ /** - * Skeleton subclass for representing a row from the 'cc_access' table. + * Skeleton subclass for representing a row from the 'cc_playlistcriteria' table. * * * @@ -13,6 +13,6 @@ * * @package propel.generator.airtime */ -class CcAccess extends BaseCcAccess { +class CcPlaylistcriteria extends BaseCcPlaylistcriteria { -} // CcAccess +} // CcPlaylistcriteria diff --git a/install_minimal/upgrades/airtime-1.9.0/propel/airtime/CcPlaylistcontentsPeer.php b/airtime_mvc/application/models/airtime/CcPlaylistcriteriaPeer.php similarity index 71% rename from install_minimal/upgrades/airtime-1.9.0/propel/airtime/CcPlaylistcontentsPeer.php rename to airtime_mvc/application/models/airtime/CcPlaylistcriteriaPeer.php index 00210575b..b3e34a3d0 100644 --- a/install_minimal/upgrades/airtime-1.9.0/propel/airtime/CcPlaylistcontentsPeer.php +++ b/airtime_mvc/application/models/airtime/CcPlaylistcriteriaPeer.php @@ -3,7 +3,7 @@ /** - * Skeleton subclass for performing query and update operations on the 'cc_playlistcontents' table. + * Skeleton subclass for performing query and update operations on the 'cc_playlistcriteria' table. * * * @@ -13,6 +13,6 @@ * * @package propel.generator.airtime */ -class CcPlaylistcontentsPeer extends BaseCcPlaylistcontentsPeer { +class CcPlaylistcriteriaPeer extends BaseCcPlaylistcriteriaPeer { -} // CcPlaylistcontentsPeer +} // CcPlaylistcriteriaPeer diff --git a/install_minimal/upgrades/airtime-1.9.0/propel/airtime/CcPlaylistcontentsQuery.php b/airtime_mvc/application/models/airtime/CcPlaylistcriteriaQuery.php similarity index 71% rename from install_minimal/upgrades/airtime-1.9.0/propel/airtime/CcPlaylistcontentsQuery.php rename to airtime_mvc/application/models/airtime/CcPlaylistcriteriaQuery.php index cd63eb96e..a3067c45d 100644 --- a/install_minimal/upgrades/airtime-1.9.0/propel/airtime/CcPlaylistcontentsQuery.php +++ b/airtime_mvc/application/models/airtime/CcPlaylistcriteriaQuery.php @@ -3,7 +3,7 @@ /** - * Skeleton subclass for performing query and update operations on the 'cc_playlistcontents' table. + * Skeleton subclass for performing query and update operations on the 'cc_playlistcriteria' table. * * * @@ -13,6 +13,6 @@ * * @package propel.generator.airtime */ -class CcPlaylistcontentsQuery extends BaseCcPlaylistcontentsQuery { +class CcPlaylistcriteriaQuery extends BaseCcPlaylistcriteriaQuery { -} // CcPlaylistcontentsQuery +} // CcPlaylistcriteriaQuery diff --git a/airtime_mvc/application/models/airtime/CcSchedule.php b/airtime_mvc/application/models/airtime/CcSchedule.php index 75a01e758..db7fb19a7 100644 --- a/airtime_mvc/application/models/airtime/CcSchedule.php +++ b/airtime_mvc/application/models/airtime/CcSchedule.php @@ -107,11 +107,16 @@ class CcSchedule extends BaseCcSchedule { */ public function setDbFadeIn($v) { + $microsecond = 0; if ($v instanceof DateTime) { $dt = $v; } else if (preg_match('/^[0-9]{1,2}(\.\d{1,6})?$/', $v)) { - $dt = DateTime::createFromFormat("s.u", $v); + // in php 5.3.2 createFromFormat() with "u" is not supported(bug) + // Hence we need to do parsing. + $info = explode('.', $v); + $microsecond = $info[1]; + $dt = DateTime::createFromFormat("s", $info[0]); } else { try { @@ -120,7 +125,12 @@ class CcSchedule extends BaseCcSchedule { throw new PropelException('Error parsing date/time value: ' . var_export($v, true), $x); } } - $this->fade_in = $dt->format('H:i:s.u'); + + if ($microsecond == 0) { + $this->fade_in = $dt->format('H:i:s.u'); + } else { + $this->fade_in = $dt->format('H:i:s').".".$microsecond; + } $this->modifiedColumns[] = CcSchedulePeer::FADE_IN; return $this; @@ -134,11 +144,16 @@ class CcSchedule extends BaseCcSchedule { */ public function setDbFadeOut($v) { + $microsecond = 0; if ($v instanceof DateTime) { $dt = $v; } else if (preg_match('/^[0-9]{1,2}(\.\d{1,6})?$/', $v)) { - $dt = DateTime::createFromFormat("s.u", $v); + // in php 5.3.2 createFromFormat() with "u" is not supported(bug) + // Hence we need to do parsing. + $info = explode('.', $v); + $microsecond = $info[1]; + $dt = DateTime::createFromFormat("s", $info[0]); } else { try { @@ -148,7 +163,11 @@ class CcSchedule extends BaseCcSchedule { } } - $this->fade_out = $dt->format('H:i:s.u'); + if ($microsecond == 0) { + $this->fade_out = $dt->format('H:i:s.u'); + } else { + $this->fade_out = $dt->format('H:i:s').".".$microsecond; + } $this->modifiedColumns[] = CcSchedulePeer::FADE_OUT; return $this; diff --git a/airtime_mvc/application/models/airtime/CcShowInstances.php b/airtime_mvc/application/models/airtime/CcShowInstances.php index ed598c5ee..4625d1f91 100644 --- a/airtime_mvc/application/models/airtime/CcShowInstances.php +++ b/airtime_mvc/application/models/airtime/CcShowInstances.php @@ -139,40 +139,40 @@ class CcShowInstances extends BaseCcShowInstances { $this->save($con); } - /** - * Computes the value of the aggregate column time_filled - * - * @param PropelPDO $con A connection object - * - * @return mixed The scalar result from the aggregate query - */ - public function computeDbTimeFilled(PropelPDO $con) - { - $stmt = $con->prepare('SELECT SUM(clip_length) FROM "cc_schedule" WHERE cc_schedule.INSTANCE_ID = :p1'); - $stmt->bindValue(':p1', $this->getDbId()); - $stmt->execute(); - return $stmt->fetchColumn(); - } - - /** - * Updates the aggregate column time_filled - * - * @param PropelPDO $con A connection object - */ - public function updateDbTimeFilled(PropelPDO $con) + /** + * Computes the value of the aggregate column time_filled + * + * @param PropelPDO $con A connection object + * + * @return mixed The scalar result from the aggregate query + */ + public function computeDbTimeFilled(PropelPDO $con) + { + $stmt = $con->prepare('SELECT SUM(clip_length) FROM "cc_schedule" WHERE cc_schedule.INSTANCE_ID = :p1'); + $stmt->bindValue(':p1', $this->getDbId()); + $stmt->execute(); + return $stmt->fetchColumn(); + } + + /** + * Updates the aggregate column time_filled + * + * @param PropelPDO $con A connection object + */ + public function updateDbTimeFilled(PropelPDO $con) { $timefilled = $this->computeDbTimeFilled($con); if(is_null($timefilled)){ $timefilled = "00:00:00"; - } - $this->setDbTimeFilled($timefilled); - $this->save($con); + } + $this->setDbTimeFilled($timefilled); + $this->save($con); } public function preInsert(PropelPDO $con = null) { - $now = new DateTime("now", new DateTimeZone("UTC")); - $this->setDbCreated($now); - return true; + $now = new DateTime("now", new DateTimeZone("UTC")); + $this->setDbCreated($now); + return true; } } // CcShowInstances diff --git a/install_minimal/upgrades/airtime-1.9.0/propel/airtime/CcCountry.php b/airtime_mvc/application/models/airtime/CcWebstream.php similarity index 65% rename from install_minimal/upgrades/airtime-1.9.0/propel/airtime/CcCountry.php rename to airtime_mvc/application/models/airtime/CcWebstream.php index 9de4e81a8..1777d12cd 100644 --- a/install_minimal/upgrades/airtime-1.9.0/propel/airtime/CcCountry.php +++ b/airtime_mvc/application/models/airtime/CcWebstream.php @@ -3,7 +3,7 @@ /** - * Skeleton subclass for representing a row from the 'cc_country' table. + * Skeleton subclass for representing a row from the 'cc_webstream' table. * * * @@ -13,6 +13,6 @@ * * @package propel.generator.airtime */ -class CcCountry extends BaseCcCountry { +class CcWebstream extends BaseCcWebstream { -} // CcCountry +} // CcWebstream diff --git a/airtime_mvc/application/models/airtime/CcWebstreamMetadata.php b/airtime_mvc/application/models/airtime/CcWebstreamMetadata.php new file mode 100644 index 000000000..6d65037f0 --- /dev/null +++ b/airtime_mvc/application/models/airtime/CcWebstreamMetadata.php @@ -0,0 +1,18 @@ +prepare($sql); - $stmt->bindValue(':f1', $time); - $stmt->bindValue(':p1', $row->getDbId()); - $stmt->execute(); - } -} diff --git a/airtime_mvc/application/models/airtime/map/CcBlockTableMap.php b/airtime_mvc/application/models/airtime/map/CcBlockTableMap.php new file mode 100644 index 000000000..4495c9b1d --- /dev/null +++ b/airtime_mvc/application/models/airtime/map/CcBlockTableMap.php @@ -0,0 +1,76 @@ +setName('cc_block'); + $this->setPhpName('CcBlock'); + $this->setClassname('CcBlock'); + $this->setPackage('airtime'); + $this->setUseIdGenerator(true); + $this->setPrimaryKeyMethodInfo('cc_block_id_seq'); + // columns + $this->addPrimaryKey('ID', 'DbId', 'INTEGER', true, null, null); + $this->addColumn('NAME', 'DbName', 'VARCHAR', true, 255, ''); + $this->addColumn('MTIME', 'DbMtime', 'TIMESTAMP', false, 6, null); + $this->addColumn('UTIME', 'DbUtime', 'TIMESTAMP', false, 6, null); + $this->addForeignKey('CREATOR_ID', 'DbCreatorId', 'INTEGER', 'cc_subjs', 'ID', false, null, null); + $this->addColumn('DESCRIPTION', 'DbDescription', 'VARCHAR', false, 512, null); + $this->addColumn('LENGTH', 'DbLength', 'VARCHAR', false, null, '00:00:00'); + $this->addColumn('TYPE', 'DbType', 'VARCHAR', false, 7, 'static'); + // validators + } // initialize() + + /** + * Build the RelationMap objects for this table relationships + */ + public function buildRelations() + { + $this->addRelation('CcSubjs', 'CcSubjs', RelationMap::MANY_TO_ONE, array('creator_id' => 'id', ), null, null); + $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); + } // buildRelations() + + /** + * + * Gets the list of behaviors registered for this table + * + * @return array Associative array (name => parameters) of behaviors + */ + public function getBehaviors() + { + return array( + 'aggregate_column' => array('name' => 'length', 'expression' => 'SUM(cliplength)', 'foreign_table' => 'cc_blockcontents', ), + ); + } // getBehaviors() + +} // CcBlockTableMap diff --git a/install_minimal/upgrades/airtime-1.9.0/propel/airtime/map/CcPlaylistcontentsTableMap.php b/airtime_mvc/application/models/airtime/map/CcBlockcontentsTableMap.php similarity index 54% rename from install_minimal/upgrades/airtime-1.9.0/propel/airtime/map/CcPlaylistcontentsTableMap.php rename to airtime_mvc/application/models/airtime/map/CcBlockcontentsTableMap.php index b00f39ade..b366a1adf 100644 --- a/install_minimal/upgrades/airtime-1.9.0/propel/airtime/map/CcPlaylistcontentsTableMap.php +++ b/airtime_mvc/application/models/airtime/map/CcBlockcontentsTableMap.php @@ -3,7 +3,7 @@ /** - * This class defines the structure of the 'cc_playlistcontents' table. + * This class defines the structure of the 'cc_blockcontents' table. * * * @@ -14,12 +14,12 @@ * * @package propel.generator.airtime.map */ -class CcPlaylistcontentsTableMap extends TableMap { +class CcBlockcontentsTableMap extends TableMap { /** * The (dot-path) name of this class */ - const CLASS_NAME = 'airtime.map.CcPlaylistcontentsTableMap'; + const CLASS_NAME = 'airtime.map.CcBlockcontentsTableMap'; /** * Initialize the table attributes, columns and validators @@ -31,20 +31,20 @@ class CcPlaylistcontentsTableMap extends TableMap { public function initialize() { // attributes - $this->setName('cc_playlistcontents'); - $this->setPhpName('CcPlaylistcontents'); - $this->setClassname('CcPlaylistcontents'); + $this->setName('cc_blockcontents'); + $this->setPhpName('CcBlockcontents'); + $this->setClassname('CcBlockcontents'); $this->setPackage('airtime'); $this->setUseIdGenerator(true); - $this->setPrimaryKeyMethodInfo('cc_playlistcontents_id_seq'); + $this->setPrimaryKeyMethodInfo('cc_blockcontents_id_seq'); // columns $this->addPrimaryKey('ID', 'DbId', 'INTEGER', true, null, null); - $this->addForeignKey('PLAYLIST_ID', 'DbPlaylistId', 'INTEGER', 'cc_playlist', 'ID', false, null, null); + $this->addForeignKey('BLOCK_ID', 'DbBlockId', 'INTEGER', 'cc_block', 'ID', false, null, null); $this->addForeignKey('FILE_ID', 'DbFileId', 'INTEGER', 'cc_files', 'ID', false, null, null); $this->addColumn('POSITION', 'DbPosition', 'INTEGER', false, null, null); - $this->addColumn('CLIPLENGTH', 'DbCliplength', 'TIME', false, null, '00:00:00'); - $this->addColumn('CUEIN', 'DbCuein', 'TIME', false, null, '00:00:00'); - $this->addColumn('CUEOUT', 'DbCueout', 'TIME', false, null, '00:00:00'); + $this->addColumn('CLIPLENGTH', 'DbCliplength', 'VARCHAR', false, null, '00:00:00'); + $this->addColumn('CUEIN', 'DbCuein', 'VARCHAR', false, null, '00:00:00'); + $this->addColumn('CUEOUT', 'DbCueout', 'VARCHAR', false, null, '00:00:00'); $this->addColumn('FADEIN', 'DbFadein', 'TIME', false, null, '00:00:00'); $this->addColumn('FADEOUT', 'DbFadeout', 'TIME', false, null, '00:00:00'); // validators @@ -56,7 +56,20 @@ class CcPlaylistcontentsTableMap extends TableMap { public function buildRelations() { $this->addRelation('CcFiles', 'CcFiles', RelationMap::MANY_TO_ONE, array('file_id' => 'id', ), 'CASCADE', null); - $this->addRelation('CcPlaylist', 'CcPlaylist', RelationMap::MANY_TO_ONE, array('playlist_id' => 'id', ), 'CASCADE', null); + $this->addRelation('CcBlock', 'CcBlock', RelationMap::MANY_TO_ONE, array('block_id' => 'id', ), 'CASCADE', null); } // buildRelations() -} // CcPlaylistcontentsTableMap + /** + * + * Gets the list of behaviors registered for this table + * + * @return array Associative array (name => parameters) of behaviors + */ + public function getBehaviors() + { + return array( + 'aggregate_column_relation' => array('foreign_table' => 'cc_block', 'update_method' => 'updateDbLength', ), + ); + } // getBehaviors() + +} // CcBlockcontentsTableMap diff --git a/install_minimal/upgrades/airtime-1.9.0/propel/airtime/map/CcShowScheduleTableMap.php b/airtime_mvc/application/models/airtime/map/CcBlockcriteriaTableMap.php similarity index 53% rename from install_minimal/upgrades/airtime-1.9.0/propel/airtime/map/CcShowScheduleTableMap.php rename to airtime_mvc/application/models/airtime/map/CcBlockcriteriaTableMap.php index 96528559c..6565bf259 100644 --- a/install_minimal/upgrades/airtime-1.9.0/propel/airtime/map/CcShowScheduleTableMap.php +++ b/airtime_mvc/application/models/airtime/map/CcBlockcriteriaTableMap.php @@ -3,7 +3,7 @@ /** - * This class defines the structure of the 'cc_show_schedule' table. + * This class defines the structure of the 'cc_blockcriteria' table. * * * @@ -14,12 +14,12 @@ * * @package propel.generator.airtime.map */ -class CcShowScheduleTableMap extends TableMap { +class CcBlockcriteriaTableMap extends TableMap { /** * The (dot-path) name of this class */ - const CLASS_NAME = 'airtime.map.CcShowScheduleTableMap'; + const CLASS_NAME = 'airtime.map.CcBlockcriteriaTableMap'; /** * Initialize the table attributes, columns and validators @@ -31,17 +31,19 @@ class CcShowScheduleTableMap extends TableMap { public function initialize() { // attributes - $this->setName('cc_show_schedule'); - $this->setPhpName('CcShowSchedule'); - $this->setClassname('CcShowSchedule'); + $this->setName('cc_blockcriteria'); + $this->setPhpName('CcBlockcriteria'); + $this->setClassname('CcBlockcriteria'); $this->setPackage('airtime'); $this->setUseIdGenerator(true); - $this->setPrimaryKeyMethodInfo('cc_show_schedule_id_seq'); + $this->setPrimaryKeyMethodInfo('cc_blockcriteria_id_seq'); // columns $this->addPrimaryKey('ID', 'DbId', 'INTEGER', true, null, null); - $this->addForeignKey('INSTANCE_ID', 'DbInstanceId', 'INTEGER', 'cc_show_instances', 'ID', true, null, null); - $this->addColumn('POSITION', 'DbPosition', 'INTEGER', false, null, null); - $this->addColumn('GROUP_ID', 'DbGroupId', 'INTEGER', true, null, null); + $this->addColumn('CRITERIA', 'DbCriteria', 'VARCHAR', true, 32, null); + $this->addColumn('MODIFIER', 'DbModifier', 'VARCHAR', true, 16, null); + $this->addColumn('VALUE', 'DbValue', 'VARCHAR', true, 512, null); + $this->addColumn('EXTRA', 'DbExtra', 'VARCHAR', false, 512, null); + $this->addForeignKey('BLOCK_ID', 'DbBlockId', 'INTEGER', 'cc_block', 'ID', true, null, null); // validators } // initialize() @@ -50,7 +52,7 @@ class CcShowScheduleTableMap extends TableMap { */ public function buildRelations() { - $this->addRelation('CcShowInstances', 'CcShowInstances', RelationMap::MANY_TO_ONE, array('instance_id' => 'id', ), 'CASCADE', null); + $this->addRelation('CcBlock', 'CcBlock', RelationMap::MANY_TO_ONE, array('block_id' => 'id', ), 'CASCADE', null); } // buildRelations() -} // CcShowScheduleTableMap +} // CcBlockcriteriaTableMap diff --git a/airtime_mvc/application/models/airtime/map/CcFilesTableMap.php b/airtime_mvc/application/models/airtime/map/CcFilesTableMap.php index 223533793..008c63007 100644 --- a/airtime_mvc/application/models/airtime/map/CcFilesTableMap.php +++ b/airtime_mvc/application/models/airtime/map/CcFilesTableMap.php @@ -39,7 +39,6 @@ class CcFilesTableMap extends TableMap { $this->setPrimaryKeyMethodInfo('cc_files_id_seq'); // columns $this->addPrimaryKey('ID', 'DbId', 'INTEGER', true, null, null); - $this->addColumn('GUNID', 'DbGunid', 'CHAR', true, 32, null); $this->addColumn('NAME', 'DbName', 'VARCHAR', true, 255, ''); $this->addColumn('MIME', 'DbMime', 'VARCHAR', true, 255, ''); $this->addColumn('FTYPE', 'DbFtype', 'VARCHAR', true, 128, ''); @@ -65,7 +64,7 @@ class CcFilesTableMap extends TableMap { $this->addColumn('TRACK_NUMBER', 'DbTrackNumber', 'INTEGER', false, null, null); $this->addColumn('CHANNELS', 'DbChannels', 'INTEGER', false, null, null); $this->addColumn('URL', 'DbUrl', 'VARCHAR', false, 1024, null); - $this->addColumn('BPM', 'DbBpm', 'VARCHAR', false, 8, null); + $this->addColumn('BPM', 'DbBpm', 'INTEGER', false, null, null); $this->addColumn('RATING', 'DbRating', 'VARCHAR', false, 8, null); $this->addColumn('ENCODED_BY', 'DbEncodedBy', 'VARCHAR', false, 255, null); $this->addColumn('DISC_NUMBER', 'DbDiscNumber', 'VARCHAR', false, 8, null); @@ -101,6 +100,8 @@ class CcFilesTableMap extends TableMap { $this->addColumn('SOUNDCLOUD_ERROR_MSG', 'DbSoundcloudErrorMsg', 'VARCHAR', false, 512, null); $this->addColumn('SOUNDCLOUD_LINK_TO_FILE', 'DbSoundcloudLinkToFile', 'VARCHAR', false, 4096, null); $this->addColumn('SOUNDCLOUD_UPLOAD_TIME', 'DbSoundCloundUploadTime', 'TIMESTAMP', false, 6, null); + $this->addColumn('REPLAY_GAIN', 'DbReplayGain', 'NUMERIC', false, null, null); + $this->addForeignKey('OWNER_ID', 'DbOwnerId', 'INTEGER', 'cc_subjs', 'ID', false, null, null); // validators } // initialize() @@ -109,10 +110,12 @@ class CcFilesTableMap extends TableMap { */ public function buildRelations() { - $this->addRelation('CcSubjs', 'CcSubjs', RelationMap::MANY_TO_ONE, array('editedby' => 'id', ), null, null); + $this->addRelation('FkOwner', 'CcSubjs', RelationMap::MANY_TO_ONE, array('owner_id' => 'id', ), null, null); + $this->addRelation('CcSubjsRelatedByDbEditedby', 'CcSubjs', RelationMap::MANY_TO_ONE, array('editedby' => 'id', ), null, null); $this->addRelation('CcMusicDirs', 'CcMusicDirs', RelationMap::MANY_TO_ONE, array('directory' => 'id', ), null, null); $this->addRelation('CcShowInstances', 'CcShowInstances', RelationMap::ONE_TO_MANY, array('id' => 'file_id', ), 'CASCADE', null); $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); } // buildRelations() diff --git a/airtime_mvc/application/models/airtime/map/CcPlaylistTableMap.php b/airtime_mvc/application/models/airtime/map/CcPlaylistTableMap.php index 3162280d0..8dba50bbd 100644 --- a/airtime_mvc/application/models/airtime/map/CcPlaylistTableMap.php +++ b/airtime_mvc/application/models/airtime/map/CcPlaylistTableMap.php @@ -53,7 +53,7 @@ class CcPlaylistTableMap extends TableMap { */ public function buildRelations() { - $this->addRelation('CcSubjs', 'CcSubjs', RelationMap::MANY_TO_ONE, array('creator_id' => 'id', ), null, null); + $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); } // buildRelations() diff --git a/airtime_mvc/application/models/airtime/map/CcPlaylistcontentsTableMap.php b/airtime_mvc/application/models/airtime/map/CcPlaylistcontentsTableMap.php index c8a01608a..68fde5847 100644 --- a/airtime_mvc/application/models/airtime/map/CcPlaylistcontentsTableMap.php +++ b/airtime_mvc/application/models/airtime/map/CcPlaylistcontentsTableMap.php @@ -41,6 +41,9 @@ class CcPlaylistcontentsTableMap extends TableMap { $this->addPrimaryKey('ID', 'DbId', 'INTEGER', true, null, null); $this->addForeignKey('PLAYLIST_ID', 'DbPlaylistId', 'INTEGER', 'cc_playlist', 'ID', false, null, null); $this->addForeignKey('FILE_ID', 'DbFileId', 'INTEGER', 'cc_files', 'ID', false, null, null); + $this->addForeignKey('BLOCK_ID', 'DbBlockId', 'INTEGER', 'cc_block', 'ID', false, null, null); + $this->addColumn('STREAM_ID', 'DbStreamId', 'INTEGER', false, null, null); + $this->addColumn('TYPE', 'DbType', 'SMALLINT', true, null, 0); $this->addColumn('POSITION', 'DbPosition', 'INTEGER', false, null, null); $this->addColumn('CLIPLENGTH', 'DbCliplength', 'VARCHAR', false, null, '00:00:00'); $this->addColumn('CUEIN', 'DbCuein', 'VARCHAR', false, null, '00:00:00'); @@ -56,6 +59,7 @@ class CcPlaylistcontentsTableMap extends TableMap { public function buildRelations() { $this->addRelation('CcFiles', 'CcFiles', RelationMap::MANY_TO_ONE, array('file_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() diff --git a/airtime_mvc/application/models/airtime/map/CcPlaylistcriteriaTableMap.php b/airtime_mvc/application/models/airtime/map/CcPlaylistcriteriaTableMap.php new file mode 100644 index 000000000..85e71d32f --- /dev/null +++ b/airtime_mvc/application/models/airtime/map/CcPlaylistcriteriaTableMap.php @@ -0,0 +1,59 @@ +setName('cc_playlistcriteria'); + $this->setPhpName('CcPlaylistcriteria'); + $this->setClassname('CcPlaylistcriteria'); + $this->setPackage('airtime'); + $this->setUseIdGenerator(true); + $this->setPrimaryKeyMethodInfo('cc_playlistcriteria_id_seq'); + // columns + $this->addPrimaryKey('ID', 'DbId', 'INTEGER', true, null, null); + $this->addColumn('CRITERIA', 'DbCriteria', 'VARCHAR', true, 16, null); + $this->addColumn('MODIFIER', 'DbModifier', 'VARCHAR', true, 16, null); + $this->addColumn('VALUE', 'DbValue', 'VARCHAR', true, 512, null); + $this->addColumn('EXTRA', 'DbExtra', 'VARCHAR', false, 512, null); + $this->addForeignKey('PLAYLIST_ID', 'DbPlaylistId', 'INTEGER', 'cc_playlist', 'ID', true, null, null); + $this->addColumn('SET_NUMBER', 'DbSetNumber', 'INTEGER', true, null, null); + // validators + } // initialize() + + /** + * Build the RelationMap objects for this table relationships + */ + public function buildRelations() + { + $this->addRelation('CcPlaylist', 'CcPlaylist', RelationMap::MANY_TO_ONE, array('playlist_id' => 'id', ), 'CASCADE', null); + } // buildRelations() + +} // CcPlaylistcriteriaTableMap diff --git a/airtime_mvc/application/models/airtime/map/CcScheduleTableMap.php b/airtime_mvc/application/models/airtime/map/CcScheduleTableMap.php index 64e9b2609..5478ac8d2 100644 --- a/airtime_mvc/application/models/airtime/map/CcScheduleTableMap.php +++ b/airtime_mvc/application/models/airtime/map/CcScheduleTableMap.php @@ -42,6 +42,7 @@ class CcScheduleTableMap extends TableMap { $this->addColumn('STARTS', 'DbStarts', 'TIMESTAMP', true, null, null); $this->addColumn('ENDS', 'DbEnds', 'TIMESTAMP', 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->addColumn('CLIP_LENGTH', 'DbClipLength', 'VARCHAR', false, null, '00:00:00'); $this->addColumn('FADE_IN', 'DbFadeIn', 'TIME', false, null, '00:00:00'); $this->addColumn('FADE_OUT', 'DbFadeOut', 'TIME', false, null, '00:00:00'); @@ -61,6 +62,8 @@ class CcScheduleTableMap extends TableMap { { $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('CcWebstreamMetadata', 'CcWebstreamMetadata', RelationMap::ONE_TO_MANY, array('id' => 'instance_id', ), 'CASCADE', null); } // buildRelations() } // CcScheduleTableMap diff --git a/airtime_mvc/application/models/airtime/map/CcSectionTableMap.php b/airtime_mvc/application/models/airtime/map/CcSectionTableMap.php new file mode 100644 index 000000000..3fb493083 --- /dev/null +++ b/airtime_mvc/application/models/airtime/map/CcSectionTableMap.php @@ -0,0 +1,76 @@ +setName('cc_section'); + $this->setPhpName('CcSection'); + $this->setClassname('CcSection'); + $this->setPackage('airtime'); + $this->setUseIdGenerator(true); + $this->setPrimaryKeyMethodInfo('cc_section_id_seq'); + // columns + $this->addPrimaryKey('ID', 'DbId', 'INTEGER', true, null, null); + $this->addColumn('NAME', 'DbName', 'VARCHAR', true, 255, ''); + $this->addColumn('MTIME', 'DbMtime', 'TIMESTAMP', false, 6, null); + $this->addColumn('UTIME', 'DbUtime', 'TIMESTAMP', false, 6, null); + $this->addForeignKey('CREATOR_ID', 'DbCreatorId', 'INTEGER', 'cc_subjs', 'ID', false, null, null); + $this->addColumn('DESCRIPTION', 'DbDescription', 'VARCHAR', false, 512, null); + $this->addColumn('LENGTH', 'DbLength', 'VARCHAR', false, null, '00:00:00'); + $this->addColumn('TYPE', 'DbType', 'VARCHAR', false, 7, 'static'); + // validators + } // initialize() + + /** + * Build the RelationMap objects for this table relationships + */ + public function buildRelations() + { + $this->addRelation('CcSubjs', 'CcSubjs', RelationMap::MANY_TO_ONE, array('creator_id' => 'id', ), null, null); + $this->addRelation('CcPlaylistcontents', 'CcPlaylistcontents', RelationMap::ONE_TO_MANY, array('id' => 'section_id', ), 'CASCADE', null); + $this->addRelation('CcSectioncontents', 'CcSectioncontents', RelationMap::ONE_TO_MANY, array('id' => 'section_id', ), 'CASCADE', null); + $this->addRelation('CcSectioncriteria', 'CcSectioncriteria', RelationMap::ONE_TO_MANY, array('id' => 'section_id', ), 'CASCADE', null); + } // buildRelations() + + /** + * + * Gets the list of behaviors registered for this table + * + * @return array Associative array (name => parameters) of behaviors + */ + public function getBehaviors() + { + return array( + 'aggregate_column' => array('name' => 'length', 'expression' => 'SUM(cliplength)', 'foreign_table' => 'cc_sectioncontents', ), + ); + } // getBehaviors() + +} // CcSectionTableMap diff --git a/install_minimal/upgrades/airtime-2.0.0/propel/airtime/map/CcPlaylistcontentsTableMap.php b/airtime_mvc/application/models/airtime/map/CcSectioncontentsTableMap.php similarity index 54% rename from install_minimal/upgrades/airtime-2.0.0/propel/airtime/map/CcPlaylistcontentsTableMap.php rename to airtime_mvc/application/models/airtime/map/CcSectioncontentsTableMap.php index b00f39ade..1d4382091 100644 --- a/install_minimal/upgrades/airtime-2.0.0/propel/airtime/map/CcPlaylistcontentsTableMap.php +++ b/airtime_mvc/application/models/airtime/map/CcSectioncontentsTableMap.php @@ -3,7 +3,7 @@ /** - * This class defines the structure of the 'cc_playlistcontents' table. + * This class defines the structure of the 'cc_sectioncontents' table. * * * @@ -14,12 +14,12 @@ * * @package propel.generator.airtime.map */ -class CcPlaylistcontentsTableMap extends TableMap { +class CcSectioncontentsTableMap extends TableMap { /** * The (dot-path) name of this class */ - const CLASS_NAME = 'airtime.map.CcPlaylistcontentsTableMap'; + const CLASS_NAME = 'airtime.map.CcSectioncontentsTableMap'; /** * Initialize the table attributes, columns and validators @@ -31,20 +31,20 @@ class CcPlaylistcontentsTableMap extends TableMap { public function initialize() { // attributes - $this->setName('cc_playlistcontents'); - $this->setPhpName('CcPlaylistcontents'); - $this->setClassname('CcPlaylistcontents'); + $this->setName('cc_sectioncontents'); + $this->setPhpName('CcSectioncontents'); + $this->setClassname('CcSectioncontents'); $this->setPackage('airtime'); $this->setUseIdGenerator(true); - $this->setPrimaryKeyMethodInfo('cc_playlistcontents_id_seq'); + $this->setPrimaryKeyMethodInfo('cc_sectioncontents_id_seq'); // columns $this->addPrimaryKey('ID', 'DbId', 'INTEGER', true, null, null); - $this->addForeignKey('PLAYLIST_ID', 'DbPlaylistId', 'INTEGER', 'cc_playlist', 'ID', false, null, null); + $this->addForeignKey('SECTION_ID', 'DbSectionId', 'INTEGER', 'cc_section', 'ID', false, null, null); $this->addForeignKey('FILE_ID', 'DbFileId', 'INTEGER', 'cc_files', 'ID', false, null, null); $this->addColumn('POSITION', 'DbPosition', 'INTEGER', false, null, null); - $this->addColumn('CLIPLENGTH', 'DbCliplength', 'TIME', false, null, '00:00:00'); - $this->addColumn('CUEIN', 'DbCuein', 'TIME', false, null, '00:00:00'); - $this->addColumn('CUEOUT', 'DbCueout', 'TIME', false, null, '00:00:00'); + $this->addColumn('CLIPLENGTH', 'DbCliplength', 'VARCHAR', false, null, '00:00:00'); + $this->addColumn('CUEIN', 'DbCuein', 'VARCHAR', false, null, '00:00:00'); + $this->addColumn('CUEOUT', 'DbCueout', 'VARCHAR', false, null, '00:00:00'); $this->addColumn('FADEIN', 'DbFadein', 'TIME', false, null, '00:00:00'); $this->addColumn('FADEOUT', 'DbFadeout', 'TIME', false, null, '00:00:00'); // validators @@ -56,7 +56,20 @@ class CcPlaylistcontentsTableMap extends TableMap { public function buildRelations() { $this->addRelation('CcFiles', 'CcFiles', RelationMap::MANY_TO_ONE, array('file_id' => 'id', ), 'CASCADE', null); - $this->addRelation('CcPlaylist', 'CcPlaylist', RelationMap::MANY_TO_ONE, array('playlist_id' => 'id', ), 'CASCADE', null); + $this->addRelation('CcSection', 'CcSection', RelationMap::MANY_TO_ONE, array('section_id' => 'id', ), 'CASCADE', null); } // buildRelations() -} // CcPlaylistcontentsTableMap + /** + * + * Gets the list of behaviors registered for this table + * + * @return array Associative array (name => parameters) of behaviors + */ + public function getBehaviors() + { + return array( + 'aggregate_column_relation' => array('foreign_table' => 'cc_section', 'update_method' => 'updateDbLength', ), + ); + } // getBehaviors() + +} // CcSectioncontentsTableMap diff --git a/install_minimal/upgrades/airtime-1.9.0/propel/airtime/map/CcShowHostsTableMap.php b/airtime_mvc/application/models/airtime/map/CcSectioncriteriaTableMap.php similarity index 51% rename from install_minimal/upgrades/airtime-1.9.0/propel/airtime/map/CcShowHostsTableMap.php rename to airtime_mvc/application/models/airtime/map/CcSectioncriteriaTableMap.php index c76efdbd3..20c30d56e 100644 --- a/install_minimal/upgrades/airtime-1.9.0/propel/airtime/map/CcShowHostsTableMap.php +++ b/airtime_mvc/application/models/airtime/map/CcSectioncriteriaTableMap.php @@ -3,7 +3,7 @@ /** - * This class defines the structure of the 'cc_show_hosts' table. + * This class defines the structure of the 'cc_sectioncriteria' table. * * * @@ -14,12 +14,12 @@ * * @package propel.generator.airtime.map */ -class CcShowHostsTableMap extends TableMap { +class CcSectioncriteriaTableMap extends TableMap { /** * The (dot-path) name of this class */ - const CLASS_NAME = 'airtime.map.CcShowHostsTableMap'; + const CLASS_NAME = 'airtime.map.CcSectioncriteriaTableMap'; /** * Initialize the table attributes, columns and validators @@ -31,16 +31,19 @@ class CcShowHostsTableMap extends TableMap { public function initialize() { // attributes - $this->setName('cc_show_hosts'); - $this->setPhpName('CcShowHosts'); - $this->setClassname('CcShowHosts'); + $this->setName('cc_sectioncriteria'); + $this->setPhpName('CcSectioncriteria'); + $this->setClassname('CcSectioncriteria'); $this->setPackage('airtime'); $this->setUseIdGenerator(true); - $this->setPrimaryKeyMethodInfo('cc_show_hosts_id_seq'); + $this->setPrimaryKeyMethodInfo('cc_sectioncriteria_id_seq'); // columns $this->addPrimaryKey('ID', 'DbId', 'INTEGER', true, null, null); - $this->addForeignKey('SHOW_ID', 'DbShow', 'INTEGER', 'cc_show', 'ID', true, null, null); - $this->addForeignKey('SUBJS_ID', 'DbHost', 'INTEGER', 'cc_subjs', 'ID', true, null, null); + $this->addColumn('CRITERIA', 'DbCriteria', 'VARCHAR', true, 16, null); + $this->addColumn('MODIFIER', 'DbModifier', 'VARCHAR', true, 16, null); + $this->addColumn('VALUE', 'DbValue', 'VARCHAR', true, 512, null); + $this->addColumn('EXTRA', 'DbExtra', 'VARCHAR', false, 512, null); + $this->addForeignKey('SECTION_ID', 'DbPlaylistId', 'INTEGER', 'cc_section', 'ID', true, null, null); // validators } // initialize() @@ -49,8 +52,7 @@ class CcShowHostsTableMap extends TableMap { */ public function buildRelations() { - $this->addRelation('CcShow', 'CcShow', RelationMap::MANY_TO_ONE, array('show_id' => 'id', ), 'CASCADE', null); - $this->addRelation('CcSubjs', 'CcSubjs', RelationMap::MANY_TO_ONE, array('subjs_id' => 'id', ), 'CASCADE', null); + $this->addRelation('CcSection', 'CcSection', RelationMap::MANY_TO_ONE, array('section_id' => 'id', ), 'CASCADE', null); } // buildRelations() -} // CcShowHostsTableMap +} // CcSectioncriteriaTableMap diff --git a/airtime_mvc/application/models/airtime/map/CcSubjsTableMap.php b/airtime_mvc/application/models/airtime/map/CcSubjsTableMap.php index 7dc2bc6a7..ffbe8cded 100644 --- a/airtime_mvc/application/models/airtime/map/CcSubjsTableMap.php +++ b/airtime_mvc/application/models/airtime/map/CcSubjsTableMap.php @@ -59,11 +59,12 @@ class CcSubjsTableMap extends TableMap { */ public function buildRelations() { - $this->addRelation('CcAccess', 'CcAccess', RelationMap::ONE_TO_MANY, array('id' => 'owner', ), null, null); - $this->addRelation('CcFiles', 'CcFiles', RelationMap::ONE_TO_MANY, array('id' => 'editedby', ), null, null); + $this->addRelation('CcFilesRelatedByDbOwnerId', 'CcFiles', RelationMap::ONE_TO_MANY, array('id' => 'owner_id', ), null, null); + $this->addRelation('CcFilesRelatedByDbEditedby', 'CcFiles', RelationMap::ONE_TO_MANY, array('id' => 'editedby', ), null, null); $this->addRelation('CcPerms', 'CcPerms', RelationMap::ONE_TO_MANY, array('id' => 'subj', ), 'CASCADE', null); $this->addRelation('CcShowHosts', 'CcShowHosts', RelationMap::ONE_TO_MANY, array('id' => 'subjs_id', ), 'CASCADE', null); - $this->addRelation('CcPlaylist', 'CcPlaylist', RelationMap::ONE_TO_MANY, array('id' => 'creator_id', ), null, null); + $this->addRelation('CcPlaylist', 'CcPlaylist', RelationMap::ONE_TO_MANY, array('id' => 'creator_id', ), 'CASCADE', null); + $this->addRelation('CcBlock', 'CcBlock', RelationMap::ONE_TO_MANY, array('id' => 'creator_id', ), null, null); $this->addRelation('CcPref', 'CcPref', RelationMap::ONE_TO_MANY, array('id' => 'subjid', ), 'CASCADE', null); $this->addRelation('CcSess', 'CcSess', RelationMap::ONE_TO_MANY, array('id' => 'userid', ), 'CASCADE', null); $this->addRelation('CcSubjsToken', 'CcSubjsToken', RelationMap::ONE_TO_MANY, array('id' => 'user_id', ), 'CASCADE', null); diff --git a/install_minimal/upgrades/airtime-2.0.0/propel/airtime/map/CcShowScheduleTableMap.php b/airtime_mvc/application/models/airtime/map/CcWebstreamMetadataTableMap.php similarity index 58% rename from install_minimal/upgrades/airtime-2.0.0/propel/airtime/map/CcShowScheduleTableMap.php rename to airtime_mvc/application/models/airtime/map/CcWebstreamMetadataTableMap.php index 96528559c..305d8189a 100644 --- a/install_minimal/upgrades/airtime-2.0.0/propel/airtime/map/CcShowScheduleTableMap.php +++ b/airtime_mvc/application/models/airtime/map/CcWebstreamMetadataTableMap.php @@ -3,7 +3,7 @@ /** - * This class defines the structure of the 'cc_show_schedule' table. + * This class defines the structure of the 'cc_webstream_metadata' table. * * * @@ -14,12 +14,12 @@ * * @package propel.generator.airtime.map */ -class CcShowScheduleTableMap extends TableMap { +class CcWebstreamMetadataTableMap extends TableMap { /** * The (dot-path) name of this class */ - const CLASS_NAME = 'airtime.map.CcShowScheduleTableMap'; + const CLASS_NAME = 'airtime.map.CcWebstreamMetadataTableMap'; /** * Initialize the table attributes, columns and validators @@ -31,17 +31,17 @@ class CcShowScheduleTableMap extends TableMap { public function initialize() { // attributes - $this->setName('cc_show_schedule'); - $this->setPhpName('CcShowSchedule'); - $this->setClassname('CcShowSchedule'); + $this->setName('cc_webstream_metadata'); + $this->setPhpName('CcWebstreamMetadata'); + $this->setClassname('CcWebstreamMetadata'); $this->setPackage('airtime'); $this->setUseIdGenerator(true); - $this->setPrimaryKeyMethodInfo('cc_show_schedule_id_seq'); + $this->setPrimaryKeyMethodInfo('cc_webstream_metadata_id_seq'); // columns $this->addPrimaryKey('ID', 'DbId', 'INTEGER', true, null, null); - $this->addForeignKey('INSTANCE_ID', 'DbInstanceId', 'INTEGER', 'cc_show_instances', 'ID', true, null, null); - $this->addColumn('POSITION', 'DbPosition', 'INTEGER', false, null, null); - $this->addColumn('GROUP_ID', 'DbGroupId', 'INTEGER', true, null, null); + $this->addForeignKey('INSTANCE_ID', 'DbInstanceId', 'INTEGER', 'cc_schedule', 'ID', true, null, null); + $this->addColumn('START_TIME', 'DbStartTime', 'TIMESTAMP', true, null, null); + $this->addColumn('LIQUIDSOAP_DATA', 'DbLiquidsoapData', 'VARCHAR', true, 1024, null); // validators } // initialize() @@ -50,7 +50,7 @@ class CcShowScheduleTableMap extends TableMap { */ public function buildRelations() { - $this->addRelation('CcShowInstances', 'CcShowInstances', RelationMap::MANY_TO_ONE, array('instance_id' => 'id', ), 'CASCADE', null); + $this->addRelation('CcSchedule', 'CcSchedule', RelationMap::MANY_TO_ONE, array('instance_id' => 'id', ), 'CASCADE', null); } // buildRelations() -} // CcShowScheduleTableMap +} // CcWebstreamMetadataTableMap diff --git a/airtime_mvc/application/models/airtime/map/CcWebstreamTableMap.php b/airtime_mvc/application/models/airtime/map/CcWebstreamTableMap.php new file mode 100644 index 000000000..c4b28a516 --- /dev/null +++ b/airtime_mvc/application/models/airtime/map/CcWebstreamTableMap.php @@ -0,0 +1,62 @@ +setName('cc_webstream'); + $this->setPhpName('CcWebstream'); + $this->setClassname('CcWebstream'); + $this->setPackage('airtime'); + $this->setUseIdGenerator(true); + $this->setPrimaryKeyMethodInfo('cc_webstream_id_seq'); + // columns + $this->addPrimaryKey('ID', 'DbId', 'INTEGER', true, null, null); + $this->addColumn('NAME', 'DbName', 'VARCHAR', true, 255, null); + $this->addColumn('DESCRIPTION', 'DbDescription', 'VARCHAR', true, 255, null); + $this->addColumn('URL', 'DbUrl', 'VARCHAR', true, 512, null); + $this->addColumn('LENGTH', 'DbLength', 'VARCHAR', true, null, '00:00:00'); + $this->addColumn('CREATOR_ID', 'DbCreatorId', 'INTEGER', true, null, null); + $this->addColumn('MTIME', 'DbMtime', 'TIMESTAMP', true, 6, null); + $this->addColumn('UTIME', 'DbUtime', 'TIMESTAMP', true, 6, null); + $this->addColumn('LPTIME', 'DbLPtime', 'TIMESTAMP', false, 6, null); + $this->addColumn('MIME', 'DbMime', 'VARCHAR', false, 255, null); + // validators + } // initialize() + + /** + * Build the RelationMap objects for this table relationships + */ + public function buildRelations() + { + $this->addRelation('CcSchedule', 'CcSchedule', RelationMap::ONE_TO_MANY, array('id' => 'stream_id', ), 'CASCADE', null); + } // buildRelations() + +} // CcWebstreamTableMap diff --git a/install_minimal/upgrades/airtime-1.9.0/propel/airtime/om/BaseCcPlaylist.php b/airtime_mvc/application/models/airtime/om/BaseCcBlock.php similarity index 58% rename from install_minimal/upgrades/airtime-1.9.0/propel/airtime/om/BaseCcPlaylist.php rename to airtime_mvc/application/models/airtime/om/BaseCcBlock.php index 222c1c6f4..f9c900c81 100644 --- a/install_minimal/upgrades/airtime-1.9.0/propel/airtime/om/BaseCcPlaylist.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcBlock.php @@ -2,25 +2,25 @@ /** - * Base class that represents a row from the 'cc_playlist' table. + * Base class that represents a row from the 'cc_block' table. * * * * @package propel.generator.airtime.om */ -abstract class BaseCcPlaylist extends BaseObject implements Persistent +abstract class BaseCcBlock extends BaseObject implements Persistent { /** * Peer class name */ - const PEER = 'CcPlaylistPeer'; + const PEER = 'CcBlockPeer'; /** * The Peer class. * Instance provides a convenient way of calling static methods on a class * that calling code may not be able to identify. - * @var CcPlaylistPeer + * @var CcBlockPeer */ protected static $peer; @@ -37,26 +37,6 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent */ protected $name; - /** - * The value for the state field. - * Note: this column has a database default value of: 'empty' - * @var string - */ - protected $state; - - /** - * The value for the currentlyaccessing field. - * Note: this column has a database default value of: 0 - * @var int - */ - protected $currentlyaccessing; - - /** - * The value for the editedby field. - * @var int - */ - protected $editedby; - /** * The value for the mtime field. * @var string @@ -64,10 +44,16 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent protected $mtime; /** - * The value for the creator field. + * The value for the utime field. * @var string */ - protected $creator; + protected $utime; + + /** + * The value for the creator_id field. + * @var int + */ + protected $creator_id; /** * The value for the description field. @@ -75,6 +61,20 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent */ protected $description; + /** + * The value for the length field. + * Note: this column has a database default value of: '00:00:00' + * @var string + */ + protected $length; + + /** + * The value for the type field. + * Note: this column has a database default value of: 'static' + * @var string + */ + protected $type; + /** * @var CcSubjs */ @@ -85,6 +85,16 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent */ protected $collCcPlaylistcontentss; + /** + * @var array CcBlockcontents[] Collection to store aggregation of CcBlockcontents objects. + */ + protected $collCcBlockcontentss; + + /** + * @var array CcBlockcriteria[] Collection to store aggregation of CcBlockcriteria objects. + */ + protected $collCcBlockcriterias; + /** * Flag to prevent endless save loop, if this object is referenced * by another object which falls in this transaction. @@ -108,12 +118,12 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent public function applyDefaultValues() { $this->name = ''; - $this->state = 'empty'; - $this->currentlyaccessing = 0; + $this->length = '00:00:00'; + $this->type = 'static'; } /** - * Initializes internal state of BaseCcPlaylist object. + * Initializes internal state of BaseCcBlock object. * @see applyDefaults() */ public function __construct() @@ -142,36 +152,6 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent return $this->name; } - /** - * Get the [state] column value. - * - * @return string - */ - public function getDbState() - { - return $this->state; - } - - /** - * Get the [currentlyaccessing] column value. - * - * @return int - */ - public function getDbCurrentlyaccessing() - { - return $this->currentlyaccessing; - } - - /** - * Get the [editedby] column value. - * - * @return int - */ - public function getDbEditedby() - { - return $this->editedby; - } - /** * Get the [optionally formatted] temporal [mtime] column value. * @@ -206,13 +186,46 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent } /** - * Get the [creator] column value. + * Get the [optionally formatted] temporal [utime] column value. * - * @return string + * + * @param string $format The date/time format string (either date()-style or strftime()-style). + * If format is NULL, then the raw DateTime object will be returned. + * @return mixed Formatted date/time value as string or DateTime object (if format is NULL), NULL if column is NULL + * @throws PropelException - if unable to parse/validate the date/time value. */ - public function getDbCreator() + public function getDbUtime($format = 'Y-m-d H:i:s') { - return $this->creator; + if ($this->utime === null) { + return null; + } + + + + try { + $dt = new DateTime($this->utime); + } catch (Exception $x) { + throw new PropelException("Internally stored date/time/timestamp value could not be converted to DateTime: " . var_export($this->utime, true), $x); + } + + if ($format === null) { + // Because propel.useDateTimeClass is TRUE, we return a DateTime object. + return $dt; + } elseif (strpos($format, '%') !== false) { + return strftime($format, $dt->format('U')); + } else { + return $dt->format($format); + } + } + + /** + * Get the [creator_id] column value. + * + * @return int + */ + public function getDbCreatorId() + { + return $this->creator_id; } /** @@ -225,11 +238,31 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent return $this->description; } + /** + * Get the [length] column value. + * + * @return string + */ + public function getDbLength() + { + return $this->length; + } + + /** + * Get the [type] column value. + * + * @return string + */ + public function getDbType() + { + return $this->type; + } + /** * Set the value of [id] column. * * @param int $v new value - * @return CcPlaylist The current object (for fluent API support) + * @return CcBlock The current object (for fluent API support) */ public function setDbId($v) { @@ -239,7 +272,7 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent if ($this->id !== $v) { $this->id = $v; - $this->modifiedColumns[] = CcPlaylistPeer::ID; + $this->modifiedColumns[] = CcBlockPeer::ID; } return $this; @@ -249,7 +282,7 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent * Set the value of [name] column. * * @param string $v new value - * @return CcPlaylist The current object (for fluent API support) + * @return CcBlock The current object (for fluent API support) */ public function setDbName($v) { @@ -259,82 +292,18 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent if ($this->name !== $v || $this->isNew()) { $this->name = $v; - $this->modifiedColumns[] = CcPlaylistPeer::NAME; + $this->modifiedColumns[] = CcBlockPeer::NAME; } return $this; } // setDbName() - /** - * Set the value of [state] column. - * - * @param string $v new value - * @return CcPlaylist The current object (for fluent API support) - */ - public function setDbState($v) - { - if ($v !== null) { - $v = (string) $v; - } - - if ($this->state !== $v || $this->isNew()) { - $this->state = $v; - $this->modifiedColumns[] = CcPlaylistPeer::STATE; - } - - return $this; - } // setDbState() - - /** - * Set the value of [currentlyaccessing] column. - * - * @param int $v new value - * @return CcPlaylist The current object (for fluent API support) - */ - public function setDbCurrentlyaccessing($v) - { - if ($v !== null) { - $v = (int) $v; - } - - if ($this->currentlyaccessing !== $v || $this->isNew()) { - $this->currentlyaccessing = $v; - $this->modifiedColumns[] = CcPlaylistPeer::CURRENTLYACCESSING; - } - - return $this; - } // setDbCurrentlyaccessing() - - /** - * Set the value of [editedby] column. - * - * @param int $v new value - * @return CcPlaylist The current object (for fluent API support) - */ - public function setDbEditedby($v) - { - if ($v !== null) { - $v = (int) $v; - } - - if ($this->editedby !== $v) { - $this->editedby = $v; - $this->modifiedColumns[] = CcPlaylistPeer::EDITEDBY; - } - - if ($this->aCcSubjs !== null && $this->aCcSubjs->getDbId() !== $v) { - $this->aCcSubjs = null; - } - - return $this; - } // setDbEditedby() - /** * Sets the value of [mtime] column to a normalized version of the date/time value specified. * * @param mixed $v string, integer (timestamp), or DateTime value. Empty string will * be treated as NULL for temporal objects. - * @return CcPlaylist The current object (for fluent API support) + * @return CcBlock The current object (for fluent API support) */ public function setDbMtime($v) { @@ -371,7 +340,7 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent ) { $this->mtime = ($dt ? $dt->format('Y-m-d\\TH:i:sO') : null); - $this->modifiedColumns[] = CcPlaylistPeer::MTIME; + $this->modifiedColumns[] = CcBlockPeer::MTIME; } } // if either are not null @@ -379,30 +348,83 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent } // setDbMtime() /** - * Set the value of [creator] column. + * Sets the value of [utime] column to a normalized version of the date/time value specified. * - * @param string $v new value - * @return CcPlaylist The current object (for fluent API support) + * @param mixed $v string, integer (timestamp), or DateTime value. Empty string will + * be treated as NULL for temporal objects. + * @return CcBlock The current object (for fluent API support) */ - public function setDbCreator($v) + public function setDbUtime($v) { - if ($v !== null) { - $v = (string) $v; + // we treat '' as NULL for temporal objects because DateTime('') == DateTime('now') + // -- which is unexpected, to say the least. + if ($v === null || $v === '') { + $dt = null; + } elseif ($v instanceof DateTime) { + $dt = $v; + } else { + // some string/numeric value passed; we normalize that so that we can + // validate it. + try { + if (is_numeric($v)) { // if it's a unix timestamp + $dt = new DateTime('@'.$v, new DateTimeZone('UTC')); + // We have to explicitly specify and then change the time zone because of a + // DateTime bug: http://bugs.php.net/bug.php?id=43003 + $dt->setTimeZone(new DateTimeZone(date_default_timezone_get())); + } else { + $dt = new DateTime($v); + } + } catch (Exception $x) { + throw new PropelException('Error parsing date/time value: ' . var_export($v, true), $x); + } } - if ($this->creator !== $v) { - $this->creator = $v; - $this->modifiedColumns[] = CcPlaylistPeer::CREATOR; + if ( $this->utime !== null || $dt !== null ) { + // (nested ifs are a little easier to read in this case) + + $currNorm = ($this->utime !== null && $tmpDt = new DateTime($this->utime)) ? $tmpDt->format('Y-m-d\\TH:i:sO') : null; + $newNorm = ($dt !== null) ? $dt->format('Y-m-d\\TH:i:sO') : null; + + if ( ($currNorm !== $newNorm) // normalized values don't match + ) + { + $this->utime = ($dt ? $dt->format('Y-m-d\\TH:i:sO') : null); + $this->modifiedColumns[] = CcBlockPeer::UTIME; + } + } // if either are not null + + return $this; + } // setDbUtime() + + /** + * Set the value of [creator_id] column. + * + * @param int $v new value + * @return CcBlock The current object (for fluent API support) + */ + public function setDbCreatorId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->creator_id !== $v) { + $this->creator_id = $v; + $this->modifiedColumns[] = CcBlockPeer::CREATOR_ID; + } + + if ($this->aCcSubjs !== null && $this->aCcSubjs->getDbId() !== $v) { + $this->aCcSubjs = null; } return $this; - } // setDbCreator() + } // setDbCreatorId() /** * Set the value of [description] column. * * @param string $v new value - * @return CcPlaylist The current object (for fluent API support) + * @return CcBlock The current object (for fluent API support) */ public function setDbDescription($v) { @@ -412,12 +434,52 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent if ($this->description !== $v) { $this->description = $v; - $this->modifiedColumns[] = CcPlaylistPeer::DESCRIPTION; + $this->modifiedColumns[] = CcBlockPeer::DESCRIPTION; } return $this; } // setDbDescription() + /** + * Set the value of [length] column. + * + * @param string $v new value + * @return CcBlock The current object (for fluent API support) + */ + public function setDbLength($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->length !== $v || $this->isNew()) { + $this->length = $v; + $this->modifiedColumns[] = CcBlockPeer::LENGTH; + } + + return $this; + } // setDbLength() + + /** + * Set the value of [type] column. + * + * @param string $v new value + * @return CcBlock The current object (for fluent API support) + */ + public function setDbType($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->type !== $v || $this->isNew()) { + $this->type = $v; + $this->modifiedColumns[] = CcBlockPeer::TYPE; + } + + return $this; + } // setDbType() + /** * Indicates whether the columns in this object are only set to default values. * @@ -432,11 +494,11 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent return false; } - if ($this->state !== 'empty') { + if ($this->length !== '00:00:00') { return false; } - if ($this->currentlyaccessing !== 0) { + if ($this->type !== 'static') { return false; } @@ -464,12 +526,12 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent $this->id = ($row[$startcol + 0] !== null) ? (int) $row[$startcol + 0] : null; $this->name = ($row[$startcol + 1] !== null) ? (string) $row[$startcol + 1] : null; - $this->state = ($row[$startcol + 2] !== null) ? (string) $row[$startcol + 2] : null; - $this->currentlyaccessing = ($row[$startcol + 3] !== null) ? (int) $row[$startcol + 3] : null; - $this->editedby = ($row[$startcol + 4] !== null) ? (int) $row[$startcol + 4] : null; - $this->mtime = ($row[$startcol + 5] !== null) ? (string) $row[$startcol + 5] : null; - $this->creator = ($row[$startcol + 6] !== null) ? (string) $row[$startcol + 6] : null; - $this->description = ($row[$startcol + 7] !== null) ? (string) $row[$startcol + 7] : null; + $this->mtime = ($row[$startcol + 2] !== null) ? (string) $row[$startcol + 2] : null; + $this->utime = ($row[$startcol + 3] !== null) ? (string) $row[$startcol + 3] : null; + $this->creator_id = ($row[$startcol + 4] !== null) ? (int) $row[$startcol + 4] : null; + $this->description = ($row[$startcol + 5] !== null) ? (string) $row[$startcol + 5] : null; + $this->length = ($row[$startcol + 6] !== null) ? (string) $row[$startcol + 6] : null; + $this->type = ($row[$startcol + 7] !== null) ? (string) $row[$startcol + 7] : null; $this->resetModified(); $this->setNew(false); @@ -478,10 +540,10 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent $this->ensureConsistency(); } - return $startcol + 8; // 8 = CcPlaylistPeer::NUM_COLUMNS - CcPlaylistPeer::NUM_LAZY_LOAD_COLUMNS). + return $startcol + 8; // 8 = CcBlockPeer::NUM_COLUMNS - CcBlockPeer::NUM_LAZY_LOAD_COLUMNS). } catch (Exception $e) { - throw new PropelException("Error populating CcPlaylist object", $e); + throw new PropelException("Error populating CcBlock object", $e); } } @@ -501,7 +563,7 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent public function ensureConsistency() { - if ($this->aCcSubjs !== null && $this->editedby !== $this->aCcSubjs->getDbId()) { + if ($this->aCcSubjs !== null && $this->creator_id !== $this->aCcSubjs->getDbId()) { $this->aCcSubjs = null; } } // ensureConsistency @@ -527,13 +589,13 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent } if ($con === null) { - $con = Propel::getConnection(CcPlaylistPeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcBlockPeer::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 = CcPlaylistPeer::doSelectStmt($this->buildPkeyCriteria(), $con); + $stmt = CcBlockPeer::doSelectStmt($this->buildPkeyCriteria(), $con); $row = $stmt->fetch(PDO::FETCH_NUM); $stmt->closeCursor(); if (!$row) { @@ -546,6 +608,10 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent $this->aCcSubjs = null; $this->collCcPlaylistcontentss = null; + $this->collCcBlockcontentss = null; + + $this->collCcBlockcriterias = null; + } // if (deep) } @@ -565,14 +631,14 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent } if ($con === null) { - $con = Propel::getConnection(CcPlaylistPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + $con = Propel::getConnection(CcBlockPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); } $con->beginTransaction(); try { $ret = $this->preDelete($con); if ($ret) { - CcPlaylistQuery::create() + CcBlockQuery::create() ->filterByPrimaryKey($this->getPrimaryKey()) ->delete($con); $this->postDelete($con); @@ -607,7 +673,7 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent } if ($con === null) { - $con = Propel::getConnection(CcPlaylistPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + $con = Propel::getConnection(CcBlockPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); } $con->beginTransaction(); @@ -627,7 +693,7 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent $this->postUpdate($con); } $this->postSave($con); - CcPlaylistPeer::addInstanceToPool($this); + CcBlockPeer::addInstanceToPool($this); } else { $affectedRows = 0; } @@ -669,15 +735,15 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent } if ($this->isNew() ) { - $this->modifiedColumns[] = CcPlaylistPeer::ID; + $this->modifiedColumns[] = CcBlockPeer::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(CcPlaylistPeer::ID) ) { - throw new PropelException('Cannot insert a value for auto-increment primary key ('.CcPlaylistPeer::ID.')'); + if ($criteria->keyContainsValue(CcBlockPeer::ID) ) { + throw new PropelException('Cannot insert a value for auto-increment primary key ('.CcBlockPeer::ID.')'); } $pk = BasePeer::doInsert($criteria, $con); @@ -685,7 +751,7 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent $this->setDbId($pk); //[IMV] update autoincrement primary key $this->setNew(false); } else { - $affectedRows += CcPlaylistPeer::doUpdate($this, $con); + $affectedRows += CcBlockPeer::doUpdate($this, $con); } $this->resetModified(); // [HL] After being saved an object is no longer 'modified' @@ -699,6 +765,22 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent } } + if ($this->collCcBlockcontentss !== null) { + foreach ($this->collCcBlockcontentss as $referrerFK) { + if (!$referrerFK->isDeleted()) { + $affectedRows += $referrerFK->save($con); + } + } + } + + if ($this->collCcBlockcriterias !== null) { + foreach ($this->collCcBlockcriterias as $referrerFK) { + if (!$referrerFK->isDeleted()) { + $affectedRows += $referrerFK->save($con); + } + } + } + $this->alreadyInSave = false; } @@ -777,7 +859,7 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent } - if (($retval = CcPlaylistPeer::doValidate($this, $columns)) !== true) { + if (($retval = CcBlockPeer::doValidate($this, $columns)) !== true) { $failureMap = array_merge($failureMap, $retval); } @@ -790,6 +872,22 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent } } + if ($this->collCcBlockcontentss !== null) { + foreach ($this->collCcBlockcontentss as $referrerFK) { + if (!$referrerFK->validate($columns)) { + $failureMap = array_merge($failureMap, $referrerFK->getValidationFailures()); + } + } + } + + if ($this->collCcBlockcriterias !== null) { + foreach ($this->collCcBlockcriterias as $referrerFK) { + if (!$referrerFK->validate($columns)) { + $failureMap = array_merge($failureMap, $referrerFK->getValidationFailures()); + } + } + } + $this->alreadyInValidation = false; } @@ -808,7 +906,7 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent */ public function getByName($name, $type = BasePeer::TYPE_PHPNAME) { - $pos = CcPlaylistPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); + $pos = CcBlockPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); $field = $this->getByPosition($pos); return $field; } @@ -830,22 +928,22 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent return $this->getDbName(); break; case 2: - return $this->getDbState(); - break; - case 3: - return $this->getDbCurrentlyaccessing(); - break; - case 4: - return $this->getDbEditedby(); - break; - case 5: return $this->getDbMtime(); break; + case 3: + return $this->getDbUtime(); + break; + case 4: + return $this->getDbCreatorId(); + break; + case 5: + return $this->getDbDescription(); + break; case 6: - return $this->getDbCreator(); + return $this->getDbLength(); break; case 7: - return $this->getDbDescription(); + return $this->getDbType(); break; default: return null; @@ -869,16 +967,16 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent */ public function toArray($keyType = BasePeer::TYPE_PHPNAME, $includeLazyLoadColumns = true, $includeForeignObjects = false) { - $keys = CcPlaylistPeer::getFieldNames($keyType); + $keys = CcBlockPeer::getFieldNames($keyType); $result = array( $keys[0] => $this->getDbId(), $keys[1] => $this->getDbName(), - $keys[2] => $this->getDbState(), - $keys[3] => $this->getDbCurrentlyaccessing(), - $keys[4] => $this->getDbEditedby(), - $keys[5] => $this->getDbMtime(), - $keys[6] => $this->getDbCreator(), - $keys[7] => $this->getDbDescription(), + $keys[2] => $this->getDbMtime(), + $keys[3] => $this->getDbUtime(), + $keys[4] => $this->getDbCreatorId(), + $keys[5] => $this->getDbDescription(), + $keys[6] => $this->getDbLength(), + $keys[7] => $this->getDbType(), ); if ($includeForeignObjects) { if (null !== $this->aCcSubjs) { @@ -900,7 +998,7 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent */ public function setByName($name, $value, $type = BasePeer::TYPE_PHPNAME) { - $pos = CcPlaylistPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); + $pos = CcBlockPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); return $this->setByPosition($pos, $value); } @@ -922,22 +1020,22 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent $this->setDbName($value); break; case 2: - $this->setDbState($value); - break; - case 3: - $this->setDbCurrentlyaccessing($value); - break; - case 4: - $this->setDbEditedby($value); - break; - case 5: $this->setDbMtime($value); break; + case 3: + $this->setDbUtime($value); + break; + case 4: + $this->setDbCreatorId($value); + break; + case 5: + $this->setDbDescription($value); + break; case 6: - $this->setDbCreator($value); + $this->setDbLength($value); break; case 7: - $this->setDbDescription($value); + $this->setDbType($value); break; } // switch() } @@ -961,16 +1059,16 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent */ public function fromArray($arr, $keyType = BasePeer::TYPE_PHPNAME) { - $keys = CcPlaylistPeer::getFieldNames($keyType); + $keys = CcBlockPeer::getFieldNames($keyType); if (array_key_exists($keys[0], $arr)) $this->setDbId($arr[$keys[0]]); if (array_key_exists($keys[1], $arr)) $this->setDbName($arr[$keys[1]]); - if (array_key_exists($keys[2], $arr)) $this->setDbState($arr[$keys[2]]); - if (array_key_exists($keys[3], $arr)) $this->setDbCurrentlyaccessing($arr[$keys[3]]); - if (array_key_exists($keys[4], $arr)) $this->setDbEditedby($arr[$keys[4]]); - if (array_key_exists($keys[5], $arr)) $this->setDbMtime($arr[$keys[5]]); - if (array_key_exists($keys[6], $arr)) $this->setDbCreator($arr[$keys[6]]); - if (array_key_exists($keys[7], $arr)) $this->setDbDescription($arr[$keys[7]]); + if (array_key_exists($keys[2], $arr)) $this->setDbMtime($arr[$keys[2]]); + if (array_key_exists($keys[3], $arr)) $this->setDbUtime($arr[$keys[3]]); + if (array_key_exists($keys[4], $arr)) $this->setDbCreatorId($arr[$keys[4]]); + if (array_key_exists($keys[5], $arr)) $this->setDbDescription($arr[$keys[5]]); + if (array_key_exists($keys[6], $arr)) $this->setDbLength($arr[$keys[6]]); + if (array_key_exists($keys[7], $arr)) $this->setDbType($arr[$keys[7]]); } /** @@ -980,16 +1078,16 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent */ public function buildCriteria() { - $criteria = new Criteria(CcPlaylistPeer::DATABASE_NAME); + $criteria = new Criteria(CcBlockPeer::DATABASE_NAME); - if ($this->isColumnModified(CcPlaylistPeer::ID)) $criteria->add(CcPlaylistPeer::ID, $this->id); - if ($this->isColumnModified(CcPlaylistPeer::NAME)) $criteria->add(CcPlaylistPeer::NAME, $this->name); - if ($this->isColumnModified(CcPlaylistPeer::STATE)) $criteria->add(CcPlaylistPeer::STATE, $this->state); - if ($this->isColumnModified(CcPlaylistPeer::CURRENTLYACCESSING)) $criteria->add(CcPlaylistPeer::CURRENTLYACCESSING, $this->currentlyaccessing); - if ($this->isColumnModified(CcPlaylistPeer::EDITEDBY)) $criteria->add(CcPlaylistPeer::EDITEDBY, $this->editedby); - if ($this->isColumnModified(CcPlaylistPeer::MTIME)) $criteria->add(CcPlaylistPeer::MTIME, $this->mtime); - if ($this->isColumnModified(CcPlaylistPeer::CREATOR)) $criteria->add(CcPlaylistPeer::CREATOR, $this->creator); - if ($this->isColumnModified(CcPlaylistPeer::DESCRIPTION)) $criteria->add(CcPlaylistPeer::DESCRIPTION, $this->description); + if ($this->isColumnModified(CcBlockPeer::ID)) $criteria->add(CcBlockPeer::ID, $this->id); + if ($this->isColumnModified(CcBlockPeer::NAME)) $criteria->add(CcBlockPeer::NAME, $this->name); + if ($this->isColumnModified(CcBlockPeer::MTIME)) $criteria->add(CcBlockPeer::MTIME, $this->mtime); + if ($this->isColumnModified(CcBlockPeer::UTIME)) $criteria->add(CcBlockPeer::UTIME, $this->utime); + if ($this->isColumnModified(CcBlockPeer::CREATOR_ID)) $criteria->add(CcBlockPeer::CREATOR_ID, $this->creator_id); + if ($this->isColumnModified(CcBlockPeer::DESCRIPTION)) $criteria->add(CcBlockPeer::DESCRIPTION, $this->description); + if ($this->isColumnModified(CcBlockPeer::LENGTH)) $criteria->add(CcBlockPeer::LENGTH, $this->length); + if ($this->isColumnModified(CcBlockPeer::TYPE)) $criteria->add(CcBlockPeer::TYPE, $this->type); return $criteria; } @@ -1004,8 +1102,8 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent */ public function buildPkeyCriteria() { - $criteria = new Criteria(CcPlaylistPeer::DATABASE_NAME); - $criteria->add(CcPlaylistPeer::ID, $this->id); + $criteria = new Criteria(CcBlockPeer::DATABASE_NAME); + $criteria->add(CcBlockPeer::ID, $this->id); return $criteria; } @@ -1045,19 +1143,19 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent * If desired, this method can also make copies of all associated (fkey referrers) * objects. * - * @param object $copyObj An object of CcPlaylist (or compatible) type. + * @param object $copyObj An object of CcBlock (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->setDbName($this->name); - $copyObj->setDbState($this->state); - $copyObj->setDbCurrentlyaccessing($this->currentlyaccessing); - $copyObj->setDbEditedby($this->editedby); $copyObj->setDbMtime($this->mtime); - $copyObj->setDbCreator($this->creator); + $copyObj->setDbUtime($this->utime); + $copyObj->setDbCreatorId($this->creator_id); $copyObj->setDbDescription($this->description); + $copyObj->setDbLength($this->length); + $copyObj->setDbType($this->type); if ($deepCopy) { // important: temporarily setNew(false) because this affects the behavior of @@ -1070,6 +1168,18 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent } } + foreach ($this->getCcBlockcontentss() as $relObj) { + if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves + $copyObj->addCcBlockcontents($relObj->copy($deepCopy)); + } + } + + foreach ($this->getCcBlockcriterias() as $relObj) { + if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves + $copyObj->addCcBlockcriteria($relObj->copy($deepCopy)); + } + } + } // if ($deepCopy) @@ -1086,7 +1196,7 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent * objects. * * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. - * @return CcPlaylist Clone of current object. + * @return CcBlock Clone of current object. * @throws PropelException */ public function copy($deepCopy = false) @@ -1105,12 +1215,12 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent * same instance for all member of this class. The method could therefore * be static, but this would prevent one from overriding the behavior. * - * @return CcPlaylistPeer + * @return CcBlockPeer */ public function getPeer() { if (self::$peer === null) { - self::$peer = new CcPlaylistPeer(); + self::$peer = new CcBlockPeer(); } return self::$peer; } @@ -1119,15 +1229,15 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent * Declares an association between this object and a CcSubjs object. * * @param CcSubjs $v - * @return CcPlaylist The current object (for fluent API support) + * @return CcBlock The current object (for fluent API support) * @throws PropelException */ public function setCcSubjs(CcSubjs $v = null) { if ($v === null) { - $this->setDbEditedby(NULL); + $this->setDbCreatorId(NULL); } else { - $this->setDbEditedby($v->getDbId()); + $this->setDbCreatorId($v->getDbId()); } $this->aCcSubjs = $v; @@ -1135,7 +1245,7 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent // Add binding for other direction of this n:n relationship. // If this object has already been added to the CcSubjs object, it will not be re-added. if ($v !== null) { - $v->addCcPlaylist($this); + $v->addCcBlock($this); } return $this; @@ -1151,14 +1261,14 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent */ public function getCcSubjs(PropelPDO $con = null) { - if ($this->aCcSubjs === null && ($this->editedby !== null)) { - $this->aCcSubjs = CcSubjsQuery::create()->findPk($this->editedby, $con); + if ($this->aCcSubjs === null && ($this->creator_id !== null)) { + $this->aCcSubjs = CcSubjsQuery::create()->findPk($this->creator_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->aCcSubjs->addCcPlaylists($this); + $this->aCcSubjs->addCcBlocks($this); */ } return $this->aCcSubjs; @@ -1199,7 +1309,7 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent * 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 CcPlaylist is new, it will return + * If this CcBlock 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 @@ -1215,7 +1325,7 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent $this->initCcPlaylistcontentss(); } else { $collCcPlaylistcontentss = CcPlaylistcontentsQuery::create(null, $criteria) - ->filterByCcPlaylist($this) + ->filterByCcBlock($this) ->find($con); if (null !== $criteria) { return $collCcPlaylistcontentss; @@ -1246,7 +1356,7 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent $query->distinct(); } return $query - ->filterByCcPlaylist($this) + ->filterByCcBlock($this) ->count($con); } } else { @@ -1269,7 +1379,7 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent } if (!$this->collCcPlaylistcontentss->contains($l)) { // only add it if the **same** object is not already associated $this->collCcPlaylistcontentss[]= $l; - $l->setCcPlaylist($this); + $l->setCcBlock($this); } } @@ -1277,13 +1387,13 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent /** * 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 + * Otherwise if this CcBlock is new, it will return + * an empty collection; or if this CcBlock has previously * been saved, it will retrieve related CcPlaylistcontentss 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. + * actually need in CcBlock. * * @param Criteria $criteria optional Criteria object to narrow the query * @param PropelPDO $con optional connection object @@ -1298,6 +1408,274 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent return $this->getCcPlaylistcontentss($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 CcPlaylistcontentss 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 CcPlaylistcontents[] List of CcPlaylistcontents objects + */ + public function getCcPlaylistcontentssJoinCcPlaylist($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $query = CcPlaylistcontentsQuery::create(null, $criteria); + $query->joinWith('CcPlaylist', $join_behavior); + + return $this->getCcPlaylistcontentss($query, $con); + } + + /** + * Clears out the collCcBlockcontentss 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 addCcBlockcontentss() + */ + public function clearCcBlockcontentss() + { + $this->collCcBlockcontentss = null; // important to set this to NULL since that means it is uninitialized + } + + /** + * Initializes the collCcBlockcontentss collection. + * + * By default this just sets the collCcBlockcontentss collection to an empty array (like clearcollCcBlockcontentss()); + * 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 initCcBlockcontentss() + { + $this->collCcBlockcontentss = new PropelObjectCollection(); + $this->collCcBlockcontentss->setModel('CcBlockcontents'); + } + + /** + * Gets an array of CcBlockcontents 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 CcBlock 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 CcBlockcontents[] List of CcBlockcontents objects + * @throws PropelException + */ + public function getCcBlockcontentss($criteria = null, PropelPDO $con = null) + { + if(null === $this->collCcBlockcontentss || null !== $criteria) { + if ($this->isNew() && null === $this->collCcBlockcontentss) { + // return empty collection + $this->initCcBlockcontentss(); + } else { + $collCcBlockcontentss = CcBlockcontentsQuery::create(null, $criteria) + ->filterByCcBlock($this) + ->find($con); + if (null !== $criteria) { + return $collCcBlockcontentss; + } + $this->collCcBlockcontentss = $collCcBlockcontentss; + } + } + return $this->collCcBlockcontentss; + } + + /** + * Returns the number of related CcBlockcontents objects. + * + * @param Criteria $criteria + * @param boolean $distinct + * @param PropelPDO $con + * @return int Count of related CcBlockcontents objects. + * @throws PropelException + */ + public function countCcBlockcontentss(Criteria $criteria = null, $distinct = false, PropelPDO $con = null) + { + if(null === $this->collCcBlockcontentss || null !== $criteria) { + if ($this->isNew() && null === $this->collCcBlockcontentss) { + return 0; + } else { + $query = CcBlockcontentsQuery::create(null, $criteria); + if($distinct) { + $query->distinct(); + } + return $query + ->filterByCcBlock($this) + ->count($con); + } + } else { + return count($this->collCcBlockcontentss); + } + } + + /** + * Method called to associate a CcBlockcontents object to this object + * through the CcBlockcontents foreign key attribute. + * + * @param CcBlockcontents $l CcBlockcontents + * @return void + * @throws PropelException + */ + public function addCcBlockcontents(CcBlockcontents $l) + { + if ($this->collCcBlockcontentss === null) { + $this->initCcBlockcontentss(); + } + if (!$this->collCcBlockcontentss->contains($l)) { // only add it if the **same** object is not already associated + $this->collCcBlockcontentss[]= $l; + $l->setCcBlock($this); + } + } + + + /** + * 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 CcBlockcontentss 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 CcBlockcontents[] List of CcBlockcontents objects + */ + public function getCcBlockcontentssJoinCcFiles($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $query = CcBlockcontentsQuery::create(null, $criteria); + $query->joinWith('CcFiles', $join_behavior); + + return $this->getCcBlockcontentss($query, $con); + } + + /** + * Clears out the collCcBlockcriterias 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 addCcBlockcriterias() + */ + public function clearCcBlockcriterias() + { + $this->collCcBlockcriterias = null; // important to set this to NULL since that means it is uninitialized + } + + /** + * Initializes the collCcBlockcriterias collection. + * + * By default this just sets the collCcBlockcriterias collection to an empty array (like clearcollCcBlockcriterias()); + * 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 initCcBlockcriterias() + { + $this->collCcBlockcriterias = new PropelObjectCollection(); + $this->collCcBlockcriterias->setModel('CcBlockcriteria'); + } + + /** + * Gets an array of CcBlockcriteria 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 CcBlock 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 CcBlockcriteria[] List of CcBlockcriteria objects + * @throws PropelException + */ + public function getCcBlockcriterias($criteria = null, PropelPDO $con = null) + { + if(null === $this->collCcBlockcriterias || null !== $criteria) { + if ($this->isNew() && null === $this->collCcBlockcriterias) { + // return empty collection + $this->initCcBlockcriterias(); + } else { + $collCcBlockcriterias = CcBlockcriteriaQuery::create(null, $criteria) + ->filterByCcBlock($this) + ->find($con); + if (null !== $criteria) { + return $collCcBlockcriterias; + } + $this->collCcBlockcriterias = $collCcBlockcriterias; + } + } + return $this->collCcBlockcriterias; + } + + /** + * Returns the number of related CcBlockcriteria objects. + * + * @param Criteria $criteria + * @param boolean $distinct + * @param PropelPDO $con + * @return int Count of related CcBlockcriteria objects. + * @throws PropelException + */ + public function countCcBlockcriterias(Criteria $criteria = null, $distinct = false, PropelPDO $con = null) + { + if(null === $this->collCcBlockcriterias || null !== $criteria) { + if ($this->isNew() && null === $this->collCcBlockcriterias) { + return 0; + } else { + $query = CcBlockcriteriaQuery::create(null, $criteria); + if($distinct) { + $query->distinct(); + } + return $query + ->filterByCcBlock($this) + ->count($con); + } + } else { + return count($this->collCcBlockcriterias); + } + } + + /** + * Method called to associate a CcBlockcriteria object to this object + * through the CcBlockcriteria foreign key attribute. + * + * @param CcBlockcriteria $l CcBlockcriteria + * @return void + * @throws PropelException + */ + public function addCcBlockcriteria(CcBlockcriteria $l) + { + if ($this->collCcBlockcriterias === null) { + $this->initCcBlockcriterias(); + } + if (!$this->collCcBlockcriterias->contains($l)) { // only add it if the **same** object is not already associated + $this->collCcBlockcriterias[]= $l; + $l->setCcBlock($this); + } + } + /** * Clears the current object and sets all attributes to their default values */ @@ -1305,12 +1683,12 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent { $this->id = null; $this->name = null; - $this->state = null; - $this->currentlyaccessing = null; - $this->editedby = null; $this->mtime = null; - $this->creator = null; + $this->utime = null; + $this->creator_id = null; $this->description = null; + $this->length = null; + $this->type = null; $this->alreadyInSave = false; $this->alreadyInValidation = false; $this->clearAllReferences(); @@ -1337,12 +1715,52 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent $o->clearAllReferences($deep); } } + if ($this->collCcBlockcontentss) { + foreach ((array) $this->collCcBlockcontentss as $o) { + $o->clearAllReferences($deep); + } + } + if ($this->collCcBlockcriterias) { + foreach ((array) $this->collCcBlockcriterias as $o) { + $o->clearAllReferences($deep); + } + } } // if ($deep) $this->collCcPlaylistcontentss = null; + $this->collCcBlockcontentss = null; + $this->collCcBlockcriterias = null; $this->aCcSubjs = null; } + // aggregate_column behavior + + /** + * Computes the value of the aggregate column length + * + * @param PropelPDO $con A connection object + * + * @return mixed The scalar result from the aggregate query + */ + public function computeDbLength(PropelPDO $con) + { + $stmt = $con->prepare('SELECT SUM(cliplength) FROM "cc_blockcontents" WHERE cc_blockcontents.BLOCK_ID = :p1'); + $stmt->bindValue(':p1', $this->getDbId()); + $stmt->execute(); + return $stmt->fetchColumn(); + } + + /** + * Updates the aggregate column length + * + * @param PropelPDO $con A connection object + */ + public function updateDbLength(PropelPDO $con) + { + $this->setDbLength($this->computeDbLength($con)); + $this->save($con); + } + /** * Catches calls to virtual methods */ @@ -1362,4 +1780,4 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent throw new PropelException('Call to undefined method: ' . $name); } -} // BaseCcPlaylist +} // BaseCcBlock diff --git a/install_minimal/upgrades/airtime-2.0.0/propel/airtime/om/BaseCcPlaylistPeer.php b/airtime_mvc/application/models/airtime/om/BaseCcBlockPeer.php similarity index 72% rename from install_minimal/upgrades/airtime-2.0.0/propel/airtime/om/BaseCcPlaylistPeer.php rename to airtime_mvc/application/models/airtime/om/BaseCcBlockPeer.php index 0e338bc39..48003ffc5 100644 --- a/install_minimal/upgrades/airtime-2.0.0/propel/airtime/om/BaseCcPlaylistPeer.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcBlockPeer.php @@ -2,28 +2,28 @@ /** - * Base static class for performing query and update operations on the 'cc_playlist' table. + * Base static class for performing query and update operations on the 'cc_block' table. * * * * @package propel.generator.airtime.om */ -abstract class BaseCcPlaylistPeer { +abstract class BaseCcBlockPeer { /** the default database name for this class */ const DATABASE_NAME = 'airtime'; /** the table name for this class */ - const TABLE_NAME = 'cc_playlist'; + const TABLE_NAME = 'cc_block'; /** the related Propel class for this table */ - const OM_CLASS = 'CcPlaylist'; + const OM_CLASS = 'CcBlock'; /** A class that can be returned by this peer. */ - const CLASS_DEFAULT = 'airtime.CcPlaylist'; + const CLASS_DEFAULT = 'airtime.CcBlock'; /** the related TableMap class for this table */ - const TM_CLASS = 'CcPlaylistTableMap'; + const TM_CLASS = 'CcBlockTableMap'; /** The total number of columns. */ const NUM_COLUMNS = 8; @@ -32,34 +32,34 @@ abstract class BaseCcPlaylistPeer { const NUM_LAZY_LOAD_COLUMNS = 0; /** the column name for the ID field */ - const ID = 'cc_playlist.ID'; + const ID = 'cc_block.ID'; /** the column name for the NAME field */ - const NAME = 'cc_playlist.NAME'; - - /** the column name for the STATE field */ - const STATE = 'cc_playlist.STATE'; - - /** the column name for the CURRENTLYACCESSING field */ - const CURRENTLYACCESSING = 'cc_playlist.CURRENTLYACCESSING'; - - /** the column name for the EDITEDBY field */ - const EDITEDBY = 'cc_playlist.EDITEDBY'; + const NAME = 'cc_block.NAME'; /** the column name for the MTIME field */ - const MTIME = 'cc_playlist.MTIME'; + const MTIME = 'cc_block.MTIME'; - /** the column name for the CREATOR field */ - const CREATOR = 'cc_playlist.CREATOR'; + /** the column name for the UTIME field */ + const UTIME = 'cc_block.UTIME'; + + /** the column name for the CREATOR_ID field */ + const CREATOR_ID = 'cc_block.CREATOR_ID'; /** the column name for the DESCRIPTION field */ - const DESCRIPTION = 'cc_playlist.DESCRIPTION'; + const DESCRIPTION = 'cc_block.DESCRIPTION'; + + /** the column name for the LENGTH field */ + const LENGTH = 'cc_block.LENGTH'; + + /** the column name for the TYPE field */ + const TYPE = 'cc_block.TYPE'; /** - * An identiy map to hold any loaded instances of CcPlaylist objects. + * An identiy map to hold any loaded instances of CcBlock objects. * This must be public so that other peer classes can access this when hydrating from JOIN * queries. - * @var array CcPlaylist[] + * @var array CcBlock[] */ public static $instances = array(); @@ -71,11 +71,11 @@ abstract class BaseCcPlaylistPeer { * e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id' */ private static $fieldNames = array ( - BasePeer::TYPE_PHPNAME => array ('DbId', 'DbName', 'DbState', 'DbCurrentlyaccessing', 'DbEditedby', 'DbMtime', 'DbCreator', 'DbDescription', ), - BasePeer::TYPE_STUDLYPHPNAME => array ('dbId', 'dbName', 'dbState', 'dbCurrentlyaccessing', 'dbEditedby', 'dbMtime', 'dbCreator', 'dbDescription', ), - BasePeer::TYPE_COLNAME => array (self::ID, self::NAME, self::STATE, self::CURRENTLYACCESSING, self::EDITEDBY, self::MTIME, self::CREATOR, self::DESCRIPTION, ), - BasePeer::TYPE_RAW_COLNAME => array ('ID', 'NAME', 'STATE', 'CURRENTLYACCESSING', 'EDITEDBY', 'MTIME', 'CREATOR', 'DESCRIPTION', ), - BasePeer::TYPE_FIELDNAME => array ('id', 'name', 'state', 'currentlyaccessing', 'editedby', 'mtime', 'creator', 'description', ), + BasePeer::TYPE_PHPNAME => array ('DbId', 'DbName', 'DbMtime', 'DbUtime', 'DbCreatorId', 'DbDescription', 'DbLength', 'DbType', ), + BasePeer::TYPE_STUDLYPHPNAME => array ('dbId', 'dbName', 'dbMtime', 'dbUtime', 'dbCreatorId', 'dbDescription', 'dbLength', 'dbType', ), + BasePeer::TYPE_COLNAME => array (self::ID, self::NAME, self::MTIME, self::UTIME, self::CREATOR_ID, self::DESCRIPTION, self::LENGTH, self::TYPE, ), + BasePeer::TYPE_RAW_COLNAME => array ('ID', 'NAME', 'MTIME', 'UTIME', 'CREATOR_ID', 'DESCRIPTION', 'LENGTH', 'TYPE', ), + BasePeer::TYPE_FIELDNAME => array ('id', 'name', 'mtime', 'utime', 'creator_id', 'description', 'length', 'type', ), BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, ) ); @@ -86,11 +86,11 @@ abstract class BaseCcPlaylistPeer { * e.g. self::$fieldNames[BasePeer::TYPE_PHPNAME]['Id'] = 0 */ private static $fieldKeys = array ( - BasePeer::TYPE_PHPNAME => array ('DbId' => 0, 'DbName' => 1, 'DbState' => 2, 'DbCurrentlyaccessing' => 3, 'DbEditedby' => 4, 'DbMtime' => 5, 'DbCreator' => 6, 'DbDescription' => 7, ), - BasePeer::TYPE_STUDLYPHPNAME => array ('dbId' => 0, 'dbName' => 1, 'dbState' => 2, 'dbCurrentlyaccessing' => 3, 'dbEditedby' => 4, 'dbMtime' => 5, 'dbCreator' => 6, 'dbDescription' => 7, ), - BasePeer::TYPE_COLNAME => array (self::ID => 0, self::NAME => 1, self::STATE => 2, self::CURRENTLYACCESSING => 3, self::EDITEDBY => 4, self::MTIME => 5, self::CREATOR => 6, self::DESCRIPTION => 7, ), - BasePeer::TYPE_RAW_COLNAME => array ('ID' => 0, 'NAME' => 1, 'STATE' => 2, 'CURRENTLYACCESSING' => 3, 'EDITEDBY' => 4, 'MTIME' => 5, 'CREATOR' => 6, 'DESCRIPTION' => 7, ), - BasePeer::TYPE_FIELDNAME => array ('id' => 0, 'name' => 1, 'state' => 2, 'currentlyaccessing' => 3, 'editedby' => 4, 'mtime' => 5, 'creator' => 6, 'description' => 7, ), + BasePeer::TYPE_PHPNAME => array ('DbId' => 0, 'DbName' => 1, 'DbMtime' => 2, 'DbUtime' => 3, 'DbCreatorId' => 4, 'DbDescription' => 5, 'DbLength' => 6, 'DbType' => 7, ), + BasePeer::TYPE_STUDLYPHPNAME => array ('dbId' => 0, 'dbName' => 1, 'dbMtime' => 2, 'dbUtime' => 3, 'dbCreatorId' => 4, 'dbDescription' => 5, 'dbLength' => 6, 'dbType' => 7, ), + BasePeer::TYPE_COLNAME => array (self::ID => 0, self::NAME => 1, self::MTIME => 2, self::UTIME => 3, self::CREATOR_ID => 4, self::DESCRIPTION => 5, self::LENGTH => 6, self::TYPE => 7, ), + BasePeer::TYPE_RAW_COLNAME => array ('ID' => 0, 'NAME' => 1, 'MTIME' => 2, 'UTIME' => 3, 'CREATOR_ID' => 4, 'DESCRIPTION' => 5, 'LENGTH' => 6, 'TYPE' => 7, ), + BasePeer::TYPE_FIELDNAME => array ('id' => 0, 'name' => 1, 'mtime' => 2, 'utime' => 3, 'creator_id' => 4, 'description' => 5, 'length' => 6, 'type' => 7, ), BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, ) ); @@ -140,12 +140,12 @@ abstract class BaseCcPlaylistPeer { * $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. CcPlaylistPeer::COLUMN_NAME). + * @param string $column The column name for current table. (i.e. CcBlockPeer::COLUMN_NAME). * @return string */ public static function alias($alias, $column) { - return str_replace(CcPlaylistPeer::TABLE_NAME.'.', $alias.'.', $column); + return str_replace(CcBlockPeer::TABLE_NAME.'.', $alias.'.', $column); } /** @@ -163,23 +163,23 @@ abstract class BaseCcPlaylistPeer { public static function addSelectColumns(Criteria $criteria, $alias = null) { if (null === $alias) { - $criteria->addSelectColumn(CcPlaylistPeer::ID); - $criteria->addSelectColumn(CcPlaylistPeer::NAME); - $criteria->addSelectColumn(CcPlaylistPeer::STATE); - $criteria->addSelectColumn(CcPlaylistPeer::CURRENTLYACCESSING); - $criteria->addSelectColumn(CcPlaylistPeer::EDITEDBY); - $criteria->addSelectColumn(CcPlaylistPeer::MTIME); - $criteria->addSelectColumn(CcPlaylistPeer::CREATOR); - $criteria->addSelectColumn(CcPlaylistPeer::DESCRIPTION); + $criteria->addSelectColumn(CcBlockPeer::ID); + $criteria->addSelectColumn(CcBlockPeer::NAME); + $criteria->addSelectColumn(CcBlockPeer::MTIME); + $criteria->addSelectColumn(CcBlockPeer::UTIME); + $criteria->addSelectColumn(CcBlockPeer::CREATOR_ID); + $criteria->addSelectColumn(CcBlockPeer::DESCRIPTION); + $criteria->addSelectColumn(CcBlockPeer::LENGTH); + $criteria->addSelectColumn(CcBlockPeer::TYPE); } else { $criteria->addSelectColumn($alias . '.ID'); $criteria->addSelectColumn($alias . '.NAME'); - $criteria->addSelectColumn($alias . '.STATE'); - $criteria->addSelectColumn($alias . '.CURRENTLYACCESSING'); - $criteria->addSelectColumn($alias . '.EDITEDBY'); $criteria->addSelectColumn($alias . '.MTIME'); - $criteria->addSelectColumn($alias . '.CREATOR'); + $criteria->addSelectColumn($alias . '.UTIME'); + $criteria->addSelectColumn($alias . '.CREATOR_ID'); $criteria->addSelectColumn($alias . '.DESCRIPTION'); + $criteria->addSelectColumn($alias . '.LENGTH'); + $criteria->addSelectColumn($alias . '.TYPE'); } } @@ -199,21 +199,21 @@ abstract class BaseCcPlaylistPeer { // 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(CcPlaylistPeer::TABLE_NAME); + $criteria->setPrimaryTableName(CcBlockPeer::TABLE_NAME); if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { $criteria->setDistinct(); } if (!$criteria->hasSelectClause()) { - CcPlaylistPeer::addSelectColumns($criteria); + CcBlockPeer::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(CcPlaylistPeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcBlockPeer::DATABASE_NAME, Propel::CONNECTION_READ); } // BasePeer returns a PDOStatement $stmt = BasePeer::doCount($criteria, $con); @@ -231,7 +231,7 @@ abstract class BaseCcPlaylistPeer { * * @param Criteria $criteria object used to create the SELECT statement. * @param PropelPDO $con - * @return CcPlaylist + * @return CcBlock * @throws PropelException Any exceptions caught during processing will be * rethrown wrapped into a PropelException. */ @@ -239,7 +239,7 @@ abstract class BaseCcPlaylistPeer { { $critcopy = clone $criteria; $critcopy->setLimit(1); - $objects = CcPlaylistPeer::doSelect($critcopy, $con); + $objects = CcBlockPeer::doSelect($critcopy, $con); if ($objects) { return $objects[0]; } @@ -256,7 +256,7 @@ abstract class BaseCcPlaylistPeer { */ public static function doSelect(Criteria $criteria, PropelPDO $con = null) { - return CcPlaylistPeer::populateObjects(CcPlaylistPeer::doSelectStmt($criteria, $con)); + return CcBlockPeer::populateObjects(CcBlockPeer::doSelectStmt($criteria, $con)); } /** * Prepares the Criteria object and uses the parent doSelect() method to execute a PDOStatement. @@ -274,12 +274,12 @@ abstract class BaseCcPlaylistPeer { public static function doSelectStmt(Criteria $criteria, PropelPDO $con = null) { if ($con === null) { - $con = Propel::getConnection(CcPlaylistPeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcBlockPeer::DATABASE_NAME, Propel::CONNECTION_READ); } if (!$criteria->hasSelectClause()) { $criteria = clone $criteria; - CcPlaylistPeer::addSelectColumns($criteria); + CcBlockPeer::addSelectColumns($criteria); } // Set the correct dbName @@ -297,10 +297,10 @@ abstract class BaseCcPlaylistPeer { * to the cache in order to ensure that the same objects are always returned by doSelect*() * and retrieveByPK*() calls. * - * @param CcPlaylist $value A CcPlaylist object. + * @param CcBlock $value A CcBlock object. * @param string $key (optional) key to use for instance map (for performance boost if key was already calculated externally). */ - public static function addInstanceToPool(CcPlaylist $obj, $key = null) + public static function addInstanceToPool(CcBlock $obj, $key = null) { if (Propel::isInstancePoolingEnabled()) { if ($key === null) { @@ -318,18 +318,18 @@ abstract class BaseCcPlaylistPeer { * 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 CcPlaylist object or a primary key value. + * @param mixed $value A CcBlock object or a primary key value. */ public static function removeInstanceFromPool($value) { if (Propel::isInstancePoolingEnabled() && $value !== null) { - if (is_object($value) && $value instanceof CcPlaylist) { + if (is_object($value) && $value instanceof CcBlock) { $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 CcPlaylist object; got " . (is_object($value) ? get_class($value) . ' object.' : var_export($value,true))); + $e = new PropelException("Invalid value passed to removeInstanceFromPool(). Expected primary key or CcBlock object; got " . (is_object($value) ? get_class($value) . ' object.' : var_export($value,true))); throw $e; } @@ -344,7 +344,7 @@ abstract class BaseCcPlaylistPeer { * 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 CcPlaylist Found object or NULL if 1) no instance exists for specified key or 2) instance pooling has been disabled. + * @return CcBlock 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) @@ -368,7 +368,7 @@ abstract class BaseCcPlaylistPeer { } /** - * Method to invalidate the instance pool of all tables related to cc_playlist + * Method to invalidate the instance pool of all tables related to cc_block * by a foreign key with ON DELETE CASCADE */ public static function clearRelatedInstancePool() @@ -376,6 +376,12 @@ 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 CcBlockcontentsPeer instance pool, + // since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule. + CcBlockcontentsPeer::clearInstancePool(); + // Invalidate objects in CcBlockcriteriaPeer instance pool, + // since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule. + CcBlockcriteriaPeer::clearInstancePool(); } /** @@ -423,11 +429,11 @@ abstract class BaseCcPlaylistPeer { $results = array(); // set the class once to avoid overhead in the loop - $cls = CcPlaylistPeer::getOMClass(false); + $cls = CcBlockPeer::getOMClass(false); // populate the object(s) while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $key = CcPlaylistPeer::getPrimaryKeyHashFromRow($row, 0); - if (null !== ($obj = CcPlaylistPeer::getInstanceFromPool($key))) { + $key = CcBlockPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj = CcBlockPeer::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 @@ -436,7 +442,7 @@ abstract class BaseCcPlaylistPeer { $obj = new $cls(); $obj->hydrate($row); $results[] = $obj; - CcPlaylistPeer::addInstanceToPool($obj, $key); + CcBlockPeer::addInstanceToPool($obj, $key); } // if key exists } $stmt->closeCursor(); @@ -449,21 +455,21 @@ abstract class BaseCcPlaylistPeer { * @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 (CcPlaylist object, last column rank) + * @return array (CcBlock object, last column rank) */ public static function populateObject($row, $startcol = 0) { - $key = CcPlaylistPeer::getPrimaryKeyHashFromRow($row, $startcol); - if (null !== ($obj = CcPlaylistPeer::getInstanceFromPool($key))) { + $key = CcBlockPeer::getPrimaryKeyHashFromRow($row, $startcol); + if (null !== ($obj = CcBlockPeer::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 + CcPlaylistPeer::NUM_COLUMNS; + $col = $startcol + CcBlockPeer::NUM_COLUMNS; } else { - $cls = CcPlaylistPeer::OM_CLASS; + $cls = CcBlockPeer::OM_CLASS; $obj = new $cls(); $col = $obj->hydrate($row, $startcol); - CcPlaylistPeer::addInstanceToPool($obj, $key); + CcBlockPeer::addInstanceToPool($obj, $key); } return array($obj, $col); } @@ -485,14 +491,14 @@ abstract class BaseCcPlaylistPeer { // 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(CcPlaylistPeer::TABLE_NAME); + $criteria->setPrimaryTableName(CcBlockPeer::TABLE_NAME); if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { $criteria->setDistinct(); } if (!$criteria->hasSelectClause()) { - CcPlaylistPeer::addSelectColumns($criteria); + CcBlockPeer::addSelectColumns($criteria); } $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count @@ -501,10 +507,10 @@ abstract class BaseCcPlaylistPeer { $criteria->setDbName(self::DATABASE_NAME); if ($con === null) { - $con = Propel::getConnection(CcPlaylistPeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcBlockPeer::DATABASE_NAME, Propel::CONNECTION_READ); } - $criteria->addJoin(CcPlaylistPeer::EDITEDBY, CcSubjsPeer::ID, $join_behavior); + $criteria->addJoin(CcBlockPeer::CREATOR_ID, CcSubjsPeer::ID, $join_behavior); $stmt = BasePeer::doCount($criteria, $con); @@ -519,11 +525,11 @@ abstract class BaseCcPlaylistPeer { /** - * Selects a collection of CcPlaylist objects pre-filled with their CcSubjs objects. + * Selects a collection of CcBlock objects pre-filled with their CcSubjs 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 CcPlaylist objects. + * @return array Array of CcBlock objects. * @throws PropelException Any exceptions caught during processing will be * rethrown wrapped into a PropelException. */ @@ -536,28 +542,28 @@ abstract class BaseCcPlaylistPeer { $criteria->setDbName(self::DATABASE_NAME); } - CcPlaylistPeer::addSelectColumns($criteria); - $startcol = (CcPlaylistPeer::NUM_COLUMNS - CcPlaylistPeer::NUM_LAZY_LOAD_COLUMNS); + CcBlockPeer::addSelectColumns($criteria); + $startcol = (CcBlockPeer::NUM_COLUMNS - CcBlockPeer::NUM_LAZY_LOAD_COLUMNS); CcSubjsPeer::addSelectColumns($criteria); - $criteria->addJoin(CcPlaylistPeer::EDITEDBY, CcSubjsPeer::ID, $join_behavior); + $criteria->addJoin(CcBlockPeer::CREATOR_ID, CcSubjsPeer::ID, $join_behavior); $stmt = BasePeer::doSelect($criteria, $con); $results = array(); while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $key1 = CcPlaylistPeer::getPrimaryKeyHashFromRow($row, 0); - if (null !== ($obj1 = CcPlaylistPeer::getInstanceFromPool($key1))) { + $key1 = CcBlockPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcBlockPeer::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 = CcPlaylistPeer::getOMClass(false); + $cls = CcBlockPeer::getOMClass(false); $obj1 = new $cls(); $obj1->hydrate($row); - CcPlaylistPeer::addInstanceToPool($obj1, $key1); + CcBlockPeer::addInstanceToPool($obj1, $key1); } // if $obj1 already loaded $key2 = CcSubjsPeer::getPrimaryKeyHashFromRow($row, $startcol); @@ -572,8 +578,8 @@ abstract class BaseCcPlaylistPeer { CcSubjsPeer::addInstanceToPool($obj2, $key2); } // if obj2 already loaded - // Add the $obj1 (CcPlaylist) to $obj2 (CcSubjs) - $obj2->addCcPlaylist($obj1); + // Add the $obj1 (CcBlock) to $obj2 (CcSubjs) + $obj2->addCcBlock($obj1); } // if joined row was not null @@ -601,14 +607,14 @@ abstract class BaseCcPlaylistPeer { // 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(CcPlaylistPeer::TABLE_NAME); + $criteria->setPrimaryTableName(CcBlockPeer::TABLE_NAME); if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { $criteria->setDistinct(); } if (!$criteria->hasSelectClause()) { - CcPlaylistPeer::addSelectColumns($criteria); + CcBlockPeer::addSelectColumns($criteria); } $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count @@ -617,10 +623,10 @@ abstract class BaseCcPlaylistPeer { $criteria->setDbName(self::DATABASE_NAME); if ($con === null) { - $con = Propel::getConnection(CcPlaylistPeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcBlockPeer::DATABASE_NAME, Propel::CONNECTION_READ); } - $criteria->addJoin(CcPlaylistPeer::EDITEDBY, CcSubjsPeer::ID, $join_behavior); + $criteria->addJoin(CcBlockPeer::CREATOR_ID, CcSubjsPeer::ID, $join_behavior); $stmt = BasePeer::doCount($criteria, $con); @@ -634,12 +640,12 @@ abstract class BaseCcPlaylistPeer { } /** - * Selects a collection of CcPlaylist objects pre-filled with all related objects. + * Selects a collection of CcBlock 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 CcPlaylist objects. + * @return array Array of CcBlock objects. * @throws PropelException Any exceptions caught during processing will be * rethrown wrapped into a PropelException. */ @@ -652,29 +658,29 @@ abstract class BaseCcPlaylistPeer { $criteria->setDbName(self::DATABASE_NAME); } - CcPlaylistPeer::addSelectColumns($criteria); - $startcol2 = (CcPlaylistPeer::NUM_COLUMNS - CcPlaylistPeer::NUM_LAZY_LOAD_COLUMNS); + CcBlockPeer::addSelectColumns($criteria); + $startcol2 = (CcBlockPeer::NUM_COLUMNS - CcBlockPeer::NUM_LAZY_LOAD_COLUMNS); CcSubjsPeer::addSelectColumns($criteria); $startcol3 = $startcol2 + (CcSubjsPeer::NUM_COLUMNS - CcSubjsPeer::NUM_LAZY_LOAD_COLUMNS); - $criteria->addJoin(CcPlaylistPeer::EDITEDBY, CcSubjsPeer::ID, $join_behavior); + $criteria->addJoin(CcBlockPeer::CREATOR_ID, CcSubjsPeer::ID, $join_behavior); $stmt = BasePeer::doSelect($criteria, $con); $results = array(); while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $key1 = CcPlaylistPeer::getPrimaryKeyHashFromRow($row, 0); - if (null !== ($obj1 = CcPlaylistPeer::getInstanceFromPool($key1))) { + $key1 = CcBlockPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcBlockPeer::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 = CcPlaylistPeer::getOMClass(false); + $cls = CcBlockPeer::getOMClass(false); $obj1 = new $cls(); $obj1->hydrate($row); - CcPlaylistPeer::addInstanceToPool($obj1, $key1); + CcBlockPeer::addInstanceToPool($obj1, $key1); } // if obj1 already loaded // Add objects for joined CcSubjs rows @@ -691,8 +697,8 @@ abstract class BaseCcPlaylistPeer { CcSubjsPeer::addInstanceToPool($obj2, $key2); } // if obj2 loaded - // Add the $obj1 (CcPlaylist) to the collection in $obj2 (CcSubjs) - $obj2->addCcPlaylist($obj1); + // Add the $obj1 (CcBlock) to the collection in $obj2 (CcSubjs) + $obj2->addCcBlock($obj1); } // if joined row not null $results[] = $obj1; @@ -718,10 +724,10 @@ abstract class BaseCcPlaylistPeer { */ public static function buildTableMap() { - $dbMap = Propel::getDatabaseMap(BaseCcPlaylistPeer::DATABASE_NAME); - if (!$dbMap->hasTable(BaseCcPlaylistPeer::TABLE_NAME)) + $dbMap = Propel::getDatabaseMap(BaseCcBlockPeer::DATABASE_NAME); + if (!$dbMap->hasTable(BaseCcBlockPeer::TABLE_NAME)) { - $dbMap->addTableObject(new CcPlaylistTableMap()); + $dbMap->addTableObject(new CcBlockTableMap()); } } @@ -738,13 +744,13 @@ abstract class BaseCcPlaylistPeer { */ public static function getOMClass($withPrefix = true) { - return $withPrefix ? CcPlaylistPeer::CLASS_DEFAULT : CcPlaylistPeer::OM_CLASS; + return $withPrefix ? CcBlockPeer::CLASS_DEFAULT : CcBlockPeer::OM_CLASS; } /** - * Method perform an INSERT on the database, given a CcPlaylist or Criteria object. + * Method perform an INSERT on the database, given a CcBlock or Criteria object. * - * @param mixed $values Criteria or CcPlaylist object containing data that is used to create the INSERT statement. + * @param mixed $values Criteria or CcBlock 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 @@ -753,17 +759,17 @@ abstract class BaseCcPlaylistPeer { public static function doInsert($values, PropelPDO $con = null) { if ($con === null) { - $con = Propel::getConnection(CcPlaylistPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + $con = Propel::getConnection(CcBlockPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); } if ($values instanceof Criteria) { $criteria = clone $values; // rename for clarity } else { - $criteria = $values->buildCriteria(); // build Criteria from CcPlaylist object + $criteria = $values->buildCriteria(); // build Criteria from CcBlock object } - if ($criteria->containsKey(CcPlaylistPeer::ID) && $criteria->keyContainsValue(CcPlaylistPeer::ID) ) { - throw new PropelException('Cannot insert a value for auto-increment primary key ('.CcPlaylistPeer::ID.')'); + if ($criteria->containsKey(CcBlockPeer::ID) && $criteria->keyContainsValue(CcBlockPeer::ID) ) { + throw new PropelException('Cannot insert a value for auto-increment primary key ('.CcBlockPeer::ID.')'); } @@ -785,9 +791,9 @@ abstract class BaseCcPlaylistPeer { } /** - * Method perform an UPDATE on the database, given a CcPlaylist or Criteria object. + * Method perform an UPDATE on the database, given a CcBlock or Criteria object. * - * @param mixed $values Criteria or CcPlaylist object containing data that is used to create the UPDATE statement. + * @param mixed $values Criteria or CcBlock 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 @@ -796,7 +802,7 @@ abstract class BaseCcPlaylistPeer { public static function doUpdate($values, PropelPDO $con = null) { if ($con === null) { - $con = Propel::getConnection(CcPlaylistPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + $con = Propel::getConnection(CcBlockPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); } $selectCriteria = new Criteria(self::DATABASE_NAME); @@ -804,15 +810,15 @@ abstract class BaseCcPlaylistPeer { if ($values instanceof Criteria) { $criteria = clone $values; // rename for clarity - $comparison = $criteria->getComparison(CcPlaylistPeer::ID); - $value = $criteria->remove(CcPlaylistPeer::ID); + $comparison = $criteria->getComparison(CcBlockPeer::ID); + $value = $criteria->remove(CcBlockPeer::ID); if ($value) { - $selectCriteria->add(CcPlaylistPeer::ID, $value, $comparison); + $selectCriteria->add(CcBlockPeer::ID, $value, $comparison); } else { - $selectCriteria->setPrimaryTableName(CcPlaylistPeer::TABLE_NAME); + $selectCriteria->setPrimaryTableName(CcBlockPeer::TABLE_NAME); } - } else { // $values is CcPlaylist object + } else { // $values is CcBlock object $criteria = $values->buildCriteria(); // gets full criteria $selectCriteria = $values->buildPkeyCriteria(); // gets criteria w/ primary key(s) } @@ -824,26 +830,26 @@ abstract class BaseCcPlaylistPeer { } /** - * Method to DELETE all rows from the cc_playlist table. + * Method to DELETE all rows from the cc_block 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(CcPlaylistPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + $con = Propel::getConnection(CcBlockPeer::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(CcPlaylistPeer::TABLE_NAME, $con, CcPlaylistPeer::DATABASE_NAME); + $affectedRows += BasePeer::doDeleteAll(CcBlockPeer::TABLE_NAME, $con, CcBlockPeer::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). - CcPlaylistPeer::clearInstancePool(); - CcPlaylistPeer::clearRelatedInstancePool(); + CcBlockPeer::clearInstancePool(); + CcBlockPeer::clearRelatedInstancePool(); $con->commit(); return $affectedRows; } catch (PropelException $e) { @@ -853,9 +859,9 @@ abstract class BaseCcPlaylistPeer { } /** - * Method perform a DELETE on the database, given a CcPlaylist or Criteria object OR a primary key value. + * Method perform a DELETE on the database, given a CcBlock or Criteria object OR a primary key value. * - * @param mixed $values Criteria or CcPlaylist object or primary key or array of primary keys + * @param mixed $values Criteria or CcBlock 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 @@ -866,27 +872,27 @@ abstract class BaseCcPlaylistPeer { public static function doDelete($values, PropelPDO $con = null) { if ($con === null) { - $con = Propel::getConnection(CcPlaylistPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + $con = Propel::getConnection(CcBlockPeer::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. - CcPlaylistPeer::clearInstancePool(); + CcBlockPeer::clearInstancePool(); // rename for clarity $criteria = clone $values; - } elseif ($values instanceof CcPlaylist) { // it's a model object + } elseif ($values instanceof CcBlock) { // it's a model object // invalidate the cache for this single object - CcPlaylistPeer::removeInstanceFromPool($values); + CcBlockPeer::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(CcPlaylistPeer::ID, (array) $values, Criteria::IN); + $criteria->add(CcBlockPeer::ID, (array) $values, Criteria::IN); // invalidate the cache for this object(s) foreach ((array) $values as $singleval) { - CcPlaylistPeer::removeInstanceFromPool($singleval); + CcBlockPeer::removeInstanceFromPool($singleval); } } @@ -901,7 +907,7 @@ abstract class BaseCcPlaylistPeer { $con->beginTransaction(); $affectedRows += BasePeer::doDelete($criteria, $con); - CcPlaylistPeer::clearRelatedInstancePool(); + CcBlockPeer::clearRelatedInstancePool(); $con->commit(); return $affectedRows; } catch (PropelException $e) { @@ -911,24 +917,24 @@ abstract class BaseCcPlaylistPeer { } /** - * Validates all modified columns of given CcPlaylist object. + * Validates all modified columns of given CcBlock 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 CcPlaylist $obj The object to validate. + * @param CcBlock $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(CcPlaylist $obj, $cols = null) + public static function doValidate(CcBlock $obj, $cols = null) { $columns = array(); if ($cols) { - $dbMap = Propel::getDatabaseMap(CcPlaylistPeer::DATABASE_NAME); - $tableMap = $dbMap->getTable(CcPlaylistPeer::TABLE_NAME); + $dbMap = Propel::getDatabaseMap(CcBlockPeer::DATABASE_NAME); + $tableMap = $dbMap->getTable(CcBlockPeer::TABLE_NAME); if (! is_array($cols)) { $cols = array($cols); @@ -944,7 +950,7 @@ abstract class BaseCcPlaylistPeer { } - return BasePeer::doValidate(CcPlaylistPeer::DATABASE_NAME, CcPlaylistPeer::TABLE_NAME, $columns); + return BasePeer::doValidate(CcBlockPeer::DATABASE_NAME, CcBlockPeer::TABLE_NAME, $columns); } /** @@ -952,23 +958,23 @@ abstract class BaseCcPlaylistPeer { * * @param int $pk the primary key. * @param PropelPDO $con the connection to use - * @return CcPlaylist + * @return CcBlock */ public static function retrieveByPK($pk, PropelPDO $con = null) { - if (null !== ($obj = CcPlaylistPeer::getInstanceFromPool((string) $pk))) { + if (null !== ($obj = CcBlockPeer::getInstanceFromPool((string) $pk))) { return $obj; } if ($con === null) { - $con = Propel::getConnection(CcPlaylistPeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcBlockPeer::DATABASE_NAME, Propel::CONNECTION_READ); } - $criteria = new Criteria(CcPlaylistPeer::DATABASE_NAME); - $criteria->add(CcPlaylistPeer::ID, $pk); + $criteria = new Criteria(CcBlockPeer::DATABASE_NAME); + $criteria->add(CcBlockPeer::ID, $pk); - $v = CcPlaylistPeer::doSelect($criteria, $con); + $v = CcBlockPeer::doSelect($criteria, $con); return !empty($v) > 0 ? $v[0] : null; } @@ -984,23 +990,23 @@ abstract class BaseCcPlaylistPeer { public static function retrieveByPKs($pks, PropelPDO $con = null) { if ($con === null) { - $con = Propel::getConnection(CcPlaylistPeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcBlockPeer::DATABASE_NAME, Propel::CONNECTION_READ); } $objs = null; if (empty($pks)) { $objs = array(); } else { - $criteria = new Criteria(CcPlaylistPeer::DATABASE_NAME); - $criteria->add(CcPlaylistPeer::ID, $pks, Criteria::IN); - $objs = CcPlaylistPeer::doSelect($criteria, $con); + $criteria = new Criteria(CcBlockPeer::DATABASE_NAME); + $criteria->add(CcBlockPeer::ID, $pks, Criteria::IN); + $objs = CcBlockPeer::doSelect($criteria, $con); } return $objs; } -} // BaseCcPlaylistPeer +} // BaseCcBlockPeer // This is the static code needed to register the TableMap for this table with the main Propel class. // -BaseCcPlaylistPeer::buildTableMap(); +BaseCcBlockPeer::buildTableMap(); diff --git a/airtime_mvc/application/models/airtime/om/BaseCcBlockQuery.php b/airtime_mvc/application/models/airtime/om/BaseCcBlockQuery.php new file mode 100644 index 000000000..100efd61e --- /dev/null +++ b/airtime_mvc/application/models/airtime/om/BaseCcBlockQuery.php @@ -0,0 +1,646 @@ +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 CcBlock|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ((null !== ($obj = CcBlockPeer::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 CcBlockQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + return $this->addUsingAlias(CcBlockPeer::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 CcBlockQuery The current query, for fluid interface + */ + public function filterByPrimaryKeys($keys) + { + return $this->addUsingAlias(CcBlockPeer::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 CcBlockQuery 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(CcBlockPeer::ID, $dbId, $comparison); + } + + /** + * Filter the query on the name column + * + * @param string $dbName 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 CcBlockQuery The current query, for fluid interface + */ + public function filterByDbName($dbName = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($dbName)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $dbName)) { + $dbName = str_replace('*', '%', $dbName); + $comparison = Criteria::LIKE; + } + } + return $this->addUsingAlias(CcBlockPeer::NAME, $dbName, $comparison); + } + + /** + * Filter the query on the mtime column + * + * @param string|array $dbMtime 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 CcBlockQuery The current query, for fluid interface + */ + public function filterByDbMtime($dbMtime = null, $comparison = null) + { + if (is_array($dbMtime)) { + $useMinMax = false; + if (isset($dbMtime['min'])) { + $this->addUsingAlias(CcBlockPeer::MTIME, $dbMtime['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbMtime['max'])) { + $this->addUsingAlias(CcBlockPeer::MTIME, $dbMtime['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcBlockPeer::MTIME, $dbMtime, $comparison); + } + + /** + * Filter the query on the utime column + * + * @param string|array $dbUtime 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 CcBlockQuery The current query, for fluid interface + */ + public function filterByDbUtime($dbUtime = null, $comparison = null) + { + if (is_array($dbUtime)) { + $useMinMax = false; + if (isset($dbUtime['min'])) { + $this->addUsingAlias(CcBlockPeer::UTIME, $dbUtime['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbUtime['max'])) { + $this->addUsingAlias(CcBlockPeer::UTIME, $dbUtime['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcBlockPeer::UTIME, $dbUtime, $comparison); + } + + /** + * Filter the query on the creator_id column + * + * @param int|array $dbCreatorId 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 CcBlockQuery The current query, for fluid interface + */ + public function filterByDbCreatorId($dbCreatorId = null, $comparison = null) + { + if (is_array($dbCreatorId)) { + $useMinMax = false; + if (isset($dbCreatorId['min'])) { + $this->addUsingAlias(CcBlockPeer::CREATOR_ID, $dbCreatorId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbCreatorId['max'])) { + $this->addUsingAlias(CcBlockPeer::CREATOR_ID, $dbCreatorId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcBlockPeer::CREATOR_ID, $dbCreatorId, $comparison); + } + + /** + * Filter the query on the description column + * + * @param string $dbDescription 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 CcBlockQuery The current query, for fluid interface + */ + public function filterByDbDescription($dbDescription = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($dbDescription)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $dbDescription)) { + $dbDescription = str_replace('*', '%', $dbDescription); + $comparison = Criteria::LIKE; + } + } + return $this->addUsingAlias(CcBlockPeer::DESCRIPTION, $dbDescription, $comparison); + } + + /** + * Filter the query on the length column + * + * @param string $dbLength 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 CcBlockQuery The current query, for fluid interface + */ + public function filterByDbLength($dbLength = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($dbLength)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $dbLength)) { + $dbLength = str_replace('*', '%', $dbLength); + $comparison = Criteria::LIKE; + } + } + return $this->addUsingAlias(CcBlockPeer::LENGTH, $dbLength, $comparison); + } + + /** + * Filter the query on the type column + * + * @param string $dbType 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 CcBlockQuery The current query, for fluid interface + */ + public function filterByDbType($dbType = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($dbType)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $dbType)) { + $dbType = str_replace('*', '%', $dbType); + $comparison = Criteria::LIKE; + } + } + return $this->addUsingAlias(CcBlockPeer::TYPE, $dbType, $comparison); + } + + /** + * Filter the query by a related CcSubjs object + * + * @param CcSubjs $ccSubjs 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 filterByCcSubjs($ccSubjs, $comparison = null) + { + return $this + ->addUsingAlias(CcBlockPeer::CREATOR_ID, $ccSubjs->getDbId(), $comparison); + } + + /** + * Adds a JOIN clause to the query using the CcSubjs 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 joinCcSubjs($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('CcSubjs'); + + // 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, 'CcSubjs'); + } + + return $this; + } + + /** + * Use the CcSubjs relation CcSubjs 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 CcSubjsQuery A secondary query class using the current class as primary query + */ + public function useCcSubjsQuery($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + { + return $this + ->joinCcSubjs($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'CcSubjs', 'CcSubjsQuery'); + } + + /** + * Filter the query by a related CcPlaylistcontents object + * + * @param CcPlaylistcontents $ccPlaylistcontents 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 filterByCcPlaylistcontents($ccPlaylistcontents, $comparison = null) + { + return $this + ->addUsingAlias(CcBlockPeer::ID, $ccPlaylistcontents->getDbBlockId(), $comparison); + } + + /** + * Adds a JOIN clause to the query using the CcPlaylistcontents 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 joinCcPlaylistcontents($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('CcPlaylistcontents'); + + // 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, 'CcPlaylistcontents'); + } + + return $this; + } + + /** + * Use the CcPlaylistcontents relation CcPlaylistcontents 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 CcPlaylistcontentsQuery A secondary query class using the current class as primary query + */ + public function useCcPlaylistcontentsQuery($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + { + return $this + ->joinCcPlaylistcontents($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'CcPlaylistcontents', 'CcPlaylistcontentsQuery'); + } + + /** + * Filter the query by a related CcBlockcontents object + * + * @param CcBlockcontents $ccBlockcontents 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 filterByCcBlockcontents($ccBlockcontents, $comparison = null) + { + return $this + ->addUsingAlias(CcBlockPeer::ID, $ccBlockcontents->getDbBlockId(), $comparison); + } + + /** + * Adds a JOIN clause to the query using the CcBlockcontents 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 joinCcBlockcontents($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('CcBlockcontents'); + + // 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, 'CcBlockcontents'); + } + + return $this; + } + + /** + * Use the CcBlockcontents relation CcBlockcontents 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 CcBlockcontentsQuery A secondary query class using the current class as primary query + */ + public function useCcBlockcontentsQuery($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + { + return $this + ->joinCcBlockcontents($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'CcBlockcontents', 'CcBlockcontentsQuery'); + } + + /** + * Filter the query by a related CcBlockcriteria object + * + * @param CcBlockcriteria $ccBlockcriteria 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 filterByCcBlockcriteria($ccBlockcriteria, $comparison = null) + { + return $this + ->addUsingAlias(CcBlockPeer::ID, $ccBlockcriteria->getDbBlockId(), $comparison); + } + + /** + * Adds a JOIN clause to the query using the CcBlockcriteria 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 joinCcBlockcriteria($relationAlias = '', $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('CcBlockcriteria'); + + // 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, 'CcBlockcriteria'); + } + + return $this; + } + + /** + * Use the CcBlockcriteria relation CcBlockcriteria 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 CcBlockcriteriaQuery A secondary query class using the current class as primary query + */ + public function useCcBlockcriteriaQuery($relationAlias = '', $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinCcBlockcriteria($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'CcBlockcriteria', 'CcBlockcriteriaQuery'); + } + + /** + * Exclude object from result + * + * @param CcBlock $ccBlock Object to remove from the list of results + * + * @return CcBlockQuery The current query, for fluid interface + */ + public function prune($ccBlock = null) + { + if ($ccBlock) { + $this->addUsingAlias(CcBlockPeer::ID, $ccBlock->getDbId(), Criteria::NOT_EQUAL); + } + + return $this; + } + +} // BaseCcBlockQuery diff --git a/install_minimal/upgrades/airtime-2.0.0/propel/airtime/om/BaseCcPlaylistcontents.php b/airtime_mvc/application/models/airtime/om/BaseCcBlockcontents.php similarity index 68% rename from install_minimal/upgrades/airtime-2.0.0/propel/airtime/om/BaseCcPlaylistcontents.php rename to airtime_mvc/application/models/airtime/om/BaseCcBlockcontents.php index 0118d5038..d6beab8b4 100644 --- a/install_minimal/upgrades/airtime-2.0.0/propel/airtime/om/BaseCcPlaylistcontents.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcBlockcontents.php @@ -2,25 +2,25 @@ /** - * Base class that represents a row from the 'cc_playlistcontents' table. + * Base class that represents a row from the 'cc_blockcontents' table. * * * * @package propel.generator.airtime.om */ -abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent +abstract class BaseCcBlockcontents extends BaseObject implements Persistent { /** * Peer class name */ - const PEER = 'CcPlaylistcontentsPeer'; + const PEER = 'CcBlockcontentsPeer'; /** * The Peer class. * Instance provides a convenient way of calling static methods on a class * that calling code may not be able to identify. - * @var CcPlaylistcontentsPeer + * @var CcBlockcontentsPeer */ protected static $peer; @@ -31,10 +31,10 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent protected $id; /** - * The value for the playlist_id field. + * The value for the block_id field. * @var int */ - protected $playlist_id; + protected $block_id; /** * The value for the file_id field. @@ -89,9 +89,9 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent protected $aCcFiles; /** - * @var CcPlaylist + * @var CcBlock */ - protected $aCcPlaylist; + protected $aCcBlock; /** * Flag to prevent endless save loop, if this object is referenced @@ -107,6 +107,9 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent */ protected $alreadyInValidation = false; + // aggregate_column_relation behavior + protected $oldCcBlock; + /** * Applies default values to this object. * This method should be called from the object's constructor (or @@ -123,7 +126,7 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent } /** - * Initializes internal state of BaseCcPlaylistcontents object. + * Initializes internal state of BaseCcBlockcontents object. * @see applyDefaults() */ public function __construct() @@ -143,13 +146,13 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent } /** - * Get the [playlist_id] column value. + * Get the [block_id] column value. * * @return int */ - public function getDbPlaylistId() + public function getDbBlockId() { - return $this->playlist_id; + return $this->block_id; } /** @@ -173,102 +176,33 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent } /** - * Get the [optionally formatted] temporal [cliplength] column value. + * Get the [cliplength] column value. * - * - * @param string $format The date/time format string (either date()-style or strftime()-style). - * If format is NULL, then the raw DateTime object will be returned. - * @return mixed Formatted date/time value as string or DateTime object (if format is NULL), NULL if column is NULL - * @throws PropelException - if unable to parse/validate the date/time value. + * @return string */ - public function getDbCliplength($format = '%X') + public function getDbCliplength() { - if ($this->cliplength === null) { - return null; - } - - - - try { - $dt = new DateTime($this->cliplength); - } catch (Exception $x) { - throw new PropelException("Internally stored date/time/timestamp value could not be converted to DateTime: " . var_export($this->cliplength, true), $x); - } - - if ($format === null) { - // Because propel.useDateTimeClass is TRUE, we return a DateTime object. - return $dt; - } elseif (strpos($format, '%') !== false) { - return strftime($format, $dt->format('U')); - } else { - return $dt->format($format); - } + return $this->cliplength; } /** - * Get the [optionally formatted] temporal [cuein] column value. + * Get the [cuein] column value. * - * - * @param string $format The date/time format string (either date()-style or strftime()-style). - * If format is NULL, then the raw DateTime object will be returned. - * @return mixed Formatted date/time value as string or DateTime object (if format is NULL), NULL if column is NULL - * @throws PropelException - if unable to parse/validate the date/time value. + * @return string */ - public function getDbCuein($format = '%X') + public function getDbCuein() { - if ($this->cuein === null) { - return null; - } - - - - try { - $dt = new DateTime($this->cuein); - } catch (Exception $x) { - throw new PropelException("Internally stored date/time/timestamp value could not be converted to DateTime: " . var_export($this->cuein, true), $x); - } - - if ($format === null) { - // Because propel.useDateTimeClass is TRUE, we return a DateTime object. - return $dt; - } elseif (strpos($format, '%') !== false) { - return strftime($format, $dt->format('U')); - } else { - return $dt->format($format); - } + return $this->cuein; } /** - * Get the [optionally formatted] temporal [cueout] column value. + * Get the [cueout] column value. * - * - * @param string $format The date/time format string (either date()-style or strftime()-style). - * If format is NULL, then the raw DateTime object will be returned. - * @return mixed Formatted date/time value as string or DateTime object (if format is NULL), NULL if column is NULL - * @throws PropelException - if unable to parse/validate the date/time value. + * @return string */ - public function getDbCueout($format = '%X') + public function getDbCueout() { - if ($this->cueout === null) { - return null; - } - - - - try { - $dt = new DateTime($this->cueout); - } catch (Exception $x) { - throw new PropelException("Internally stored date/time/timestamp value could not be converted to DateTime: " . var_export($this->cueout, true), $x); - } - - if ($format === null) { - // Because propel.useDateTimeClass is TRUE, we return a DateTime object. - return $dt; - } elseif (strpos($format, '%') !== false) { - return strftime($format, $dt->format('U')); - } else { - return $dt->format($format); - } + return $this->cueout; } /** @@ -341,7 +275,7 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent * Set the value of [id] column. * * @param int $v new value - * @return CcPlaylistcontents The current object (for fluent API support) + * @return CcBlockcontents The current object (for fluent API support) */ public function setDbId($v) { @@ -351,41 +285,41 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent if ($this->id !== $v) { $this->id = $v; - $this->modifiedColumns[] = CcPlaylistcontentsPeer::ID; + $this->modifiedColumns[] = CcBlockcontentsPeer::ID; } return $this; } // setDbId() /** - * Set the value of [playlist_id] column. + * Set the value of [block_id] column. * * @param int $v new value - * @return CcPlaylistcontents The current object (for fluent API support) + * @return CcBlockcontents The current object (for fluent API support) */ - public function setDbPlaylistId($v) + public function setDbBlockId($v) { if ($v !== null) { $v = (int) $v; } - if ($this->playlist_id !== $v) { - $this->playlist_id = $v; - $this->modifiedColumns[] = CcPlaylistcontentsPeer::PLAYLIST_ID; + if ($this->block_id !== $v) { + $this->block_id = $v; + $this->modifiedColumns[] = CcBlockcontentsPeer::BLOCK_ID; } - if ($this->aCcPlaylist !== null && $this->aCcPlaylist->getDbId() !== $v) { - $this->aCcPlaylist = null; + if ($this->aCcBlock !== null && $this->aCcBlock->getDbId() !== $v) { + $this->aCcBlock = null; } return $this; - } // setDbPlaylistId() + } // setDbBlockId() /** * Set the value of [file_id] column. * * @param int $v new value - * @return CcPlaylistcontents The current object (for fluent API support) + * @return CcBlockcontents The current object (for fluent API support) */ public function setDbFileId($v) { @@ -395,7 +329,7 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent if ($this->file_id !== $v) { $this->file_id = $v; - $this->modifiedColumns[] = CcPlaylistcontentsPeer::FILE_ID; + $this->modifiedColumns[] = CcBlockcontentsPeer::FILE_ID; } if ($this->aCcFiles !== null && $this->aCcFiles->getDbId() !== $v) { @@ -409,7 +343,7 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent * Set the value of [position] column. * * @param int $v new value - * @return CcPlaylistcontents The current object (for fluent API support) + * @return CcBlockcontents The current object (for fluent API support) */ public function setDbPosition($v) { @@ -419,158 +353,68 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent if ($this->position !== $v) { $this->position = $v; - $this->modifiedColumns[] = CcPlaylistcontentsPeer::POSITION; + $this->modifiedColumns[] = CcBlockcontentsPeer::POSITION; } return $this; } // setDbPosition() /** - * Sets the value of [cliplength] column to a normalized version of the date/time value specified. + * Set the value of [cliplength] column. * - * @param mixed $v string, integer (timestamp), or DateTime value. Empty string will - * be treated as NULL for temporal objects. - * @return CcPlaylistcontents The current object (for fluent API support) + * @param string $v new value + * @return CcBlockcontents The current object (for fluent API support) */ public function setDbCliplength($v) { - // we treat '' as NULL for temporal objects because DateTime('') == DateTime('now') - // -- which is unexpected, to say the least. - if ($v === null || $v === '') { - $dt = null; - } elseif ($v instanceof DateTime) { - $dt = $v; - } else { - // some string/numeric value passed; we normalize that so that we can - // validate it. - try { - if (is_numeric($v)) { // if it's a unix timestamp - $dt = new DateTime('@'.$v, new DateTimeZone('UTC')); - // We have to explicitly specify and then change the time zone because of a - // DateTime bug: http://bugs.php.net/bug.php?id=43003 - $dt->setTimeZone(new DateTimeZone(date_default_timezone_get())); - } else { - $dt = new DateTime($v); - } - } catch (Exception $x) { - throw new PropelException('Error parsing date/time value: ' . var_export($v, true), $x); - } + if ($v !== null) { + $v = (string) $v; } - if ( $this->cliplength !== null || $dt !== null ) { - // (nested ifs are a little easier to read in this case) - - $currNorm = ($this->cliplength !== null && $tmpDt = new DateTime($this->cliplength)) ? $tmpDt->format('H:i:s') : null; - $newNorm = ($dt !== null) ? $dt->format('H:i:s') : null; - - if ( ($currNorm !== $newNorm) // normalized values don't match - || ($dt->format('H:i:s') === '00:00:00') // or the entered value matches the default - ) - { - $this->cliplength = ($dt ? $dt->format('H:i:s') : null); - $this->modifiedColumns[] = CcPlaylistcontentsPeer::CLIPLENGTH; - } - } // if either are not null + if ($this->cliplength !== $v || $this->isNew()) { + $this->cliplength = $v; + $this->modifiedColumns[] = CcBlockcontentsPeer::CLIPLENGTH; + } return $this; } // setDbCliplength() /** - * Sets the value of [cuein] column to a normalized version of the date/time value specified. + * Set the value of [cuein] column. * - * @param mixed $v string, integer (timestamp), or DateTime value. Empty string will - * be treated as NULL for temporal objects. - * @return CcPlaylistcontents The current object (for fluent API support) + * @param string $v new value + * @return CcBlockcontents The current object (for fluent API support) */ public function setDbCuein($v) { - // we treat '' as NULL for temporal objects because DateTime('') == DateTime('now') - // -- which is unexpected, to say the least. - if ($v === null || $v === '') { - $dt = null; - } elseif ($v instanceof DateTime) { - $dt = $v; - } else { - // some string/numeric value passed; we normalize that so that we can - // validate it. - try { - if (is_numeric($v)) { // if it's a unix timestamp - $dt = new DateTime('@'.$v, new DateTimeZone('UTC')); - // We have to explicitly specify and then change the time zone because of a - // DateTime bug: http://bugs.php.net/bug.php?id=43003 - $dt->setTimeZone(new DateTimeZone(date_default_timezone_get())); - } else { - $dt = new DateTime($v); - } - } catch (Exception $x) { - throw new PropelException('Error parsing date/time value: ' . var_export($v, true), $x); - } + if ($v !== null) { + $v = (string) $v; } - if ( $this->cuein !== null || $dt !== null ) { - // (nested ifs are a little easier to read in this case) - - $currNorm = ($this->cuein !== null && $tmpDt = new DateTime($this->cuein)) ? $tmpDt->format('H:i:s') : null; - $newNorm = ($dt !== null) ? $dt->format('H:i:s') : null; - - if ( ($currNorm !== $newNorm) // normalized values don't match - || ($dt->format('H:i:s') === '00:00:00') // or the entered value matches the default - ) - { - $this->cuein = ($dt ? $dt->format('H:i:s') : null); - $this->modifiedColumns[] = CcPlaylistcontentsPeer::CUEIN; - } - } // if either are not null + if ($this->cuein !== $v || $this->isNew()) { + $this->cuein = $v; + $this->modifiedColumns[] = CcBlockcontentsPeer::CUEIN; + } return $this; } // setDbCuein() /** - * Sets the value of [cueout] column to a normalized version of the date/time value specified. + * Set the value of [cueout] column. * - * @param mixed $v string, integer (timestamp), or DateTime value. Empty string will - * be treated as NULL for temporal objects. - * @return CcPlaylistcontents The current object (for fluent API support) + * @param string $v new value + * @return CcBlockcontents The current object (for fluent API support) */ public function setDbCueout($v) { - // we treat '' as NULL for temporal objects because DateTime('') == DateTime('now') - // -- which is unexpected, to say the least. - if ($v === null || $v === '') { - $dt = null; - } elseif ($v instanceof DateTime) { - $dt = $v; - } else { - // some string/numeric value passed; we normalize that so that we can - // validate it. - try { - if (is_numeric($v)) { // if it's a unix timestamp - $dt = new DateTime('@'.$v, new DateTimeZone('UTC')); - // We have to explicitly specify and then change the time zone because of a - // DateTime bug: http://bugs.php.net/bug.php?id=43003 - $dt->setTimeZone(new DateTimeZone(date_default_timezone_get())); - } else { - $dt = new DateTime($v); - } - } catch (Exception $x) { - throw new PropelException('Error parsing date/time value: ' . var_export($v, true), $x); - } + if ($v !== null) { + $v = (string) $v; } - if ( $this->cueout !== null || $dt !== null ) { - // (nested ifs are a little easier to read in this case) - - $currNorm = ($this->cueout !== null && $tmpDt = new DateTime($this->cueout)) ? $tmpDt->format('H:i:s') : null; - $newNorm = ($dt !== null) ? $dt->format('H:i:s') : null; - - if ( ($currNorm !== $newNorm) // normalized values don't match - || ($dt->format('H:i:s') === '00:00:00') // or the entered value matches the default - ) - { - $this->cueout = ($dt ? $dt->format('H:i:s') : null); - $this->modifiedColumns[] = CcPlaylistcontentsPeer::CUEOUT; - } - } // if either are not null + if ($this->cueout !== $v || $this->isNew()) { + $this->cueout = $v; + $this->modifiedColumns[] = CcBlockcontentsPeer::CUEOUT; + } return $this; } // setDbCueout() @@ -580,7 +424,7 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent * * @param mixed $v string, integer (timestamp), or DateTime value. Empty string will * be treated as NULL for temporal objects. - * @return CcPlaylistcontents The current object (for fluent API support) + * @return CcBlockcontents The current object (for fluent API support) */ public function setDbFadein($v) { @@ -618,7 +462,7 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent ) { $this->fadein = ($dt ? $dt->format('H:i:s') : null); - $this->modifiedColumns[] = CcPlaylistcontentsPeer::FADEIN; + $this->modifiedColumns[] = CcBlockcontentsPeer::FADEIN; } } // if either are not null @@ -630,7 +474,7 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent * * @param mixed $v string, integer (timestamp), or DateTime value. Empty string will * be treated as NULL for temporal objects. - * @return CcPlaylistcontents The current object (for fluent API support) + * @return CcBlockcontents The current object (for fluent API support) */ public function setDbFadeout($v) { @@ -668,7 +512,7 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent ) { $this->fadeout = ($dt ? $dt->format('H:i:s') : null); - $this->modifiedColumns[] = CcPlaylistcontentsPeer::FADEOUT; + $this->modifiedColumns[] = CcBlockcontentsPeer::FADEOUT; } } // if either are not null @@ -728,7 +572,7 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent try { $this->id = ($row[$startcol + 0] !== null) ? (int) $row[$startcol + 0] : null; - $this->playlist_id = ($row[$startcol + 1] !== null) ? (int) $row[$startcol + 1] : null; + $this->block_id = ($row[$startcol + 1] !== null) ? (int) $row[$startcol + 1] : null; $this->file_id = ($row[$startcol + 2] !== null) ? (int) $row[$startcol + 2] : null; $this->position = ($row[$startcol + 3] !== null) ? (int) $row[$startcol + 3] : null; $this->cliplength = ($row[$startcol + 4] !== null) ? (string) $row[$startcol + 4] : null; @@ -744,10 +588,10 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent $this->ensureConsistency(); } - return $startcol + 9; // 9 = CcPlaylistcontentsPeer::NUM_COLUMNS - CcPlaylistcontentsPeer::NUM_LAZY_LOAD_COLUMNS). + return $startcol + 9; // 9 = CcBlockcontentsPeer::NUM_COLUMNS - CcBlockcontentsPeer::NUM_LAZY_LOAD_COLUMNS). } catch (Exception $e) { - throw new PropelException("Error populating CcPlaylistcontents object", $e); + throw new PropelException("Error populating CcBlockcontents object", $e); } } @@ -767,8 +611,8 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent public function ensureConsistency() { - if ($this->aCcPlaylist !== null && $this->playlist_id !== $this->aCcPlaylist->getDbId()) { - $this->aCcPlaylist = null; + if ($this->aCcBlock !== null && $this->block_id !== $this->aCcBlock->getDbId()) { + $this->aCcBlock = null; } if ($this->aCcFiles !== null && $this->file_id !== $this->aCcFiles->getDbId()) { $this->aCcFiles = null; @@ -796,13 +640,13 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent } if ($con === null) { - $con = Propel::getConnection(CcPlaylistcontentsPeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcBlockcontentsPeer::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 = CcPlaylistcontentsPeer::doSelectStmt($this->buildPkeyCriteria(), $con); + $stmt = CcBlockcontentsPeer::doSelectStmt($this->buildPkeyCriteria(), $con); $row = $stmt->fetch(PDO::FETCH_NUM); $stmt->closeCursor(); if (!$row) { @@ -813,7 +657,7 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent if ($deep) { // also de-associate any related objects? $this->aCcFiles = null; - $this->aCcPlaylist = null; + $this->aCcBlock = null; } // if (deep) } @@ -833,14 +677,14 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent } if ($con === null) { - $con = Propel::getConnection(CcPlaylistcontentsPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + $con = Propel::getConnection(CcBlockcontentsPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); } $con->beginTransaction(); try { $ret = $this->preDelete($con); if ($ret) { - CcPlaylistcontentsQuery::create() + CcBlockcontentsQuery::create() ->filterByPrimaryKey($this->getPrimaryKey()) ->delete($con); $this->postDelete($con); @@ -875,7 +719,7 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent } if ($con === null) { - $con = Propel::getConnection(CcPlaylistcontentsPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + $con = Propel::getConnection(CcBlockcontentsPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); } $con->beginTransaction(); @@ -895,7 +739,9 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent $this->postUpdate($con); } $this->postSave($con); - CcPlaylistcontentsPeer::addInstanceToPool($this); + // aggregate_column_relation behavior + $this->updateRelatedCcBlock($con); + CcBlockcontentsPeer::addInstanceToPool($this); } else { $affectedRows = 0; } @@ -936,23 +782,23 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent $this->setCcFiles($this->aCcFiles); } - if ($this->aCcPlaylist !== null) { - if ($this->aCcPlaylist->isModified() || $this->aCcPlaylist->isNew()) { - $affectedRows += $this->aCcPlaylist->save($con); + if ($this->aCcBlock !== null) { + if ($this->aCcBlock->isModified() || $this->aCcBlock->isNew()) { + $affectedRows += $this->aCcBlock->save($con); } - $this->setCcPlaylist($this->aCcPlaylist); + $this->setCcBlock($this->aCcBlock); } if ($this->isNew() ) { - $this->modifiedColumns[] = CcPlaylistcontentsPeer::ID; + $this->modifiedColumns[] = CcBlockcontentsPeer::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(CcPlaylistcontentsPeer::ID) ) { - throw new PropelException('Cannot insert a value for auto-increment primary key ('.CcPlaylistcontentsPeer::ID.')'); + if ($criteria->keyContainsValue(CcBlockcontentsPeer::ID) ) { + throw new PropelException('Cannot insert a value for auto-increment primary key ('.CcBlockcontentsPeer::ID.')'); } $pk = BasePeer::doInsert($criteria, $con); @@ -960,7 +806,7 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent $this->setDbId($pk); //[IMV] update autoincrement primary key $this->setNew(false); } else { - $affectedRows += CcPlaylistcontentsPeer::doUpdate($this, $con); + $affectedRows += CcBlockcontentsPeer::doUpdate($this, $con); } $this->resetModified(); // [HL] After being saved an object is no longer 'modified' @@ -1043,14 +889,14 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent } } - if ($this->aCcPlaylist !== null) { - if (!$this->aCcPlaylist->validate($columns)) { - $failureMap = array_merge($failureMap, $this->aCcPlaylist->getValidationFailures()); + if ($this->aCcBlock !== null) { + if (!$this->aCcBlock->validate($columns)) { + $failureMap = array_merge($failureMap, $this->aCcBlock->getValidationFailures()); } } - if (($retval = CcPlaylistcontentsPeer::doValidate($this, $columns)) !== true) { + if (($retval = CcBlockcontentsPeer::doValidate($this, $columns)) !== true) { $failureMap = array_merge($failureMap, $retval); } @@ -1073,7 +919,7 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent */ public function getByName($name, $type = BasePeer::TYPE_PHPNAME) { - $pos = CcPlaylistcontentsPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); + $pos = CcBlockcontentsPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); $field = $this->getByPosition($pos); return $field; } @@ -1092,7 +938,7 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent return $this->getDbId(); break; case 1: - return $this->getDbPlaylistId(); + return $this->getDbBlockId(); break; case 2: return $this->getDbFileId(); @@ -1137,10 +983,10 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent */ public function toArray($keyType = BasePeer::TYPE_PHPNAME, $includeLazyLoadColumns = true, $includeForeignObjects = false) { - $keys = CcPlaylistcontentsPeer::getFieldNames($keyType); + $keys = CcBlockcontentsPeer::getFieldNames($keyType); $result = array( $keys[0] => $this->getDbId(), - $keys[1] => $this->getDbPlaylistId(), + $keys[1] => $this->getDbBlockId(), $keys[2] => $this->getDbFileId(), $keys[3] => $this->getDbPosition(), $keys[4] => $this->getDbCliplength(), @@ -1153,8 +999,8 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent if (null !== $this->aCcFiles) { $result['CcFiles'] = $this->aCcFiles->toArray($keyType, $includeLazyLoadColumns, true); } - if (null !== $this->aCcPlaylist) { - $result['CcPlaylist'] = $this->aCcPlaylist->toArray($keyType, $includeLazyLoadColumns, true); + if (null !== $this->aCcBlock) { + $result['CcBlock'] = $this->aCcBlock->toArray($keyType, $includeLazyLoadColumns, true); } } return $result; @@ -1172,7 +1018,7 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent */ public function setByName($name, $value, $type = BasePeer::TYPE_PHPNAME) { - $pos = CcPlaylistcontentsPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); + $pos = CcBlockcontentsPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); return $this->setByPosition($pos, $value); } @@ -1191,7 +1037,7 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent $this->setDbId($value); break; case 1: - $this->setDbPlaylistId($value); + $this->setDbBlockId($value); break; case 2: $this->setDbFileId($value); @@ -1236,10 +1082,10 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent */ public function fromArray($arr, $keyType = BasePeer::TYPE_PHPNAME) { - $keys = CcPlaylistcontentsPeer::getFieldNames($keyType); + $keys = CcBlockcontentsPeer::getFieldNames($keyType); if (array_key_exists($keys[0], $arr)) $this->setDbId($arr[$keys[0]]); - if (array_key_exists($keys[1], $arr)) $this->setDbPlaylistId($arr[$keys[1]]); + if (array_key_exists($keys[1], $arr)) $this->setDbBlockId($arr[$keys[1]]); if (array_key_exists($keys[2], $arr)) $this->setDbFileId($arr[$keys[2]]); if (array_key_exists($keys[3], $arr)) $this->setDbPosition($arr[$keys[3]]); if (array_key_exists($keys[4], $arr)) $this->setDbCliplength($arr[$keys[4]]); @@ -1256,17 +1102,17 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent */ public function buildCriteria() { - $criteria = new Criteria(CcPlaylistcontentsPeer::DATABASE_NAME); + $criteria = new Criteria(CcBlockcontentsPeer::DATABASE_NAME); - if ($this->isColumnModified(CcPlaylistcontentsPeer::ID)) $criteria->add(CcPlaylistcontentsPeer::ID, $this->id); - if ($this->isColumnModified(CcPlaylistcontentsPeer::PLAYLIST_ID)) $criteria->add(CcPlaylistcontentsPeer::PLAYLIST_ID, $this->playlist_id); - if ($this->isColumnModified(CcPlaylistcontentsPeer::FILE_ID)) $criteria->add(CcPlaylistcontentsPeer::FILE_ID, $this->file_id); - if ($this->isColumnModified(CcPlaylistcontentsPeer::POSITION)) $criteria->add(CcPlaylistcontentsPeer::POSITION, $this->position); - if ($this->isColumnModified(CcPlaylistcontentsPeer::CLIPLENGTH)) $criteria->add(CcPlaylistcontentsPeer::CLIPLENGTH, $this->cliplength); - if ($this->isColumnModified(CcPlaylistcontentsPeer::CUEIN)) $criteria->add(CcPlaylistcontentsPeer::CUEIN, $this->cuein); - if ($this->isColumnModified(CcPlaylistcontentsPeer::CUEOUT)) $criteria->add(CcPlaylistcontentsPeer::CUEOUT, $this->cueout); - if ($this->isColumnModified(CcPlaylistcontentsPeer::FADEIN)) $criteria->add(CcPlaylistcontentsPeer::FADEIN, $this->fadein); - if ($this->isColumnModified(CcPlaylistcontentsPeer::FADEOUT)) $criteria->add(CcPlaylistcontentsPeer::FADEOUT, $this->fadeout); + if ($this->isColumnModified(CcBlockcontentsPeer::ID)) $criteria->add(CcBlockcontentsPeer::ID, $this->id); + if ($this->isColumnModified(CcBlockcontentsPeer::BLOCK_ID)) $criteria->add(CcBlockcontentsPeer::BLOCK_ID, $this->block_id); + if ($this->isColumnModified(CcBlockcontentsPeer::FILE_ID)) $criteria->add(CcBlockcontentsPeer::FILE_ID, $this->file_id); + if ($this->isColumnModified(CcBlockcontentsPeer::POSITION)) $criteria->add(CcBlockcontentsPeer::POSITION, $this->position); + if ($this->isColumnModified(CcBlockcontentsPeer::CLIPLENGTH)) $criteria->add(CcBlockcontentsPeer::CLIPLENGTH, $this->cliplength); + if ($this->isColumnModified(CcBlockcontentsPeer::CUEIN)) $criteria->add(CcBlockcontentsPeer::CUEIN, $this->cuein); + if ($this->isColumnModified(CcBlockcontentsPeer::CUEOUT)) $criteria->add(CcBlockcontentsPeer::CUEOUT, $this->cueout); + if ($this->isColumnModified(CcBlockcontentsPeer::FADEIN)) $criteria->add(CcBlockcontentsPeer::FADEIN, $this->fadein); + if ($this->isColumnModified(CcBlockcontentsPeer::FADEOUT)) $criteria->add(CcBlockcontentsPeer::FADEOUT, $this->fadeout); return $criteria; } @@ -1281,8 +1127,8 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent */ public function buildPkeyCriteria() { - $criteria = new Criteria(CcPlaylistcontentsPeer::DATABASE_NAME); - $criteria->add(CcPlaylistcontentsPeer::ID, $this->id); + $criteria = new Criteria(CcBlockcontentsPeer::DATABASE_NAME); + $criteria->add(CcBlockcontentsPeer::ID, $this->id); return $criteria; } @@ -1322,13 +1168,13 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent * If desired, this method can also make copies of all associated (fkey referrers) * objects. * - * @param object $copyObj An object of CcPlaylistcontents (or compatible) type. + * @param object $copyObj An object of CcBlockcontents (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->setDbPlaylistId($this->playlist_id); + $copyObj->setDbBlockId($this->block_id); $copyObj->setDbFileId($this->file_id); $copyObj->setDbPosition($this->position); $copyObj->setDbCliplength($this->cliplength); @@ -1350,7 +1196,7 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent * objects. * * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. - * @return CcPlaylistcontents Clone of current object. + * @return CcBlockcontents Clone of current object. * @throws PropelException */ public function copy($deepCopy = false) @@ -1369,12 +1215,12 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent * same instance for all member of this class. The method could therefore * be static, but this would prevent one from overriding the behavior. * - * @return CcPlaylistcontentsPeer + * @return CcBlockcontentsPeer */ public function getPeer() { if (self::$peer === null) { - self::$peer = new CcPlaylistcontentsPeer(); + self::$peer = new CcBlockcontentsPeer(); } return self::$peer; } @@ -1383,7 +1229,7 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent * Declares an association between this object and a CcFiles object. * * @param CcFiles $v - * @return CcPlaylistcontents The current object (for fluent API support) + * @return CcBlockcontents The current object (for fluent API support) * @throws PropelException */ public function setCcFiles(CcFiles $v = null) @@ -1399,7 +1245,7 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent // 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->addCcPlaylistcontents($this); + $v->addCcBlockcontents($this); } return $this; @@ -1422,33 +1268,37 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent 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->addCcPlaylistcontentss($this); + $this->aCcFiles->addCcBlockcontentss($this); */ } return $this->aCcFiles; } /** - * Declares an association between this object and a CcPlaylist object. + * Declares an association between this object and a CcBlock object. * - * @param CcPlaylist $v - * @return CcPlaylistcontents The current object (for fluent API support) + * @param CcBlock $v + * @return CcBlockcontents The current object (for fluent API support) * @throws PropelException */ - public function setCcPlaylist(CcPlaylist $v = null) + public function setCcBlock(CcBlock $v = null) { + // aggregate_column_relation behavior + if (null !== $this->aCcBlock && $v !== $this->aCcBlock) { + $this->oldCcBlock = $this->aCcBlock; + } if ($v === null) { - $this->setDbPlaylistId(NULL); + $this->setDbBlockId(NULL); } else { - $this->setDbPlaylistId($v->getDbId()); + $this->setDbBlockId($v->getDbId()); } - $this->aCcPlaylist = $v; + $this->aCcBlock = $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 this object has already been added to the CcBlock object, it will not be re-added. if ($v !== null) { - $v->addCcPlaylistcontents($this); + $v->addCcBlockcontents($this); } return $this; @@ -1456,25 +1306,25 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent /** - * Get the associated CcPlaylist object + * Get the associated CcBlock object * * @param PropelPDO Optional Connection object. - * @return CcPlaylist The associated CcPlaylist object. + * @return CcBlock The associated CcBlock object. * @throws PropelException */ - public function getCcPlaylist(PropelPDO $con = null) + public function getCcBlock(PropelPDO $con = null) { - if ($this->aCcPlaylist === null && ($this->playlist_id !== null)) { - $this->aCcPlaylist = CcPlaylistQuery::create()->findPk($this->playlist_id, $con); + 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->aCcPlaylist->addCcPlaylistcontentss($this); + $this->aCcBlock->addCcBlockcontentss($this); */ } - return $this->aCcPlaylist; + return $this->aCcBlock; } /** @@ -1483,7 +1333,7 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent public function clear() { $this->id = null; - $this->playlist_id = null; + $this->block_id = null; $this->file_id = null; $this->position = null; $this->cliplength = null; @@ -1515,7 +1365,25 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent } // if ($deep) $this->aCcFiles = null; - $this->aCcPlaylist = null; + $this->aCcBlock = null; + } + + // aggregate_column_relation behavior + + /** + * Update the aggregate column in the related CcBlock object + * + * @param PropelPDO $con A connection object + */ + protected function updateRelatedCcBlock(PropelPDO $con) + { + if ($ccBlock = $this->getCcBlock()) { + $ccBlock->updateDbLength($con); + } + if ($this->oldCcBlock) { + $this->oldCcBlock->updateDbLength($con); + $this->oldCcBlock = null; + } } /** @@ -1537,4 +1405,4 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent throw new PropelException('Call to undefined method: ' . $name); } -} // BaseCcPlaylistcontents +} // BaseCcBlockcontents diff --git a/install_minimal/upgrades/airtime-2.0.0/propel/airtime/om/BaseCcPlaylistcontentsPeer.php b/airtime_mvc/application/models/airtime/om/BaseCcBlockcontentsPeer.php similarity index 68% rename from install_minimal/upgrades/airtime-2.0.0/propel/airtime/om/BaseCcPlaylistcontentsPeer.php rename to airtime_mvc/application/models/airtime/om/BaseCcBlockcontentsPeer.php index 0bb899b67..7bee15279 100644 --- a/install_minimal/upgrades/airtime-2.0.0/propel/airtime/om/BaseCcPlaylistcontentsPeer.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcBlockcontentsPeer.php @@ -2,28 +2,28 @@ /** - * Base static class for performing query and update operations on the 'cc_playlistcontents' table. + * Base static class for performing query and update operations on the 'cc_blockcontents' table. * * * * @package propel.generator.airtime.om */ -abstract class BaseCcPlaylistcontentsPeer { +abstract class BaseCcBlockcontentsPeer { /** the default database name for this class */ const DATABASE_NAME = 'airtime'; /** the table name for this class */ - const TABLE_NAME = 'cc_playlistcontents'; + const TABLE_NAME = 'cc_blockcontents'; /** the related Propel class for this table */ - const OM_CLASS = 'CcPlaylistcontents'; + const OM_CLASS = 'CcBlockcontents'; /** A class that can be returned by this peer. */ - const CLASS_DEFAULT = 'airtime.CcPlaylistcontents'; + const CLASS_DEFAULT = 'airtime.CcBlockcontents'; /** the related TableMap class for this table */ - const TM_CLASS = 'CcPlaylistcontentsTableMap'; + const TM_CLASS = 'CcBlockcontentsTableMap'; /** The total number of columns. */ const NUM_COLUMNS = 9; @@ -32,37 +32,37 @@ abstract class BaseCcPlaylistcontentsPeer { const NUM_LAZY_LOAD_COLUMNS = 0; /** the column name for the ID field */ - const ID = 'cc_playlistcontents.ID'; + const ID = 'cc_blockcontents.ID'; - /** the column name for the PLAYLIST_ID field */ - const PLAYLIST_ID = 'cc_playlistcontents.PLAYLIST_ID'; + /** the column name for the BLOCK_ID field */ + const BLOCK_ID = 'cc_blockcontents.BLOCK_ID'; /** the column name for the FILE_ID field */ - const FILE_ID = 'cc_playlistcontents.FILE_ID'; + const FILE_ID = 'cc_blockcontents.FILE_ID'; /** the column name for the POSITION field */ - const POSITION = 'cc_playlistcontents.POSITION'; + const POSITION = 'cc_blockcontents.POSITION'; /** the column name for the CLIPLENGTH field */ - const CLIPLENGTH = 'cc_playlistcontents.CLIPLENGTH'; + const CLIPLENGTH = 'cc_blockcontents.CLIPLENGTH'; /** the column name for the CUEIN field */ - const CUEIN = 'cc_playlistcontents.CUEIN'; + const CUEIN = 'cc_blockcontents.CUEIN'; /** the column name for the CUEOUT field */ - const CUEOUT = 'cc_playlistcontents.CUEOUT'; + const CUEOUT = 'cc_blockcontents.CUEOUT'; /** the column name for the FADEIN field */ - const FADEIN = 'cc_playlistcontents.FADEIN'; + const FADEIN = 'cc_blockcontents.FADEIN'; /** the column name for the FADEOUT field */ - const FADEOUT = 'cc_playlistcontents.FADEOUT'; + const FADEOUT = 'cc_blockcontents.FADEOUT'; /** - * An identiy map to hold any loaded instances of CcPlaylistcontents objects. + * An identiy map to hold any loaded instances of CcBlockcontents objects. * This must be public so that other peer classes can access this when hydrating from JOIN * queries. - * @var array CcPlaylistcontents[] + * @var array CcBlockcontents[] */ public static $instances = array(); @@ -74,11 +74,11 @@ abstract class BaseCcPlaylistcontentsPeer { * e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id' */ private static $fieldNames = array ( - BasePeer::TYPE_PHPNAME => array ('DbId', 'DbPlaylistId', 'DbFileId', 'DbPosition', 'DbCliplength', 'DbCuein', 'DbCueout', 'DbFadein', 'DbFadeout', ), - BasePeer::TYPE_STUDLYPHPNAME => array ('dbId', 'dbPlaylistId', 'dbFileId', 'dbPosition', 'dbCliplength', 'dbCuein', 'dbCueout', 'dbFadein', 'dbFadeout', ), - BasePeer::TYPE_COLNAME => array (self::ID, self::PLAYLIST_ID, self::FILE_ID, self::POSITION, self::CLIPLENGTH, self::CUEIN, self::CUEOUT, self::FADEIN, self::FADEOUT, ), - BasePeer::TYPE_RAW_COLNAME => array ('ID', 'PLAYLIST_ID', 'FILE_ID', 'POSITION', 'CLIPLENGTH', 'CUEIN', 'CUEOUT', 'FADEIN', 'FADEOUT', ), - BasePeer::TYPE_FIELDNAME => array ('id', 'playlist_id', 'file_id', 'position', 'cliplength', 'cuein', 'cueout', 'fadein', 'fadeout', ), + BasePeer::TYPE_PHPNAME => array ('DbId', 'DbBlockId', 'DbFileId', 'DbPosition', 'DbCliplength', 'DbCuein', 'DbCueout', 'DbFadein', 'DbFadeout', ), + BasePeer::TYPE_STUDLYPHPNAME => array ('dbId', 'dbBlockId', 'dbFileId', 'dbPosition', 'dbCliplength', 'dbCuein', 'dbCueout', 'dbFadein', 'dbFadeout', ), + BasePeer::TYPE_COLNAME => array (self::ID, self::BLOCK_ID, self::FILE_ID, self::POSITION, self::CLIPLENGTH, self::CUEIN, self::CUEOUT, self::FADEIN, self::FADEOUT, ), + BasePeer::TYPE_RAW_COLNAME => array ('ID', 'BLOCK_ID', 'FILE_ID', 'POSITION', 'CLIPLENGTH', 'CUEIN', 'CUEOUT', 'FADEIN', 'FADEOUT', ), + BasePeer::TYPE_FIELDNAME => array ('id', 'block_id', 'file_id', 'position', 'cliplength', 'cuein', 'cueout', 'fadein', 'fadeout', ), BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, ) ); @@ -89,11 +89,11 @@ abstract class BaseCcPlaylistcontentsPeer { * e.g. self::$fieldNames[BasePeer::TYPE_PHPNAME]['Id'] = 0 */ private static $fieldKeys = array ( - BasePeer::TYPE_PHPNAME => array ('DbId' => 0, 'DbPlaylistId' => 1, 'DbFileId' => 2, 'DbPosition' => 3, 'DbCliplength' => 4, 'DbCuein' => 5, 'DbCueout' => 6, 'DbFadein' => 7, 'DbFadeout' => 8, ), - BasePeer::TYPE_STUDLYPHPNAME => array ('dbId' => 0, 'dbPlaylistId' => 1, 'dbFileId' => 2, 'dbPosition' => 3, 'dbCliplength' => 4, 'dbCuein' => 5, 'dbCueout' => 6, 'dbFadein' => 7, 'dbFadeout' => 8, ), - BasePeer::TYPE_COLNAME => array (self::ID => 0, self::PLAYLIST_ID => 1, self::FILE_ID => 2, self::POSITION => 3, self::CLIPLENGTH => 4, self::CUEIN => 5, self::CUEOUT => 6, self::FADEIN => 7, self::FADEOUT => 8, ), - BasePeer::TYPE_RAW_COLNAME => array ('ID' => 0, 'PLAYLIST_ID' => 1, 'FILE_ID' => 2, 'POSITION' => 3, 'CLIPLENGTH' => 4, 'CUEIN' => 5, 'CUEOUT' => 6, 'FADEIN' => 7, 'FADEOUT' => 8, ), - BasePeer::TYPE_FIELDNAME => array ('id' => 0, 'playlist_id' => 1, 'file_id' => 2, 'position' => 3, 'cliplength' => 4, 'cuein' => 5, 'cueout' => 6, 'fadein' => 7, 'fadeout' => 8, ), + BasePeer::TYPE_PHPNAME => array ('DbId' => 0, 'DbBlockId' => 1, 'DbFileId' => 2, 'DbPosition' => 3, 'DbCliplength' => 4, 'DbCuein' => 5, 'DbCueout' => 6, 'DbFadein' => 7, 'DbFadeout' => 8, ), + BasePeer::TYPE_STUDLYPHPNAME => array ('dbId' => 0, 'dbBlockId' => 1, 'dbFileId' => 2, 'dbPosition' => 3, 'dbCliplength' => 4, 'dbCuein' => 5, 'dbCueout' => 6, 'dbFadein' => 7, 'dbFadeout' => 8, ), + BasePeer::TYPE_COLNAME => array (self::ID => 0, self::BLOCK_ID => 1, self::FILE_ID => 2, self::POSITION => 3, self::CLIPLENGTH => 4, self::CUEIN => 5, self::CUEOUT => 6, self::FADEIN => 7, self::FADEOUT => 8, ), + BasePeer::TYPE_RAW_COLNAME => array ('ID' => 0, 'BLOCK_ID' => 1, 'FILE_ID' => 2, 'POSITION' => 3, 'CLIPLENGTH' => 4, 'CUEIN' => 5, 'CUEOUT' => 6, 'FADEIN' => 7, 'FADEOUT' => 8, ), + BasePeer::TYPE_FIELDNAME => array ('id' => 0, 'block_id' => 1, 'file_id' => 2, 'position' => 3, 'cliplength' => 4, 'cuein' => 5, 'cueout' => 6, 'fadein' => 7, 'fadeout' => 8, ), BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, ) ); @@ -143,12 +143,12 @@ abstract class BaseCcPlaylistcontentsPeer { * $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. CcPlaylistcontentsPeer::COLUMN_NAME). + * @param string $column The column name for current table. (i.e. CcBlockcontentsPeer::COLUMN_NAME). * @return string */ public static function alias($alias, $column) { - return str_replace(CcPlaylistcontentsPeer::TABLE_NAME.'.', $alias.'.', $column); + return str_replace(CcBlockcontentsPeer::TABLE_NAME.'.', $alias.'.', $column); } /** @@ -166,18 +166,18 @@ abstract class BaseCcPlaylistcontentsPeer { public static function addSelectColumns(Criteria $criteria, $alias = null) { if (null === $alias) { - $criteria->addSelectColumn(CcPlaylistcontentsPeer::ID); - $criteria->addSelectColumn(CcPlaylistcontentsPeer::PLAYLIST_ID); - $criteria->addSelectColumn(CcPlaylistcontentsPeer::FILE_ID); - $criteria->addSelectColumn(CcPlaylistcontentsPeer::POSITION); - $criteria->addSelectColumn(CcPlaylistcontentsPeer::CLIPLENGTH); - $criteria->addSelectColumn(CcPlaylistcontentsPeer::CUEIN); - $criteria->addSelectColumn(CcPlaylistcontentsPeer::CUEOUT); - $criteria->addSelectColumn(CcPlaylistcontentsPeer::FADEIN); - $criteria->addSelectColumn(CcPlaylistcontentsPeer::FADEOUT); + $criteria->addSelectColumn(CcBlockcontentsPeer::ID); + $criteria->addSelectColumn(CcBlockcontentsPeer::BLOCK_ID); + $criteria->addSelectColumn(CcBlockcontentsPeer::FILE_ID); + $criteria->addSelectColumn(CcBlockcontentsPeer::POSITION); + $criteria->addSelectColumn(CcBlockcontentsPeer::CLIPLENGTH); + $criteria->addSelectColumn(CcBlockcontentsPeer::CUEIN); + $criteria->addSelectColumn(CcBlockcontentsPeer::CUEOUT); + $criteria->addSelectColumn(CcBlockcontentsPeer::FADEIN); + $criteria->addSelectColumn(CcBlockcontentsPeer::FADEOUT); } else { $criteria->addSelectColumn($alias . '.ID'); - $criteria->addSelectColumn($alias . '.PLAYLIST_ID'); + $criteria->addSelectColumn($alias . '.BLOCK_ID'); $criteria->addSelectColumn($alias . '.FILE_ID'); $criteria->addSelectColumn($alias . '.POSITION'); $criteria->addSelectColumn($alias . '.CLIPLENGTH'); @@ -204,21 +204,21 @@ abstract class BaseCcPlaylistcontentsPeer { // 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(CcPlaylistcontentsPeer::TABLE_NAME); + $criteria->setPrimaryTableName(CcBlockcontentsPeer::TABLE_NAME); if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { $criteria->setDistinct(); } if (!$criteria->hasSelectClause()) { - CcPlaylistcontentsPeer::addSelectColumns($criteria); + CcBlockcontentsPeer::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(CcPlaylistcontentsPeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcBlockcontentsPeer::DATABASE_NAME, Propel::CONNECTION_READ); } // BasePeer returns a PDOStatement $stmt = BasePeer::doCount($criteria, $con); @@ -236,7 +236,7 @@ abstract class BaseCcPlaylistcontentsPeer { * * @param Criteria $criteria object used to create the SELECT statement. * @param PropelPDO $con - * @return CcPlaylistcontents + * @return CcBlockcontents * @throws PropelException Any exceptions caught during processing will be * rethrown wrapped into a PropelException. */ @@ -244,7 +244,7 @@ abstract class BaseCcPlaylistcontentsPeer { { $critcopy = clone $criteria; $critcopy->setLimit(1); - $objects = CcPlaylistcontentsPeer::doSelect($critcopy, $con); + $objects = CcBlockcontentsPeer::doSelect($critcopy, $con); if ($objects) { return $objects[0]; } @@ -261,7 +261,7 @@ abstract class BaseCcPlaylistcontentsPeer { */ public static function doSelect(Criteria $criteria, PropelPDO $con = null) { - return CcPlaylistcontentsPeer::populateObjects(CcPlaylistcontentsPeer::doSelectStmt($criteria, $con)); + return CcBlockcontentsPeer::populateObjects(CcBlockcontentsPeer::doSelectStmt($criteria, $con)); } /** * Prepares the Criteria object and uses the parent doSelect() method to execute a PDOStatement. @@ -279,12 +279,12 @@ abstract class BaseCcPlaylistcontentsPeer { public static function doSelectStmt(Criteria $criteria, PropelPDO $con = null) { if ($con === null) { - $con = Propel::getConnection(CcPlaylistcontentsPeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcBlockcontentsPeer::DATABASE_NAME, Propel::CONNECTION_READ); } if (!$criteria->hasSelectClause()) { $criteria = clone $criteria; - CcPlaylistcontentsPeer::addSelectColumns($criteria); + CcBlockcontentsPeer::addSelectColumns($criteria); } // Set the correct dbName @@ -302,10 +302,10 @@ abstract class BaseCcPlaylistcontentsPeer { * to the cache in order to ensure that the same objects are always returned by doSelect*() * and retrieveByPK*() calls. * - * @param CcPlaylistcontents $value A CcPlaylistcontents object. + * @param CcBlockcontents $value A CcBlockcontents object. * @param string $key (optional) key to use for instance map (for performance boost if key was already calculated externally). */ - public static function addInstanceToPool(CcPlaylistcontents $obj, $key = null) + public static function addInstanceToPool(CcBlockcontents $obj, $key = null) { if (Propel::isInstancePoolingEnabled()) { if ($key === null) { @@ -323,18 +323,18 @@ abstract class BaseCcPlaylistcontentsPeer { * 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 CcPlaylistcontents object or a primary key value. + * @param mixed $value A CcBlockcontents object or a primary key value. */ public static function removeInstanceFromPool($value) { if (Propel::isInstancePoolingEnabled() && $value !== null) { - if (is_object($value) && $value instanceof CcPlaylistcontents) { + if (is_object($value) && $value instanceof CcBlockcontents) { $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 CcPlaylistcontents object; got " . (is_object($value) ? get_class($value) . ' object.' : var_export($value,true))); + $e = new PropelException("Invalid value passed to removeInstanceFromPool(). Expected primary key or CcBlockcontents object; got " . (is_object($value) ? get_class($value) . ' object.' : var_export($value,true))); throw $e; } @@ -349,7 +349,7 @@ abstract class BaseCcPlaylistcontentsPeer { * 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 CcPlaylistcontents Found object or NULL if 1) no instance exists for specified key or 2) instance pooling has been disabled. + * @return CcBlockcontents 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) @@ -373,7 +373,7 @@ abstract class BaseCcPlaylistcontentsPeer { } /** - * Method to invalidate the instance pool of all tables related to cc_playlistcontents + * Method to invalidate the instance pool of all tables related to cc_blockcontents * by a foreign key with ON DELETE CASCADE */ public static function clearRelatedInstancePool() @@ -425,11 +425,11 @@ abstract class BaseCcPlaylistcontentsPeer { $results = array(); // set the class once to avoid overhead in the loop - $cls = CcPlaylistcontentsPeer::getOMClass(false); + $cls = CcBlockcontentsPeer::getOMClass(false); // populate the object(s) while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $key = CcPlaylistcontentsPeer::getPrimaryKeyHashFromRow($row, 0); - if (null !== ($obj = CcPlaylistcontentsPeer::getInstanceFromPool($key))) { + $key = CcBlockcontentsPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj = CcBlockcontentsPeer::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 @@ -438,7 +438,7 @@ abstract class BaseCcPlaylistcontentsPeer { $obj = new $cls(); $obj->hydrate($row); $results[] = $obj; - CcPlaylistcontentsPeer::addInstanceToPool($obj, $key); + CcBlockcontentsPeer::addInstanceToPool($obj, $key); } // if key exists } $stmt->closeCursor(); @@ -451,21 +451,21 @@ abstract class BaseCcPlaylistcontentsPeer { * @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 (CcPlaylistcontents object, last column rank) + * @return array (CcBlockcontents object, last column rank) */ public static function populateObject($row, $startcol = 0) { - $key = CcPlaylistcontentsPeer::getPrimaryKeyHashFromRow($row, $startcol); - if (null !== ($obj = CcPlaylistcontentsPeer::getInstanceFromPool($key))) { + $key = CcBlockcontentsPeer::getPrimaryKeyHashFromRow($row, $startcol); + if (null !== ($obj = CcBlockcontentsPeer::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 + CcPlaylistcontentsPeer::NUM_COLUMNS; + $col = $startcol + CcBlockcontentsPeer::NUM_COLUMNS; } else { - $cls = CcPlaylistcontentsPeer::OM_CLASS; + $cls = CcBlockcontentsPeer::OM_CLASS; $obj = new $cls(); $col = $obj->hydrate($row, $startcol); - CcPlaylistcontentsPeer::addInstanceToPool($obj, $key); + CcBlockcontentsPeer::addInstanceToPool($obj, $key); } return array($obj, $col); } @@ -487,14 +487,14 @@ abstract class BaseCcPlaylistcontentsPeer { // 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(CcPlaylistcontentsPeer::TABLE_NAME); + $criteria->setPrimaryTableName(CcBlockcontentsPeer::TABLE_NAME); if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { $criteria->setDistinct(); } if (!$criteria->hasSelectClause()) { - CcPlaylistcontentsPeer::addSelectColumns($criteria); + CcBlockcontentsPeer::addSelectColumns($criteria); } $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count @@ -503,10 +503,10 @@ abstract class BaseCcPlaylistcontentsPeer { $criteria->setDbName(self::DATABASE_NAME); if ($con === null) { - $con = Propel::getConnection(CcPlaylistcontentsPeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcBlockcontentsPeer::DATABASE_NAME, Propel::CONNECTION_READ); } - $criteria->addJoin(CcPlaylistcontentsPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + $criteria->addJoin(CcBlockcontentsPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); $stmt = BasePeer::doCount($criteria, $con); @@ -521,7 +521,7 @@ abstract class BaseCcPlaylistcontentsPeer { /** - * Returns the number of rows matching criteria, joining the related CcPlaylist table + * 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. @@ -529,7 +529,7 @@ abstract class BaseCcPlaylistcontentsPeer { * @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) + 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; @@ -537,14 +537,14 @@ abstract class BaseCcPlaylistcontentsPeer { // 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(CcPlaylistcontentsPeer::TABLE_NAME); + $criteria->setPrimaryTableName(CcBlockcontentsPeer::TABLE_NAME); if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { $criteria->setDistinct(); } if (!$criteria->hasSelectClause()) { - CcPlaylistcontentsPeer::addSelectColumns($criteria); + CcBlockcontentsPeer::addSelectColumns($criteria); } $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count @@ -553,10 +553,10 @@ abstract class BaseCcPlaylistcontentsPeer { $criteria->setDbName(self::DATABASE_NAME); if ($con === null) { - $con = Propel::getConnection(CcPlaylistcontentsPeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcBlockcontentsPeer::DATABASE_NAME, Propel::CONNECTION_READ); } - $criteria->addJoin(CcPlaylistcontentsPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); + $criteria->addJoin(CcBlockcontentsPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); $stmt = BasePeer::doCount($criteria, $con); @@ -571,11 +571,11 @@ abstract class BaseCcPlaylistcontentsPeer { /** - * Selects a collection of CcPlaylistcontents objects pre-filled with their CcFiles objects. + * Selects a collection of CcBlockcontents 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 CcPlaylistcontents objects. + * @return array Array of CcBlockcontents objects. * @throws PropelException Any exceptions caught during processing will be * rethrown wrapped into a PropelException. */ @@ -588,28 +588,28 @@ abstract class BaseCcPlaylistcontentsPeer { $criteria->setDbName(self::DATABASE_NAME); } - CcPlaylistcontentsPeer::addSelectColumns($criteria); - $startcol = (CcPlaylistcontentsPeer::NUM_COLUMNS - CcPlaylistcontentsPeer::NUM_LAZY_LOAD_COLUMNS); + CcBlockcontentsPeer::addSelectColumns($criteria); + $startcol = (CcBlockcontentsPeer::NUM_COLUMNS - CcBlockcontentsPeer::NUM_LAZY_LOAD_COLUMNS); CcFilesPeer::addSelectColumns($criteria); - $criteria->addJoin(CcPlaylistcontentsPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + $criteria->addJoin(CcBlockcontentsPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); $stmt = BasePeer::doSelect($criteria, $con); $results = array(); while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $key1 = CcPlaylistcontentsPeer::getPrimaryKeyHashFromRow($row, 0); - if (null !== ($obj1 = CcPlaylistcontentsPeer::getInstanceFromPool($key1))) { + $key1 = CcBlockcontentsPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcBlockcontentsPeer::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 = CcPlaylistcontentsPeer::getOMClass(false); + $cls = CcBlockcontentsPeer::getOMClass(false); $obj1 = new $cls(); $obj1->hydrate($row); - CcPlaylistcontentsPeer::addInstanceToPool($obj1, $key1); + CcBlockcontentsPeer::addInstanceToPool($obj1, $key1); } // if $obj1 already loaded $key2 = CcFilesPeer::getPrimaryKeyHashFromRow($row, $startcol); @@ -624,8 +624,8 @@ abstract class BaseCcPlaylistcontentsPeer { CcFilesPeer::addInstanceToPool($obj2, $key2); } // if obj2 already loaded - // Add the $obj1 (CcPlaylistcontents) to $obj2 (CcFiles) - $obj2->addCcPlaylistcontents($obj1); + // Add the $obj1 (CcBlockcontents) to $obj2 (CcFiles) + $obj2->addCcBlockcontents($obj1); } // if joined row was not null @@ -637,15 +637,15 @@ abstract class BaseCcPlaylistcontentsPeer { /** - * Selects a collection of CcPlaylistcontents objects pre-filled with their CcPlaylist objects. + * Selects a collection of CcBlockcontents 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 CcPlaylistcontents objects. + * @return array Array of CcBlockcontents 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) + public static function doSelectJoinCcBlock(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) { $criteria = clone $criteria; @@ -654,44 +654,44 @@ abstract class BaseCcPlaylistcontentsPeer { $criteria->setDbName(self::DATABASE_NAME); } - CcPlaylistcontentsPeer::addSelectColumns($criteria); - $startcol = (CcPlaylistcontentsPeer::NUM_COLUMNS - CcPlaylistcontentsPeer::NUM_LAZY_LOAD_COLUMNS); - CcPlaylistPeer::addSelectColumns($criteria); + CcBlockcontentsPeer::addSelectColumns($criteria); + $startcol = (CcBlockcontentsPeer::NUM_COLUMNS - CcBlockcontentsPeer::NUM_LAZY_LOAD_COLUMNS); + CcBlockPeer::addSelectColumns($criteria); - $criteria->addJoin(CcPlaylistcontentsPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); + $criteria->addJoin(CcBlockcontentsPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); $stmt = BasePeer::doSelect($criteria, $con); $results = array(); while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $key1 = CcPlaylistcontentsPeer::getPrimaryKeyHashFromRow($row, 0); - if (null !== ($obj1 = CcPlaylistcontentsPeer::getInstanceFromPool($key1))) { + $key1 = CcBlockcontentsPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcBlockcontentsPeer::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 = CcPlaylistcontentsPeer::getOMClass(false); + $cls = CcBlockcontentsPeer::getOMClass(false); $obj1 = new $cls(); $obj1->hydrate($row); - CcPlaylistcontentsPeer::addInstanceToPool($obj1, $key1); + CcBlockcontentsPeer::addInstanceToPool($obj1, $key1); } // if $obj1 already loaded - $key2 = CcPlaylistPeer::getPrimaryKeyHashFromRow($row, $startcol); + $key2 = CcBlockPeer::getPrimaryKeyHashFromRow($row, $startcol); if ($key2 !== null) { - $obj2 = CcPlaylistPeer::getInstanceFromPool($key2); + $obj2 = CcBlockPeer::getInstanceFromPool($key2); if (!$obj2) { - $cls = CcPlaylistPeer::getOMClass(false); + $cls = CcBlockPeer::getOMClass(false); $obj2 = new $cls(); $obj2->hydrate($row, $startcol); - CcPlaylistPeer::addInstanceToPool($obj2, $key2); + CcBlockPeer::addInstanceToPool($obj2, $key2); } // if obj2 already loaded - // Add the $obj1 (CcPlaylistcontents) to $obj2 (CcPlaylist) - $obj2->addCcPlaylistcontents($obj1); + // Add the $obj1 (CcBlockcontents) to $obj2 (CcBlock) + $obj2->addCcBlockcontents($obj1); } // if joined row was not null @@ -719,14 +719,14 @@ abstract class BaseCcPlaylistcontentsPeer { // 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(CcPlaylistcontentsPeer::TABLE_NAME); + $criteria->setPrimaryTableName(CcBlockcontentsPeer::TABLE_NAME); if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { $criteria->setDistinct(); } if (!$criteria->hasSelectClause()) { - CcPlaylistcontentsPeer::addSelectColumns($criteria); + CcBlockcontentsPeer::addSelectColumns($criteria); } $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count @@ -735,12 +735,12 @@ abstract class BaseCcPlaylistcontentsPeer { $criteria->setDbName(self::DATABASE_NAME); if ($con === null) { - $con = Propel::getConnection(CcPlaylistcontentsPeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcBlockcontentsPeer::DATABASE_NAME, Propel::CONNECTION_READ); } - $criteria->addJoin(CcPlaylistcontentsPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + $criteria->addJoin(CcBlockcontentsPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); - $criteria->addJoin(CcPlaylistcontentsPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); + $criteria->addJoin(CcBlockcontentsPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); $stmt = BasePeer::doCount($criteria, $con); @@ -754,12 +754,12 @@ abstract class BaseCcPlaylistcontentsPeer { } /** - * Selects a collection of CcPlaylistcontents objects pre-filled with all related objects. + * Selects a collection of CcBlockcontents 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 CcPlaylistcontents objects. + * @return array Array of CcBlockcontents objects. * @throws PropelException Any exceptions caught during processing will be * rethrown wrapped into a PropelException. */ @@ -772,34 +772,34 @@ abstract class BaseCcPlaylistcontentsPeer { $criteria->setDbName(self::DATABASE_NAME); } - CcPlaylistcontentsPeer::addSelectColumns($criteria); - $startcol2 = (CcPlaylistcontentsPeer::NUM_COLUMNS - CcPlaylistcontentsPeer::NUM_LAZY_LOAD_COLUMNS); + CcBlockcontentsPeer::addSelectColumns($criteria); + $startcol2 = (CcBlockcontentsPeer::NUM_COLUMNS - CcBlockcontentsPeer::NUM_LAZY_LOAD_COLUMNS); CcFilesPeer::addSelectColumns($criteria); $startcol3 = $startcol2 + (CcFilesPeer::NUM_COLUMNS - CcFilesPeer::NUM_LAZY_LOAD_COLUMNS); - CcPlaylistPeer::addSelectColumns($criteria); - $startcol4 = $startcol3 + (CcPlaylistPeer::NUM_COLUMNS - CcPlaylistPeer::NUM_LAZY_LOAD_COLUMNS); + CcBlockPeer::addSelectColumns($criteria); + $startcol4 = $startcol3 + (CcBlockPeer::NUM_COLUMNS - CcBlockPeer::NUM_LAZY_LOAD_COLUMNS); - $criteria->addJoin(CcPlaylistcontentsPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + $criteria->addJoin(CcBlockcontentsPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); - $criteria->addJoin(CcPlaylistcontentsPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); + $criteria->addJoin(CcBlockcontentsPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); $stmt = BasePeer::doSelect($criteria, $con); $results = array(); while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $key1 = CcPlaylistcontentsPeer::getPrimaryKeyHashFromRow($row, 0); - if (null !== ($obj1 = CcPlaylistcontentsPeer::getInstanceFromPool($key1))) { + $key1 = CcBlockcontentsPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcBlockcontentsPeer::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 = CcPlaylistcontentsPeer::getOMClass(false); + $cls = CcBlockcontentsPeer::getOMClass(false); $obj1 = new $cls(); $obj1->hydrate($row); - CcPlaylistcontentsPeer::addInstanceToPool($obj1, $key1); + CcBlockcontentsPeer::addInstanceToPool($obj1, $key1); } // if obj1 already loaded // Add objects for joined CcFiles rows @@ -816,26 +816,26 @@ abstract class BaseCcPlaylistcontentsPeer { CcFilesPeer::addInstanceToPool($obj2, $key2); } // if obj2 loaded - // Add the $obj1 (CcPlaylistcontents) to the collection in $obj2 (CcFiles) - $obj2->addCcPlaylistcontents($obj1); + // Add the $obj1 (CcBlockcontents) to the collection in $obj2 (CcFiles) + $obj2->addCcBlockcontents($obj1); } // if joined row not null - // Add objects for joined CcPlaylist rows + // Add objects for joined CcBlock rows - $key3 = CcPlaylistPeer::getPrimaryKeyHashFromRow($row, $startcol3); + $key3 = CcBlockPeer::getPrimaryKeyHashFromRow($row, $startcol3); if ($key3 !== null) { - $obj3 = CcPlaylistPeer::getInstanceFromPool($key3); + $obj3 = CcBlockPeer::getInstanceFromPool($key3); if (!$obj3) { - $cls = CcPlaylistPeer::getOMClass(false); + $cls = CcBlockPeer::getOMClass(false); $obj3 = new $cls(); $obj3->hydrate($row, $startcol3); - CcPlaylistPeer::addInstanceToPool($obj3, $key3); + CcBlockPeer::addInstanceToPool($obj3, $key3); } // if obj3 loaded - // Add the $obj1 (CcPlaylistcontents) to the collection in $obj3 (CcPlaylist) - $obj3->addCcPlaylistcontents($obj1); + // Add the $obj1 (CcBlockcontents) to the collection in $obj3 (CcBlock) + $obj3->addCcBlockcontents($obj1); } // if joined row not null $results[] = $obj1; @@ -862,14 +862,14 @@ abstract class BaseCcPlaylistcontentsPeer { // 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(CcPlaylistcontentsPeer::TABLE_NAME); + $criteria->setPrimaryTableName(CcBlockcontentsPeer::TABLE_NAME); if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { $criteria->setDistinct(); } if (!$criteria->hasSelectClause()) { - CcPlaylistcontentsPeer::addSelectColumns($criteria); + CcBlockcontentsPeer::addSelectColumns($criteria); } $criteria->clearOrderByColumns(); // ORDER BY should not affect count @@ -878,10 +878,10 @@ abstract class BaseCcPlaylistcontentsPeer { $criteria->setDbName(self::DATABASE_NAME); if ($con === null) { - $con = Propel::getConnection(CcPlaylistcontentsPeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcBlockcontentsPeer::DATABASE_NAME, Propel::CONNECTION_READ); } - $criteria->addJoin(CcPlaylistcontentsPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); + $criteria->addJoin(CcBlockcontentsPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); $stmt = BasePeer::doCount($criteria, $con); @@ -896,7 +896,7 @@ abstract class BaseCcPlaylistcontentsPeer { /** - * Returns the number of rows matching criteria, joining the related CcPlaylist table + * 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. @@ -904,7 +904,7 @@ abstract class BaseCcPlaylistcontentsPeer { * @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) + 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; @@ -912,14 +912,14 @@ abstract class BaseCcPlaylistcontentsPeer { // 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(CcPlaylistcontentsPeer::TABLE_NAME); + $criteria->setPrimaryTableName(CcBlockcontentsPeer::TABLE_NAME); if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { $criteria->setDistinct(); } if (!$criteria->hasSelectClause()) { - CcPlaylistcontentsPeer::addSelectColumns($criteria); + CcBlockcontentsPeer::addSelectColumns($criteria); } $criteria->clearOrderByColumns(); // ORDER BY should not affect count @@ -928,10 +928,10 @@ abstract class BaseCcPlaylistcontentsPeer { $criteria->setDbName(self::DATABASE_NAME); if ($con === null) { - $con = Propel::getConnection(CcPlaylistcontentsPeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcBlockcontentsPeer::DATABASE_NAME, Propel::CONNECTION_READ); } - $criteria->addJoin(CcPlaylistcontentsPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + $criteria->addJoin(CcBlockcontentsPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); $stmt = BasePeer::doCount($criteria, $con); @@ -946,12 +946,12 @@ abstract class BaseCcPlaylistcontentsPeer { /** - * Selects a collection of CcPlaylistcontents objects pre-filled with all related objects except CcFiles. + * Selects a collection of CcBlockcontents 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 CcPlaylistcontents objects. + * @return array Array of CcBlockcontents objects. * @throws PropelException Any exceptions caught during processing will be * rethrown wrapped into a PropelException. */ @@ -966,48 +966,48 @@ abstract class BaseCcPlaylistcontentsPeer { $criteria->setDbName(self::DATABASE_NAME); } - CcPlaylistcontentsPeer::addSelectColumns($criteria); - $startcol2 = (CcPlaylistcontentsPeer::NUM_COLUMNS - CcPlaylistcontentsPeer::NUM_LAZY_LOAD_COLUMNS); + CcBlockcontentsPeer::addSelectColumns($criteria); + $startcol2 = (CcBlockcontentsPeer::NUM_COLUMNS - CcBlockcontentsPeer::NUM_LAZY_LOAD_COLUMNS); - CcPlaylistPeer::addSelectColumns($criteria); - $startcol3 = $startcol2 + (CcPlaylistPeer::NUM_COLUMNS - CcPlaylistPeer::NUM_LAZY_LOAD_COLUMNS); + CcBlockPeer::addSelectColumns($criteria); + $startcol3 = $startcol2 + (CcBlockPeer::NUM_COLUMNS - CcBlockPeer::NUM_LAZY_LOAD_COLUMNS); - $criteria->addJoin(CcPlaylistcontentsPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); + $criteria->addJoin(CcBlockcontentsPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); $stmt = BasePeer::doSelect($criteria, $con); $results = array(); while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $key1 = CcPlaylistcontentsPeer::getPrimaryKeyHashFromRow($row, 0); - if (null !== ($obj1 = CcPlaylistcontentsPeer::getInstanceFromPool($key1))) { + $key1 = CcBlockcontentsPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcBlockcontentsPeer::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 = CcPlaylistcontentsPeer::getOMClass(false); + $cls = CcBlockcontentsPeer::getOMClass(false); $obj1 = new $cls(); $obj1->hydrate($row); - CcPlaylistcontentsPeer::addInstanceToPool($obj1, $key1); + CcBlockcontentsPeer::addInstanceToPool($obj1, $key1); } // if obj1 already loaded - // Add objects for joined CcPlaylist rows + // Add objects for joined CcBlock rows - $key2 = CcPlaylistPeer::getPrimaryKeyHashFromRow($row, $startcol2); + $key2 = CcBlockPeer::getPrimaryKeyHashFromRow($row, $startcol2); if ($key2 !== null) { - $obj2 = CcPlaylistPeer::getInstanceFromPool($key2); + $obj2 = CcBlockPeer::getInstanceFromPool($key2); if (!$obj2) { - $cls = CcPlaylistPeer::getOMClass(false); + $cls = CcBlockPeer::getOMClass(false); $obj2 = new $cls(); $obj2->hydrate($row, $startcol2); - CcPlaylistPeer::addInstanceToPool($obj2, $key2); + CcBlockPeer::addInstanceToPool($obj2, $key2); } // if $obj2 already loaded - // Add the $obj1 (CcPlaylistcontents) to the collection in $obj2 (CcPlaylist) - $obj2->addCcPlaylistcontents($obj1); + // Add the $obj1 (CcBlockcontents) to the collection in $obj2 (CcBlock) + $obj2->addCcBlockcontents($obj1); } // if joined row is not null @@ -1019,16 +1019,16 @@ abstract class BaseCcPlaylistcontentsPeer { /** - * Selects a collection of CcPlaylistcontents objects pre-filled with all related objects except CcPlaylist. + * Selects a collection of CcBlockcontents 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 CcPlaylistcontents objects. + * @return array Array of CcBlockcontents 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) + public static function doSelectJoinAllExceptCcBlock(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) { $criteria = clone $criteria; @@ -1039,30 +1039,30 @@ abstract class BaseCcPlaylistcontentsPeer { $criteria->setDbName(self::DATABASE_NAME); } - CcPlaylistcontentsPeer::addSelectColumns($criteria); - $startcol2 = (CcPlaylistcontentsPeer::NUM_COLUMNS - CcPlaylistcontentsPeer::NUM_LAZY_LOAD_COLUMNS); + CcBlockcontentsPeer::addSelectColumns($criteria); + $startcol2 = (CcBlockcontentsPeer::NUM_COLUMNS - CcBlockcontentsPeer::NUM_LAZY_LOAD_COLUMNS); CcFilesPeer::addSelectColumns($criteria); $startcol3 = $startcol2 + (CcFilesPeer::NUM_COLUMNS - CcFilesPeer::NUM_LAZY_LOAD_COLUMNS); - $criteria->addJoin(CcPlaylistcontentsPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + $criteria->addJoin(CcBlockcontentsPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); $stmt = BasePeer::doSelect($criteria, $con); $results = array(); while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $key1 = CcPlaylistcontentsPeer::getPrimaryKeyHashFromRow($row, 0); - if (null !== ($obj1 = CcPlaylistcontentsPeer::getInstanceFromPool($key1))) { + $key1 = CcBlockcontentsPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcBlockcontentsPeer::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 = CcPlaylistcontentsPeer::getOMClass(false); + $cls = CcBlockcontentsPeer::getOMClass(false); $obj1 = new $cls(); $obj1->hydrate($row); - CcPlaylistcontentsPeer::addInstanceToPool($obj1, $key1); + CcBlockcontentsPeer::addInstanceToPool($obj1, $key1); } // if obj1 already loaded // Add objects for joined CcFiles rows @@ -1079,8 +1079,8 @@ abstract class BaseCcPlaylistcontentsPeer { CcFilesPeer::addInstanceToPool($obj2, $key2); } // if $obj2 already loaded - // Add the $obj1 (CcPlaylistcontents) to the collection in $obj2 (CcFiles) - $obj2->addCcPlaylistcontents($obj1); + // Add the $obj1 (CcBlockcontents) to the collection in $obj2 (CcFiles) + $obj2->addCcBlockcontents($obj1); } // if joined row is not null @@ -1107,10 +1107,10 @@ abstract class BaseCcPlaylistcontentsPeer { */ public static function buildTableMap() { - $dbMap = Propel::getDatabaseMap(BaseCcPlaylistcontentsPeer::DATABASE_NAME); - if (!$dbMap->hasTable(BaseCcPlaylistcontentsPeer::TABLE_NAME)) + $dbMap = Propel::getDatabaseMap(BaseCcBlockcontentsPeer::DATABASE_NAME); + if (!$dbMap->hasTable(BaseCcBlockcontentsPeer::TABLE_NAME)) { - $dbMap->addTableObject(new CcPlaylistcontentsTableMap()); + $dbMap->addTableObject(new CcBlockcontentsTableMap()); } } @@ -1127,13 +1127,13 @@ abstract class BaseCcPlaylistcontentsPeer { */ public static function getOMClass($withPrefix = true) { - return $withPrefix ? CcPlaylistcontentsPeer::CLASS_DEFAULT : CcPlaylistcontentsPeer::OM_CLASS; + return $withPrefix ? CcBlockcontentsPeer::CLASS_DEFAULT : CcBlockcontentsPeer::OM_CLASS; } /** - * Method perform an INSERT on the database, given a CcPlaylistcontents or Criteria object. + * Method perform an INSERT on the database, given a CcBlockcontents or Criteria object. * - * @param mixed $values Criteria or CcPlaylistcontents object containing data that is used to create the INSERT statement. + * @param mixed $values Criteria or CcBlockcontents 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 @@ -1142,17 +1142,17 @@ abstract class BaseCcPlaylistcontentsPeer { public static function doInsert($values, PropelPDO $con = null) { if ($con === null) { - $con = Propel::getConnection(CcPlaylistcontentsPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + $con = Propel::getConnection(CcBlockcontentsPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); } if ($values instanceof Criteria) { $criteria = clone $values; // rename for clarity } else { - $criteria = $values->buildCriteria(); // build Criteria from CcPlaylistcontents object + $criteria = $values->buildCriteria(); // build Criteria from CcBlockcontents object } - if ($criteria->containsKey(CcPlaylistcontentsPeer::ID) && $criteria->keyContainsValue(CcPlaylistcontentsPeer::ID) ) { - throw new PropelException('Cannot insert a value for auto-increment primary key ('.CcPlaylistcontentsPeer::ID.')'); + if ($criteria->containsKey(CcBlockcontentsPeer::ID) && $criteria->keyContainsValue(CcBlockcontentsPeer::ID) ) { + throw new PropelException('Cannot insert a value for auto-increment primary key ('.CcBlockcontentsPeer::ID.')'); } @@ -1174,9 +1174,9 @@ abstract class BaseCcPlaylistcontentsPeer { } /** - * Method perform an UPDATE on the database, given a CcPlaylistcontents or Criteria object. + * Method perform an UPDATE on the database, given a CcBlockcontents or Criteria object. * - * @param mixed $values Criteria or CcPlaylistcontents object containing data that is used to create the UPDATE statement. + * @param mixed $values Criteria or CcBlockcontents 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 @@ -1185,7 +1185,7 @@ abstract class BaseCcPlaylistcontentsPeer { public static function doUpdate($values, PropelPDO $con = null) { if ($con === null) { - $con = Propel::getConnection(CcPlaylistcontentsPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + $con = Propel::getConnection(CcBlockcontentsPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); } $selectCriteria = new Criteria(self::DATABASE_NAME); @@ -1193,15 +1193,15 @@ abstract class BaseCcPlaylistcontentsPeer { if ($values instanceof Criteria) { $criteria = clone $values; // rename for clarity - $comparison = $criteria->getComparison(CcPlaylistcontentsPeer::ID); - $value = $criteria->remove(CcPlaylistcontentsPeer::ID); + $comparison = $criteria->getComparison(CcBlockcontentsPeer::ID); + $value = $criteria->remove(CcBlockcontentsPeer::ID); if ($value) { - $selectCriteria->add(CcPlaylistcontentsPeer::ID, $value, $comparison); + $selectCriteria->add(CcBlockcontentsPeer::ID, $value, $comparison); } else { - $selectCriteria->setPrimaryTableName(CcPlaylistcontentsPeer::TABLE_NAME); + $selectCriteria->setPrimaryTableName(CcBlockcontentsPeer::TABLE_NAME); } - } else { // $values is CcPlaylistcontents object + } else { // $values is CcBlockcontents object $criteria = $values->buildCriteria(); // gets full criteria $selectCriteria = $values->buildPkeyCriteria(); // gets criteria w/ primary key(s) } @@ -1213,26 +1213,26 @@ abstract class BaseCcPlaylistcontentsPeer { } /** - * Method to DELETE all rows from the cc_playlistcontents table. + * Method to DELETE all rows from the cc_blockcontents 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(CcPlaylistcontentsPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + $con = Propel::getConnection(CcBlockcontentsPeer::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(CcPlaylistcontentsPeer::TABLE_NAME, $con, CcPlaylistcontentsPeer::DATABASE_NAME); + $affectedRows += BasePeer::doDeleteAll(CcBlockcontentsPeer::TABLE_NAME, $con, CcBlockcontentsPeer::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). - CcPlaylistcontentsPeer::clearInstancePool(); - CcPlaylistcontentsPeer::clearRelatedInstancePool(); + CcBlockcontentsPeer::clearInstancePool(); + CcBlockcontentsPeer::clearRelatedInstancePool(); $con->commit(); return $affectedRows; } catch (PropelException $e) { @@ -1242,9 +1242,9 @@ abstract class BaseCcPlaylistcontentsPeer { } /** - * Method perform a DELETE on the database, given a CcPlaylistcontents or Criteria object OR a primary key value. + * Method perform a DELETE on the database, given a CcBlockcontents or Criteria object OR a primary key value. * - * @param mixed $values Criteria or CcPlaylistcontents object or primary key or array of primary keys + * @param mixed $values Criteria or CcBlockcontents 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 @@ -1255,27 +1255,27 @@ abstract class BaseCcPlaylistcontentsPeer { public static function doDelete($values, PropelPDO $con = null) { if ($con === null) { - $con = Propel::getConnection(CcPlaylistcontentsPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + $con = Propel::getConnection(CcBlockcontentsPeer::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. - CcPlaylistcontentsPeer::clearInstancePool(); + CcBlockcontentsPeer::clearInstancePool(); // rename for clarity $criteria = clone $values; - } elseif ($values instanceof CcPlaylistcontents) { // it's a model object + } elseif ($values instanceof CcBlockcontents) { // it's a model object // invalidate the cache for this single object - CcPlaylistcontentsPeer::removeInstanceFromPool($values); + CcBlockcontentsPeer::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(CcPlaylistcontentsPeer::ID, (array) $values, Criteria::IN); + $criteria->add(CcBlockcontentsPeer::ID, (array) $values, Criteria::IN); // invalidate the cache for this object(s) foreach ((array) $values as $singleval) { - CcPlaylistcontentsPeer::removeInstanceFromPool($singleval); + CcBlockcontentsPeer::removeInstanceFromPool($singleval); } } @@ -1290,7 +1290,7 @@ abstract class BaseCcPlaylistcontentsPeer { $con->beginTransaction(); $affectedRows += BasePeer::doDelete($criteria, $con); - CcPlaylistcontentsPeer::clearRelatedInstancePool(); + CcBlockcontentsPeer::clearRelatedInstancePool(); $con->commit(); return $affectedRows; } catch (PropelException $e) { @@ -1300,24 +1300,24 @@ abstract class BaseCcPlaylistcontentsPeer { } /** - * Validates all modified columns of given CcPlaylistcontents object. + * Validates all modified columns of given CcBlockcontents 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 CcPlaylistcontents $obj The object to validate. + * @param CcBlockcontents $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(CcPlaylistcontents $obj, $cols = null) + public static function doValidate(CcBlockcontents $obj, $cols = null) { $columns = array(); if ($cols) { - $dbMap = Propel::getDatabaseMap(CcPlaylistcontentsPeer::DATABASE_NAME); - $tableMap = $dbMap->getTable(CcPlaylistcontentsPeer::TABLE_NAME); + $dbMap = Propel::getDatabaseMap(CcBlockcontentsPeer::DATABASE_NAME); + $tableMap = $dbMap->getTable(CcBlockcontentsPeer::TABLE_NAME); if (! is_array($cols)) { $cols = array($cols); @@ -1333,7 +1333,7 @@ abstract class BaseCcPlaylistcontentsPeer { } - return BasePeer::doValidate(CcPlaylistcontentsPeer::DATABASE_NAME, CcPlaylistcontentsPeer::TABLE_NAME, $columns); + return BasePeer::doValidate(CcBlockcontentsPeer::DATABASE_NAME, CcBlockcontentsPeer::TABLE_NAME, $columns); } /** @@ -1341,23 +1341,23 @@ abstract class BaseCcPlaylistcontentsPeer { * * @param int $pk the primary key. * @param PropelPDO $con the connection to use - * @return CcPlaylistcontents + * @return CcBlockcontents */ public static function retrieveByPK($pk, PropelPDO $con = null) { - if (null !== ($obj = CcPlaylistcontentsPeer::getInstanceFromPool((string) $pk))) { + if (null !== ($obj = CcBlockcontentsPeer::getInstanceFromPool((string) $pk))) { return $obj; } if ($con === null) { - $con = Propel::getConnection(CcPlaylistcontentsPeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcBlockcontentsPeer::DATABASE_NAME, Propel::CONNECTION_READ); } - $criteria = new Criteria(CcPlaylistcontentsPeer::DATABASE_NAME); - $criteria->add(CcPlaylistcontentsPeer::ID, $pk); + $criteria = new Criteria(CcBlockcontentsPeer::DATABASE_NAME); + $criteria->add(CcBlockcontentsPeer::ID, $pk); - $v = CcPlaylistcontentsPeer::doSelect($criteria, $con); + $v = CcBlockcontentsPeer::doSelect($criteria, $con); return !empty($v) > 0 ? $v[0] : null; } @@ -1373,23 +1373,23 @@ abstract class BaseCcPlaylistcontentsPeer { public static function retrieveByPKs($pks, PropelPDO $con = null) { if ($con === null) { - $con = Propel::getConnection(CcPlaylistcontentsPeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcBlockcontentsPeer::DATABASE_NAME, Propel::CONNECTION_READ); } $objs = null; if (empty($pks)) { $objs = array(); } else { - $criteria = new Criteria(CcPlaylistcontentsPeer::DATABASE_NAME); - $criteria->add(CcPlaylistcontentsPeer::ID, $pks, Criteria::IN); - $objs = CcPlaylistcontentsPeer::doSelect($criteria, $con); + $criteria = new Criteria(CcBlockcontentsPeer::DATABASE_NAME); + $criteria->add(CcBlockcontentsPeer::ID, $pks, Criteria::IN); + $objs = CcBlockcontentsPeer::doSelect($criteria, $con); } return $objs; } -} // BaseCcPlaylistcontentsPeer +} // BaseCcBlockcontentsPeer // This is the static code needed to register the TableMap for this table with the main Propel class. // -BaseCcPlaylistcontentsPeer::buildTableMap(); +BaseCcBlockcontentsPeer::buildTableMap(); diff --git a/airtime_mvc/application/models/airtime/om/BaseCcBlockcontentsQuery.php b/airtime_mvc/application/models/airtime/om/BaseCcBlockcontentsQuery.php new file mode 100644 index 000000000..6cc00d53c --- /dev/null +++ b/airtime_mvc/application/models/airtime/om/BaseCcBlockcontentsQuery.php @@ -0,0 +1,640 @@ +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 CcBlockcontents|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ((null !== ($obj = CcBlockcontentsPeer::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 CcBlockcontentsQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + return $this->addUsingAlias(CcBlockcontentsPeer::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 CcBlockcontentsQuery The current query, for fluid interface + */ + public function filterByPrimaryKeys($keys) + { + return $this->addUsingAlias(CcBlockcontentsPeer::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 CcBlockcontentsQuery 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(CcBlockcontentsPeer::ID, $dbId, $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 CcBlockcontentsQuery 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(CcBlockcontentsPeer::BLOCK_ID, $dbBlockId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbBlockId['max'])) { + $this->addUsingAlias(CcBlockcontentsPeer::BLOCK_ID, $dbBlockId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcBlockcontentsPeer::BLOCK_ID, $dbBlockId, $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 CcBlockcontentsQuery 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(CcBlockcontentsPeer::FILE_ID, $dbFileId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbFileId['max'])) { + $this->addUsingAlias(CcBlockcontentsPeer::FILE_ID, $dbFileId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcBlockcontentsPeer::FILE_ID, $dbFileId, $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 CcBlockcontentsQuery 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(CcBlockcontentsPeer::POSITION, $dbPosition['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbPosition['max'])) { + $this->addUsingAlias(CcBlockcontentsPeer::POSITION, $dbPosition['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcBlockcontentsPeer::POSITION, $dbPosition, $comparison); + } + + /** + * Filter the query on the cliplength 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 CcBlockcontentsQuery 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(CcBlockcontentsPeer::CLIPLENGTH, $dbCliplength, $comparison); + } + + /** + * Filter the query on the cuein 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 CcBlockcontentsQuery 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(CcBlockcontentsPeer::CUEIN, $dbCuein, $comparison); + } + + /** + * Filter the query on the cueout 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 CcBlockcontentsQuery 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(CcBlockcontentsPeer::CUEOUT, $dbCueout, $comparison); + } + + /** + * Filter the query on the fadein column + * + * @param string|array $dbFadein 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 CcBlockcontentsQuery The current query, for fluid interface + */ + public function filterByDbFadein($dbFadein = null, $comparison = null) + { + if (is_array($dbFadein)) { + $useMinMax = false; + if (isset($dbFadein['min'])) { + $this->addUsingAlias(CcBlockcontentsPeer::FADEIN, $dbFadein['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbFadein['max'])) { + $this->addUsingAlias(CcBlockcontentsPeer::FADEIN, $dbFadein['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcBlockcontentsPeer::FADEIN, $dbFadein, $comparison); + } + + /** + * Filter the query on the fadeout column + * + * @param string|array $dbFadeout 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 CcBlockcontentsQuery The current query, for fluid interface + */ + public function filterByDbFadeout($dbFadeout = null, $comparison = null) + { + if (is_array($dbFadeout)) { + $useMinMax = false; + if (isset($dbFadeout['min'])) { + $this->addUsingAlias(CcBlockcontentsPeer::FADEOUT, $dbFadeout['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbFadeout['max'])) { + $this->addUsingAlias(CcBlockcontentsPeer::FADEOUT, $dbFadeout['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcBlockcontentsPeer::FADEOUT, $dbFadeout, $comparison); + } + + /** + * 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 CcBlockcontentsQuery The current query, for fluid interface + */ + public function filterByCcFiles($ccFiles, $comparison = null) + { + return $this + ->addUsingAlias(CcBlockcontentsPeer::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 CcBlockcontentsQuery 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 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 CcBlockcontentsQuery The current query, for fluid interface + */ + public function filterByCcBlock($ccBlock, $comparison = null) + { + return $this + ->addUsingAlias(CcBlockcontentsPeer::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 CcBlockcontentsQuery 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'); + } + + /** + * Exclude object from result + * + * @param CcBlockcontents $ccBlockcontents Object to remove from the list of results + * + * @return CcBlockcontentsQuery The current query, for fluid interface + */ + public function prune($ccBlockcontents = null) + { + if ($ccBlockcontents) { + $this->addUsingAlias(CcBlockcontentsPeer::ID, $ccBlockcontents->getDbId(), Criteria::NOT_EQUAL); + } + + return $this; + } + + /** + * Code to execute before every DELETE statement + * + * @param PropelPDO $con The connection object used by the query + */ + protected function basePreDelete(PropelPDO $con) + { + // aggregate_column_relation behavior + $this->findRelatedCcBlocks($con); + + return $this->preDelete($con); + } + + /** + * Code to execute after every DELETE statement + * + * @param int $affectedRows the number of deleted rows + * @param PropelPDO $con The connection object used by the query + */ + protected function basePostDelete($affectedRows, PropelPDO $con) + { + // aggregate_column_relation behavior + $this->updateRelatedCcBlocks($con); + + return $this->postDelete($affectedRows, $con); + } + + /** + * Code to execute before every UPDATE statement + * + * @param array $values The associatiove array of columns and values for the update + * @param PropelPDO $con The connection object used by the query + * @param boolean $forceIndividualSaves If false (default), the resulting call is a BasePeer::doUpdate(), ortherwise it is a series of save() calls on all the found objects + */ + protected function basePreUpdate(&$values, PropelPDO $con, $forceIndividualSaves = false) + { + // aggregate_column_relation behavior + $this->findRelatedCcBlocks($con); + + return $this->preUpdate($values, $con, $forceIndividualSaves); + } + + /** + * Code to execute after every UPDATE statement + * + * @param int $affectedRows the number of udated rows + * @param PropelPDO $con The connection object used by the query + */ + protected function basePostUpdate($affectedRows, PropelPDO $con) + { + // aggregate_column_relation behavior + $this->updateRelatedCcBlocks($con); + + return $this->postUpdate($affectedRows, $con); + } + + // aggregate_column_relation behavior + + /** + * Finds the related CcBlock objects and keep them for later + * + * @param PropelPDO $con A connection object + */ + protected function findRelatedCcBlocks($con) + { + $criteria = clone $this; + if ($this->useAliasInSQL) { + $alias = $this->getModelAlias(); + $criteria->removeAlias($alias); + } else { + $alias = ''; + } + $this->ccBlocks = CcBlockQuery::create() + ->joinCcBlockcontents($alias) + ->mergeWith($criteria) + ->find($con); + } + + protected function updateRelatedCcBlocks($con) + { + foreach ($this->ccBlocks as $ccBlock) { + $ccBlock->updateDbLength($con); + } + $this->ccBlocks = array(); + } + +} // BaseCcBlockcontentsQuery diff --git a/install_minimal/upgrades/airtime-2.0.0/propel/airtime/om/BaseCcShowSchedule.php b/airtime_mvc/application/models/airtime/om/BaseCcBlockcriteria.php similarity index 68% rename from install_minimal/upgrades/airtime-2.0.0/propel/airtime/om/BaseCcShowSchedule.php rename to airtime_mvc/application/models/airtime/om/BaseCcBlockcriteria.php index bf8b384e6..2982a3b86 100644 --- a/install_minimal/upgrades/airtime-2.0.0/propel/airtime/om/BaseCcShowSchedule.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcBlockcriteria.php @@ -2,25 +2,25 @@ /** - * Base class that represents a row from the 'cc_show_schedule' table. + * Base class that represents a row from the 'cc_blockcriteria' table. * * * * @package propel.generator.airtime.om */ -abstract class BaseCcShowSchedule extends BaseObject implements Persistent +abstract class BaseCcBlockcriteria extends BaseObject implements Persistent { /** * Peer class name */ - const PEER = 'CcShowSchedulePeer'; + const PEER = 'CcBlockcriteriaPeer'; /** * The Peer class. * Instance provides a convenient way of calling static methods on a class * that calling code may not be able to identify. - * @var CcShowSchedulePeer + * @var CcBlockcriteriaPeer */ protected static $peer; @@ -31,27 +31,39 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent protected $id; /** - * The value for the instance_id field. - * @var int + * The value for the criteria field. + * @var string */ - protected $instance_id; + protected $criteria; /** - * The value for the position field. - * @var int + * The value for the modifier field. + * @var string */ - protected $position; + protected $modifier; /** - * The value for the group_id field. - * @var int + * The value for the value field. + * @var string */ - protected $group_id; + protected $value; /** - * @var CcShowInstances + * The value for the extra field. + * @var string */ - protected $aCcShowInstances; + protected $extra; + + /** + * The value for the block_id field. + * @var int + */ + protected $block_id; + + /** + * @var CcBlock + */ + protected $aCcBlock; /** * Flag to prevent endless save loop, if this object is referenced @@ -78,40 +90,60 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent } /** - * Get the [instance_id] column value. + * Get the [criteria] column value. * - * @return int + * @return string */ - public function getDbInstanceId() + public function getDbCriteria() { - return $this->instance_id; + return $this->criteria; } /** - * Get the [position] column value. + * Get the [modifier] column value. * - * @return int + * @return string */ - public function getDbPosition() + public function getDbModifier() { - return $this->position; + return $this->modifier; } /** - * Get the [group_id] column value. + * Get the [value] column value. + * + * @return string + */ + public function getDbValue() + { + return $this->value; + } + + /** + * Get the [extra] column value. + * + * @return string + */ + public function getDbExtra() + { + return $this->extra; + } + + /** + * Get the [block_id] column value. * * @return int */ - public function getDbGroupId() + public function getDbBlockId() { - return $this->group_id; + return $this->block_id; } /** * Set the value of [id] column. * * @param int $v new value - * @return CcShowSchedule The current object (for fluent API support) + * @return CcBlockcriteria The current object (for fluent API support) */ public function setDbId($v) { @@ -121,75 +153,115 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent if ($this->id !== $v) { $this->id = $v; - $this->modifiedColumns[] = CcShowSchedulePeer::ID; + $this->modifiedColumns[] = CcBlockcriteriaPeer::ID; } return $this; } // setDbId() /** - * Set the value of [instance_id] column. + * Set the value of [criteria] column. * - * @param int $v new value - * @return CcShowSchedule The current object (for fluent API support) + * @param string $v new value + * @return CcBlockcriteria The current object (for fluent API support) */ - public function setDbInstanceId($v) + public function setDbCriteria($v) { if ($v !== null) { - $v = (int) $v; + $v = (string) $v; } - if ($this->instance_id !== $v) { - $this->instance_id = $v; - $this->modifiedColumns[] = CcShowSchedulePeer::INSTANCE_ID; - } - - if ($this->aCcShowInstances !== null && $this->aCcShowInstances->getDbId() !== $v) { - $this->aCcShowInstances = null; + if ($this->criteria !== $v) { + $this->criteria = $v; + $this->modifiedColumns[] = CcBlockcriteriaPeer::CRITERIA; } return $this; - } // setDbInstanceId() + } // setDbCriteria() /** - * Set the value of [position] column. + * Set the value of [modifier] column. * - * @param int $v new value - * @return CcShowSchedule The current object (for fluent API support) + * @param string $v new value + * @return CcBlockcriteria The current object (for fluent API support) */ - public function setDbPosition($v) + public function setDbModifier($v) { if ($v !== null) { - $v = (int) $v; + $v = (string) $v; } - if ($this->position !== $v) { - $this->position = $v; - $this->modifiedColumns[] = CcShowSchedulePeer::POSITION; + if ($this->modifier !== $v) { + $this->modifier = $v; + $this->modifiedColumns[] = CcBlockcriteriaPeer::MODIFIER; } return $this; - } // setDbPosition() + } // setDbModifier() /** - * Set the value of [group_id] column. + * Set the value of [value] column. + * + * @param string $v new value + * @return CcBlockcriteria The current object (for fluent API support) + */ + public function setDbValue($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->value !== $v) { + $this->value = $v; + $this->modifiedColumns[] = CcBlockcriteriaPeer::VALUE; + } + + return $this; + } // setDbValue() + + /** + * Set the value of [extra] column. + * + * @param string $v new value + * @return CcBlockcriteria The current object (for fluent API support) + */ + public function setDbExtra($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->extra !== $v) { + $this->extra = $v; + $this->modifiedColumns[] = CcBlockcriteriaPeer::EXTRA; + } + + return $this; + } // setDbExtra() + + /** + * Set the value of [block_id] column. * * @param int $v new value - * @return CcShowSchedule The current object (for fluent API support) + * @return CcBlockcriteria The current object (for fluent API support) */ - public function setDbGroupId($v) + public function setDbBlockId($v) { if ($v !== null) { $v = (int) $v; } - if ($this->group_id !== $v) { - $this->group_id = $v; - $this->modifiedColumns[] = CcShowSchedulePeer::GROUP_ID; + if ($this->block_id !== $v) { + $this->block_id = $v; + $this->modifiedColumns[] = CcBlockcriteriaPeer::BLOCK_ID; + } + + if ($this->aCcBlock !== null && $this->aCcBlock->getDbId() !== $v) { + $this->aCcBlock = null; } return $this; - } // setDbGroupId() + } // setDbBlockId() /** * Indicates whether the columns in this object are only set to default values. @@ -224,9 +296,11 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent try { $this->id = ($row[$startcol + 0] !== null) ? (int) $row[$startcol + 0] : null; - $this->instance_id = ($row[$startcol + 1] !== null) ? (int) $row[$startcol + 1] : null; - $this->position = ($row[$startcol + 2] !== null) ? (int) $row[$startcol + 2] : null; - $this->group_id = ($row[$startcol + 3] !== null) ? (int) $row[$startcol + 3] : null; + $this->criteria = ($row[$startcol + 1] !== null) ? (string) $row[$startcol + 1] : null; + $this->modifier = ($row[$startcol + 2] !== null) ? (string) $row[$startcol + 2] : null; + $this->value = ($row[$startcol + 3] !== null) ? (string) $row[$startcol + 3] : null; + $this->extra = ($row[$startcol + 4] !== null) ? (string) $row[$startcol + 4] : null; + $this->block_id = ($row[$startcol + 5] !== null) ? (int) $row[$startcol + 5] : null; $this->resetModified(); $this->setNew(false); @@ -235,10 +309,10 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent $this->ensureConsistency(); } - return $startcol + 4; // 4 = CcShowSchedulePeer::NUM_COLUMNS - CcShowSchedulePeer::NUM_LAZY_LOAD_COLUMNS). + return $startcol + 6; // 6 = CcBlockcriteriaPeer::NUM_COLUMNS - CcBlockcriteriaPeer::NUM_LAZY_LOAD_COLUMNS). } catch (Exception $e) { - throw new PropelException("Error populating CcShowSchedule object", $e); + throw new PropelException("Error populating CcBlockcriteria object", $e); } } @@ -258,8 +332,8 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent public function ensureConsistency() { - if ($this->aCcShowInstances !== null && $this->instance_id !== $this->aCcShowInstances->getDbId()) { - $this->aCcShowInstances = null; + if ($this->aCcBlock !== null && $this->block_id !== $this->aCcBlock->getDbId()) { + $this->aCcBlock = null; } } // ensureConsistency @@ -284,13 +358,13 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent } if ($con === null) { - $con = Propel::getConnection(CcShowSchedulePeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcBlockcriteriaPeer::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 = CcShowSchedulePeer::doSelectStmt($this->buildPkeyCriteria(), $con); + $stmt = CcBlockcriteriaPeer::doSelectStmt($this->buildPkeyCriteria(), $con); $row = $stmt->fetch(PDO::FETCH_NUM); $stmt->closeCursor(); if (!$row) { @@ -300,7 +374,7 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent if ($deep) { // also de-associate any related objects? - $this->aCcShowInstances = null; + $this->aCcBlock = null; } // if (deep) } @@ -320,14 +394,14 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent } if ($con === null) { - $con = Propel::getConnection(CcShowSchedulePeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + $con = Propel::getConnection(CcBlockcriteriaPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); } $con->beginTransaction(); try { $ret = $this->preDelete($con); if ($ret) { - CcShowScheduleQuery::create() + CcBlockcriteriaQuery::create() ->filterByPrimaryKey($this->getPrimaryKey()) ->delete($con); $this->postDelete($con); @@ -362,7 +436,7 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent } if ($con === null) { - $con = Propel::getConnection(CcShowSchedulePeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + $con = Propel::getConnection(CcBlockcriteriaPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); } $con->beginTransaction(); @@ -382,7 +456,7 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent $this->postUpdate($con); } $this->postSave($con); - CcShowSchedulePeer::addInstanceToPool($this); + CcBlockcriteriaPeer::addInstanceToPool($this); } else { $affectedRows = 0; } @@ -416,23 +490,23 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent // method. This object relates to these object(s) by a // foreign key reference. - if ($this->aCcShowInstances !== null) { - if ($this->aCcShowInstances->isModified() || $this->aCcShowInstances->isNew()) { - $affectedRows += $this->aCcShowInstances->save($con); + if ($this->aCcBlock !== null) { + if ($this->aCcBlock->isModified() || $this->aCcBlock->isNew()) { + $affectedRows += $this->aCcBlock->save($con); } - $this->setCcShowInstances($this->aCcShowInstances); + $this->setCcBlock($this->aCcBlock); } if ($this->isNew() ) { - $this->modifiedColumns[] = CcShowSchedulePeer::ID; + $this->modifiedColumns[] = CcBlockcriteriaPeer::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(CcShowSchedulePeer::ID) ) { - throw new PropelException('Cannot insert a value for auto-increment primary key ('.CcShowSchedulePeer::ID.')'); + if ($criteria->keyContainsValue(CcBlockcriteriaPeer::ID) ) { + throw new PropelException('Cannot insert a value for auto-increment primary key ('.CcBlockcriteriaPeer::ID.')'); } $pk = BasePeer::doInsert($criteria, $con); @@ -440,7 +514,7 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent $this->setDbId($pk); //[IMV] update autoincrement primary key $this->setNew(false); } else { - $affectedRows += CcShowSchedulePeer::doUpdate($this, $con); + $affectedRows += CcBlockcriteriaPeer::doUpdate($this, $con); } $this->resetModified(); // [HL] After being saved an object is no longer 'modified' @@ -517,14 +591,14 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent // method. This object relates to these object(s) by a // foreign key reference. - if ($this->aCcShowInstances !== null) { - if (!$this->aCcShowInstances->validate($columns)) { - $failureMap = array_merge($failureMap, $this->aCcShowInstances->getValidationFailures()); + if ($this->aCcBlock !== null) { + if (!$this->aCcBlock->validate($columns)) { + $failureMap = array_merge($failureMap, $this->aCcBlock->getValidationFailures()); } } - if (($retval = CcShowSchedulePeer::doValidate($this, $columns)) !== true) { + if (($retval = CcBlockcriteriaPeer::doValidate($this, $columns)) !== true) { $failureMap = array_merge($failureMap, $retval); } @@ -547,7 +621,7 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent */ public function getByName($name, $type = BasePeer::TYPE_PHPNAME) { - $pos = CcShowSchedulePeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); + $pos = CcBlockcriteriaPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); $field = $this->getByPosition($pos); return $field; } @@ -566,13 +640,19 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent return $this->getDbId(); break; case 1: - return $this->getDbInstanceId(); + return $this->getDbCriteria(); break; case 2: - return $this->getDbPosition(); + return $this->getDbModifier(); break; case 3: - return $this->getDbGroupId(); + return $this->getDbValue(); + break; + case 4: + return $this->getDbExtra(); + break; + case 5: + return $this->getDbBlockId(); break; default: return null; @@ -596,16 +676,18 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent */ public function toArray($keyType = BasePeer::TYPE_PHPNAME, $includeLazyLoadColumns = true, $includeForeignObjects = false) { - $keys = CcShowSchedulePeer::getFieldNames($keyType); + $keys = CcBlockcriteriaPeer::getFieldNames($keyType); $result = array( $keys[0] => $this->getDbId(), - $keys[1] => $this->getDbInstanceId(), - $keys[2] => $this->getDbPosition(), - $keys[3] => $this->getDbGroupId(), + $keys[1] => $this->getDbCriteria(), + $keys[2] => $this->getDbModifier(), + $keys[3] => $this->getDbValue(), + $keys[4] => $this->getDbExtra(), + $keys[5] => $this->getDbBlockId(), ); if ($includeForeignObjects) { - if (null !== $this->aCcShowInstances) { - $result['CcShowInstances'] = $this->aCcShowInstances->toArray($keyType, $includeLazyLoadColumns, true); + if (null !== $this->aCcBlock) { + $result['CcBlock'] = $this->aCcBlock->toArray($keyType, $includeLazyLoadColumns, true); } } return $result; @@ -623,7 +705,7 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent */ public function setByName($name, $value, $type = BasePeer::TYPE_PHPNAME) { - $pos = CcShowSchedulePeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); + $pos = CcBlockcriteriaPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); return $this->setByPosition($pos, $value); } @@ -642,13 +724,19 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent $this->setDbId($value); break; case 1: - $this->setDbInstanceId($value); + $this->setDbCriteria($value); break; case 2: - $this->setDbPosition($value); + $this->setDbModifier($value); break; case 3: - $this->setDbGroupId($value); + $this->setDbValue($value); + break; + case 4: + $this->setDbExtra($value); + break; + case 5: + $this->setDbBlockId($value); break; } // switch() } @@ -672,12 +760,14 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent */ public function fromArray($arr, $keyType = BasePeer::TYPE_PHPNAME) { - $keys = CcShowSchedulePeer::getFieldNames($keyType); + $keys = CcBlockcriteriaPeer::getFieldNames($keyType); if (array_key_exists($keys[0], $arr)) $this->setDbId($arr[$keys[0]]); - if (array_key_exists($keys[1], $arr)) $this->setDbInstanceId($arr[$keys[1]]); - if (array_key_exists($keys[2], $arr)) $this->setDbPosition($arr[$keys[2]]); - if (array_key_exists($keys[3], $arr)) $this->setDbGroupId($arr[$keys[3]]); + if (array_key_exists($keys[1], $arr)) $this->setDbCriteria($arr[$keys[1]]); + if (array_key_exists($keys[2], $arr)) $this->setDbModifier($arr[$keys[2]]); + if (array_key_exists($keys[3], $arr)) $this->setDbValue($arr[$keys[3]]); + if (array_key_exists($keys[4], $arr)) $this->setDbExtra($arr[$keys[4]]); + if (array_key_exists($keys[5], $arr)) $this->setDbBlockId($arr[$keys[5]]); } /** @@ -687,12 +777,14 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent */ public function buildCriteria() { - $criteria = new Criteria(CcShowSchedulePeer::DATABASE_NAME); + $criteria = new Criteria(CcBlockcriteriaPeer::DATABASE_NAME); - if ($this->isColumnModified(CcShowSchedulePeer::ID)) $criteria->add(CcShowSchedulePeer::ID, $this->id); - if ($this->isColumnModified(CcShowSchedulePeer::INSTANCE_ID)) $criteria->add(CcShowSchedulePeer::INSTANCE_ID, $this->instance_id); - if ($this->isColumnModified(CcShowSchedulePeer::POSITION)) $criteria->add(CcShowSchedulePeer::POSITION, $this->position); - if ($this->isColumnModified(CcShowSchedulePeer::GROUP_ID)) $criteria->add(CcShowSchedulePeer::GROUP_ID, $this->group_id); + if ($this->isColumnModified(CcBlockcriteriaPeer::ID)) $criteria->add(CcBlockcriteriaPeer::ID, $this->id); + if ($this->isColumnModified(CcBlockcriteriaPeer::CRITERIA)) $criteria->add(CcBlockcriteriaPeer::CRITERIA, $this->criteria); + if ($this->isColumnModified(CcBlockcriteriaPeer::MODIFIER)) $criteria->add(CcBlockcriteriaPeer::MODIFIER, $this->modifier); + if ($this->isColumnModified(CcBlockcriteriaPeer::VALUE)) $criteria->add(CcBlockcriteriaPeer::VALUE, $this->value); + if ($this->isColumnModified(CcBlockcriteriaPeer::EXTRA)) $criteria->add(CcBlockcriteriaPeer::EXTRA, $this->extra); + if ($this->isColumnModified(CcBlockcriteriaPeer::BLOCK_ID)) $criteria->add(CcBlockcriteriaPeer::BLOCK_ID, $this->block_id); return $criteria; } @@ -707,8 +799,8 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent */ public function buildPkeyCriteria() { - $criteria = new Criteria(CcShowSchedulePeer::DATABASE_NAME); - $criteria->add(CcShowSchedulePeer::ID, $this->id); + $criteria = new Criteria(CcBlockcriteriaPeer::DATABASE_NAME); + $criteria->add(CcBlockcriteriaPeer::ID, $this->id); return $criteria; } @@ -748,15 +840,17 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent * If desired, this method can also make copies of all associated (fkey referrers) * objects. * - * @param object $copyObj An object of CcShowSchedule (or compatible) type. + * @param object $copyObj An object of CcBlockcriteria (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->setDbInstanceId($this->instance_id); - $copyObj->setDbPosition($this->position); - $copyObj->setDbGroupId($this->group_id); + $copyObj->setDbCriteria($this->criteria); + $copyObj->setDbModifier($this->modifier); + $copyObj->setDbValue($this->value); + $copyObj->setDbExtra($this->extra); + $copyObj->setDbBlockId($this->block_id); $copyObj->setNew(true); $copyObj->setDbId(NULL); // this is a auto-increment column, so set to default value @@ -771,7 +865,7 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent * objects. * * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. - * @return CcShowSchedule Clone of current object. + * @return CcBlockcriteria Clone of current object. * @throws PropelException */ public function copy($deepCopy = false) @@ -790,37 +884,37 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent * same instance for all member of this class. The method could therefore * be static, but this would prevent one from overriding the behavior. * - * @return CcShowSchedulePeer + * @return CcBlockcriteriaPeer */ public function getPeer() { if (self::$peer === null) { - self::$peer = new CcShowSchedulePeer(); + self::$peer = new CcBlockcriteriaPeer(); } return self::$peer; } /** - * Declares an association between this object and a CcShowInstances object. + * Declares an association between this object and a CcBlock object. * - * @param CcShowInstances $v - * @return CcShowSchedule The current object (for fluent API support) + * @param CcBlock $v + * @return CcBlockcriteria The current object (for fluent API support) * @throws PropelException */ - public function setCcShowInstances(CcShowInstances $v = null) + public function setCcBlock(CcBlock $v = null) { if ($v === null) { - $this->setDbInstanceId(NULL); + $this->setDbBlockId(NULL); } else { - $this->setDbInstanceId($v->getDbId()); + $this->setDbBlockId($v->getDbId()); } - $this->aCcShowInstances = $v; + $this->aCcBlock = $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 this object has already been added to the CcBlock object, it will not be re-added. if ($v !== null) { - $v->addCcShowSchedule($this); + $v->addCcBlockcriteria($this); } return $this; @@ -828,25 +922,25 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent /** - * Get the associated CcShowInstances object + * Get the associated CcBlock object * * @param PropelPDO Optional Connection object. - * @return CcShowInstances The associated CcShowInstances object. + * @return CcBlock The associated CcBlock object. * @throws PropelException */ - public function getCcShowInstances(PropelPDO $con = null) + public function getCcBlock(PropelPDO $con = null) { - if ($this->aCcShowInstances === null && ($this->instance_id !== null)) { - $this->aCcShowInstances = CcShowInstancesQuery::create()->findPk($this->instance_id, $con); + 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->aCcShowInstances->addCcShowSchedules($this); + $this->aCcBlock->addCcBlockcriterias($this); */ } - return $this->aCcShowInstances; + return $this->aCcBlock; } /** @@ -855,9 +949,11 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent public function clear() { $this->id = null; - $this->instance_id = null; - $this->position = null; - $this->group_id = null; + $this->criteria = null; + $this->modifier = null; + $this->value = null; + $this->extra = null; + $this->block_id = null; $this->alreadyInSave = false; $this->alreadyInValidation = false; $this->clearAllReferences(); @@ -880,7 +976,7 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent if ($deep) { } // if ($deep) - $this->aCcShowInstances = null; + $this->aCcBlock = null; } /** @@ -902,4 +998,4 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent throw new PropelException('Call to undefined method: ' . $name); } -} // BaseCcShowSchedule +} // BaseCcBlockcriteria diff --git a/install_minimal/upgrades/airtime-2.0.0/propel/airtime/om/BaseCcAccessPeer.php b/airtime_mvc/application/models/airtime/om/BaseCcBlockcriteriaPeer.php similarity index 69% rename from install_minimal/upgrades/airtime-2.0.0/propel/airtime/om/BaseCcAccessPeer.php rename to airtime_mvc/application/models/airtime/om/BaseCcBlockcriteriaPeer.php index c14312b14..a523024ad 100644 --- a/install_minimal/upgrades/airtime-2.0.0/propel/airtime/om/BaseCcAccessPeer.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcBlockcriteriaPeer.php @@ -2,67 +2,58 @@ /** - * Base static class for performing query and update operations on the 'cc_access' table. + * Base static class for performing query and update operations on the 'cc_blockcriteria' table. * * * * @package propel.generator.airtime.om */ -abstract class BaseCcAccessPeer { +abstract class BaseCcBlockcriteriaPeer { /** the default database name for this class */ const DATABASE_NAME = 'airtime'; /** the table name for this class */ - const TABLE_NAME = 'cc_access'; + const TABLE_NAME = 'cc_blockcriteria'; /** the related Propel class for this table */ - const OM_CLASS = 'CcAccess'; + const OM_CLASS = 'CcBlockcriteria'; /** A class that can be returned by this peer. */ - const CLASS_DEFAULT = 'airtime.CcAccess'; + const CLASS_DEFAULT = 'airtime.CcBlockcriteria'; /** the related TableMap class for this table */ - const TM_CLASS = 'CcAccessTableMap'; + const TM_CLASS = 'CcBlockcriteriaTableMap'; /** The total number of columns. */ - const NUM_COLUMNS = 9; + const NUM_COLUMNS = 6; /** The number of lazy-loaded columns. */ const NUM_LAZY_LOAD_COLUMNS = 0; /** the column name for the ID field */ - const ID = 'cc_access.ID'; + const ID = 'cc_blockcriteria.ID'; - /** the column name for the GUNID field */ - const GUNID = 'cc_access.GUNID'; + /** the column name for the CRITERIA field */ + const CRITERIA = 'cc_blockcriteria.CRITERIA'; - /** the column name for the TOKEN field */ - const TOKEN = 'cc_access.TOKEN'; + /** the column name for the MODIFIER field */ + const MODIFIER = 'cc_blockcriteria.MODIFIER'; - /** the column name for the CHSUM field */ - const CHSUM = 'cc_access.CHSUM'; + /** the column name for the VALUE field */ + const VALUE = 'cc_blockcriteria.VALUE'; - /** the column name for the EXT field */ - const EXT = 'cc_access.EXT'; + /** the column name for the EXTRA field */ + const EXTRA = 'cc_blockcriteria.EXTRA'; - /** the column name for the TYPE field */ - const TYPE = 'cc_access.TYPE'; - - /** the column name for the PARENT field */ - const PARENT = 'cc_access.PARENT'; - - /** the column name for the OWNER field */ - const OWNER = 'cc_access.OWNER'; - - /** the column name for the TS field */ - const TS = 'cc_access.TS'; + /** the column name for the BLOCK_ID field */ + const BLOCK_ID = 'cc_blockcriteria.BLOCK_ID'; /** - * An identiy map to hold any loaded instances of CcAccess objects. + * An identiy map to hold any loaded instances of CcBlockcriteria objects. * This must be public so that other peer classes can access this when hydrating from JOIN * queries. - * @var array CcAccess[] + * @var array CcBlockcriteria[] */ public static $instances = array(); @@ -74,12 +65,12 @@ abstract class BaseCcAccessPeer { * e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id' */ private static $fieldNames = array ( - BasePeer::TYPE_PHPNAME => array ('Id', 'Gunid', 'Token', 'Chsum', 'Ext', 'Type', 'Parent', 'Owner', 'Ts', ), - BasePeer::TYPE_STUDLYPHPNAME => array ('id', 'gunid', 'token', 'chsum', 'ext', 'type', 'parent', 'owner', 'ts', ), - BasePeer::TYPE_COLNAME => array (self::ID, self::GUNID, self::TOKEN, self::CHSUM, self::EXT, self::TYPE, self::PARENT, self::OWNER, self::TS, ), - BasePeer::TYPE_RAW_COLNAME => array ('ID', 'GUNID', 'TOKEN', 'CHSUM', 'EXT', 'TYPE', 'PARENT', 'OWNER', 'TS', ), - BasePeer::TYPE_FIELDNAME => array ('id', 'gunid', 'token', 'chsum', 'ext', 'type', 'parent', 'owner', 'ts', ), - BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, ) + BasePeer::TYPE_PHPNAME => array ('DbId', 'DbCriteria', 'DbModifier', 'DbValue', 'DbExtra', 'DbBlockId', ), + BasePeer::TYPE_STUDLYPHPNAME => array ('dbId', 'dbCriteria', 'dbModifier', 'dbValue', 'dbExtra', 'dbBlockId', ), + BasePeer::TYPE_COLNAME => array (self::ID, self::CRITERIA, self::MODIFIER, self::VALUE, self::EXTRA, self::BLOCK_ID, ), + BasePeer::TYPE_RAW_COLNAME => array ('ID', 'CRITERIA', 'MODIFIER', 'VALUE', 'EXTRA', 'BLOCK_ID', ), + BasePeer::TYPE_FIELDNAME => array ('id', 'criteria', 'modifier', 'value', 'extra', 'block_id', ), + BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, ) ); /** @@ -89,12 +80,12 @@ abstract class BaseCcAccessPeer { * e.g. self::$fieldNames[BasePeer::TYPE_PHPNAME]['Id'] = 0 */ private static $fieldKeys = array ( - BasePeer::TYPE_PHPNAME => array ('Id' => 0, 'Gunid' => 1, 'Token' => 2, 'Chsum' => 3, 'Ext' => 4, 'Type' => 5, 'Parent' => 6, 'Owner' => 7, 'Ts' => 8, ), - BasePeer::TYPE_STUDLYPHPNAME => array ('id' => 0, 'gunid' => 1, 'token' => 2, 'chsum' => 3, 'ext' => 4, 'type' => 5, 'parent' => 6, 'owner' => 7, 'ts' => 8, ), - BasePeer::TYPE_COLNAME => array (self::ID => 0, self::GUNID => 1, self::TOKEN => 2, self::CHSUM => 3, self::EXT => 4, self::TYPE => 5, self::PARENT => 6, self::OWNER => 7, self::TS => 8, ), - BasePeer::TYPE_RAW_COLNAME => array ('ID' => 0, 'GUNID' => 1, 'TOKEN' => 2, 'CHSUM' => 3, 'EXT' => 4, 'TYPE' => 5, 'PARENT' => 6, 'OWNER' => 7, 'TS' => 8, ), - BasePeer::TYPE_FIELDNAME => array ('id' => 0, 'gunid' => 1, 'token' => 2, 'chsum' => 3, 'ext' => 4, 'type' => 5, 'parent' => 6, 'owner' => 7, 'ts' => 8, ), - BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, ) + BasePeer::TYPE_PHPNAME => array ('DbId' => 0, 'DbCriteria' => 1, 'DbModifier' => 2, 'DbValue' => 3, 'DbExtra' => 4, 'DbBlockId' => 5, ), + BasePeer::TYPE_STUDLYPHPNAME => array ('dbId' => 0, 'dbCriteria' => 1, 'dbModifier' => 2, 'dbValue' => 3, 'dbExtra' => 4, 'dbBlockId' => 5, ), + BasePeer::TYPE_COLNAME => array (self::ID => 0, self::CRITERIA => 1, self::MODIFIER => 2, self::VALUE => 3, self::EXTRA => 4, self::BLOCK_ID => 5, ), + BasePeer::TYPE_RAW_COLNAME => array ('ID' => 0, 'CRITERIA' => 1, 'MODIFIER' => 2, 'VALUE' => 3, 'EXTRA' => 4, 'BLOCK_ID' => 5, ), + BasePeer::TYPE_FIELDNAME => array ('id' => 0, 'criteria' => 1, 'modifier' => 2, 'value' => 3, 'extra' => 4, 'block_id' => 5, ), + BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, ) ); /** @@ -143,12 +134,12 @@ abstract class BaseCcAccessPeer { * $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. CcAccessPeer::COLUMN_NAME). + * @param string $column The column name for current table. (i.e. CcBlockcriteriaPeer::COLUMN_NAME). * @return string */ public static function alias($alias, $column) { - return str_replace(CcAccessPeer::TABLE_NAME.'.', $alias.'.', $column); + return str_replace(CcBlockcriteriaPeer::TABLE_NAME.'.', $alias.'.', $column); } /** @@ -166,25 +157,19 @@ abstract class BaseCcAccessPeer { public static function addSelectColumns(Criteria $criteria, $alias = null) { if (null === $alias) { - $criteria->addSelectColumn(CcAccessPeer::ID); - $criteria->addSelectColumn(CcAccessPeer::GUNID); - $criteria->addSelectColumn(CcAccessPeer::TOKEN); - $criteria->addSelectColumn(CcAccessPeer::CHSUM); - $criteria->addSelectColumn(CcAccessPeer::EXT); - $criteria->addSelectColumn(CcAccessPeer::TYPE); - $criteria->addSelectColumn(CcAccessPeer::PARENT); - $criteria->addSelectColumn(CcAccessPeer::OWNER); - $criteria->addSelectColumn(CcAccessPeer::TS); + $criteria->addSelectColumn(CcBlockcriteriaPeer::ID); + $criteria->addSelectColumn(CcBlockcriteriaPeer::CRITERIA); + $criteria->addSelectColumn(CcBlockcriteriaPeer::MODIFIER); + $criteria->addSelectColumn(CcBlockcriteriaPeer::VALUE); + $criteria->addSelectColumn(CcBlockcriteriaPeer::EXTRA); + $criteria->addSelectColumn(CcBlockcriteriaPeer::BLOCK_ID); } else { $criteria->addSelectColumn($alias . '.ID'); - $criteria->addSelectColumn($alias . '.GUNID'); - $criteria->addSelectColumn($alias . '.TOKEN'); - $criteria->addSelectColumn($alias . '.CHSUM'); - $criteria->addSelectColumn($alias . '.EXT'); - $criteria->addSelectColumn($alias . '.TYPE'); - $criteria->addSelectColumn($alias . '.PARENT'); - $criteria->addSelectColumn($alias . '.OWNER'); - $criteria->addSelectColumn($alias . '.TS'); + $criteria->addSelectColumn($alias . '.CRITERIA'); + $criteria->addSelectColumn($alias . '.MODIFIER'); + $criteria->addSelectColumn($alias . '.VALUE'); + $criteria->addSelectColumn($alias . '.EXTRA'); + $criteria->addSelectColumn($alias . '.BLOCK_ID'); } } @@ -204,21 +189,21 @@ abstract class BaseCcAccessPeer { // 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(CcAccessPeer::TABLE_NAME); + $criteria->setPrimaryTableName(CcBlockcriteriaPeer::TABLE_NAME); if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { $criteria->setDistinct(); } if (!$criteria->hasSelectClause()) { - CcAccessPeer::addSelectColumns($criteria); + CcBlockcriteriaPeer::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(CcAccessPeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcBlockcriteriaPeer::DATABASE_NAME, Propel::CONNECTION_READ); } // BasePeer returns a PDOStatement $stmt = BasePeer::doCount($criteria, $con); @@ -236,7 +221,7 @@ abstract class BaseCcAccessPeer { * * @param Criteria $criteria object used to create the SELECT statement. * @param PropelPDO $con - * @return CcAccess + * @return CcBlockcriteria * @throws PropelException Any exceptions caught during processing will be * rethrown wrapped into a PropelException. */ @@ -244,7 +229,7 @@ abstract class BaseCcAccessPeer { { $critcopy = clone $criteria; $critcopy->setLimit(1); - $objects = CcAccessPeer::doSelect($critcopy, $con); + $objects = CcBlockcriteriaPeer::doSelect($critcopy, $con); if ($objects) { return $objects[0]; } @@ -261,7 +246,7 @@ abstract class BaseCcAccessPeer { */ public static function doSelect(Criteria $criteria, PropelPDO $con = null) { - return CcAccessPeer::populateObjects(CcAccessPeer::doSelectStmt($criteria, $con)); + return CcBlockcriteriaPeer::populateObjects(CcBlockcriteriaPeer::doSelectStmt($criteria, $con)); } /** * Prepares the Criteria object and uses the parent doSelect() method to execute a PDOStatement. @@ -279,12 +264,12 @@ abstract class BaseCcAccessPeer { public static function doSelectStmt(Criteria $criteria, PropelPDO $con = null) { if ($con === null) { - $con = Propel::getConnection(CcAccessPeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcBlockcriteriaPeer::DATABASE_NAME, Propel::CONNECTION_READ); } if (!$criteria->hasSelectClause()) { $criteria = clone $criteria; - CcAccessPeer::addSelectColumns($criteria); + CcBlockcriteriaPeer::addSelectColumns($criteria); } // Set the correct dbName @@ -302,14 +287,14 @@ abstract class BaseCcAccessPeer { * to the cache in order to ensure that the same objects are always returned by doSelect*() * and retrieveByPK*() calls. * - * @param CcAccess $value A CcAccess object. + * @param CcBlockcriteria $value A CcBlockcriteria object. * @param string $key (optional) key to use for instance map (for performance boost if key was already calculated externally). */ - public static function addInstanceToPool(CcAccess $obj, $key = null) + public static function addInstanceToPool(CcBlockcriteria $obj, $key = null) { if (Propel::isInstancePoolingEnabled()) { if ($key === null) { - $key = (string) $obj->getId(); + $key = (string) $obj->getDbId(); } // if key === null self::$instances[$key] = $obj; } @@ -323,18 +308,18 @@ abstract class BaseCcAccessPeer { * 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 CcAccess object or a primary key value. + * @param mixed $value A CcBlockcriteria object or a primary key value. */ public static function removeInstanceFromPool($value) { if (Propel::isInstancePoolingEnabled() && $value !== null) { - if (is_object($value) && $value instanceof CcAccess) { - $key = (string) $value->getId(); + if (is_object($value) && $value instanceof CcBlockcriteria) { + $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 CcAccess object; got " . (is_object($value) ? get_class($value) . ' object.' : var_export($value,true))); + $e = new PropelException("Invalid value passed to removeInstanceFromPool(). Expected primary key or CcBlockcriteria object; got " . (is_object($value) ? get_class($value) . ' object.' : var_export($value,true))); throw $e; } @@ -349,7 +334,7 @@ abstract class BaseCcAccessPeer { * 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 CcAccess Found object or NULL if 1) no instance exists for specified key or 2) instance pooling has been disabled. + * @return CcBlockcriteria 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) @@ -373,7 +358,7 @@ abstract class BaseCcAccessPeer { } /** - * Method to invalidate the instance pool of all tables related to cc_access + * Method to invalidate the instance pool of all tables related to cc_blockcriteria * by a foreign key with ON DELETE CASCADE */ public static function clearRelatedInstancePool() @@ -425,11 +410,11 @@ abstract class BaseCcAccessPeer { $results = array(); // set the class once to avoid overhead in the loop - $cls = CcAccessPeer::getOMClass(false); + $cls = CcBlockcriteriaPeer::getOMClass(false); // populate the object(s) while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $key = CcAccessPeer::getPrimaryKeyHashFromRow($row, 0); - if (null !== ($obj = CcAccessPeer::getInstanceFromPool($key))) { + $key = CcBlockcriteriaPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj = CcBlockcriteriaPeer::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 @@ -438,7 +423,7 @@ abstract class BaseCcAccessPeer { $obj = new $cls(); $obj->hydrate($row); $results[] = $obj; - CcAccessPeer::addInstanceToPool($obj, $key); + CcBlockcriteriaPeer::addInstanceToPool($obj, $key); } // if key exists } $stmt->closeCursor(); @@ -451,27 +436,27 @@ abstract class BaseCcAccessPeer { * @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 (CcAccess object, last column rank) + * @return array (CcBlockcriteria object, last column rank) */ public static function populateObject($row, $startcol = 0) { - $key = CcAccessPeer::getPrimaryKeyHashFromRow($row, $startcol); - if (null !== ($obj = CcAccessPeer::getInstanceFromPool($key))) { + $key = CcBlockcriteriaPeer::getPrimaryKeyHashFromRow($row, $startcol); + if (null !== ($obj = CcBlockcriteriaPeer::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 + CcAccessPeer::NUM_COLUMNS; + $col = $startcol + CcBlockcriteriaPeer::NUM_COLUMNS; } else { - $cls = CcAccessPeer::OM_CLASS; + $cls = CcBlockcriteriaPeer::OM_CLASS; $obj = new $cls(); $col = $obj->hydrate($row, $startcol); - CcAccessPeer::addInstanceToPool($obj, $key); + CcBlockcriteriaPeer::addInstanceToPool($obj, $key); } return array($obj, $col); } /** - * Returns the number of rows matching criteria, joining the related CcSubjs table + * 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. @@ -479,7 +464,7 @@ abstract class BaseCcAccessPeer { * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN * @return int Number of matching rows. */ - public static function doCountJoinCcSubjs(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) + 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; @@ -487,14 +472,14 @@ abstract class BaseCcAccessPeer { // 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(CcAccessPeer::TABLE_NAME); + $criteria->setPrimaryTableName(CcBlockcriteriaPeer::TABLE_NAME); if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { $criteria->setDistinct(); } if (!$criteria->hasSelectClause()) { - CcAccessPeer::addSelectColumns($criteria); + CcBlockcriteriaPeer::addSelectColumns($criteria); } $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count @@ -503,10 +488,10 @@ abstract class BaseCcAccessPeer { $criteria->setDbName(self::DATABASE_NAME); if ($con === null) { - $con = Propel::getConnection(CcAccessPeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcBlockcriteriaPeer::DATABASE_NAME, Propel::CONNECTION_READ); } - $criteria->addJoin(CcAccessPeer::OWNER, CcSubjsPeer::ID, $join_behavior); + $criteria->addJoin(CcBlockcriteriaPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); $stmt = BasePeer::doCount($criteria, $con); @@ -521,15 +506,15 @@ abstract class BaseCcAccessPeer { /** - * Selects a collection of CcAccess objects pre-filled with their CcSubjs objects. + * Selects a collection of CcBlockcriteria 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 CcAccess objects. + * @return array Array of CcBlockcriteria objects. * @throws PropelException Any exceptions caught during processing will be * rethrown wrapped into a PropelException. */ - public static function doSelectJoinCcSubjs(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) + public static function doSelectJoinCcBlock(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) { $criteria = clone $criteria; @@ -538,44 +523,44 @@ abstract class BaseCcAccessPeer { $criteria->setDbName(self::DATABASE_NAME); } - CcAccessPeer::addSelectColumns($criteria); - $startcol = (CcAccessPeer::NUM_COLUMNS - CcAccessPeer::NUM_LAZY_LOAD_COLUMNS); - CcSubjsPeer::addSelectColumns($criteria); + CcBlockcriteriaPeer::addSelectColumns($criteria); + $startcol = (CcBlockcriteriaPeer::NUM_COLUMNS - CcBlockcriteriaPeer::NUM_LAZY_LOAD_COLUMNS); + CcBlockPeer::addSelectColumns($criteria); - $criteria->addJoin(CcAccessPeer::OWNER, CcSubjsPeer::ID, $join_behavior); + $criteria->addJoin(CcBlockcriteriaPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); $stmt = BasePeer::doSelect($criteria, $con); $results = array(); while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $key1 = CcAccessPeer::getPrimaryKeyHashFromRow($row, 0); - if (null !== ($obj1 = CcAccessPeer::getInstanceFromPool($key1))) { + $key1 = CcBlockcriteriaPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcBlockcriteriaPeer::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 = CcAccessPeer::getOMClass(false); + $cls = CcBlockcriteriaPeer::getOMClass(false); $obj1 = new $cls(); $obj1->hydrate($row); - CcAccessPeer::addInstanceToPool($obj1, $key1); + CcBlockcriteriaPeer::addInstanceToPool($obj1, $key1); } // if $obj1 already loaded - $key2 = CcSubjsPeer::getPrimaryKeyHashFromRow($row, $startcol); + $key2 = CcBlockPeer::getPrimaryKeyHashFromRow($row, $startcol); if ($key2 !== null) { - $obj2 = CcSubjsPeer::getInstanceFromPool($key2); + $obj2 = CcBlockPeer::getInstanceFromPool($key2); if (!$obj2) { - $cls = CcSubjsPeer::getOMClass(false); + $cls = CcBlockPeer::getOMClass(false); $obj2 = new $cls(); $obj2->hydrate($row, $startcol); - CcSubjsPeer::addInstanceToPool($obj2, $key2); + CcBlockPeer::addInstanceToPool($obj2, $key2); } // if obj2 already loaded - // Add the $obj1 (CcAccess) to $obj2 (CcSubjs) - $obj2->addCcAccess($obj1); + // Add the $obj1 (CcBlockcriteria) to $obj2 (CcBlock) + $obj2->addCcBlockcriteria($obj1); } // if joined row was not null @@ -603,14 +588,14 @@ abstract class BaseCcAccessPeer { // 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(CcAccessPeer::TABLE_NAME); + $criteria->setPrimaryTableName(CcBlockcriteriaPeer::TABLE_NAME); if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { $criteria->setDistinct(); } if (!$criteria->hasSelectClause()) { - CcAccessPeer::addSelectColumns($criteria); + CcBlockcriteriaPeer::addSelectColumns($criteria); } $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count @@ -619,10 +604,10 @@ abstract class BaseCcAccessPeer { $criteria->setDbName(self::DATABASE_NAME); if ($con === null) { - $con = Propel::getConnection(CcAccessPeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcBlockcriteriaPeer::DATABASE_NAME, Propel::CONNECTION_READ); } - $criteria->addJoin(CcAccessPeer::OWNER, CcSubjsPeer::ID, $join_behavior); + $criteria->addJoin(CcBlockcriteriaPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); $stmt = BasePeer::doCount($criteria, $con); @@ -636,12 +621,12 @@ abstract class BaseCcAccessPeer { } /** - * Selects a collection of CcAccess objects pre-filled with all related objects. + * Selects a collection of CcBlockcriteria 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 CcAccess objects. + * @return array Array of CcBlockcriteria objects. * @throws PropelException Any exceptions caught during processing will be * rethrown wrapped into a PropelException. */ @@ -654,47 +639,47 @@ abstract class BaseCcAccessPeer { $criteria->setDbName(self::DATABASE_NAME); } - CcAccessPeer::addSelectColumns($criteria); - $startcol2 = (CcAccessPeer::NUM_COLUMNS - CcAccessPeer::NUM_LAZY_LOAD_COLUMNS); + CcBlockcriteriaPeer::addSelectColumns($criteria); + $startcol2 = (CcBlockcriteriaPeer::NUM_COLUMNS - CcBlockcriteriaPeer::NUM_LAZY_LOAD_COLUMNS); - CcSubjsPeer::addSelectColumns($criteria); - $startcol3 = $startcol2 + (CcSubjsPeer::NUM_COLUMNS - CcSubjsPeer::NUM_LAZY_LOAD_COLUMNS); + CcBlockPeer::addSelectColumns($criteria); + $startcol3 = $startcol2 + (CcBlockPeer::NUM_COLUMNS - CcBlockPeer::NUM_LAZY_LOAD_COLUMNS); - $criteria->addJoin(CcAccessPeer::OWNER, CcSubjsPeer::ID, $join_behavior); + $criteria->addJoin(CcBlockcriteriaPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); $stmt = BasePeer::doSelect($criteria, $con); $results = array(); while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $key1 = CcAccessPeer::getPrimaryKeyHashFromRow($row, 0); - if (null !== ($obj1 = CcAccessPeer::getInstanceFromPool($key1))) { + $key1 = CcBlockcriteriaPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcBlockcriteriaPeer::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 = CcAccessPeer::getOMClass(false); + $cls = CcBlockcriteriaPeer::getOMClass(false); $obj1 = new $cls(); $obj1->hydrate($row); - CcAccessPeer::addInstanceToPool($obj1, $key1); + CcBlockcriteriaPeer::addInstanceToPool($obj1, $key1); } // if obj1 already loaded - // Add objects for joined CcSubjs rows + // Add objects for joined CcBlock rows - $key2 = CcSubjsPeer::getPrimaryKeyHashFromRow($row, $startcol2); + $key2 = CcBlockPeer::getPrimaryKeyHashFromRow($row, $startcol2); if ($key2 !== null) { - $obj2 = CcSubjsPeer::getInstanceFromPool($key2); + $obj2 = CcBlockPeer::getInstanceFromPool($key2); if (!$obj2) { - $cls = CcSubjsPeer::getOMClass(false); + $cls = CcBlockPeer::getOMClass(false); $obj2 = new $cls(); $obj2->hydrate($row, $startcol2); - CcSubjsPeer::addInstanceToPool($obj2, $key2); + CcBlockPeer::addInstanceToPool($obj2, $key2); } // if obj2 loaded - // Add the $obj1 (CcAccess) to the collection in $obj2 (CcSubjs) - $obj2->addCcAccess($obj1); + // Add the $obj1 (CcBlockcriteria) to the collection in $obj2 (CcBlock) + $obj2->addCcBlockcriteria($obj1); } // if joined row not null $results[] = $obj1; @@ -720,10 +705,10 @@ abstract class BaseCcAccessPeer { */ public static function buildTableMap() { - $dbMap = Propel::getDatabaseMap(BaseCcAccessPeer::DATABASE_NAME); - if (!$dbMap->hasTable(BaseCcAccessPeer::TABLE_NAME)) + $dbMap = Propel::getDatabaseMap(BaseCcBlockcriteriaPeer::DATABASE_NAME); + if (!$dbMap->hasTable(BaseCcBlockcriteriaPeer::TABLE_NAME)) { - $dbMap->addTableObject(new CcAccessTableMap()); + $dbMap->addTableObject(new CcBlockcriteriaTableMap()); } } @@ -740,13 +725,13 @@ abstract class BaseCcAccessPeer { */ public static function getOMClass($withPrefix = true) { - return $withPrefix ? CcAccessPeer::CLASS_DEFAULT : CcAccessPeer::OM_CLASS; + return $withPrefix ? CcBlockcriteriaPeer::CLASS_DEFAULT : CcBlockcriteriaPeer::OM_CLASS; } /** - * Method perform an INSERT on the database, given a CcAccess or Criteria object. + * Method perform an INSERT on the database, given a CcBlockcriteria or Criteria object. * - * @param mixed $values Criteria or CcAccess object containing data that is used to create the INSERT statement. + * @param mixed $values Criteria or CcBlockcriteria 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 @@ -755,17 +740,17 @@ abstract class BaseCcAccessPeer { public static function doInsert($values, PropelPDO $con = null) { if ($con === null) { - $con = Propel::getConnection(CcAccessPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + $con = Propel::getConnection(CcBlockcriteriaPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); } if ($values instanceof Criteria) { $criteria = clone $values; // rename for clarity } else { - $criteria = $values->buildCriteria(); // build Criteria from CcAccess object + $criteria = $values->buildCriteria(); // build Criteria from CcBlockcriteria object } - if ($criteria->containsKey(CcAccessPeer::ID) && $criteria->keyContainsValue(CcAccessPeer::ID) ) { - throw new PropelException('Cannot insert a value for auto-increment primary key ('.CcAccessPeer::ID.')'); + if ($criteria->containsKey(CcBlockcriteriaPeer::ID) && $criteria->keyContainsValue(CcBlockcriteriaPeer::ID) ) { + throw new PropelException('Cannot insert a value for auto-increment primary key ('.CcBlockcriteriaPeer::ID.')'); } @@ -787,9 +772,9 @@ abstract class BaseCcAccessPeer { } /** - * Method perform an UPDATE on the database, given a CcAccess or Criteria object. + * Method perform an UPDATE on the database, given a CcBlockcriteria or Criteria object. * - * @param mixed $values Criteria or CcAccess object containing data that is used to create the UPDATE statement. + * @param mixed $values Criteria or CcBlockcriteria 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 @@ -798,7 +783,7 @@ abstract class BaseCcAccessPeer { public static function doUpdate($values, PropelPDO $con = null) { if ($con === null) { - $con = Propel::getConnection(CcAccessPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + $con = Propel::getConnection(CcBlockcriteriaPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); } $selectCriteria = new Criteria(self::DATABASE_NAME); @@ -806,15 +791,15 @@ abstract class BaseCcAccessPeer { if ($values instanceof Criteria) { $criteria = clone $values; // rename for clarity - $comparison = $criteria->getComparison(CcAccessPeer::ID); - $value = $criteria->remove(CcAccessPeer::ID); + $comparison = $criteria->getComparison(CcBlockcriteriaPeer::ID); + $value = $criteria->remove(CcBlockcriteriaPeer::ID); if ($value) { - $selectCriteria->add(CcAccessPeer::ID, $value, $comparison); + $selectCriteria->add(CcBlockcriteriaPeer::ID, $value, $comparison); } else { - $selectCriteria->setPrimaryTableName(CcAccessPeer::TABLE_NAME); + $selectCriteria->setPrimaryTableName(CcBlockcriteriaPeer::TABLE_NAME); } - } else { // $values is CcAccess object + } else { // $values is CcBlockcriteria object $criteria = $values->buildCriteria(); // gets full criteria $selectCriteria = $values->buildPkeyCriteria(); // gets criteria w/ primary key(s) } @@ -826,26 +811,26 @@ abstract class BaseCcAccessPeer { } /** - * Method to DELETE all rows from the cc_access table. + * Method to DELETE all rows from the cc_blockcriteria 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(CcAccessPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + $con = Propel::getConnection(CcBlockcriteriaPeer::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(CcAccessPeer::TABLE_NAME, $con, CcAccessPeer::DATABASE_NAME); + $affectedRows += BasePeer::doDeleteAll(CcBlockcriteriaPeer::TABLE_NAME, $con, CcBlockcriteriaPeer::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). - CcAccessPeer::clearInstancePool(); - CcAccessPeer::clearRelatedInstancePool(); + CcBlockcriteriaPeer::clearInstancePool(); + CcBlockcriteriaPeer::clearRelatedInstancePool(); $con->commit(); return $affectedRows; } catch (PropelException $e) { @@ -855,9 +840,9 @@ abstract class BaseCcAccessPeer { } /** - * Method perform a DELETE on the database, given a CcAccess or Criteria object OR a primary key value. + * Method perform a DELETE on the database, given a CcBlockcriteria or Criteria object OR a primary key value. * - * @param mixed $values Criteria or CcAccess object or primary key or array of primary keys + * @param mixed $values Criteria or CcBlockcriteria 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 @@ -868,27 +853,27 @@ abstract class BaseCcAccessPeer { public static function doDelete($values, PropelPDO $con = null) { if ($con === null) { - $con = Propel::getConnection(CcAccessPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + $con = Propel::getConnection(CcBlockcriteriaPeer::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. - CcAccessPeer::clearInstancePool(); + CcBlockcriteriaPeer::clearInstancePool(); // rename for clarity $criteria = clone $values; - } elseif ($values instanceof CcAccess) { // it's a model object + } elseif ($values instanceof CcBlockcriteria) { // it's a model object // invalidate the cache for this single object - CcAccessPeer::removeInstanceFromPool($values); + CcBlockcriteriaPeer::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(CcAccessPeer::ID, (array) $values, Criteria::IN); + $criteria->add(CcBlockcriteriaPeer::ID, (array) $values, Criteria::IN); // invalidate the cache for this object(s) foreach ((array) $values as $singleval) { - CcAccessPeer::removeInstanceFromPool($singleval); + CcBlockcriteriaPeer::removeInstanceFromPool($singleval); } } @@ -903,7 +888,7 @@ abstract class BaseCcAccessPeer { $con->beginTransaction(); $affectedRows += BasePeer::doDelete($criteria, $con); - CcAccessPeer::clearRelatedInstancePool(); + CcBlockcriteriaPeer::clearRelatedInstancePool(); $con->commit(); return $affectedRows; } catch (PropelException $e) { @@ -913,24 +898,24 @@ abstract class BaseCcAccessPeer { } /** - * Validates all modified columns of given CcAccess object. + * Validates all modified columns of given CcBlockcriteria 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 CcAccess $obj The object to validate. + * @param CcBlockcriteria $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(CcAccess $obj, $cols = null) + public static function doValidate(CcBlockcriteria $obj, $cols = null) { $columns = array(); if ($cols) { - $dbMap = Propel::getDatabaseMap(CcAccessPeer::DATABASE_NAME); - $tableMap = $dbMap->getTable(CcAccessPeer::TABLE_NAME); + $dbMap = Propel::getDatabaseMap(CcBlockcriteriaPeer::DATABASE_NAME); + $tableMap = $dbMap->getTable(CcBlockcriteriaPeer::TABLE_NAME); if (! is_array($cols)) { $cols = array($cols); @@ -946,7 +931,7 @@ abstract class BaseCcAccessPeer { } - return BasePeer::doValidate(CcAccessPeer::DATABASE_NAME, CcAccessPeer::TABLE_NAME, $columns); + return BasePeer::doValidate(CcBlockcriteriaPeer::DATABASE_NAME, CcBlockcriteriaPeer::TABLE_NAME, $columns); } /** @@ -954,23 +939,23 @@ abstract class BaseCcAccessPeer { * * @param int $pk the primary key. * @param PropelPDO $con the connection to use - * @return CcAccess + * @return CcBlockcriteria */ public static function retrieveByPK($pk, PropelPDO $con = null) { - if (null !== ($obj = CcAccessPeer::getInstanceFromPool((string) $pk))) { + if (null !== ($obj = CcBlockcriteriaPeer::getInstanceFromPool((string) $pk))) { return $obj; } if ($con === null) { - $con = Propel::getConnection(CcAccessPeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcBlockcriteriaPeer::DATABASE_NAME, Propel::CONNECTION_READ); } - $criteria = new Criteria(CcAccessPeer::DATABASE_NAME); - $criteria->add(CcAccessPeer::ID, $pk); + $criteria = new Criteria(CcBlockcriteriaPeer::DATABASE_NAME); + $criteria->add(CcBlockcriteriaPeer::ID, $pk); - $v = CcAccessPeer::doSelect($criteria, $con); + $v = CcBlockcriteriaPeer::doSelect($criteria, $con); return !empty($v) > 0 ? $v[0] : null; } @@ -986,23 +971,23 @@ abstract class BaseCcAccessPeer { public static function retrieveByPKs($pks, PropelPDO $con = null) { if ($con === null) { - $con = Propel::getConnection(CcAccessPeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcBlockcriteriaPeer::DATABASE_NAME, Propel::CONNECTION_READ); } $objs = null; if (empty($pks)) { $objs = array(); } else { - $criteria = new Criteria(CcAccessPeer::DATABASE_NAME); - $criteria->add(CcAccessPeer::ID, $pks, Criteria::IN); - $objs = CcAccessPeer::doSelect($criteria, $con); + $criteria = new Criteria(CcBlockcriteriaPeer::DATABASE_NAME); + $criteria->add(CcBlockcriteriaPeer::ID, $pks, Criteria::IN); + $objs = CcBlockcriteriaPeer::doSelect($criteria, $con); } return $objs; } -} // BaseCcAccessPeer +} // BaseCcBlockcriteriaPeer // This is the static code needed to register the TableMap for this table with the main Propel class. // -BaseCcAccessPeer::buildTableMap(); +BaseCcBlockcriteriaPeer::buildTableMap(); diff --git a/airtime_mvc/application/models/airtime/om/BaseCcBlockcriteriaQuery.php b/airtime_mvc/application/models/airtime/om/BaseCcBlockcriteriaQuery.php new file mode 100644 index 000000000..9baabbd74 --- /dev/null +++ b/airtime_mvc/application/models/airtime/om/BaseCcBlockcriteriaQuery.php @@ -0,0 +1,372 @@ +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 CcBlockcriteria|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ((null !== ($obj = CcBlockcriteriaPeer::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 CcBlockcriteriaQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + return $this->addUsingAlias(CcBlockcriteriaPeer::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 CcBlockcriteriaQuery The current query, for fluid interface + */ + public function filterByPrimaryKeys($keys) + { + return $this->addUsingAlias(CcBlockcriteriaPeer::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 CcBlockcriteriaQuery 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(CcBlockcriteriaPeer::ID, $dbId, $comparison); + } + + /** + * Filter the query on the criteria column + * + * @param string $dbCriteria 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 CcBlockcriteriaQuery The current query, for fluid interface + */ + public function filterByDbCriteria($dbCriteria = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($dbCriteria)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $dbCriteria)) { + $dbCriteria = str_replace('*', '%', $dbCriteria); + $comparison = Criteria::LIKE; + } + } + return $this->addUsingAlias(CcBlockcriteriaPeer::CRITERIA, $dbCriteria, $comparison); + } + + /** + * Filter the query on the modifier column + * + * @param string $dbModifier 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 CcBlockcriteriaQuery The current query, for fluid interface + */ + public function filterByDbModifier($dbModifier = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($dbModifier)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $dbModifier)) { + $dbModifier = str_replace('*', '%', $dbModifier); + $comparison = Criteria::LIKE; + } + } + return $this->addUsingAlias(CcBlockcriteriaPeer::MODIFIER, $dbModifier, $comparison); + } + + /** + * Filter the query on the value column + * + * @param string $dbValue 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 CcBlockcriteriaQuery The current query, for fluid interface + */ + public function filterByDbValue($dbValue = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($dbValue)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $dbValue)) { + $dbValue = str_replace('*', '%', $dbValue); + $comparison = Criteria::LIKE; + } + } + return $this->addUsingAlias(CcBlockcriteriaPeer::VALUE, $dbValue, $comparison); + } + + /** + * Filter the query on the extra column + * + * @param string $dbExtra 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 CcBlockcriteriaQuery The current query, for fluid interface + */ + public function filterByDbExtra($dbExtra = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($dbExtra)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $dbExtra)) { + $dbExtra = str_replace('*', '%', $dbExtra); + $comparison = Criteria::LIKE; + } + } + return $this->addUsingAlias(CcBlockcriteriaPeer::EXTRA, $dbExtra, $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 CcBlockcriteriaQuery 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(CcBlockcriteriaPeer::BLOCK_ID, $dbBlockId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbBlockId['max'])) { + $this->addUsingAlias(CcBlockcriteriaPeer::BLOCK_ID, $dbBlockId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcBlockcriteriaPeer::BLOCK_ID, $dbBlockId, $comparison); + } + + /** + * 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 CcBlockcriteriaQuery The current query, for fluid interface + */ + public function filterByCcBlock($ccBlock, $comparison = null) + { + return $this + ->addUsingAlias(CcBlockcriteriaPeer::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 CcBlockcriteriaQuery The current query, for fluid interface + */ + public function joinCcBlock($relationAlias = '', $joinType = Criteria::INNER_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::INNER_JOIN) + { + return $this + ->joinCcBlock($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'CcBlock', 'CcBlockQuery'); + } + + /** + * Exclude object from result + * + * @param CcBlockcriteria $ccBlockcriteria Object to remove from the list of results + * + * @return CcBlockcriteriaQuery The current query, for fluid interface + */ + public function prune($ccBlockcriteria = null) + { + if ($ccBlockcriteria) { + $this->addUsingAlias(CcBlockcriteriaPeer::ID, $ccBlockcriteria->getDbId(), Criteria::NOT_EQUAL); + } + + return $this; + } + +} // BaseCcBlockcriteriaQuery diff --git a/airtime_mvc/application/models/airtime/om/BaseCcFiles.php b/airtime_mvc/application/models/airtime/om/BaseCcFiles.php index f3f60d2e1..a18d65dca 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcFiles.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcFiles.php @@ -30,12 +30,6 @@ abstract class BaseCcFiles extends BaseObject implements Persistent */ protected $id; - /** - * The value for the gunid field. - * @var string - */ - protected $gunid; - /** * The value for the name field. * Note: this column has a database default value of: '' @@ -195,7 +189,7 @@ abstract class BaseCcFiles extends BaseObject implements Persistent /** * The value for the bpm field. - * @var string + * @var int */ protected $bpm; @@ -410,10 +404,27 @@ abstract class BaseCcFiles extends BaseObject implements Persistent */ protected $soundcloud_upload_time; + /** + * The value for the replay_gain field. + * @var string + */ + protected $replay_gain; + + /** + * The value for the owner_id field. + * @var int + */ + protected $owner_id; + /** * @var CcSubjs */ - protected $aCcSubjs; + protected $aFkOwner; + + /** + * @var CcSubjs + */ + protected $aCcSubjsRelatedByDbEditedby; /** * @var CcMusicDirs @@ -430,6 +441,11 @@ abstract class BaseCcFiles extends BaseObject implements Persistent */ protected $collCcPlaylistcontentss; + /** + * @var array CcBlockcontents[] Collection to store aggregation of CcBlockcontents objects. + */ + protected $collCcBlockcontentss; + /** * @var array CcSchedule[] Collection to store aggregation of CcSchedule objects. */ @@ -487,16 +503,6 @@ abstract class BaseCcFiles extends BaseObject implements Persistent return $this->id; } - /** - * Get the [gunid] column value. - * - * @return string - */ - public function getDbGunid() - { - return $this->gunid; - } - /** * Get the [name] column value. * @@ -819,7 +825,7 @@ abstract class BaseCcFiles extends BaseObject implements Persistent /** * Get the [bpm] column value. * - * @return string + * @return int */ public function getDbBpm() { @@ -1199,6 +1205,26 @@ abstract class BaseCcFiles extends BaseObject implements Persistent } } + /** + * Get the [replay_gain] column value. + * + * @return string + */ + public function getDbReplayGain() + { + return $this->replay_gain; + } + + /** + * Get the [owner_id] column value. + * + * @return int + */ + public function getDbOwnerId() + { + return $this->owner_id; + } + /** * Set the value of [id] column. * @@ -1219,26 +1245,6 @@ abstract class BaseCcFiles extends BaseObject implements Persistent return $this; } // setDbId() - /** - * Set the value of [gunid] column. - * - * @param string $v new value - * @return CcFiles The current object (for fluent API support) - */ - public function setDbGunid($v) - { - if ($v !== null) { - $v = (string) $v; - } - - if ($this->gunid !== $v) { - $this->gunid = $v; - $this->modifiedColumns[] = CcFilesPeer::GUNID; - } - - return $this; - } // setDbGunid() - /** * Set the value of [name] column. * @@ -1400,8 +1406,8 @@ abstract class BaseCcFiles extends BaseObject implements Persistent $this->modifiedColumns[] = CcFilesPeer::EDITEDBY; } - if ($this->aCcSubjs !== null && $this->aCcSubjs->getDbId() !== $v) { - $this->aCcSubjs = null; + if ($this->aCcSubjsRelatedByDbEditedby !== null && $this->aCcSubjsRelatedByDbEditedby->getDbId() !== $v) { + $this->aCcSubjsRelatedByDbEditedby = null; } return $this; @@ -1837,13 +1843,13 @@ abstract class BaseCcFiles extends BaseObject implements Persistent /** * Set the value of [bpm] column. * - * @param string $v new value + * @param int $v new value * @return CcFiles The current object (for fluent API support) */ public function setDbBpm($v) { if ($v !== null) { - $v = (string) $v; + $v = (int) $v; } if ($this->bpm !== $v) { @@ -2583,6 +2589,50 @@ abstract class BaseCcFiles extends BaseObject implements Persistent return $this; } // setDbSoundCloundUploadTime() + /** + * Set the value of [replay_gain] column. + * + * @param string $v new value + * @return CcFiles The current object (for fluent API support) + */ + public function setDbReplayGain($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->replay_gain !== $v) { + $this->replay_gain = $v; + $this->modifiedColumns[] = CcFilesPeer::REPLAY_GAIN; + } + + return $this; + } // setDbReplayGain() + + /** + * Set the value of [owner_id] column. + * + * @param int $v new value + * @return CcFiles The current object (for fluent API support) + */ + public function setDbOwnerId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->owner_id !== $v) { + $this->owner_id = $v; + $this->modifiedColumns[] = CcFilesPeer::OWNER_ID; + } + + if ($this->aFkOwner !== null && $this->aFkOwner->getDbId() !== $v) { + $this->aFkOwner = null; + } + + return $this; + } // setDbOwnerId() + /** * Indicates whether the columns in this object are only set to default values. * @@ -2648,68 +2698,69 @@ abstract class BaseCcFiles extends BaseObject implements Persistent try { $this->id = ($row[$startcol + 0] !== null) ? (int) $row[$startcol + 0] : null; - $this->gunid = ($row[$startcol + 1] !== null) ? (string) $row[$startcol + 1] : null; - $this->name = ($row[$startcol + 2] !== null) ? (string) $row[$startcol + 2] : null; - $this->mime = ($row[$startcol + 3] !== null) ? (string) $row[$startcol + 3] : null; - $this->ftype = ($row[$startcol + 4] !== null) ? (string) $row[$startcol + 4] : null; - $this->directory = ($row[$startcol + 5] !== null) ? (int) $row[$startcol + 5] : null; - $this->filepath = ($row[$startcol + 6] !== null) ? (string) $row[$startcol + 6] : null; - $this->state = ($row[$startcol + 7] !== null) ? (string) $row[$startcol + 7] : null; - $this->currentlyaccessing = ($row[$startcol + 8] !== null) ? (int) $row[$startcol + 8] : null; - $this->editedby = ($row[$startcol + 9] !== null) ? (int) $row[$startcol + 9] : null; - $this->mtime = ($row[$startcol + 10] !== null) ? (string) $row[$startcol + 10] : null; - $this->utime = ($row[$startcol + 11] !== null) ? (string) $row[$startcol + 11] : null; - $this->lptime = ($row[$startcol + 12] !== null) ? (string) $row[$startcol + 12] : null; - $this->md5 = ($row[$startcol + 13] !== null) ? (string) $row[$startcol + 13] : null; - $this->track_title = ($row[$startcol + 14] !== null) ? (string) $row[$startcol + 14] : null; - $this->artist_name = ($row[$startcol + 15] !== null) ? (string) $row[$startcol + 15] : null; - $this->bit_rate = ($row[$startcol + 16] !== null) ? (int) $row[$startcol + 16] : null; - $this->sample_rate = ($row[$startcol + 17] !== null) ? (int) $row[$startcol + 17] : null; - $this->format = ($row[$startcol + 18] !== null) ? (string) $row[$startcol + 18] : null; - $this->length = ($row[$startcol + 19] !== null) ? (string) $row[$startcol + 19] : null; - $this->album_title = ($row[$startcol + 20] !== null) ? (string) $row[$startcol + 20] : null; - $this->genre = ($row[$startcol + 21] !== null) ? (string) $row[$startcol + 21] : null; - $this->comments = ($row[$startcol + 22] !== null) ? (string) $row[$startcol + 22] : null; - $this->year = ($row[$startcol + 23] !== null) ? (string) $row[$startcol + 23] : null; - $this->track_number = ($row[$startcol + 24] !== null) ? (int) $row[$startcol + 24] : null; - $this->channels = ($row[$startcol + 25] !== null) ? (int) $row[$startcol + 25] : null; - $this->url = ($row[$startcol + 26] !== null) ? (string) $row[$startcol + 26] : null; - $this->bpm = ($row[$startcol + 27] !== null) ? (string) $row[$startcol + 27] : null; - $this->rating = ($row[$startcol + 28] !== null) ? (string) $row[$startcol + 28] : null; - $this->encoded_by = ($row[$startcol + 29] !== null) ? (string) $row[$startcol + 29] : null; - $this->disc_number = ($row[$startcol + 30] !== null) ? (string) $row[$startcol + 30] : null; - $this->mood = ($row[$startcol + 31] !== null) ? (string) $row[$startcol + 31] : null; - $this->label = ($row[$startcol + 32] !== null) ? (string) $row[$startcol + 32] : null; - $this->composer = ($row[$startcol + 33] !== null) ? (string) $row[$startcol + 33] : null; - $this->encoder = ($row[$startcol + 34] !== null) ? (string) $row[$startcol + 34] : null; - $this->checksum = ($row[$startcol + 35] !== null) ? (string) $row[$startcol + 35] : null; - $this->lyrics = ($row[$startcol + 36] !== null) ? (string) $row[$startcol + 36] : null; - $this->orchestra = ($row[$startcol + 37] !== null) ? (string) $row[$startcol + 37] : null; - $this->conductor = ($row[$startcol + 38] !== null) ? (string) $row[$startcol + 38] : null; - $this->lyricist = ($row[$startcol + 39] !== null) ? (string) $row[$startcol + 39] : null; - $this->original_lyricist = ($row[$startcol + 40] !== null) ? (string) $row[$startcol + 40] : null; - $this->radio_station_name = ($row[$startcol + 41] !== null) ? (string) $row[$startcol + 41] : null; - $this->info_url = ($row[$startcol + 42] !== null) ? (string) $row[$startcol + 42] : null; - $this->artist_url = ($row[$startcol + 43] !== null) ? (string) $row[$startcol + 43] : null; - $this->audio_source_url = ($row[$startcol + 44] !== null) ? (string) $row[$startcol + 44] : null; - $this->radio_station_url = ($row[$startcol + 45] !== null) ? (string) $row[$startcol + 45] : null; - $this->buy_this_url = ($row[$startcol + 46] !== null) ? (string) $row[$startcol + 46] : null; - $this->isrc_number = ($row[$startcol + 47] !== null) ? (string) $row[$startcol + 47] : null; - $this->catalog_number = ($row[$startcol + 48] !== null) ? (string) $row[$startcol + 48] : null; - $this->original_artist = ($row[$startcol + 49] !== null) ? (string) $row[$startcol + 49] : null; - $this->copyright = ($row[$startcol + 50] !== null) ? (string) $row[$startcol + 50] : null; - $this->report_datetime = ($row[$startcol + 51] !== null) ? (string) $row[$startcol + 51] : null; - $this->report_location = ($row[$startcol + 52] !== null) ? (string) $row[$startcol + 52] : null; - $this->report_organization = ($row[$startcol + 53] !== null) ? (string) $row[$startcol + 53] : null; - $this->subject = ($row[$startcol + 54] !== null) ? (string) $row[$startcol + 54] : null; - $this->contributor = ($row[$startcol + 55] !== null) ? (string) $row[$startcol + 55] : null; - $this->language = ($row[$startcol + 56] !== null) ? (string) $row[$startcol + 56] : null; - $this->file_exists = ($row[$startcol + 57] !== null) ? (boolean) $row[$startcol + 57] : null; - $this->soundcloud_id = ($row[$startcol + 58] !== null) ? (int) $row[$startcol + 58] : null; - $this->soundcloud_error_code = ($row[$startcol + 59] !== null) ? (int) $row[$startcol + 59] : null; - $this->soundcloud_error_msg = ($row[$startcol + 60] !== null) ? (string) $row[$startcol + 60] : null; - $this->soundcloud_link_to_file = ($row[$startcol + 61] !== null) ? (string) $row[$startcol + 61] : null; - $this->soundcloud_upload_time = ($row[$startcol + 62] !== null) ? (string) $row[$startcol + 62] : null; + $this->name = ($row[$startcol + 1] !== null) ? (string) $row[$startcol + 1] : null; + $this->mime = ($row[$startcol + 2] !== null) ? (string) $row[$startcol + 2] : null; + $this->ftype = ($row[$startcol + 3] !== null) ? (string) $row[$startcol + 3] : null; + $this->directory = ($row[$startcol + 4] !== null) ? (int) $row[$startcol + 4] : null; + $this->filepath = ($row[$startcol + 5] !== null) ? (string) $row[$startcol + 5] : null; + $this->state = ($row[$startcol + 6] !== null) ? (string) $row[$startcol + 6] : null; + $this->currentlyaccessing = ($row[$startcol + 7] !== null) ? (int) $row[$startcol + 7] : null; + $this->editedby = ($row[$startcol + 8] !== null) ? (int) $row[$startcol + 8] : null; + $this->mtime = ($row[$startcol + 9] !== null) ? (string) $row[$startcol + 9] : null; + $this->utime = ($row[$startcol + 10] !== null) ? (string) $row[$startcol + 10] : null; + $this->lptime = ($row[$startcol + 11] !== null) ? (string) $row[$startcol + 11] : null; + $this->md5 = ($row[$startcol + 12] !== null) ? (string) $row[$startcol + 12] : null; + $this->track_title = ($row[$startcol + 13] !== null) ? (string) $row[$startcol + 13] : null; + $this->artist_name = ($row[$startcol + 14] !== null) ? (string) $row[$startcol + 14] : null; + $this->bit_rate = ($row[$startcol + 15] !== null) ? (int) $row[$startcol + 15] : null; + $this->sample_rate = ($row[$startcol + 16] !== null) ? (int) $row[$startcol + 16] : null; + $this->format = ($row[$startcol + 17] !== null) ? (string) $row[$startcol + 17] : null; + $this->length = ($row[$startcol + 18] !== null) ? (string) $row[$startcol + 18] : null; + $this->album_title = ($row[$startcol + 19] !== null) ? (string) $row[$startcol + 19] : null; + $this->genre = ($row[$startcol + 20] !== null) ? (string) $row[$startcol + 20] : null; + $this->comments = ($row[$startcol + 21] !== null) ? (string) $row[$startcol + 21] : null; + $this->year = ($row[$startcol + 22] !== null) ? (string) $row[$startcol + 22] : null; + $this->track_number = ($row[$startcol + 23] !== null) ? (int) $row[$startcol + 23] : null; + $this->channels = ($row[$startcol + 24] !== null) ? (int) $row[$startcol + 24] : null; + $this->url = ($row[$startcol + 25] !== null) ? (string) $row[$startcol + 25] : null; + $this->bpm = ($row[$startcol + 26] !== null) ? (int) $row[$startcol + 26] : null; + $this->rating = ($row[$startcol + 27] !== null) ? (string) $row[$startcol + 27] : null; + $this->encoded_by = ($row[$startcol + 28] !== null) ? (string) $row[$startcol + 28] : null; + $this->disc_number = ($row[$startcol + 29] !== null) ? (string) $row[$startcol + 29] : null; + $this->mood = ($row[$startcol + 30] !== null) ? (string) $row[$startcol + 30] : null; + $this->label = ($row[$startcol + 31] !== null) ? (string) $row[$startcol + 31] : null; + $this->composer = ($row[$startcol + 32] !== null) ? (string) $row[$startcol + 32] : null; + $this->encoder = ($row[$startcol + 33] !== null) ? (string) $row[$startcol + 33] : null; + $this->checksum = ($row[$startcol + 34] !== null) ? (string) $row[$startcol + 34] : null; + $this->lyrics = ($row[$startcol + 35] !== null) ? (string) $row[$startcol + 35] : null; + $this->orchestra = ($row[$startcol + 36] !== null) ? (string) $row[$startcol + 36] : null; + $this->conductor = ($row[$startcol + 37] !== null) ? (string) $row[$startcol + 37] : null; + $this->lyricist = ($row[$startcol + 38] !== null) ? (string) $row[$startcol + 38] : null; + $this->original_lyricist = ($row[$startcol + 39] !== null) ? (string) $row[$startcol + 39] : null; + $this->radio_station_name = ($row[$startcol + 40] !== null) ? (string) $row[$startcol + 40] : null; + $this->info_url = ($row[$startcol + 41] !== null) ? (string) $row[$startcol + 41] : null; + $this->artist_url = ($row[$startcol + 42] !== null) ? (string) $row[$startcol + 42] : null; + $this->audio_source_url = ($row[$startcol + 43] !== null) ? (string) $row[$startcol + 43] : null; + $this->radio_station_url = ($row[$startcol + 44] !== null) ? (string) $row[$startcol + 44] : null; + $this->buy_this_url = ($row[$startcol + 45] !== null) ? (string) $row[$startcol + 45] : null; + $this->isrc_number = ($row[$startcol + 46] !== null) ? (string) $row[$startcol + 46] : null; + $this->catalog_number = ($row[$startcol + 47] !== null) ? (string) $row[$startcol + 47] : null; + $this->original_artist = ($row[$startcol + 48] !== null) ? (string) $row[$startcol + 48] : null; + $this->copyright = ($row[$startcol + 49] !== null) ? (string) $row[$startcol + 49] : null; + $this->report_datetime = ($row[$startcol + 50] !== null) ? (string) $row[$startcol + 50] : null; + $this->report_location = ($row[$startcol + 51] !== null) ? (string) $row[$startcol + 51] : null; + $this->report_organization = ($row[$startcol + 52] !== null) ? (string) $row[$startcol + 52] : null; + $this->subject = ($row[$startcol + 53] !== null) ? (string) $row[$startcol + 53] : null; + $this->contributor = ($row[$startcol + 54] !== null) ? (string) $row[$startcol + 54] : null; + $this->language = ($row[$startcol + 55] !== null) ? (string) $row[$startcol + 55] : null; + $this->file_exists = ($row[$startcol + 56] !== null) ? (boolean) $row[$startcol + 56] : null; + $this->soundcloud_id = ($row[$startcol + 57] !== null) ? (int) $row[$startcol + 57] : null; + $this->soundcloud_error_code = ($row[$startcol + 58] !== null) ? (int) $row[$startcol + 58] : null; + $this->soundcloud_error_msg = ($row[$startcol + 59] !== null) ? (string) $row[$startcol + 59] : null; + $this->soundcloud_link_to_file = ($row[$startcol + 60] !== null) ? (string) $row[$startcol + 60] : null; + $this->soundcloud_upload_time = ($row[$startcol + 61] !== null) ? (string) $row[$startcol + 61] : null; + $this->replay_gain = ($row[$startcol + 62] !== null) ? (string) $row[$startcol + 62] : null; + $this->owner_id = ($row[$startcol + 63] !== null) ? (int) $row[$startcol + 63] : null; $this->resetModified(); $this->setNew(false); @@ -2718,7 +2769,7 @@ abstract class BaseCcFiles extends BaseObject implements Persistent $this->ensureConsistency(); } - return $startcol + 63; // 63 = CcFilesPeer::NUM_COLUMNS - CcFilesPeer::NUM_LAZY_LOAD_COLUMNS). + return $startcol + 64; // 64 = CcFilesPeer::NUM_COLUMNS - CcFilesPeer::NUM_LAZY_LOAD_COLUMNS). } catch (Exception $e) { throw new PropelException("Error populating CcFiles object", $e); @@ -2744,8 +2795,11 @@ abstract class BaseCcFiles extends BaseObject implements Persistent if ($this->aCcMusicDirs !== null && $this->directory !== $this->aCcMusicDirs->getId()) { $this->aCcMusicDirs = null; } - if ($this->aCcSubjs !== null && $this->editedby !== $this->aCcSubjs->getDbId()) { - $this->aCcSubjs = null; + if ($this->aCcSubjsRelatedByDbEditedby !== null && $this->editedby !== $this->aCcSubjsRelatedByDbEditedby->getDbId()) { + $this->aCcSubjsRelatedByDbEditedby = null; + } + if ($this->aFkOwner !== null && $this->owner_id !== $this->aFkOwner->getDbId()) { + $this->aFkOwner = null; } } // ensureConsistency @@ -2786,12 +2840,15 @@ abstract class BaseCcFiles extends BaseObject implements Persistent if ($deep) { // also de-associate any related objects? - $this->aCcSubjs = null; + $this->aFkOwner = null; + $this->aCcSubjsRelatedByDbEditedby = null; $this->aCcMusicDirs = null; $this->collCcShowInstancess = null; $this->collCcPlaylistcontentss = null; + $this->collCcBlockcontentss = null; + $this->collCcSchedules = null; } // if (deep) @@ -2909,11 +2966,18 @@ abstract class BaseCcFiles extends BaseObject implements Persistent // method. This object relates to these object(s) by a // foreign key reference. - if ($this->aCcSubjs !== null) { - if ($this->aCcSubjs->isModified() || $this->aCcSubjs->isNew()) { - $affectedRows += $this->aCcSubjs->save($con); + if ($this->aFkOwner !== null) { + if ($this->aFkOwner->isModified() || $this->aFkOwner->isNew()) { + $affectedRows += $this->aFkOwner->save($con); } - $this->setCcSubjs($this->aCcSubjs); + $this->setFkOwner($this->aFkOwner); + } + + if ($this->aCcSubjsRelatedByDbEditedby !== null) { + if ($this->aCcSubjsRelatedByDbEditedby->isModified() || $this->aCcSubjsRelatedByDbEditedby->isNew()) { + $affectedRows += $this->aCcSubjsRelatedByDbEditedby->save($con); + } + $this->setCcSubjsRelatedByDbEditedby($this->aCcSubjsRelatedByDbEditedby); } if ($this->aCcMusicDirs !== null) { @@ -2962,6 +3026,14 @@ abstract class BaseCcFiles extends BaseObject implements Persistent } } + if ($this->collCcBlockcontentss !== null) { + foreach ($this->collCcBlockcontentss as $referrerFK) { + if (!$referrerFK->isDeleted()) { + $affectedRows += $referrerFK->save($con); + } + } + } + if ($this->collCcSchedules !== null) { foreach ($this->collCcSchedules as $referrerFK) { if (!$referrerFK->isDeleted()) { @@ -3041,9 +3113,15 @@ abstract class BaseCcFiles extends BaseObject implements Persistent // method. This object relates to these object(s) by a // foreign key reference. - if ($this->aCcSubjs !== null) { - if (!$this->aCcSubjs->validate($columns)) { - $failureMap = array_merge($failureMap, $this->aCcSubjs->getValidationFailures()); + if ($this->aFkOwner !== null) { + if (!$this->aFkOwner->validate($columns)) { + $failureMap = array_merge($failureMap, $this->aFkOwner->getValidationFailures()); + } + } + + if ($this->aCcSubjsRelatedByDbEditedby !== null) { + if (!$this->aCcSubjsRelatedByDbEditedby->validate($columns)) { + $failureMap = array_merge($failureMap, $this->aCcSubjsRelatedByDbEditedby->getValidationFailures()); } } @@ -3075,6 +3153,14 @@ abstract class BaseCcFiles extends BaseObject implements Persistent } } + if ($this->collCcBlockcontentss !== null) { + foreach ($this->collCcBlockcontentss as $referrerFK) { + if (!$referrerFK->validate($columns)) { + $failureMap = array_merge($failureMap, $referrerFK->getValidationFailures()); + } + } + } + if ($this->collCcSchedules !== null) { foreach ($this->collCcSchedules as $referrerFK) { if (!$referrerFK->validate($columns)) { @@ -3120,191 +3206,194 @@ abstract class BaseCcFiles extends BaseObject implements Persistent return $this->getDbId(); break; case 1: - return $this->getDbGunid(); - break; - case 2: return $this->getDbName(); break; - case 3: + case 2: return $this->getDbMime(); break; - case 4: + case 3: return $this->getDbFtype(); break; - case 5: + case 4: return $this->getDbDirectory(); break; - case 6: + case 5: return $this->getDbFilepath(); break; - case 7: + case 6: return $this->getDbState(); break; - case 8: + case 7: return $this->getDbCurrentlyaccessing(); break; - case 9: + case 8: return $this->getDbEditedby(); break; - case 10: + case 9: return $this->getDbMtime(); break; - case 11: + case 10: return $this->getDbUtime(); break; - case 12: + case 11: return $this->getDbLPtime(); break; - case 13: + case 12: return $this->getDbMd5(); break; - case 14: + case 13: return $this->getDbTrackTitle(); break; - case 15: + case 14: return $this->getDbArtistName(); break; - case 16: + case 15: return $this->getDbBitRate(); break; - case 17: + case 16: return $this->getDbSampleRate(); break; - case 18: + case 17: return $this->getDbFormat(); break; - case 19: + case 18: return $this->getDbLength(); break; - case 20: + case 19: return $this->getDbAlbumTitle(); break; - case 21: + case 20: return $this->getDbGenre(); break; - case 22: + case 21: return $this->getDbComments(); break; - case 23: + case 22: return $this->getDbYear(); break; - case 24: + case 23: return $this->getDbTrackNumber(); break; - case 25: + case 24: return $this->getDbChannels(); break; - case 26: + case 25: return $this->getDbUrl(); break; - case 27: + case 26: return $this->getDbBpm(); break; - case 28: + case 27: return $this->getDbRating(); break; - case 29: + case 28: return $this->getDbEncodedBy(); break; - case 30: + case 29: return $this->getDbDiscNumber(); break; - case 31: + case 30: return $this->getDbMood(); break; - case 32: + case 31: return $this->getDbLabel(); break; - case 33: + case 32: return $this->getDbComposer(); break; - case 34: + case 33: return $this->getDbEncoder(); break; - case 35: + case 34: return $this->getDbChecksum(); break; - case 36: + case 35: return $this->getDbLyrics(); break; - case 37: + case 36: return $this->getDbOrchestra(); break; - case 38: + case 37: return $this->getDbConductor(); break; - case 39: + case 38: return $this->getDbLyricist(); break; - case 40: + case 39: return $this->getDbOriginalLyricist(); break; - case 41: + case 40: return $this->getDbRadioStationName(); break; - case 42: + case 41: return $this->getDbInfoUrl(); break; - case 43: + case 42: return $this->getDbArtistUrl(); break; - case 44: + case 43: return $this->getDbAudioSourceUrl(); break; - case 45: + case 44: return $this->getDbRadioStationUrl(); break; - case 46: + case 45: return $this->getDbBuyThisUrl(); break; - case 47: + case 46: return $this->getDbIsrcNumber(); break; - case 48: + case 47: return $this->getDbCatalogNumber(); break; - case 49: + case 48: return $this->getDbOriginalArtist(); break; - case 50: + case 49: return $this->getDbCopyright(); break; - case 51: + case 50: return $this->getDbReportDatetime(); break; - case 52: + case 51: return $this->getDbReportLocation(); break; - case 53: + case 52: return $this->getDbReportOrganization(); break; - case 54: + case 53: return $this->getDbSubject(); break; - case 55: + case 54: return $this->getDbContributor(); break; - case 56: + case 55: return $this->getDbLanguage(); break; - case 57: + case 56: return $this->getDbFileExists(); break; - case 58: + case 57: return $this->getDbSoundcloudId(); break; - case 59: + case 58: return $this->getDbSoundcloudErrorCode(); break; - case 60: + case 59: return $this->getDbSoundcloudErrorMsg(); break; - case 61: + case 60: return $this->getDbSoundcloudLinkToFile(); break; - case 62: + case 61: return $this->getDbSoundCloundUploadTime(); break; + case 62: + return $this->getDbReplayGain(); + break; + case 63: + return $this->getDbOwnerId(); + break; default: return null; break; @@ -3330,72 +3419,76 @@ abstract class BaseCcFiles extends BaseObject implements Persistent $keys = CcFilesPeer::getFieldNames($keyType); $result = array( $keys[0] => $this->getDbId(), - $keys[1] => $this->getDbGunid(), - $keys[2] => $this->getDbName(), - $keys[3] => $this->getDbMime(), - $keys[4] => $this->getDbFtype(), - $keys[5] => $this->getDbDirectory(), - $keys[6] => $this->getDbFilepath(), - $keys[7] => $this->getDbState(), - $keys[8] => $this->getDbCurrentlyaccessing(), - $keys[9] => $this->getDbEditedby(), - $keys[10] => $this->getDbMtime(), - $keys[11] => $this->getDbUtime(), - $keys[12] => $this->getDbLPtime(), - $keys[13] => $this->getDbMd5(), - $keys[14] => $this->getDbTrackTitle(), - $keys[15] => $this->getDbArtistName(), - $keys[16] => $this->getDbBitRate(), - $keys[17] => $this->getDbSampleRate(), - $keys[18] => $this->getDbFormat(), - $keys[19] => $this->getDbLength(), - $keys[20] => $this->getDbAlbumTitle(), - $keys[21] => $this->getDbGenre(), - $keys[22] => $this->getDbComments(), - $keys[23] => $this->getDbYear(), - $keys[24] => $this->getDbTrackNumber(), - $keys[25] => $this->getDbChannels(), - $keys[26] => $this->getDbUrl(), - $keys[27] => $this->getDbBpm(), - $keys[28] => $this->getDbRating(), - $keys[29] => $this->getDbEncodedBy(), - $keys[30] => $this->getDbDiscNumber(), - $keys[31] => $this->getDbMood(), - $keys[32] => $this->getDbLabel(), - $keys[33] => $this->getDbComposer(), - $keys[34] => $this->getDbEncoder(), - $keys[35] => $this->getDbChecksum(), - $keys[36] => $this->getDbLyrics(), - $keys[37] => $this->getDbOrchestra(), - $keys[38] => $this->getDbConductor(), - $keys[39] => $this->getDbLyricist(), - $keys[40] => $this->getDbOriginalLyricist(), - $keys[41] => $this->getDbRadioStationName(), - $keys[42] => $this->getDbInfoUrl(), - $keys[43] => $this->getDbArtistUrl(), - $keys[44] => $this->getDbAudioSourceUrl(), - $keys[45] => $this->getDbRadioStationUrl(), - $keys[46] => $this->getDbBuyThisUrl(), - $keys[47] => $this->getDbIsrcNumber(), - $keys[48] => $this->getDbCatalogNumber(), - $keys[49] => $this->getDbOriginalArtist(), - $keys[50] => $this->getDbCopyright(), - $keys[51] => $this->getDbReportDatetime(), - $keys[52] => $this->getDbReportLocation(), - $keys[53] => $this->getDbReportOrganization(), - $keys[54] => $this->getDbSubject(), - $keys[55] => $this->getDbContributor(), - $keys[56] => $this->getDbLanguage(), - $keys[57] => $this->getDbFileExists(), - $keys[58] => $this->getDbSoundcloudId(), - $keys[59] => $this->getDbSoundcloudErrorCode(), - $keys[60] => $this->getDbSoundcloudErrorMsg(), - $keys[61] => $this->getDbSoundcloudLinkToFile(), - $keys[62] => $this->getDbSoundCloundUploadTime(), + $keys[1] => $this->getDbName(), + $keys[2] => $this->getDbMime(), + $keys[3] => $this->getDbFtype(), + $keys[4] => $this->getDbDirectory(), + $keys[5] => $this->getDbFilepath(), + $keys[6] => $this->getDbState(), + $keys[7] => $this->getDbCurrentlyaccessing(), + $keys[8] => $this->getDbEditedby(), + $keys[9] => $this->getDbMtime(), + $keys[10] => $this->getDbUtime(), + $keys[11] => $this->getDbLPtime(), + $keys[12] => $this->getDbMd5(), + $keys[13] => $this->getDbTrackTitle(), + $keys[14] => $this->getDbArtistName(), + $keys[15] => $this->getDbBitRate(), + $keys[16] => $this->getDbSampleRate(), + $keys[17] => $this->getDbFormat(), + $keys[18] => $this->getDbLength(), + $keys[19] => $this->getDbAlbumTitle(), + $keys[20] => $this->getDbGenre(), + $keys[21] => $this->getDbComments(), + $keys[22] => $this->getDbYear(), + $keys[23] => $this->getDbTrackNumber(), + $keys[24] => $this->getDbChannels(), + $keys[25] => $this->getDbUrl(), + $keys[26] => $this->getDbBpm(), + $keys[27] => $this->getDbRating(), + $keys[28] => $this->getDbEncodedBy(), + $keys[29] => $this->getDbDiscNumber(), + $keys[30] => $this->getDbMood(), + $keys[31] => $this->getDbLabel(), + $keys[32] => $this->getDbComposer(), + $keys[33] => $this->getDbEncoder(), + $keys[34] => $this->getDbChecksum(), + $keys[35] => $this->getDbLyrics(), + $keys[36] => $this->getDbOrchestra(), + $keys[37] => $this->getDbConductor(), + $keys[38] => $this->getDbLyricist(), + $keys[39] => $this->getDbOriginalLyricist(), + $keys[40] => $this->getDbRadioStationName(), + $keys[41] => $this->getDbInfoUrl(), + $keys[42] => $this->getDbArtistUrl(), + $keys[43] => $this->getDbAudioSourceUrl(), + $keys[44] => $this->getDbRadioStationUrl(), + $keys[45] => $this->getDbBuyThisUrl(), + $keys[46] => $this->getDbIsrcNumber(), + $keys[47] => $this->getDbCatalogNumber(), + $keys[48] => $this->getDbOriginalArtist(), + $keys[49] => $this->getDbCopyright(), + $keys[50] => $this->getDbReportDatetime(), + $keys[51] => $this->getDbReportLocation(), + $keys[52] => $this->getDbReportOrganization(), + $keys[53] => $this->getDbSubject(), + $keys[54] => $this->getDbContributor(), + $keys[55] => $this->getDbLanguage(), + $keys[56] => $this->getDbFileExists(), + $keys[57] => $this->getDbSoundcloudId(), + $keys[58] => $this->getDbSoundcloudErrorCode(), + $keys[59] => $this->getDbSoundcloudErrorMsg(), + $keys[60] => $this->getDbSoundcloudLinkToFile(), + $keys[61] => $this->getDbSoundCloundUploadTime(), + $keys[62] => $this->getDbReplayGain(), + $keys[63] => $this->getDbOwnerId(), ); if ($includeForeignObjects) { - if (null !== $this->aCcSubjs) { - $result['CcSubjs'] = $this->aCcSubjs->toArray($keyType, $includeLazyLoadColumns, true); + if (null !== $this->aFkOwner) { + $result['FkOwner'] = $this->aFkOwner->toArray($keyType, $includeLazyLoadColumns, true); + } + if (null !== $this->aCcSubjsRelatedByDbEditedby) { + $result['CcSubjsRelatedByDbEditedby'] = $this->aCcSubjsRelatedByDbEditedby->toArray($keyType, $includeLazyLoadColumns, true); } if (null !== $this->aCcMusicDirs) { $result['CcMusicDirs'] = $this->aCcMusicDirs->toArray($keyType, $includeLazyLoadColumns, true); @@ -3435,191 +3528,194 @@ abstract class BaseCcFiles extends BaseObject implements Persistent $this->setDbId($value); break; case 1: - $this->setDbGunid($value); - break; - case 2: $this->setDbName($value); break; - case 3: + case 2: $this->setDbMime($value); break; - case 4: + case 3: $this->setDbFtype($value); break; - case 5: + case 4: $this->setDbDirectory($value); break; - case 6: + case 5: $this->setDbFilepath($value); break; - case 7: + case 6: $this->setDbState($value); break; - case 8: + case 7: $this->setDbCurrentlyaccessing($value); break; - case 9: + case 8: $this->setDbEditedby($value); break; - case 10: + case 9: $this->setDbMtime($value); break; - case 11: + case 10: $this->setDbUtime($value); break; - case 12: + case 11: $this->setDbLPtime($value); break; - case 13: + case 12: $this->setDbMd5($value); break; - case 14: + case 13: $this->setDbTrackTitle($value); break; - case 15: + case 14: $this->setDbArtistName($value); break; - case 16: + case 15: $this->setDbBitRate($value); break; - case 17: + case 16: $this->setDbSampleRate($value); break; - case 18: + case 17: $this->setDbFormat($value); break; - case 19: + case 18: $this->setDbLength($value); break; - case 20: + case 19: $this->setDbAlbumTitle($value); break; - case 21: + case 20: $this->setDbGenre($value); break; - case 22: + case 21: $this->setDbComments($value); break; - case 23: + case 22: $this->setDbYear($value); break; - case 24: + case 23: $this->setDbTrackNumber($value); break; - case 25: + case 24: $this->setDbChannels($value); break; - case 26: + case 25: $this->setDbUrl($value); break; - case 27: + case 26: $this->setDbBpm($value); break; - case 28: + case 27: $this->setDbRating($value); break; - case 29: + case 28: $this->setDbEncodedBy($value); break; - case 30: + case 29: $this->setDbDiscNumber($value); break; - case 31: + case 30: $this->setDbMood($value); break; - case 32: + case 31: $this->setDbLabel($value); break; - case 33: + case 32: $this->setDbComposer($value); break; - case 34: + case 33: $this->setDbEncoder($value); break; - case 35: + case 34: $this->setDbChecksum($value); break; - case 36: + case 35: $this->setDbLyrics($value); break; - case 37: + case 36: $this->setDbOrchestra($value); break; - case 38: + case 37: $this->setDbConductor($value); break; - case 39: + case 38: $this->setDbLyricist($value); break; - case 40: + case 39: $this->setDbOriginalLyricist($value); break; - case 41: + case 40: $this->setDbRadioStationName($value); break; - case 42: + case 41: $this->setDbInfoUrl($value); break; - case 43: + case 42: $this->setDbArtistUrl($value); break; - case 44: + case 43: $this->setDbAudioSourceUrl($value); break; - case 45: + case 44: $this->setDbRadioStationUrl($value); break; - case 46: + case 45: $this->setDbBuyThisUrl($value); break; - case 47: + case 46: $this->setDbIsrcNumber($value); break; - case 48: + case 47: $this->setDbCatalogNumber($value); break; - case 49: + case 48: $this->setDbOriginalArtist($value); break; - case 50: + case 49: $this->setDbCopyright($value); break; - case 51: + case 50: $this->setDbReportDatetime($value); break; - case 52: + case 51: $this->setDbReportLocation($value); break; - case 53: + case 52: $this->setDbReportOrganization($value); break; - case 54: + case 53: $this->setDbSubject($value); break; - case 55: + case 54: $this->setDbContributor($value); break; - case 56: + case 55: $this->setDbLanguage($value); break; - case 57: + case 56: $this->setDbFileExists($value); break; - case 58: + case 57: $this->setDbSoundcloudId($value); break; - case 59: + case 58: $this->setDbSoundcloudErrorCode($value); break; - case 60: + case 59: $this->setDbSoundcloudErrorMsg($value); break; - case 61: + case 60: $this->setDbSoundcloudLinkToFile($value); break; - case 62: + case 61: $this->setDbSoundCloundUploadTime($value); break; + case 62: + $this->setDbReplayGain($value); + break; + case 63: + $this->setDbOwnerId($value); + break; } // switch() } @@ -3645,68 +3741,69 @@ abstract class BaseCcFiles extends BaseObject implements Persistent $keys = CcFilesPeer::getFieldNames($keyType); if (array_key_exists($keys[0], $arr)) $this->setDbId($arr[$keys[0]]); - if (array_key_exists($keys[1], $arr)) $this->setDbGunid($arr[$keys[1]]); - if (array_key_exists($keys[2], $arr)) $this->setDbName($arr[$keys[2]]); - if (array_key_exists($keys[3], $arr)) $this->setDbMime($arr[$keys[3]]); - if (array_key_exists($keys[4], $arr)) $this->setDbFtype($arr[$keys[4]]); - if (array_key_exists($keys[5], $arr)) $this->setDbDirectory($arr[$keys[5]]); - if (array_key_exists($keys[6], $arr)) $this->setDbFilepath($arr[$keys[6]]); - if (array_key_exists($keys[7], $arr)) $this->setDbState($arr[$keys[7]]); - if (array_key_exists($keys[8], $arr)) $this->setDbCurrentlyaccessing($arr[$keys[8]]); - if (array_key_exists($keys[9], $arr)) $this->setDbEditedby($arr[$keys[9]]); - if (array_key_exists($keys[10], $arr)) $this->setDbMtime($arr[$keys[10]]); - if (array_key_exists($keys[11], $arr)) $this->setDbUtime($arr[$keys[11]]); - if (array_key_exists($keys[12], $arr)) $this->setDbLPtime($arr[$keys[12]]); - if (array_key_exists($keys[13], $arr)) $this->setDbMd5($arr[$keys[13]]); - if (array_key_exists($keys[14], $arr)) $this->setDbTrackTitle($arr[$keys[14]]); - if (array_key_exists($keys[15], $arr)) $this->setDbArtistName($arr[$keys[15]]); - if (array_key_exists($keys[16], $arr)) $this->setDbBitRate($arr[$keys[16]]); - if (array_key_exists($keys[17], $arr)) $this->setDbSampleRate($arr[$keys[17]]); - if (array_key_exists($keys[18], $arr)) $this->setDbFormat($arr[$keys[18]]); - if (array_key_exists($keys[19], $arr)) $this->setDbLength($arr[$keys[19]]); - if (array_key_exists($keys[20], $arr)) $this->setDbAlbumTitle($arr[$keys[20]]); - if (array_key_exists($keys[21], $arr)) $this->setDbGenre($arr[$keys[21]]); - if (array_key_exists($keys[22], $arr)) $this->setDbComments($arr[$keys[22]]); - if (array_key_exists($keys[23], $arr)) $this->setDbYear($arr[$keys[23]]); - if (array_key_exists($keys[24], $arr)) $this->setDbTrackNumber($arr[$keys[24]]); - if (array_key_exists($keys[25], $arr)) $this->setDbChannels($arr[$keys[25]]); - if (array_key_exists($keys[26], $arr)) $this->setDbUrl($arr[$keys[26]]); - if (array_key_exists($keys[27], $arr)) $this->setDbBpm($arr[$keys[27]]); - if (array_key_exists($keys[28], $arr)) $this->setDbRating($arr[$keys[28]]); - if (array_key_exists($keys[29], $arr)) $this->setDbEncodedBy($arr[$keys[29]]); - if (array_key_exists($keys[30], $arr)) $this->setDbDiscNumber($arr[$keys[30]]); - if (array_key_exists($keys[31], $arr)) $this->setDbMood($arr[$keys[31]]); - if (array_key_exists($keys[32], $arr)) $this->setDbLabel($arr[$keys[32]]); - if (array_key_exists($keys[33], $arr)) $this->setDbComposer($arr[$keys[33]]); - if (array_key_exists($keys[34], $arr)) $this->setDbEncoder($arr[$keys[34]]); - if (array_key_exists($keys[35], $arr)) $this->setDbChecksum($arr[$keys[35]]); - if (array_key_exists($keys[36], $arr)) $this->setDbLyrics($arr[$keys[36]]); - if (array_key_exists($keys[37], $arr)) $this->setDbOrchestra($arr[$keys[37]]); - if (array_key_exists($keys[38], $arr)) $this->setDbConductor($arr[$keys[38]]); - if (array_key_exists($keys[39], $arr)) $this->setDbLyricist($arr[$keys[39]]); - if (array_key_exists($keys[40], $arr)) $this->setDbOriginalLyricist($arr[$keys[40]]); - if (array_key_exists($keys[41], $arr)) $this->setDbRadioStationName($arr[$keys[41]]); - if (array_key_exists($keys[42], $arr)) $this->setDbInfoUrl($arr[$keys[42]]); - if (array_key_exists($keys[43], $arr)) $this->setDbArtistUrl($arr[$keys[43]]); - if (array_key_exists($keys[44], $arr)) $this->setDbAudioSourceUrl($arr[$keys[44]]); - if (array_key_exists($keys[45], $arr)) $this->setDbRadioStationUrl($arr[$keys[45]]); - if (array_key_exists($keys[46], $arr)) $this->setDbBuyThisUrl($arr[$keys[46]]); - if (array_key_exists($keys[47], $arr)) $this->setDbIsrcNumber($arr[$keys[47]]); - if (array_key_exists($keys[48], $arr)) $this->setDbCatalogNumber($arr[$keys[48]]); - if (array_key_exists($keys[49], $arr)) $this->setDbOriginalArtist($arr[$keys[49]]); - if (array_key_exists($keys[50], $arr)) $this->setDbCopyright($arr[$keys[50]]); - if (array_key_exists($keys[51], $arr)) $this->setDbReportDatetime($arr[$keys[51]]); - if (array_key_exists($keys[52], $arr)) $this->setDbReportLocation($arr[$keys[52]]); - if (array_key_exists($keys[53], $arr)) $this->setDbReportOrganization($arr[$keys[53]]); - if (array_key_exists($keys[54], $arr)) $this->setDbSubject($arr[$keys[54]]); - if (array_key_exists($keys[55], $arr)) $this->setDbContributor($arr[$keys[55]]); - if (array_key_exists($keys[56], $arr)) $this->setDbLanguage($arr[$keys[56]]); - if (array_key_exists($keys[57], $arr)) $this->setDbFileExists($arr[$keys[57]]); - if (array_key_exists($keys[58], $arr)) $this->setDbSoundcloudId($arr[$keys[58]]); - if (array_key_exists($keys[59], $arr)) $this->setDbSoundcloudErrorCode($arr[$keys[59]]); - if (array_key_exists($keys[60], $arr)) $this->setDbSoundcloudErrorMsg($arr[$keys[60]]); - if (array_key_exists($keys[61], $arr)) $this->setDbSoundcloudLinkToFile($arr[$keys[61]]); - if (array_key_exists($keys[62], $arr)) $this->setDbSoundCloundUploadTime($arr[$keys[62]]); + if (array_key_exists($keys[1], $arr)) $this->setDbName($arr[$keys[1]]); + if (array_key_exists($keys[2], $arr)) $this->setDbMime($arr[$keys[2]]); + if (array_key_exists($keys[3], $arr)) $this->setDbFtype($arr[$keys[3]]); + if (array_key_exists($keys[4], $arr)) $this->setDbDirectory($arr[$keys[4]]); + if (array_key_exists($keys[5], $arr)) $this->setDbFilepath($arr[$keys[5]]); + if (array_key_exists($keys[6], $arr)) $this->setDbState($arr[$keys[6]]); + if (array_key_exists($keys[7], $arr)) $this->setDbCurrentlyaccessing($arr[$keys[7]]); + if (array_key_exists($keys[8], $arr)) $this->setDbEditedby($arr[$keys[8]]); + if (array_key_exists($keys[9], $arr)) $this->setDbMtime($arr[$keys[9]]); + if (array_key_exists($keys[10], $arr)) $this->setDbUtime($arr[$keys[10]]); + if (array_key_exists($keys[11], $arr)) $this->setDbLPtime($arr[$keys[11]]); + if (array_key_exists($keys[12], $arr)) $this->setDbMd5($arr[$keys[12]]); + if (array_key_exists($keys[13], $arr)) $this->setDbTrackTitle($arr[$keys[13]]); + if (array_key_exists($keys[14], $arr)) $this->setDbArtistName($arr[$keys[14]]); + if (array_key_exists($keys[15], $arr)) $this->setDbBitRate($arr[$keys[15]]); + if (array_key_exists($keys[16], $arr)) $this->setDbSampleRate($arr[$keys[16]]); + if (array_key_exists($keys[17], $arr)) $this->setDbFormat($arr[$keys[17]]); + if (array_key_exists($keys[18], $arr)) $this->setDbLength($arr[$keys[18]]); + if (array_key_exists($keys[19], $arr)) $this->setDbAlbumTitle($arr[$keys[19]]); + if (array_key_exists($keys[20], $arr)) $this->setDbGenre($arr[$keys[20]]); + if (array_key_exists($keys[21], $arr)) $this->setDbComments($arr[$keys[21]]); + if (array_key_exists($keys[22], $arr)) $this->setDbYear($arr[$keys[22]]); + if (array_key_exists($keys[23], $arr)) $this->setDbTrackNumber($arr[$keys[23]]); + if (array_key_exists($keys[24], $arr)) $this->setDbChannels($arr[$keys[24]]); + if (array_key_exists($keys[25], $arr)) $this->setDbUrl($arr[$keys[25]]); + if (array_key_exists($keys[26], $arr)) $this->setDbBpm($arr[$keys[26]]); + if (array_key_exists($keys[27], $arr)) $this->setDbRating($arr[$keys[27]]); + if (array_key_exists($keys[28], $arr)) $this->setDbEncodedBy($arr[$keys[28]]); + if (array_key_exists($keys[29], $arr)) $this->setDbDiscNumber($arr[$keys[29]]); + if (array_key_exists($keys[30], $arr)) $this->setDbMood($arr[$keys[30]]); + if (array_key_exists($keys[31], $arr)) $this->setDbLabel($arr[$keys[31]]); + if (array_key_exists($keys[32], $arr)) $this->setDbComposer($arr[$keys[32]]); + if (array_key_exists($keys[33], $arr)) $this->setDbEncoder($arr[$keys[33]]); + if (array_key_exists($keys[34], $arr)) $this->setDbChecksum($arr[$keys[34]]); + if (array_key_exists($keys[35], $arr)) $this->setDbLyrics($arr[$keys[35]]); + if (array_key_exists($keys[36], $arr)) $this->setDbOrchestra($arr[$keys[36]]); + if (array_key_exists($keys[37], $arr)) $this->setDbConductor($arr[$keys[37]]); + if (array_key_exists($keys[38], $arr)) $this->setDbLyricist($arr[$keys[38]]); + if (array_key_exists($keys[39], $arr)) $this->setDbOriginalLyricist($arr[$keys[39]]); + if (array_key_exists($keys[40], $arr)) $this->setDbRadioStationName($arr[$keys[40]]); + if (array_key_exists($keys[41], $arr)) $this->setDbInfoUrl($arr[$keys[41]]); + if (array_key_exists($keys[42], $arr)) $this->setDbArtistUrl($arr[$keys[42]]); + if (array_key_exists($keys[43], $arr)) $this->setDbAudioSourceUrl($arr[$keys[43]]); + if (array_key_exists($keys[44], $arr)) $this->setDbRadioStationUrl($arr[$keys[44]]); + if (array_key_exists($keys[45], $arr)) $this->setDbBuyThisUrl($arr[$keys[45]]); + if (array_key_exists($keys[46], $arr)) $this->setDbIsrcNumber($arr[$keys[46]]); + if (array_key_exists($keys[47], $arr)) $this->setDbCatalogNumber($arr[$keys[47]]); + if (array_key_exists($keys[48], $arr)) $this->setDbOriginalArtist($arr[$keys[48]]); + if (array_key_exists($keys[49], $arr)) $this->setDbCopyright($arr[$keys[49]]); + if (array_key_exists($keys[50], $arr)) $this->setDbReportDatetime($arr[$keys[50]]); + if (array_key_exists($keys[51], $arr)) $this->setDbReportLocation($arr[$keys[51]]); + if (array_key_exists($keys[52], $arr)) $this->setDbReportOrganization($arr[$keys[52]]); + if (array_key_exists($keys[53], $arr)) $this->setDbSubject($arr[$keys[53]]); + if (array_key_exists($keys[54], $arr)) $this->setDbContributor($arr[$keys[54]]); + if (array_key_exists($keys[55], $arr)) $this->setDbLanguage($arr[$keys[55]]); + if (array_key_exists($keys[56], $arr)) $this->setDbFileExists($arr[$keys[56]]); + if (array_key_exists($keys[57], $arr)) $this->setDbSoundcloudId($arr[$keys[57]]); + if (array_key_exists($keys[58], $arr)) $this->setDbSoundcloudErrorCode($arr[$keys[58]]); + if (array_key_exists($keys[59], $arr)) $this->setDbSoundcloudErrorMsg($arr[$keys[59]]); + if (array_key_exists($keys[60], $arr)) $this->setDbSoundcloudLinkToFile($arr[$keys[60]]); + if (array_key_exists($keys[61], $arr)) $this->setDbSoundCloundUploadTime($arr[$keys[61]]); + if (array_key_exists($keys[62], $arr)) $this->setDbReplayGain($arr[$keys[62]]); + if (array_key_exists($keys[63], $arr)) $this->setDbOwnerId($arr[$keys[63]]); } /** @@ -3719,7 +3816,6 @@ abstract class BaseCcFiles extends BaseObject implements Persistent $criteria = new Criteria(CcFilesPeer::DATABASE_NAME); if ($this->isColumnModified(CcFilesPeer::ID)) $criteria->add(CcFilesPeer::ID, $this->id); - if ($this->isColumnModified(CcFilesPeer::GUNID)) $criteria->add(CcFilesPeer::GUNID, $this->gunid); if ($this->isColumnModified(CcFilesPeer::NAME)) $criteria->add(CcFilesPeer::NAME, $this->name); if ($this->isColumnModified(CcFilesPeer::MIME)) $criteria->add(CcFilesPeer::MIME, $this->mime); if ($this->isColumnModified(CcFilesPeer::FTYPE)) $criteria->add(CcFilesPeer::FTYPE, $this->ftype); @@ -3781,6 +3877,8 @@ abstract class BaseCcFiles extends BaseObject implements Persistent if ($this->isColumnModified(CcFilesPeer::SOUNDCLOUD_ERROR_MSG)) $criteria->add(CcFilesPeer::SOUNDCLOUD_ERROR_MSG, $this->soundcloud_error_msg); if ($this->isColumnModified(CcFilesPeer::SOUNDCLOUD_LINK_TO_FILE)) $criteria->add(CcFilesPeer::SOUNDCLOUD_LINK_TO_FILE, $this->soundcloud_link_to_file); if ($this->isColumnModified(CcFilesPeer::SOUNDCLOUD_UPLOAD_TIME)) $criteria->add(CcFilesPeer::SOUNDCLOUD_UPLOAD_TIME, $this->soundcloud_upload_time); + if ($this->isColumnModified(CcFilesPeer::REPLAY_GAIN)) $criteria->add(CcFilesPeer::REPLAY_GAIN, $this->replay_gain); + if ($this->isColumnModified(CcFilesPeer::OWNER_ID)) $criteria->add(CcFilesPeer::OWNER_ID, $this->owner_id); return $criteria; } @@ -3842,7 +3940,6 @@ abstract class BaseCcFiles extends BaseObject implements Persistent */ public function copyInto($copyObj, $deepCopy = false) { - $copyObj->setDbGunid($this->gunid); $copyObj->setDbName($this->name); $copyObj->setDbMime($this->mime); $copyObj->setDbFtype($this->ftype); @@ -3904,6 +4001,8 @@ abstract class BaseCcFiles extends BaseObject implements Persistent $copyObj->setDbSoundcloudErrorMsg($this->soundcloud_error_msg); $copyObj->setDbSoundcloudLinkToFile($this->soundcloud_link_to_file); $copyObj->setDbSoundCloundUploadTime($this->soundcloud_upload_time); + $copyObj->setDbReplayGain($this->replay_gain); + $copyObj->setDbOwnerId($this->owner_id); if ($deepCopy) { // important: temporarily setNew(false) because this affects the behavior of @@ -3922,6 +4021,12 @@ abstract class BaseCcFiles extends BaseObject implements Persistent } } + foreach ($this->getCcBlockcontentss() as $relObj) { + if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves + $copyObj->addCcBlockcontents($relObj->copy($deepCopy)); + } + } + foreach ($this->getCcSchedules() as $relObj) { if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves $copyObj->addCcSchedule($relObj->copy($deepCopy)); @@ -3980,20 +4085,20 @@ abstract class BaseCcFiles extends BaseObject implements Persistent * @return CcFiles The current object (for fluent API support) * @throws PropelException */ - public function setCcSubjs(CcSubjs $v = null) + public function setFkOwner(CcSubjs $v = null) { if ($v === null) { - $this->setDbEditedby(NULL); + $this->setDbOwnerId(NULL); } else { - $this->setDbEditedby($v->getDbId()); + $this->setDbOwnerId($v->getDbId()); } - $this->aCcSubjs = $v; + $this->aFkOwner = $v; // Add binding for other direction of this n:n relationship. // If this object has already been added to the CcSubjs object, it will not be re-added. if ($v !== null) { - $v->addCcFiles($this); + $v->addCcFilesRelatedByDbOwnerId($this); } return $this; @@ -4007,19 +4112,68 @@ abstract class BaseCcFiles extends BaseObject implements Persistent * @return CcSubjs The associated CcSubjs object. * @throws PropelException */ - public function getCcSubjs(PropelPDO $con = null) + public function getFkOwner(PropelPDO $con = null) { - if ($this->aCcSubjs === null && ($this->editedby !== null)) { - $this->aCcSubjs = CcSubjsQuery::create()->findPk($this->editedby, $con); + if ($this->aFkOwner === null && ($this->owner_id !== null)) { + $this->aFkOwner = CcSubjsQuery::create()->findPk($this->owner_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->aCcSubjs->addCcFiless($this); + $this->aFkOwner->addCcFilessRelatedByDbOwnerId($this); */ } - return $this->aCcSubjs; + return $this->aFkOwner; + } + + /** + * Declares an association between this object and a CcSubjs object. + * + * @param CcSubjs $v + * @return CcFiles The current object (for fluent API support) + * @throws PropelException + */ + public function setCcSubjsRelatedByDbEditedby(CcSubjs $v = null) + { + if ($v === null) { + $this->setDbEditedby(NULL); + } else { + $this->setDbEditedby($v->getDbId()); + } + + $this->aCcSubjsRelatedByDbEditedby = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the CcSubjs object, it will not be re-added. + if ($v !== null) { + $v->addCcFilesRelatedByDbEditedby($this); + } + + return $this; + } + + + /** + * Get the associated CcSubjs object + * + * @param PropelPDO Optional Connection object. + * @return CcSubjs The associated CcSubjs object. + * @throws PropelException + */ + public function getCcSubjsRelatedByDbEditedby(PropelPDO $con = null) + { + if ($this->aCcSubjsRelatedByDbEditedby === null && ($this->editedby !== null)) { + $this->aCcSubjsRelatedByDbEditedby = CcSubjsQuery::create()->findPk($this->editedby, $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->aCcSubjsRelatedByDbEditedby->addCcFilessRelatedByDbEditedby($this); + */ + } + return $this->aCcSubjsRelatedByDbEditedby; } /** @@ -4340,6 +4494,31 @@ abstract class BaseCcFiles extends BaseObject implements Persistent } + /** + * 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 CcPlaylistcontentss 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 CcPlaylistcontents[] List of CcPlaylistcontents objects + */ + public function getCcPlaylistcontentssJoinCcBlock($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $query = CcPlaylistcontentsQuery::create(null, $criteria); + $query->joinWith('CcBlock', $join_behavior); + + return $this->getCcPlaylistcontentss($query, $con); + } + + /** * If this collection has already been initialized with * an identical criteria, it returns the collection. @@ -4364,6 +4543,140 @@ abstract class BaseCcFiles extends BaseObject implements Persistent return $this->getCcPlaylistcontentss($query, $con); } + /** + * Clears out the collCcBlockcontentss 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 addCcBlockcontentss() + */ + public function clearCcBlockcontentss() + { + $this->collCcBlockcontentss = null; // important to set this to NULL since that means it is uninitialized + } + + /** + * Initializes the collCcBlockcontentss collection. + * + * By default this just sets the collCcBlockcontentss collection to an empty array (like clearcollCcBlockcontentss()); + * 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 initCcBlockcontentss() + { + $this->collCcBlockcontentss = new PropelObjectCollection(); + $this->collCcBlockcontentss->setModel('CcBlockcontents'); + } + + /** + * Gets an array of CcBlockcontents 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 CcFiles 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 CcBlockcontents[] List of CcBlockcontents objects + * @throws PropelException + */ + public function getCcBlockcontentss($criteria = null, PropelPDO $con = null) + { + if(null === $this->collCcBlockcontentss || null !== $criteria) { + if ($this->isNew() && null === $this->collCcBlockcontentss) { + // return empty collection + $this->initCcBlockcontentss(); + } else { + $collCcBlockcontentss = CcBlockcontentsQuery::create(null, $criteria) + ->filterByCcFiles($this) + ->find($con); + if (null !== $criteria) { + return $collCcBlockcontentss; + } + $this->collCcBlockcontentss = $collCcBlockcontentss; + } + } + return $this->collCcBlockcontentss; + } + + /** + * Returns the number of related CcBlockcontents objects. + * + * @param Criteria $criteria + * @param boolean $distinct + * @param PropelPDO $con + * @return int Count of related CcBlockcontents objects. + * @throws PropelException + */ + public function countCcBlockcontentss(Criteria $criteria = null, $distinct = false, PropelPDO $con = null) + { + if(null === $this->collCcBlockcontentss || null !== $criteria) { + if ($this->isNew() && null === $this->collCcBlockcontentss) { + return 0; + } else { + $query = CcBlockcontentsQuery::create(null, $criteria); + if($distinct) { + $query->distinct(); + } + return $query + ->filterByCcFiles($this) + ->count($con); + } + } else { + return count($this->collCcBlockcontentss); + } + } + + /** + * Method called to associate a CcBlockcontents object to this object + * through the CcBlockcontents foreign key attribute. + * + * @param CcBlockcontents $l CcBlockcontents + * @return void + * @throws PropelException + */ + public function addCcBlockcontents(CcBlockcontents $l) + { + if ($this->collCcBlockcontentss === null) { + $this->initCcBlockcontentss(); + } + if (!$this->collCcBlockcontentss->contains($l)) { // only add it if the **same** object is not already associated + $this->collCcBlockcontentss[]= $l; + $l->setCcFiles($this); + } + } + + + /** + * 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 CcBlockcontentss 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 CcBlockcontents[] List of CcBlockcontents objects + */ + public function getCcBlockcontentssJoinCcBlock($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $query = CcBlockcontentsQuery::create(null, $criteria); + $query->joinWith('CcBlock', $join_behavior); + + return $this->getCcBlockcontentss($query, $con); + } + /** * Clears out the collCcSchedules collection * @@ -4498,13 +4811,37 @@ abstract class BaseCcFiles extends BaseObject implements Persistent return $this->getCcSchedules($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 CcSchedules 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 CcSchedule[] List of CcSchedule objects + */ + public function getCcSchedulesJoinCcWebstream($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $query = CcScheduleQuery::create(null, $criteria); + $query->joinWith('CcWebstream', $join_behavior); + + return $this->getCcSchedules($query, $con); + } + /** * Clears the current object and sets all attributes to their default values */ public function clear() { $this->id = null; - $this->gunid = null; $this->name = null; $this->mime = null; $this->ftype = null; @@ -4566,6 +4903,8 @@ abstract class BaseCcFiles extends BaseObject implements Persistent $this->soundcloud_error_msg = null; $this->soundcloud_link_to_file = null; $this->soundcloud_upload_time = null; + $this->replay_gain = null; + $this->owner_id = null; $this->alreadyInSave = false; $this->alreadyInValidation = false; $this->clearAllReferences(); @@ -4597,6 +4936,11 @@ abstract class BaseCcFiles extends BaseObject implements Persistent $o->clearAllReferences($deep); } } + if ($this->collCcBlockcontentss) { + foreach ((array) $this->collCcBlockcontentss as $o) { + $o->clearAllReferences($deep); + } + } if ($this->collCcSchedules) { foreach ((array) $this->collCcSchedules as $o) { $o->clearAllReferences($deep); @@ -4606,8 +4950,10 @@ abstract class BaseCcFiles extends BaseObject implements Persistent $this->collCcShowInstancess = null; $this->collCcPlaylistcontentss = null; + $this->collCcBlockcontentss = null; $this->collCcSchedules = null; - $this->aCcSubjs = 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 6d35d597a..c155c3c2a 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcFilesPeer.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcFilesPeer.php @@ -26,7 +26,7 @@ abstract class BaseCcFilesPeer { const TM_CLASS = 'CcFilesTableMap'; /** The total number of columns. */ - const NUM_COLUMNS = 63; + const NUM_COLUMNS = 64; /** The number of lazy-loaded columns. */ const NUM_LAZY_LOAD_COLUMNS = 0; @@ -34,9 +34,6 @@ abstract class BaseCcFilesPeer { /** the column name for the ID field */ const ID = 'cc_files.ID'; - /** the column name for the GUNID field */ - const GUNID = 'cc_files.GUNID'; - /** the column name for the NAME field */ const NAME = 'cc_files.NAME'; @@ -220,6 +217,12 @@ abstract class BaseCcFilesPeer { /** the column name for the SOUNDCLOUD_UPLOAD_TIME field */ const SOUNDCLOUD_UPLOAD_TIME = 'cc_files.SOUNDCLOUD_UPLOAD_TIME'; + /** the column name for the REPLAY_GAIN field */ + const REPLAY_GAIN = 'cc_files.REPLAY_GAIN'; + + /** the column name for the OWNER_ID field */ + const OWNER_ID = 'cc_files.OWNER_ID'; + /** * An identiy map to hold any loaded instances of CcFiles objects. * This must be public so that other peer classes can access this when hydrating from JOIN @@ -236,12 +239,12 @@ abstract class BaseCcFilesPeer { * e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id' */ private static $fieldNames = array ( - BasePeer::TYPE_PHPNAME => array ('DbId', 'DbGunid', 'DbName', 'DbMime', 'DbFtype', 'DbDirectory', 'DbFilepath', 'DbState', 'DbCurrentlyaccessing', 'DbEditedby', 'DbMtime', 'DbUtime', 'DbLPtime', 'DbMd5', 'DbTrackTitle', 'DbArtistName', 'DbBitRate', 'DbSampleRate', 'DbFormat', 'DbLength', 'DbAlbumTitle', 'DbGenre', 'DbComments', 'DbYear', 'DbTrackNumber', 'DbChannels', 'DbUrl', 'DbBpm', 'DbRating', 'DbEncodedBy', 'DbDiscNumber', 'DbMood', 'DbLabel', 'DbComposer', 'DbEncoder', 'DbChecksum', 'DbLyrics', 'DbOrchestra', 'DbConductor', 'DbLyricist', 'DbOriginalLyricist', 'DbRadioStationName', 'DbInfoUrl', 'DbArtistUrl', 'DbAudioSourceUrl', 'DbRadioStationUrl', 'DbBuyThisUrl', 'DbIsrcNumber', 'DbCatalogNumber', 'DbOriginalArtist', 'DbCopyright', 'DbReportDatetime', 'DbReportLocation', 'DbReportOrganization', 'DbSubject', 'DbContributor', 'DbLanguage', 'DbFileExists', 'DbSoundcloudId', 'DbSoundcloudErrorCode', 'DbSoundcloudErrorMsg', 'DbSoundcloudLinkToFile', 'DbSoundCloundUploadTime', ), - BasePeer::TYPE_STUDLYPHPNAME => array ('dbId', 'dbGunid', 'dbName', 'dbMime', 'dbFtype', 'dbDirectory', 'dbFilepath', 'dbState', 'dbCurrentlyaccessing', 'dbEditedby', 'dbMtime', 'dbUtime', 'dbLPtime', 'dbMd5', 'dbTrackTitle', 'dbArtistName', 'dbBitRate', 'dbSampleRate', 'dbFormat', 'dbLength', 'dbAlbumTitle', 'dbGenre', 'dbComments', 'dbYear', 'dbTrackNumber', 'dbChannels', 'dbUrl', 'dbBpm', 'dbRating', 'dbEncodedBy', 'dbDiscNumber', 'dbMood', 'dbLabel', 'dbComposer', 'dbEncoder', 'dbChecksum', 'dbLyrics', 'dbOrchestra', 'dbConductor', 'dbLyricist', 'dbOriginalLyricist', 'dbRadioStationName', 'dbInfoUrl', 'dbArtistUrl', 'dbAudioSourceUrl', 'dbRadioStationUrl', 'dbBuyThisUrl', 'dbIsrcNumber', 'dbCatalogNumber', 'dbOriginalArtist', 'dbCopyright', 'dbReportDatetime', 'dbReportLocation', 'dbReportOrganization', 'dbSubject', 'dbContributor', 'dbLanguage', 'dbFileExists', 'dbSoundcloudId', 'dbSoundcloudErrorCode', 'dbSoundcloudErrorMsg', 'dbSoundcloudLinkToFile', 'dbSoundCloundUploadTime', ), - BasePeer::TYPE_COLNAME => array (self::ID, self::GUNID, self::NAME, self::MIME, self::FTYPE, self::DIRECTORY, self::FILEPATH, self::STATE, self::CURRENTLYACCESSING, self::EDITEDBY, self::MTIME, self::UTIME, self::LPTIME, self::MD5, self::TRACK_TITLE, self::ARTIST_NAME, self::BIT_RATE, self::SAMPLE_RATE, self::FORMAT, self::LENGTH, self::ALBUM_TITLE, self::GENRE, self::COMMENTS, self::YEAR, self::TRACK_NUMBER, self::CHANNELS, self::URL, self::BPM, self::RATING, self::ENCODED_BY, self::DISC_NUMBER, self::MOOD, self::LABEL, self::COMPOSER, self::ENCODER, self::CHECKSUM, self::LYRICS, self::ORCHESTRA, self::CONDUCTOR, self::LYRICIST, self::ORIGINAL_LYRICIST, self::RADIO_STATION_NAME, self::INFO_URL, self::ARTIST_URL, self::AUDIO_SOURCE_URL, self::RADIO_STATION_URL, self::BUY_THIS_URL, self::ISRC_NUMBER, self::CATALOG_NUMBER, self::ORIGINAL_ARTIST, self::COPYRIGHT, self::REPORT_DATETIME, self::REPORT_LOCATION, self::REPORT_ORGANIZATION, self::SUBJECT, self::CONTRIBUTOR, self::LANGUAGE, self::FILE_EXISTS, self::SOUNDCLOUD_ID, self::SOUNDCLOUD_ERROR_CODE, self::SOUNDCLOUD_ERROR_MSG, self::SOUNDCLOUD_LINK_TO_FILE, self::SOUNDCLOUD_UPLOAD_TIME, ), - BasePeer::TYPE_RAW_COLNAME => array ('ID', 'GUNID', 'NAME', 'MIME', 'FTYPE', 'DIRECTORY', 'FILEPATH', 'STATE', 'CURRENTLYACCESSING', 'EDITEDBY', 'MTIME', 'UTIME', 'LPTIME', 'MD5', 'TRACK_TITLE', 'ARTIST_NAME', 'BIT_RATE', 'SAMPLE_RATE', 'FORMAT', 'LENGTH', 'ALBUM_TITLE', 'GENRE', 'COMMENTS', 'YEAR', 'TRACK_NUMBER', 'CHANNELS', 'URL', 'BPM', 'RATING', 'ENCODED_BY', 'DISC_NUMBER', 'MOOD', 'LABEL', 'COMPOSER', 'ENCODER', 'CHECKSUM', 'LYRICS', 'ORCHESTRA', 'CONDUCTOR', 'LYRICIST', 'ORIGINAL_LYRICIST', 'RADIO_STATION_NAME', 'INFO_URL', 'ARTIST_URL', 'AUDIO_SOURCE_URL', 'RADIO_STATION_URL', 'BUY_THIS_URL', 'ISRC_NUMBER', 'CATALOG_NUMBER', 'ORIGINAL_ARTIST', 'COPYRIGHT', 'REPORT_DATETIME', 'REPORT_LOCATION', 'REPORT_ORGANIZATION', 'SUBJECT', 'CONTRIBUTOR', 'LANGUAGE', 'FILE_EXISTS', 'SOUNDCLOUD_ID', 'SOUNDCLOUD_ERROR_CODE', 'SOUNDCLOUD_ERROR_MSG', 'SOUNDCLOUD_LINK_TO_FILE', 'SOUNDCLOUD_UPLOAD_TIME', ), - BasePeer::TYPE_FIELDNAME => array ('id', 'gunid', 'name', 'mime', 'ftype', 'directory', 'filepath', 'state', 'currentlyaccessing', 'editedby', 'mtime', 'utime', 'lptime', 'md5', 'track_title', 'artist_name', 'bit_rate', 'sample_rate', 'format', 'length', 'album_title', 'genre', 'comments', 'year', 'track_number', 'channels', 'url', 'bpm', 'rating', 'encoded_by', 'disc_number', 'mood', 'label', 'composer', 'encoder', 'checksum', 'lyrics', 'orchestra', 'conductor', 'lyricist', 'original_lyricist', 'radio_station_name', 'info_url', 'artist_url', 'audio_source_url', 'radio_station_url', 'buy_this_url', 'isrc_number', 'catalog_number', 'original_artist', 'copyright', 'report_datetime', 'report_location', 'report_organization', 'subject', 'contributor', 'language', 'file_exists', 'soundcloud_id', 'soundcloud_error_code', 'soundcloud_error_msg', 'soundcloud_link_to_file', 'soundcloud_upload_time', ), - BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, ) + BasePeer::TYPE_PHPNAME => array ('DbId', 'DbName', 'DbMime', 'DbFtype', 'DbDirectory', 'DbFilepath', 'DbState', 'DbCurrentlyaccessing', 'DbEditedby', 'DbMtime', 'DbUtime', 'DbLPtime', 'DbMd5', 'DbTrackTitle', 'DbArtistName', 'DbBitRate', 'DbSampleRate', 'DbFormat', 'DbLength', 'DbAlbumTitle', 'DbGenre', 'DbComments', 'DbYear', 'DbTrackNumber', 'DbChannels', 'DbUrl', 'DbBpm', 'DbRating', 'DbEncodedBy', 'DbDiscNumber', 'DbMood', 'DbLabel', 'DbComposer', 'DbEncoder', 'DbChecksum', 'DbLyrics', 'DbOrchestra', 'DbConductor', 'DbLyricist', 'DbOriginalLyricist', 'DbRadioStationName', 'DbInfoUrl', 'DbArtistUrl', 'DbAudioSourceUrl', 'DbRadioStationUrl', 'DbBuyThisUrl', 'DbIsrcNumber', 'DbCatalogNumber', 'DbOriginalArtist', 'DbCopyright', 'DbReportDatetime', 'DbReportLocation', 'DbReportOrganization', 'DbSubject', 'DbContributor', 'DbLanguage', 'DbFileExists', 'DbSoundcloudId', 'DbSoundcloudErrorCode', 'DbSoundcloudErrorMsg', 'DbSoundcloudLinkToFile', 'DbSoundCloundUploadTime', 'DbReplayGain', 'DbOwnerId', ), + BasePeer::TYPE_STUDLYPHPNAME => array ('dbId', 'dbName', 'dbMime', 'dbFtype', 'dbDirectory', 'dbFilepath', 'dbState', 'dbCurrentlyaccessing', 'dbEditedby', 'dbMtime', 'dbUtime', 'dbLPtime', 'dbMd5', 'dbTrackTitle', 'dbArtistName', 'dbBitRate', 'dbSampleRate', 'dbFormat', 'dbLength', 'dbAlbumTitle', 'dbGenre', 'dbComments', 'dbYear', 'dbTrackNumber', 'dbChannels', 'dbUrl', 'dbBpm', 'dbRating', 'dbEncodedBy', 'dbDiscNumber', 'dbMood', 'dbLabel', 'dbComposer', 'dbEncoder', 'dbChecksum', 'dbLyrics', 'dbOrchestra', 'dbConductor', 'dbLyricist', 'dbOriginalLyricist', 'dbRadioStationName', 'dbInfoUrl', 'dbArtistUrl', 'dbAudioSourceUrl', 'dbRadioStationUrl', 'dbBuyThisUrl', 'dbIsrcNumber', 'dbCatalogNumber', 'dbOriginalArtist', 'dbCopyright', 'dbReportDatetime', 'dbReportLocation', 'dbReportOrganization', 'dbSubject', 'dbContributor', 'dbLanguage', 'dbFileExists', 'dbSoundcloudId', 'dbSoundcloudErrorCode', 'dbSoundcloudErrorMsg', 'dbSoundcloudLinkToFile', 'dbSoundCloundUploadTime', 'dbReplayGain', 'dbOwnerId', ), + BasePeer::TYPE_COLNAME => array (self::ID, self::NAME, self::MIME, self::FTYPE, self::DIRECTORY, self::FILEPATH, self::STATE, self::CURRENTLYACCESSING, self::EDITEDBY, self::MTIME, self::UTIME, self::LPTIME, self::MD5, self::TRACK_TITLE, self::ARTIST_NAME, self::BIT_RATE, self::SAMPLE_RATE, self::FORMAT, self::LENGTH, self::ALBUM_TITLE, self::GENRE, self::COMMENTS, self::YEAR, self::TRACK_NUMBER, self::CHANNELS, self::URL, self::BPM, self::RATING, self::ENCODED_BY, self::DISC_NUMBER, self::MOOD, self::LABEL, self::COMPOSER, self::ENCODER, self::CHECKSUM, self::LYRICS, self::ORCHESTRA, self::CONDUCTOR, self::LYRICIST, self::ORIGINAL_LYRICIST, self::RADIO_STATION_NAME, self::INFO_URL, self::ARTIST_URL, self::AUDIO_SOURCE_URL, self::RADIO_STATION_URL, self::BUY_THIS_URL, self::ISRC_NUMBER, self::CATALOG_NUMBER, self::ORIGINAL_ARTIST, self::COPYRIGHT, self::REPORT_DATETIME, self::REPORT_LOCATION, self::REPORT_ORGANIZATION, self::SUBJECT, self::CONTRIBUTOR, self::LANGUAGE, self::FILE_EXISTS, self::SOUNDCLOUD_ID, self::SOUNDCLOUD_ERROR_CODE, self::SOUNDCLOUD_ERROR_MSG, self::SOUNDCLOUD_LINK_TO_FILE, self::SOUNDCLOUD_UPLOAD_TIME, self::REPLAY_GAIN, self::OWNER_ID, ), + BasePeer::TYPE_RAW_COLNAME => array ('ID', 'NAME', 'MIME', 'FTYPE', 'DIRECTORY', 'FILEPATH', 'STATE', 'CURRENTLYACCESSING', 'EDITEDBY', 'MTIME', 'UTIME', 'LPTIME', 'MD5', 'TRACK_TITLE', 'ARTIST_NAME', 'BIT_RATE', 'SAMPLE_RATE', 'FORMAT', 'LENGTH', 'ALBUM_TITLE', 'GENRE', 'COMMENTS', 'YEAR', 'TRACK_NUMBER', 'CHANNELS', 'URL', 'BPM', 'RATING', 'ENCODED_BY', 'DISC_NUMBER', 'MOOD', 'LABEL', 'COMPOSER', 'ENCODER', 'CHECKSUM', 'LYRICS', 'ORCHESTRA', 'CONDUCTOR', 'LYRICIST', 'ORIGINAL_LYRICIST', 'RADIO_STATION_NAME', 'INFO_URL', 'ARTIST_URL', 'AUDIO_SOURCE_URL', 'RADIO_STATION_URL', 'BUY_THIS_URL', 'ISRC_NUMBER', 'CATALOG_NUMBER', 'ORIGINAL_ARTIST', 'COPYRIGHT', 'REPORT_DATETIME', 'REPORT_LOCATION', 'REPORT_ORGANIZATION', 'SUBJECT', 'CONTRIBUTOR', 'LANGUAGE', 'FILE_EXISTS', 'SOUNDCLOUD_ID', 'SOUNDCLOUD_ERROR_CODE', 'SOUNDCLOUD_ERROR_MSG', 'SOUNDCLOUD_LINK_TO_FILE', 'SOUNDCLOUD_UPLOAD_TIME', 'REPLAY_GAIN', 'OWNER_ID', ), + BasePeer::TYPE_FIELDNAME => array ('id', 'name', 'mime', 'ftype', 'directory', 'filepath', 'state', 'currentlyaccessing', 'editedby', 'mtime', 'utime', 'lptime', 'md5', 'track_title', 'artist_name', 'bit_rate', 'sample_rate', 'format', 'length', 'album_title', 'genre', 'comments', 'year', 'track_number', 'channels', 'url', 'bpm', 'rating', 'encoded_by', 'disc_number', 'mood', 'label', 'composer', 'encoder', 'checksum', 'lyrics', 'orchestra', 'conductor', 'lyricist', 'original_lyricist', 'radio_station_name', 'info_url', 'artist_url', 'audio_source_url', 'radio_station_url', 'buy_this_url', 'isrc_number', 'catalog_number', 'original_artist', 'copyright', 'report_datetime', 'report_location', 'report_organization', 'subject', 'contributor', 'language', 'file_exists', 'soundcloud_id', 'soundcloud_error_code', 'soundcloud_error_msg', 'soundcloud_link_to_file', 'soundcloud_upload_time', 'replay_gain', 'owner_id', ), + BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, ) ); /** @@ -251,12 +254,12 @@ abstract class BaseCcFilesPeer { * e.g. self::$fieldNames[BasePeer::TYPE_PHPNAME]['Id'] = 0 */ private static $fieldKeys = array ( - BasePeer::TYPE_PHPNAME => array ('DbId' => 0, 'DbGunid' => 1, 'DbName' => 2, 'DbMime' => 3, 'DbFtype' => 4, 'DbDirectory' => 5, 'DbFilepath' => 6, 'DbState' => 7, 'DbCurrentlyaccessing' => 8, 'DbEditedby' => 9, 'DbMtime' => 10, 'DbUtime' => 11, 'DbLPtime' => 12, 'DbMd5' => 13, 'DbTrackTitle' => 14, 'DbArtistName' => 15, 'DbBitRate' => 16, 'DbSampleRate' => 17, 'DbFormat' => 18, 'DbLength' => 19, 'DbAlbumTitle' => 20, 'DbGenre' => 21, 'DbComments' => 22, 'DbYear' => 23, 'DbTrackNumber' => 24, 'DbChannels' => 25, 'DbUrl' => 26, 'DbBpm' => 27, 'DbRating' => 28, 'DbEncodedBy' => 29, 'DbDiscNumber' => 30, 'DbMood' => 31, 'DbLabel' => 32, 'DbComposer' => 33, 'DbEncoder' => 34, 'DbChecksum' => 35, 'DbLyrics' => 36, 'DbOrchestra' => 37, 'DbConductor' => 38, 'DbLyricist' => 39, 'DbOriginalLyricist' => 40, 'DbRadioStationName' => 41, 'DbInfoUrl' => 42, 'DbArtistUrl' => 43, 'DbAudioSourceUrl' => 44, 'DbRadioStationUrl' => 45, 'DbBuyThisUrl' => 46, 'DbIsrcNumber' => 47, 'DbCatalogNumber' => 48, 'DbOriginalArtist' => 49, 'DbCopyright' => 50, 'DbReportDatetime' => 51, 'DbReportLocation' => 52, 'DbReportOrganization' => 53, 'DbSubject' => 54, 'DbContributor' => 55, 'DbLanguage' => 56, 'DbFileExists' => 57, 'DbSoundcloudId' => 58, 'DbSoundcloudErrorCode' => 59, 'DbSoundcloudErrorMsg' => 60, 'DbSoundcloudLinkToFile' => 61, 'DbSoundCloundUploadTime' => 62, ), - BasePeer::TYPE_STUDLYPHPNAME => array ('dbId' => 0, 'dbGunid' => 1, 'dbName' => 2, 'dbMime' => 3, 'dbFtype' => 4, 'dbDirectory' => 5, 'dbFilepath' => 6, 'dbState' => 7, 'dbCurrentlyaccessing' => 8, 'dbEditedby' => 9, 'dbMtime' => 10, 'dbUtime' => 11, 'dbLPtime' => 12, 'dbMd5' => 13, 'dbTrackTitle' => 14, 'dbArtistName' => 15, 'dbBitRate' => 16, 'dbSampleRate' => 17, 'dbFormat' => 18, 'dbLength' => 19, 'dbAlbumTitle' => 20, 'dbGenre' => 21, 'dbComments' => 22, 'dbYear' => 23, 'dbTrackNumber' => 24, 'dbChannels' => 25, 'dbUrl' => 26, 'dbBpm' => 27, 'dbRating' => 28, 'dbEncodedBy' => 29, 'dbDiscNumber' => 30, 'dbMood' => 31, 'dbLabel' => 32, 'dbComposer' => 33, 'dbEncoder' => 34, 'dbChecksum' => 35, 'dbLyrics' => 36, 'dbOrchestra' => 37, 'dbConductor' => 38, 'dbLyricist' => 39, 'dbOriginalLyricist' => 40, 'dbRadioStationName' => 41, 'dbInfoUrl' => 42, 'dbArtistUrl' => 43, 'dbAudioSourceUrl' => 44, 'dbRadioStationUrl' => 45, 'dbBuyThisUrl' => 46, 'dbIsrcNumber' => 47, 'dbCatalogNumber' => 48, 'dbOriginalArtist' => 49, 'dbCopyright' => 50, 'dbReportDatetime' => 51, 'dbReportLocation' => 52, 'dbReportOrganization' => 53, 'dbSubject' => 54, 'dbContributor' => 55, 'dbLanguage' => 56, 'dbFileExists' => 57, 'dbSoundcloudId' => 58, 'dbSoundcloudErrorCode' => 59, 'dbSoundcloudErrorMsg' => 60, 'dbSoundcloudLinkToFile' => 61, 'dbSoundCloundUploadTime' => 62, ), - BasePeer::TYPE_COLNAME => array (self::ID => 0, self::GUNID => 1, self::NAME => 2, self::MIME => 3, self::FTYPE => 4, self::DIRECTORY => 5, self::FILEPATH => 6, self::STATE => 7, self::CURRENTLYACCESSING => 8, self::EDITEDBY => 9, self::MTIME => 10, self::UTIME => 11, self::LPTIME => 12, self::MD5 => 13, self::TRACK_TITLE => 14, self::ARTIST_NAME => 15, self::BIT_RATE => 16, self::SAMPLE_RATE => 17, self::FORMAT => 18, self::LENGTH => 19, self::ALBUM_TITLE => 20, self::GENRE => 21, self::COMMENTS => 22, self::YEAR => 23, self::TRACK_NUMBER => 24, self::CHANNELS => 25, self::URL => 26, self::BPM => 27, self::RATING => 28, self::ENCODED_BY => 29, self::DISC_NUMBER => 30, self::MOOD => 31, self::LABEL => 32, self::COMPOSER => 33, self::ENCODER => 34, self::CHECKSUM => 35, self::LYRICS => 36, self::ORCHESTRA => 37, self::CONDUCTOR => 38, self::LYRICIST => 39, self::ORIGINAL_LYRICIST => 40, self::RADIO_STATION_NAME => 41, self::INFO_URL => 42, self::ARTIST_URL => 43, self::AUDIO_SOURCE_URL => 44, self::RADIO_STATION_URL => 45, self::BUY_THIS_URL => 46, self::ISRC_NUMBER => 47, self::CATALOG_NUMBER => 48, self::ORIGINAL_ARTIST => 49, self::COPYRIGHT => 50, self::REPORT_DATETIME => 51, self::REPORT_LOCATION => 52, self::REPORT_ORGANIZATION => 53, self::SUBJECT => 54, self::CONTRIBUTOR => 55, self::LANGUAGE => 56, self::FILE_EXISTS => 57, self::SOUNDCLOUD_ID => 58, self::SOUNDCLOUD_ERROR_CODE => 59, self::SOUNDCLOUD_ERROR_MSG => 60, self::SOUNDCLOUD_LINK_TO_FILE => 61, self::SOUNDCLOUD_UPLOAD_TIME => 62, ), - BasePeer::TYPE_RAW_COLNAME => array ('ID' => 0, 'GUNID' => 1, 'NAME' => 2, 'MIME' => 3, 'FTYPE' => 4, 'DIRECTORY' => 5, 'FILEPATH' => 6, 'STATE' => 7, 'CURRENTLYACCESSING' => 8, 'EDITEDBY' => 9, 'MTIME' => 10, 'UTIME' => 11, 'LPTIME' => 12, 'MD5' => 13, 'TRACK_TITLE' => 14, 'ARTIST_NAME' => 15, 'BIT_RATE' => 16, 'SAMPLE_RATE' => 17, 'FORMAT' => 18, 'LENGTH' => 19, 'ALBUM_TITLE' => 20, 'GENRE' => 21, 'COMMENTS' => 22, 'YEAR' => 23, 'TRACK_NUMBER' => 24, 'CHANNELS' => 25, 'URL' => 26, 'BPM' => 27, 'RATING' => 28, 'ENCODED_BY' => 29, 'DISC_NUMBER' => 30, 'MOOD' => 31, 'LABEL' => 32, 'COMPOSER' => 33, 'ENCODER' => 34, 'CHECKSUM' => 35, 'LYRICS' => 36, 'ORCHESTRA' => 37, 'CONDUCTOR' => 38, 'LYRICIST' => 39, 'ORIGINAL_LYRICIST' => 40, 'RADIO_STATION_NAME' => 41, 'INFO_URL' => 42, 'ARTIST_URL' => 43, 'AUDIO_SOURCE_URL' => 44, 'RADIO_STATION_URL' => 45, 'BUY_THIS_URL' => 46, 'ISRC_NUMBER' => 47, 'CATALOG_NUMBER' => 48, 'ORIGINAL_ARTIST' => 49, 'COPYRIGHT' => 50, 'REPORT_DATETIME' => 51, 'REPORT_LOCATION' => 52, 'REPORT_ORGANIZATION' => 53, 'SUBJECT' => 54, 'CONTRIBUTOR' => 55, 'LANGUAGE' => 56, 'FILE_EXISTS' => 57, 'SOUNDCLOUD_ID' => 58, 'SOUNDCLOUD_ERROR_CODE' => 59, 'SOUNDCLOUD_ERROR_MSG' => 60, 'SOUNDCLOUD_LINK_TO_FILE' => 61, 'SOUNDCLOUD_UPLOAD_TIME' => 62, ), - BasePeer::TYPE_FIELDNAME => array ('id' => 0, 'gunid' => 1, 'name' => 2, 'mime' => 3, 'ftype' => 4, 'directory' => 5, 'filepath' => 6, 'state' => 7, 'currentlyaccessing' => 8, 'editedby' => 9, 'mtime' => 10, 'utime' => 11, 'lptime' => 12, 'md5' => 13, 'track_title' => 14, 'artist_name' => 15, 'bit_rate' => 16, 'sample_rate' => 17, 'format' => 18, 'length' => 19, 'album_title' => 20, 'genre' => 21, 'comments' => 22, 'year' => 23, 'track_number' => 24, 'channels' => 25, 'url' => 26, 'bpm' => 27, 'rating' => 28, 'encoded_by' => 29, 'disc_number' => 30, 'mood' => 31, 'label' => 32, 'composer' => 33, 'encoder' => 34, 'checksum' => 35, 'lyrics' => 36, 'orchestra' => 37, 'conductor' => 38, 'lyricist' => 39, 'original_lyricist' => 40, 'radio_station_name' => 41, 'info_url' => 42, 'artist_url' => 43, 'audio_source_url' => 44, 'radio_station_url' => 45, 'buy_this_url' => 46, 'isrc_number' => 47, 'catalog_number' => 48, 'original_artist' => 49, 'copyright' => 50, 'report_datetime' => 51, 'report_location' => 52, 'report_organization' => 53, 'subject' => 54, 'contributor' => 55, 'language' => 56, 'file_exists' => 57, 'soundcloud_id' => 58, 'soundcloud_error_code' => 59, 'soundcloud_error_msg' => 60, 'soundcloud_link_to_file' => 61, 'soundcloud_upload_time' => 62, ), - BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, ) + BasePeer::TYPE_PHPNAME => array ('DbId' => 0, 'DbName' => 1, 'DbMime' => 2, 'DbFtype' => 3, 'DbDirectory' => 4, 'DbFilepath' => 5, 'DbState' => 6, 'DbCurrentlyaccessing' => 7, 'DbEditedby' => 8, 'DbMtime' => 9, 'DbUtime' => 10, 'DbLPtime' => 11, 'DbMd5' => 12, 'DbTrackTitle' => 13, 'DbArtistName' => 14, 'DbBitRate' => 15, 'DbSampleRate' => 16, 'DbFormat' => 17, 'DbLength' => 18, 'DbAlbumTitle' => 19, 'DbGenre' => 20, 'DbComments' => 21, 'DbYear' => 22, 'DbTrackNumber' => 23, 'DbChannels' => 24, 'DbUrl' => 25, 'DbBpm' => 26, 'DbRating' => 27, 'DbEncodedBy' => 28, 'DbDiscNumber' => 29, 'DbMood' => 30, 'DbLabel' => 31, 'DbComposer' => 32, 'DbEncoder' => 33, 'DbChecksum' => 34, 'DbLyrics' => 35, 'DbOrchestra' => 36, 'DbConductor' => 37, 'DbLyricist' => 38, 'DbOriginalLyricist' => 39, 'DbRadioStationName' => 40, 'DbInfoUrl' => 41, 'DbArtistUrl' => 42, 'DbAudioSourceUrl' => 43, 'DbRadioStationUrl' => 44, 'DbBuyThisUrl' => 45, 'DbIsrcNumber' => 46, 'DbCatalogNumber' => 47, 'DbOriginalArtist' => 48, 'DbCopyright' => 49, 'DbReportDatetime' => 50, 'DbReportLocation' => 51, 'DbReportOrganization' => 52, 'DbSubject' => 53, 'DbContributor' => 54, 'DbLanguage' => 55, 'DbFileExists' => 56, 'DbSoundcloudId' => 57, 'DbSoundcloudErrorCode' => 58, 'DbSoundcloudErrorMsg' => 59, 'DbSoundcloudLinkToFile' => 60, 'DbSoundCloundUploadTime' => 61, 'DbReplayGain' => 62, 'DbOwnerId' => 63, ), + BasePeer::TYPE_STUDLYPHPNAME => array ('dbId' => 0, 'dbName' => 1, 'dbMime' => 2, 'dbFtype' => 3, 'dbDirectory' => 4, 'dbFilepath' => 5, 'dbState' => 6, 'dbCurrentlyaccessing' => 7, 'dbEditedby' => 8, 'dbMtime' => 9, 'dbUtime' => 10, 'dbLPtime' => 11, 'dbMd5' => 12, 'dbTrackTitle' => 13, 'dbArtistName' => 14, 'dbBitRate' => 15, 'dbSampleRate' => 16, 'dbFormat' => 17, 'dbLength' => 18, 'dbAlbumTitle' => 19, 'dbGenre' => 20, 'dbComments' => 21, 'dbYear' => 22, 'dbTrackNumber' => 23, 'dbChannels' => 24, 'dbUrl' => 25, 'dbBpm' => 26, 'dbRating' => 27, 'dbEncodedBy' => 28, 'dbDiscNumber' => 29, 'dbMood' => 30, 'dbLabel' => 31, 'dbComposer' => 32, 'dbEncoder' => 33, 'dbChecksum' => 34, 'dbLyrics' => 35, 'dbOrchestra' => 36, 'dbConductor' => 37, 'dbLyricist' => 38, 'dbOriginalLyricist' => 39, 'dbRadioStationName' => 40, 'dbInfoUrl' => 41, 'dbArtistUrl' => 42, 'dbAudioSourceUrl' => 43, 'dbRadioStationUrl' => 44, 'dbBuyThisUrl' => 45, 'dbIsrcNumber' => 46, 'dbCatalogNumber' => 47, 'dbOriginalArtist' => 48, 'dbCopyright' => 49, 'dbReportDatetime' => 50, 'dbReportLocation' => 51, 'dbReportOrganization' => 52, 'dbSubject' => 53, 'dbContributor' => 54, 'dbLanguage' => 55, 'dbFileExists' => 56, 'dbSoundcloudId' => 57, 'dbSoundcloudErrorCode' => 58, 'dbSoundcloudErrorMsg' => 59, 'dbSoundcloudLinkToFile' => 60, 'dbSoundCloundUploadTime' => 61, 'dbReplayGain' => 62, 'dbOwnerId' => 63, ), + BasePeer::TYPE_COLNAME => array (self::ID => 0, self::NAME => 1, self::MIME => 2, self::FTYPE => 3, self::DIRECTORY => 4, self::FILEPATH => 5, self::STATE => 6, self::CURRENTLYACCESSING => 7, self::EDITEDBY => 8, self::MTIME => 9, self::UTIME => 10, self::LPTIME => 11, self::MD5 => 12, self::TRACK_TITLE => 13, self::ARTIST_NAME => 14, self::BIT_RATE => 15, self::SAMPLE_RATE => 16, self::FORMAT => 17, self::LENGTH => 18, self::ALBUM_TITLE => 19, self::GENRE => 20, self::COMMENTS => 21, self::YEAR => 22, self::TRACK_NUMBER => 23, self::CHANNELS => 24, self::URL => 25, self::BPM => 26, self::RATING => 27, self::ENCODED_BY => 28, self::DISC_NUMBER => 29, self::MOOD => 30, self::LABEL => 31, self::COMPOSER => 32, self::ENCODER => 33, self::CHECKSUM => 34, self::LYRICS => 35, self::ORCHESTRA => 36, self::CONDUCTOR => 37, self::LYRICIST => 38, self::ORIGINAL_LYRICIST => 39, self::RADIO_STATION_NAME => 40, self::INFO_URL => 41, self::ARTIST_URL => 42, self::AUDIO_SOURCE_URL => 43, self::RADIO_STATION_URL => 44, self::BUY_THIS_URL => 45, self::ISRC_NUMBER => 46, self::CATALOG_NUMBER => 47, self::ORIGINAL_ARTIST => 48, self::COPYRIGHT => 49, self::REPORT_DATETIME => 50, self::REPORT_LOCATION => 51, self::REPORT_ORGANIZATION => 52, self::SUBJECT => 53, self::CONTRIBUTOR => 54, self::LANGUAGE => 55, self::FILE_EXISTS => 56, self::SOUNDCLOUD_ID => 57, self::SOUNDCLOUD_ERROR_CODE => 58, self::SOUNDCLOUD_ERROR_MSG => 59, self::SOUNDCLOUD_LINK_TO_FILE => 60, self::SOUNDCLOUD_UPLOAD_TIME => 61, self::REPLAY_GAIN => 62, self::OWNER_ID => 63, ), + BasePeer::TYPE_RAW_COLNAME => array ('ID' => 0, 'NAME' => 1, 'MIME' => 2, 'FTYPE' => 3, 'DIRECTORY' => 4, 'FILEPATH' => 5, 'STATE' => 6, 'CURRENTLYACCESSING' => 7, 'EDITEDBY' => 8, 'MTIME' => 9, 'UTIME' => 10, 'LPTIME' => 11, 'MD5' => 12, 'TRACK_TITLE' => 13, 'ARTIST_NAME' => 14, 'BIT_RATE' => 15, 'SAMPLE_RATE' => 16, 'FORMAT' => 17, 'LENGTH' => 18, 'ALBUM_TITLE' => 19, 'GENRE' => 20, 'COMMENTS' => 21, 'YEAR' => 22, 'TRACK_NUMBER' => 23, 'CHANNELS' => 24, 'URL' => 25, 'BPM' => 26, 'RATING' => 27, 'ENCODED_BY' => 28, 'DISC_NUMBER' => 29, 'MOOD' => 30, 'LABEL' => 31, 'COMPOSER' => 32, 'ENCODER' => 33, 'CHECKSUM' => 34, 'LYRICS' => 35, 'ORCHESTRA' => 36, 'CONDUCTOR' => 37, 'LYRICIST' => 38, 'ORIGINAL_LYRICIST' => 39, 'RADIO_STATION_NAME' => 40, 'INFO_URL' => 41, 'ARTIST_URL' => 42, 'AUDIO_SOURCE_URL' => 43, 'RADIO_STATION_URL' => 44, 'BUY_THIS_URL' => 45, 'ISRC_NUMBER' => 46, 'CATALOG_NUMBER' => 47, 'ORIGINAL_ARTIST' => 48, 'COPYRIGHT' => 49, 'REPORT_DATETIME' => 50, 'REPORT_LOCATION' => 51, 'REPORT_ORGANIZATION' => 52, 'SUBJECT' => 53, 'CONTRIBUTOR' => 54, 'LANGUAGE' => 55, 'FILE_EXISTS' => 56, 'SOUNDCLOUD_ID' => 57, 'SOUNDCLOUD_ERROR_CODE' => 58, 'SOUNDCLOUD_ERROR_MSG' => 59, 'SOUNDCLOUD_LINK_TO_FILE' => 60, 'SOUNDCLOUD_UPLOAD_TIME' => 61, 'REPLAY_GAIN' => 62, 'OWNER_ID' => 63, ), + BasePeer::TYPE_FIELDNAME => array ('id' => 0, 'name' => 1, 'mime' => 2, 'ftype' => 3, 'directory' => 4, 'filepath' => 5, 'state' => 6, 'currentlyaccessing' => 7, 'editedby' => 8, 'mtime' => 9, 'utime' => 10, 'lptime' => 11, 'md5' => 12, 'track_title' => 13, 'artist_name' => 14, 'bit_rate' => 15, 'sample_rate' => 16, 'format' => 17, 'length' => 18, 'album_title' => 19, 'genre' => 20, 'comments' => 21, 'year' => 22, 'track_number' => 23, 'channels' => 24, 'url' => 25, 'bpm' => 26, 'rating' => 27, 'encoded_by' => 28, 'disc_number' => 29, 'mood' => 30, 'label' => 31, 'composer' => 32, 'encoder' => 33, 'checksum' => 34, 'lyrics' => 35, 'orchestra' => 36, 'conductor' => 37, 'lyricist' => 38, 'original_lyricist' => 39, 'radio_station_name' => 40, 'info_url' => 41, 'artist_url' => 42, 'audio_source_url' => 43, 'radio_station_url' => 44, 'buy_this_url' => 45, 'isrc_number' => 46, 'catalog_number' => 47, 'original_artist' => 48, 'copyright' => 49, 'report_datetime' => 50, 'report_location' => 51, 'report_organization' => 52, 'subject' => 53, 'contributor' => 54, 'language' => 55, 'file_exists' => 56, 'soundcloud_id' => 57, 'soundcloud_error_code' => 58, 'soundcloud_error_msg' => 59, 'soundcloud_link_to_file' => 60, 'soundcloud_upload_time' => 61, 'replay_gain' => 62, 'owner_id' => 63, ), + BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, ) ); /** @@ -329,7 +332,6 @@ abstract class BaseCcFilesPeer { { if (null === $alias) { $criteria->addSelectColumn(CcFilesPeer::ID); - $criteria->addSelectColumn(CcFilesPeer::GUNID); $criteria->addSelectColumn(CcFilesPeer::NAME); $criteria->addSelectColumn(CcFilesPeer::MIME); $criteria->addSelectColumn(CcFilesPeer::FTYPE); @@ -391,9 +393,10 @@ abstract class BaseCcFilesPeer { $criteria->addSelectColumn(CcFilesPeer::SOUNDCLOUD_ERROR_MSG); $criteria->addSelectColumn(CcFilesPeer::SOUNDCLOUD_LINK_TO_FILE); $criteria->addSelectColumn(CcFilesPeer::SOUNDCLOUD_UPLOAD_TIME); + $criteria->addSelectColumn(CcFilesPeer::REPLAY_GAIN); + $criteria->addSelectColumn(CcFilesPeer::OWNER_ID); } else { $criteria->addSelectColumn($alias . '.ID'); - $criteria->addSelectColumn($alias . '.GUNID'); $criteria->addSelectColumn($alias . '.NAME'); $criteria->addSelectColumn($alias . '.MIME'); $criteria->addSelectColumn($alias . '.FTYPE'); @@ -455,6 +458,8 @@ abstract class BaseCcFilesPeer { $criteria->addSelectColumn($alias . '.SOUNDCLOUD_ERROR_MSG'); $criteria->addSelectColumn($alias . '.SOUNDCLOUD_LINK_TO_FILE'); $criteria->addSelectColumn($alias . '.SOUNDCLOUD_UPLOAD_TIME'); + $criteria->addSelectColumn($alias . '.REPLAY_GAIN'); + $criteria->addSelectColumn($alias . '.OWNER_ID'); } } @@ -654,6 +659,9 @@ abstract class BaseCcFilesPeer { // 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 CcBlockcontentsPeer instance pool, + // since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule. + CcBlockcontentsPeer::clearInstancePool(); // Invalidate objects in CcSchedulePeer instance pool, // since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule. CcSchedulePeer::clearInstancePool(); @@ -750,7 +758,7 @@ abstract class BaseCcFilesPeer { } /** - * Returns the number of rows matching criteria, joining the related CcSubjs table + * Returns the number of rows matching criteria, joining the related FkOwner table * * @param Criteria $criteria * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. @@ -758,7 +766,57 @@ abstract class BaseCcFilesPeer { * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN * @return int Number of matching rows. */ - public static function doCountJoinCcSubjs(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) + public static function doCountJoinFkOwner(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(CcFilesPeer::TABLE_NAME); + + if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->setDistinct(); + } + + if (!$criteria->hasSelectClause()) { + CcFilesPeer::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(CcFilesPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $criteria->addJoin(CcFilesPeer::OWNER_ID, CcSubjsPeer::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 CcSubjsRelatedByDbEditedby 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 doCountJoinCcSubjsRelatedByDbEditedby(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; @@ -858,7 +916,73 @@ abstract class BaseCcFilesPeer { * @throws PropelException Any exceptions caught during processing will be * rethrown wrapped into a PropelException. */ - public static function doSelectJoinCcSubjs(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) + public static function doSelectJoinFkOwner(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); + } + + CcFilesPeer::addSelectColumns($criteria); + $startcol = (CcFilesPeer::NUM_COLUMNS - CcFilesPeer::NUM_LAZY_LOAD_COLUMNS); + CcSubjsPeer::addSelectColumns($criteria); + + $criteria->addJoin(CcFilesPeer::OWNER_ID, CcSubjsPeer::ID, $join_behavior); + + $stmt = BasePeer::doSelect($criteria, $con); + $results = array(); + + while ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $key1 = CcFilesPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcFilesPeer::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 = CcFilesPeer::getOMClass(false); + + $obj1 = new $cls(); + $obj1->hydrate($row); + CcFilesPeer::addInstanceToPool($obj1, $key1); + } // if $obj1 already loaded + + $key2 = CcSubjsPeer::getPrimaryKeyHashFromRow($row, $startcol); + if ($key2 !== null) { + $obj2 = CcSubjsPeer::getInstanceFromPool($key2); + if (!$obj2) { + + $cls = CcSubjsPeer::getOMClass(false); + + $obj2 = new $cls(); + $obj2->hydrate($row, $startcol); + CcSubjsPeer::addInstanceToPool($obj2, $key2); + } // if obj2 already loaded + + // Add the $obj1 (CcFiles) to $obj2 (CcSubjs) + $obj2->addCcFilesRelatedByDbOwnerId($obj1); + + } // if joined row was not null + + $results[] = $obj1; + } + $stmt->closeCursor(); + return $results; + } + + + /** + * Selects a collection of CcFiles objects pre-filled with their CcSubjs 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 CcFiles objects. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelectJoinCcSubjsRelatedByDbEditedby(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) { $criteria = clone $criteria; @@ -904,7 +1028,7 @@ abstract class BaseCcFilesPeer { } // if obj2 already loaded // Add the $obj1 (CcFiles) to $obj2 (CcSubjs) - $obj2->addCcFiles($obj1); + $obj2->addCcFilesRelatedByDbEditedby($obj1); } // if joined row was not null @@ -1017,6 +1141,8 @@ abstract class BaseCcFilesPeer { $con = Propel::getConnection(CcFilesPeer::DATABASE_NAME, Propel::CONNECTION_READ); } + $criteria->addJoin(CcFilesPeer::OWNER_ID, CcSubjsPeer::ID, $join_behavior); + $criteria->addJoin(CcFilesPeer::EDITEDBY, CcSubjsPeer::ID, $join_behavior); $criteria->addJoin(CcFilesPeer::DIRECTORY, CcMusicDirsPeer::ID, $join_behavior); @@ -1057,8 +1183,13 @@ abstract class BaseCcFilesPeer { CcSubjsPeer::addSelectColumns($criteria); $startcol3 = $startcol2 + (CcSubjsPeer::NUM_COLUMNS - CcSubjsPeer::NUM_LAZY_LOAD_COLUMNS); + CcSubjsPeer::addSelectColumns($criteria); + $startcol4 = $startcol3 + (CcSubjsPeer::NUM_COLUMNS - CcSubjsPeer::NUM_LAZY_LOAD_COLUMNS); + CcMusicDirsPeer::addSelectColumns($criteria); - $startcol4 = $startcol3 + (CcMusicDirsPeer::NUM_COLUMNS - CcMusicDirsPeer::NUM_LAZY_LOAD_COLUMNS); + $startcol5 = $startcol4 + (CcMusicDirsPeer::NUM_COLUMNS - CcMusicDirsPeer::NUM_LAZY_LOAD_COLUMNS); + + $criteria->addJoin(CcFilesPeer::OWNER_ID, CcSubjsPeer::ID, $join_behavior); $criteria->addJoin(CcFilesPeer::EDITEDBY, CcSubjsPeer::ID, $join_behavior); @@ -1096,25 +1227,43 @@ abstract class BaseCcFilesPeer { } // if obj2 loaded // Add the $obj1 (CcFiles) to the collection in $obj2 (CcSubjs) - $obj2->addCcFiles($obj1); + $obj2->addCcFilesRelatedByDbOwnerId($obj1); + } // if joined row not null + + // Add objects for joined CcSubjs rows + + $key3 = CcSubjsPeer::getPrimaryKeyHashFromRow($row, $startcol3); + if ($key3 !== null) { + $obj3 = CcSubjsPeer::getInstanceFromPool($key3); + if (!$obj3) { + + $cls = CcSubjsPeer::getOMClass(false); + + $obj3 = new $cls(); + $obj3->hydrate($row, $startcol3); + CcSubjsPeer::addInstanceToPool($obj3, $key3); + } // if obj3 loaded + + // Add the $obj1 (CcFiles) to the collection in $obj3 (CcSubjs) + $obj3->addCcFilesRelatedByDbEditedby($obj1); } // if joined row not null // Add objects for joined CcMusicDirs rows - $key3 = CcMusicDirsPeer::getPrimaryKeyHashFromRow($row, $startcol3); - if ($key3 !== null) { - $obj3 = CcMusicDirsPeer::getInstanceFromPool($key3); - if (!$obj3) { + $key4 = CcMusicDirsPeer::getPrimaryKeyHashFromRow($row, $startcol4); + if ($key4 !== null) { + $obj4 = CcMusicDirsPeer::getInstanceFromPool($key4); + if (!$obj4) { $cls = CcMusicDirsPeer::getOMClass(false); - $obj3 = new $cls(); - $obj3->hydrate($row, $startcol3); - CcMusicDirsPeer::addInstanceToPool($obj3, $key3); - } // if obj3 loaded + $obj4 = new $cls(); + $obj4->hydrate($row, $startcol4); + CcMusicDirsPeer::addInstanceToPool($obj4, $key4); + } // if obj4 loaded - // Add the $obj1 (CcFiles) to the collection in $obj3 (CcMusicDirs) - $obj3->addCcFiles($obj1); + // Add the $obj1 (CcFiles) to the collection in $obj4 (CcMusicDirs) + $obj4->addCcFiles($obj1); } // if joined row not null $results[] = $obj1; @@ -1125,7 +1274,7 @@ abstract class BaseCcFilesPeer { /** - * Returns the number of rows matching criteria, joining the related CcSubjs table + * Returns the number of rows matching criteria, joining the related FkOwner table * * @param Criteria $criteria * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. @@ -1133,7 +1282,57 @@ abstract class BaseCcFilesPeer { * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN * @return int Number of matching rows. */ - public static function doCountJoinAllExceptCcSubjs(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) + public static function doCountJoinAllExceptFkOwner(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(CcFilesPeer::TABLE_NAME); + + if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->setDistinct(); + } + + if (!$criteria->hasSelectClause()) { + CcFilesPeer::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(CcFilesPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $criteria->addJoin(CcFilesPeer::DIRECTORY, CcMusicDirsPeer::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 CcSubjsRelatedByDbEditedby 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 doCountJoinAllExceptCcSubjsRelatedByDbEditedby(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; @@ -1210,6 +1409,8 @@ abstract class BaseCcFilesPeer { $con = Propel::getConnection(CcFilesPeer::DATABASE_NAME, Propel::CONNECTION_READ); } + $criteria->addJoin(CcFilesPeer::OWNER_ID, CcSubjsPeer::ID, $join_behavior); + $criteria->addJoin(CcFilesPeer::EDITEDBY, CcSubjsPeer::ID, $join_behavior); $stmt = BasePeer::doCount($criteria, $con); @@ -1225,7 +1426,7 @@ abstract class BaseCcFilesPeer { /** - * Selects a collection of CcFiles objects pre-filled with all related objects except CcSubjs. + * Selects a collection of CcFiles objects pre-filled with all related objects except FkOwner. * * @param Criteria $criteria * @param PropelPDO $con @@ -1234,7 +1435,80 @@ abstract class BaseCcFilesPeer { * @throws PropelException Any exceptions caught during processing will be * rethrown wrapped into a PropelException. */ - public static function doSelectJoinAllExceptCcSubjs(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) + public static function doSelectJoinAllExceptFkOwner(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); + } + + CcFilesPeer::addSelectColumns($criteria); + $startcol2 = (CcFilesPeer::NUM_COLUMNS - CcFilesPeer::NUM_LAZY_LOAD_COLUMNS); + + CcMusicDirsPeer::addSelectColumns($criteria); + $startcol3 = $startcol2 + (CcMusicDirsPeer::NUM_COLUMNS - CcMusicDirsPeer::NUM_LAZY_LOAD_COLUMNS); + + $criteria->addJoin(CcFilesPeer::DIRECTORY, CcMusicDirsPeer::ID, $join_behavior); + + + $stmt = BasePeer::doSelect($criteria, $con); + $results = array(); + + while ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $key1 = CcFilesPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcFilesPeer::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 = CcFilesPeer::getOMClass(false); + + $obj1 = new $cls(); + $obj1->hydrate($row); + CcFilesPeer::addInstanceToPool($obj1, $key1); + } // if obj1 already loaded + + // Add objects for joined CcMusicDirs rows + + $key2 = CcMusicDirsPeer::getPrimaryKeyHashFromRow($row, $startcol2); + if ($key2 !== null) { + $obj2 = CcMusicDirsPeer::getInstanceFromPool($key2); + if (!$obj2) { + + $cls = CcMusicDirsPeer::getOMClass(false); + + $obj2 = new $cls(); + $obj2->hydrate($row, $startcol2); + CcMusicDirsPeer::addInstanceToPool($obj2, $key2); + } // if $obj2 already loaded + + // Add the $obj1 (CcFiles) to the collection in $obj2 (CcMusicDirs) + $obj2->addCcFiles($obj1); + + } // if joined row is not null + + $results[] = $obj1; + } + $stmt->closeCursor(); + return $results; + } + + + /** + * Selects a collection of CcFiles objects pre-filled with all related objects except CcSubjsRelatedByDbEditedby. + * + * @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 CcFiles objects. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelectJoinAllExceptCcSubjsRelatedByDbEditedby(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) { $criteria = clone $criteria; @@ -1324,6 +1598,11 @@ abstract class BaseCcFilesPeer { CcSubjsPeer::addSelectColumns($criteria); $startcol3 = $startcol2 + (CcSubjsPeer::NUM_COLUMNS - CcSubjsPeer::NUM_LAZY_LOAD_COLUMNS); + CcSubjsPeer::addSelectColumns($criteria); + $startcol4 = $startcol3 + (CcSubjsPeer::NUM_COLUMNS - CcSubjsPeer::NUM_LAZY_LOAD_COLUMNS); + + $criteria->addJoin(CcFilesPeer::OWNER_ID, CcSubjsPeer::ID, $join_behavior); + $criteria->addJoin(CcFilesPeer::EDITEDBY, CcSubjsPeer::ID, $join_behavior); @@ -1359,7 +1638,26 @@ abstract class BaseCcFilesPeer { } // if $obj2 already loaded // Add the $obj1 (CcFiles) to the collection in $obj2 (CcSubjs) - $obj2->addCcFiles($obj1); + $obj2->addCcFilesRelatedByDbOwnerId($obj1); + + } // if joined row is not null + + // Add objects for joined CcSubjs rows + + $key3 = CcSubjsPeer::getPrimaryKeyHashFromRow($row, $startcol3); + if ($key3 !== null) { + $obj3 = CcSubjsPeer::getInstanceFromPool($key3); + if (!$obj3) { + + $cls = CcSubjsPeer::getOMClass(false); + + $obj3 = new $cls(); + $obj3->hydrate($row, $startcol3); + CcSubjsPeer::addInstanceToPool($obj3, $key3); + } // if $obj3 already loaded + + // Add the $obj1 (CcFiles) to the collection in $obj3 (CcSubjs) + $obj3->addCcFilesRelatedByDbEditedby($obj1); } // if joined row is not null diff --git a/airtime_mvc/application/models/airtime/om/BaseCcFilesQuery.php b/airtime_mvc/application/models/airtime/om/BaseCcFilesQuery.php index 0d31b43bd..0599719ac 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcFilesQuery.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcFilesQuery.php @@ -7,7 +7,6 @@ * * * @method CcFilesQuery orderByDbId($order = Criteria::ASC) Order by the id column - * @method CcFilesQuery orderByDbGunid($order = Criteria::ASC) Order by the gunid column * @method CcFilesQuery orderByDbName($order = Criteria::ASC) Order by the name column * @method CcFilesQuery orderByDbMime($order = Criteria::ASC) Order by the mime column * @method CcFilesQuery orderByDbFtype($order = Criteria::ASC) Order by the ftype column @@ -69,9 +68,10 @@ * @method CcFilesQuery orderByDbSoundcloudErrorMsg($order = Criteria::ASC) Order by the soundcloud_error_msg column * @method CcFilesQuery orderByDbSoundcloudLinkToFile($order = Criteria::ASC) Order by the soundcloud_link_to_file column * @method CcFilesQuery orderByDbSoundCloundUploadTime($order = Criteria::ASC) Order by the soundcloud_upload_time column + * @method CcFilesQuery orderByDbReplayGain($order = Criteria::ASC) Order by the replay_gain column + * @method CcFilesQuery orderByDbOwnerId($order = Criteria::ASC) Order by the owner_id column * * @method CcFilesQuery groupByDbId() Group by the id column - * @method CcFilesQuery groupByDbGunid() Group by the gunid column * @method CcFilesQuery groupByDbName() Group by the name column * @method CcFilesQuery groupByDbMime() Group by the mime column * @method CcFilesQuery groupByDbFtype() Group by the ftype column @@ -133,14 +133,20 @@ * @method CcFilesQuery groupByDbSoundcloudErrorMsg() Group by the soundcloud_error_msg column * @method CcFilesQuery groupByDbSoundcloudLinkToFile() Group by the soundcloud_link_to_file column * @method CcFilesQuery groupByDbSoundCloundUploadTime() Group by the soundcloud_upload_time column + * @method CcFilesQuery groupByDbReplayGain() Group by the replay_gain column + * @method CcFilesQuery groupByDbOwnerId() Group by the owner_id column * * @method CcFilesQuery leftJoin($relation) Adds a LEFT JOIN clause to the query * @method CcFilesQuery rightJoin($relation) Adds a RIGHT JOIN clause to the query * @method CcFilesQuery innerJoin($relation) Adds a INNER JOIN clause to the query * - * @method CcFilesQuery leftJoinCcSubjs($relationAlias = '') Adds a LEFT JOIN clause to the query using the CcSubjs relation - * @method CcFilesQuery rightJoinCcSubjs($relationAlias = '') Adds a RIGHT JOIN clause to the query using the CcSubjs relation - * @method CcFilesQuery innerJoinCcSubjs($relationAlias = '') Adds a INNER JOIN clause to the query using the CcSubjs relation + * @method CcFilesQuery leftJoinFkOwner($relationAlias = '') Adds a LEFT JOIN clause to the query using the FkOwner relation + * @method CcFilesQuery rightJoinFkOwner($relationAlias = '') Adds a RIGHT JOIN clause to the query using the FkOwner relation + * @method CcFilesQuery innerJoinFkOwner($relationAlias = '') Adds a INNER JOIN clause to the query using the FkOwner relation + * + * @method CcFilesQuery leftJoinCcSubjsRelatedByDbEditedby($relationAlias = '') Adds a LEFT JOIN clause to the query using the CcSubjsRelatedByDbEditedby relation + * @method CcFilesQuery rightJoinCcSubjsRelatedByDbEditedby($relationAlias = '') Adds a RIGHT JOIN clause to the query using the CcSubjsRelatedByDbEditedby relation + * @method CcFilesQuery innerJoinCcSubjsRelatedByDbEditedby($relationAlias = '') Adds a INNER JOIN clause to the query using the CcSubjsRelatedByDbEditedby relation * * @method CcFilesQuery leftJoinCcMusicDirs($relationAlias = '') Adds a LEFT JOIN clause to the query using the CcMusicDirs relation * @method CcFilesQuery rightJoinCcMusicDirs($relationAlias = '') Adds a RIGHT JOIN clause to the query using the CcMusicDirs relation @@ -154,6 +160,10 @@ * @method CcFilesQuery rightJoinCcPlaylistcontents($relationAlias = '') Adds a RIGHT JOIN clause to the query using the CcPlaylistcontents relation * @method CcFilesQuery innerJoinCcPlaylistcontents($relationAlias = '') Adds a INNER JOIN clause to the query using the CcPlaylistcontents relation * + * @method CcFilesQuery leftJoinCcBlockcontents($relationAlias = '') Adds a LEFT JOIN clause to the query using the CcBlockcontents relation + * @method CcFilesQuery rightJoinCcBlockcontents($relationAlias = '') Adds a RIGHT JOIN clause to the query using the CcBlockcontents relation + * @method CcFilesQuery innerJoinCcBlockcontents($relationAlias = '') Adds a INNER JOIN clause to the query using the CcBlockcontents relation + * * @method CcFilesQuery leftJoinCcSchedule($relationAlias = '') Adds a LEFT JOIN clause to the query using the CcSchedule relation * @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 @@ -162,7 +172,6 @@ * @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 * * @method CcFiles findOneByDbId(int $id) Return the first CcFiles filtered by the id column - * @method CcFiles findOneByDbGunid(string $gunid) Return the first CcFiles filtered by the gunid column * @method CcFiles findOneByDbName(string $name) Return the first CcFiles filtered by the name column * @method CcFiles findOneByDbMime(string $mime) Return the first CcFiles filtered by the mime column * @method CcFiles findOneByDbFtype(string $ftype) Return the first CcFiles filtered by the ftype column @@ -188,7 +197,7 @@ * @method CcFiles findOneByDbTrackNumber(int $track_number) Return the first CcFiles filtered by the track_number column * @method CcFiles findOneByDbChannels(int $channels) Return the first CcFiles filtered by the channels column * @method CcFiles findOneByDbUrl(string $url) Return the first CcFiles filtered by the url column - * @method CcFiles findOneByDbBpm(string $bpm) Return the first CcFiles filtered by the bpm column + * @method CcFiles findOneByDbBpm(int $bpm) Return the first CcFiles filtered by the bpm column * @method CcFiles findOneByDbRating(string $rating) Return the first CcFiles filtered by the rating column * @method CcFiles findOneByDbEncodedBy(string $encoded_by) Return the first CcFiles filtered by the encoded_by column * @method CcFiles findOneByDbDiscNumber(string $disc_number) Return the first CcFiles filtered by the disc_number column @@ -224,9 +233,10 @@ * @method CcFiles findOneByDbSoundcloudErrorMsg(string $soundcloud_error_msg) Return the first CcFiles filtered by the soundcloud_error_msg column * @method CcFiles findOneByDbSoundcloudLinkToFile(string $soundcloud_link_to_file) Return the first CcFiles filtered by the soundcloud_link_to_file column * @method CcFiles findOneByDbSoundCloundUploadTime(string $soundcloud_upload_time) Return the first CcFiles filtered by the soundcloud_upload_time column + * @method CcFiles findOneByDbReplayGain(string $replay_gain) Return the first CcFiles filtered by the replay_gain column + * @method CcFiles findOneByDbOwnerId(int $owner_id) Return the first CcFiles filtered by the owner_id column * * @method array findByDbId(int $id) Return CcFiles objects filtered by the id column - * @method array findByDbGunid(string $gunid) Return CcFiles objects filtered by the gunid column * @method array findByDbName(string $name) Return CcFiles objects filtered by the name column * @method array findByDbMime(string $mime) Return CcFiles objects filtered by the mime column * @method array findByDbFtype(string $ftype) Return CcFiles objects filtered by the ftype column @@ -252,7 +262,7 @@ * @method array findByDbTrackNumber(int $track_number) Return CcFiles objects filtered by the track_number column * @method array findByDbChannels(int $channels) Return CcFiles objects filtered by the channels column * @method array findByDbUrl(string $url) Return CcFiles objects filtered by the url column - * @method array findByDbBpm(string $bpm) Return CcFiles objects filtered by the bpm column + * @method array findByDbBpm(int $bpm) Return CcFiles objects filtered by the bpm column * @method array findByDbRating(string $rating) Return CcFiles objects filtered by the rating column * @method array findByDbEncodedBy(string $encoded_by) Return CcFiles objects filtered by the encoded_by column * @method array findByDbDiscNumber(string $disc_number) Return CcFiles objects filtered by the disc_number column @@ -288,6 +298,8 @@ * @method array findByDbSoundcloudErrorMsg(string $soundcloud_error_msg) Return CcFiles objects filtered by the soundcloud_error_msg column * @method array findByDbSoundcloudLinkToFile(string $soundcloud_link_to_file) Return CcFiles objects filtered by the soundcloud_link_to_file column * @method array findByDbSoundCloundUploadTime(string $soundcloud_upload_time) Return CcFiles objects filtered by the soundcloud_upload_time column + * @method array findByDbReplayGain(string $replay_gain) Return CcFiles objects filtered by the replay_gain column + * @method array findByDbOwnerId(int $owner_id) Return CcFiles objects filtered by the owner_id column * * @package propel.generator.airtime.om */ @@ -414,28 +426,6 @@ abstract class BaseCcFilesQuery extends ModelCriteria return $this->addUsingAlias(CcFilesPeer::ID, $dbId, $comparison); } - /** - * Filter the query on the gunid column - * - * @param string $dbGunid 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 CcFilesQuery The current query, for fluid interface - */ - public function filterByDbGunid($dbGunid = null, $comparison = null) - { - if (null === $comparison) { - if (is_array($dbGunid)) { - $comparison = Criteria::IN; - } elseif (preg_match('/[\%\*]/', $dbGunid)) { - $dbGunid = str_replace('*', '%', $dbGunid); - $comparison = Criteria::LIKE; - } - } - return $this->addUsingAlias(CcFilesPeer::GUNID, $dbGunid, $comparison); - } - /** * Filter the query on the name column * @@ -1079,20 +1069,29 @@ abstract class BaseCcFilesQuery extends ModelCriteria /** * Filter the query on the bpm column * - * @param string $dbBpm The value to use as filter. - * Accepts wildcards (* and % trigger a LIKE) + * @param int|array $dbBpm 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 CcFilesQuery The current query, for fluid interface */ public function filterByDbBpm($dbBpm = null, $comparison = null) { - if (null === $comparison) { - if (is_array($dbBpm)) { + if (is_array($dbBpm)) { + $useMinMax = false; + if (isset($dbBpm['min'])) { + $this->addUsingAlias(CcFilesPeer::BPM, $dbBpm['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbBpm['max'])) { + $this->addUsingAlias(CcFilesPeer::BPM, $dbBpm['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { $comparison = Criteria::IN; - } elseif (preg_match('/[\%\*]/', $dbBpm)) { - $dbBpm = str_replace('*', '%', $dbBpm); - $comparison = Criteria::LIKE; } } return $this->addUsingAlias(CcFilesPeer::BPM, $dbBpm, $comparison); @@ -1890,6 +1889,68 @@ abstract class BaseCcFilesQuery extends ModelCriteria return $this->addUsingAlias(CcFilesPeer::SOUNDCLOUD_UPLOAD_TIME, $dbSoundCloundUploadTime, $comparison); } + /** + * Filter the query on the replay_gain column + * + * @param string|array $dbReplayGain 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 CcFilesQuery The current query, for fluid interface + */ + public function filterByDbReplayGain($dbReplayGain = null, $comparison = null) + { + if (is_array($dbReplayGain)) { + $useMinMax = false; + if (isset($dbReplayGain['min'])) { + $this->addUsingAlias(CcFilesPeer::REPLAY_GAIN, $dbReplayGain['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbReplayGain['max'])) { + $this->addUsingAlias(CcFilesPeer::REPLAY_GAIN, $dbReplayGain['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcFilesPeer::REPLAY_GAIN, $dbReplayGain, $comparison); + } + + /** + * Filter the query on the owner_id column + * + * @param int|array $dbOwnerId 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 CcFilesQuery The current query, for fluid interface + */ + public function filterByDbOwnerId($dbOwnerId = null, $comparison = null) + { + if (is_array($dbOwnerId)) { + $useMinMax = false; + if (isset($dbOwnerId['min'])) { + $this->addUsingAlias(CcFilesPeer::OWNER_ID, $dbOwnerId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbOwnerId['max'])) { + $this->addUsingAlias(CcFilesPeer::OWNER_ID, $dbOwnerId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcFilesPeer::OWNER_ID, $dbOwnerId, $comparison); + } + /** * Filter the query by a related CcSubjs object * @@ -1898,24 +1959,24 @@ abstract class BaseCcFilesQuery extends ModelCriteria * * @return CcFilesQuery The current query, for fluid interface */ - public function filterByCcSubjs($ccSubjs, $comparison = null) + public function filterByFkOwner($ccSubjs, $comparison = null) { return $this - ->addUsingAlias(CcFilesPeer::EDITEDBY, $ccSubjs->getDbId(), $comparison); + ->addUsingAlias(CcFilesPeer::OWNER_ID, $ccSubjs->getDbId(), $comparison); } /** - * Adds a JOIN clause to the query using the CcSubjs relation + * Adds a JOIN clause to the query using the FkOwner 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 joinCcSubjs($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + public function joinFkOwner($relationAlias = '', $joinType = Criteria::LEFT_JOIN) { $tableMap = $this->getTableMap(); - $relationMap = $tableMap->getRelation('CcSubjs'); + $relationMap = $tableMap->getRelation('FkOwner'); // create a ModelJoin object for this join $join = new ModelJoin(); @@ -1930,14 +1991,14 @@ abstract class BaseCcFilesQuery extends ModelCriteria $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); $this->addJoinObject($join, $relationAlias); } else { - $this->addJoinObject($join, 'CcSubjs'); + $this->addJoinObject($join, 'FkOwner'); } return $this; } /** - * Use the CcSubjs relation CcSubjs object + * Use the FkOwner relation CcSubjs object * * @see useQuery() * @@ -1947,11 +2008,75 @@ abstract class BaseCcFilesQuery extends ModelCriteria * * @return CcSubjsQuery A secondary query class using the current class as primary query */ - public function useCcSubjsQuery($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + public function useFkOwnerQuery($relationAlias = '', $joinType = Criteria::LEFT_JOIN) { return $this - ->joinCcSubjs($relationAlias, $joinType) - ->useQuery($relationAlias ? $relationAlias : 'CcSubjs', 'CcSubjsQuery'); + ->joinFkOwner($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'FkOwner', 'CcSubjsQuery'); + } + + /** + * Filter the query by a related CcSubjs object + * + * @param CcSubjs $ccSubjs 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 filterByCcSubjsRelatedByDbEditedby($ccSubjs, $comparison = null) + { + return $this + ->addUsingAlias(CcFilesPeer::EDITEDBY, $ccSubjs->getDbId(), $comparison); + } + + /** + * Adds a JOIN clause to the query using the CcSubjsRelatedByDbEditedby 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 joinCcSubjsRelatedByDbEditedby($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('CcSubjsRelatedByDbEditedby'); + + // 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, 'CcSubjsRelatedByDbEditedby'); + } + + return $this; + } + + /** + * Use the CcSubjsRelatedByDbEditedby relation CcSubjs 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 CcSubjsQuery A secondary query class using the current class as primary query + */ + public function useCcSubjsRelatedByDbEditedbyQuery($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + { + return $this + ->joinCcSubjsRelatedByDbEditedby($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'CcSubjsRelatedByDbEditedby', 'CcSubjsQuery'); } /** @@ -2146,6 +2271,70 @@ abstract class BaseCcFilesQuery extends ModelCriteria ->useQuery($relationAlias ? $relationAlias : 'CcPlaylistcontents', 'CcPlaylistcontentsQuery'); } + /** + * Filter the query by a related CcBlockcontents object + * + * @param CcBlockcontents $ccBlockcontents 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 filterByCcBlockcontents($ccBlockcontents, $comparison = null) + { + return $this + ->addUsingAlias(CcFilesPeer::ID, $ccBlockcontents->getDbFileId(), $comparison); + } + + /** + * Adds a JOIN clause to the query using the CcBlockcontents 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 joinCcBlockcontents($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('CcBlockcontents'); + + // 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, 'CcBlockcontents'); + } + + return $this; + } + + /** + * Use the CcBlockcontents relation CcBlockcontents 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 CcBlockcontentsQuery A secondary query class using the current class as primary query + */ + public function useCcBlockcontentsQuery($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + { + return $this + ->joinCcBlockcontents($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'CcBlockcontents', 'CcBlockcontentsQuery'); + } + /** * Filter the query by a related CcSchedule object * diff --git a/airtime_mvc/application/models/airtime/om/BaseCcMusicDirs.php b/airtime_mvc/application/models/airtime/om/BaseCcMusicDirs.php index 4752a822e..f58915945 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcMusicDirs.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcMusicDirs.php @@ -999,10 +999,35 @@ abstract class BaseCcMusicDirs extends BaseObject implements Persistent * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) * @return PropelCollection|array CcFiles[] List of CcFiles objects */ - public function getCcFilessJoinCcSubjs($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) + public function getCcFilessJoinFkOwner($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { $query = CcFilesQuery::create(null, $criteria); - $query->joinWith('CcSubjs', $join_behavior); + $query->joinWith('FkOwner', $join_behavior); + + return $this->getCcFiless($query, $con); + } + + + /** + * If this collection has already been initialized with + * an identical criteria, it returns the collection. + * Otherwise if this CcMusicDirs is new, it will return + * an empty collection; or if this CcMusicDirs has previously + * been saved, it will retrieve related CcFiless 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 CcMusicDirs. + * + * @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 CcFiles[] List of CcFiles objects + */ + public function getCcFilessJoinCcSubjsRelatedByDbEditedby($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $query = CcFilesQuery::create(null, $criteria); + $query->joinWith('CcSubjsRelatedByDbEditedby', $join_behavior); return $this->getCcFiless($query, $con); } diff --git a/airtime_mvc/application/models/airtime/om/BaseCcPlaylist.php b/airtime_mvc/application/models/airtime/om/BaseCcPlaylist.php index db4e4d222..73b081708 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcPlaylist.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcPlaylist.php @@ -1297,6 +1297,31 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent return $this->getCcPlaylistcontentss($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 CcPlaylistcontentss 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 CcPlaylistcontents[] List of CcPlaylistcontents objects + */ + public function getCcPlaylistcontentssJoinCcBlock($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $query = CcPlaylistcontentsQuery::create(null, $criteria); + $query->joinWith('CcBlock', $join_behavior); + + return $this->getCcPlaylistcontentss($query, $con); + } + /** * Clears the current object and sets all attributes to their default values */ diff --git a/airtime_mvc/application/models/airtime/om/BaseCcPlaylistcontents.php b/airtime_mvc/application/models/airtime/om/BaseCcPlaylistcontents.php index 8f823a25e..f8630b15b 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcPlaylistcontents.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcPlaylistcontents.php @@ -42,6 +42,25 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent */ protected $file_id; + /** + * The value for the block_id field. + * @var int + */ + protected $block_id; + + /** + * The value for the stream_id field. + * @var int + */ + protected $stream_id; + + /** + * The value for the type field. + * Note: this column has a database default value of: 0 + * @var int + */ + protected $type; + /** * The value for the position field. * @var int @@ -88,6 +107,11 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent */ protected $aCcFiles; + /** + * @var CcBlock + */ + protected $aCcBlock; + /** * @var CcPlaylist */ @@ -118,6 +142,7 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent */ public function applyDefaultValues() { + $this->type = 0; $this->cliplength = '00:00:00'; $this->cuein = '00:00:00'; $this->cueout = '00:00:00'; @@ -165,6 +190,36 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent return $this->file_id; } + /** + * Get the [block_id] column value. + * + * @return int + */ + public function getDbBlockId() + { + return $this->block_id; + } + + /** + * Get the [stream_id] column value. + * + * @return int + */ + public function getDbStreamId() + { + return $this->stream_id; + } + + /** + * Get the [type] column value. + * + * @return int + */ + public function getDbType() + { + return $this->type; + } + /** * Get the [position] column value. * @@ -339,6 +394,70 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent return $this; } // setDbFileId() + /** + * Set the value of [block_id] column. + * + * @param int $v new value + * @return CcPlaylistcontents 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[] = CcPlaylistcontentsPeer::BLOCK_ID; + } + + if ($this->aCcBlock !== null && $this->aCcBlock->getDbId() !== $v) { + $this->aCcBlock = null; + } + + return $this; + } // setDbBlockId() + + /** + * Set the value of [stream_id] column. + * + * @param int $v new value + * @return CcPlaylistcontents 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[] = CcPlaylistcontentsPeer::STREAM_ID; + } + + return $this; + } // setDbStreamId() + + /** + * Set the value of [type] column. + * + * @param int $v new value + * @return CcPlaylistcontents The current object (for fluent API support) + */ + public function setDbType($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->type !== $v || $this->isNew()) { + $this->type = $v; + $this->modifiedColumns[] = CcPlaylistcontentsPeer::TYPE; + } + + return $this; + } // setDbType() + /** * Set the value of [position] column. * @@ -529,6 +648,10 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent */ public function hasOnlyDefaultValues() { + if ($this->type !== 0) { + return false; + } + if ($this->cliplength !== '00:00:00') { return false; } @@ -574,12 +697,15 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent $this->id = ($row[$startcol + 0] !== null) ? (int) $row[$startcol + 0] : null; $this->playlist_id = ($row[$startcol + 1] !== null) ? (int) $row[$startcol + 1] : null; $this->file_id = ($row[$startcol + 2] !== null) ? (int) $row[$startcol + 2] : null; - $this->position = ($row[$startcol + 3] !== null) ? (int) $row[$startcol + 3] : null; - $this->cliplength = ($row[$startcol + 4] !== null) ? (string) $row[$startcol + 4] : null; - $this->cuein = ($row[$startcol + 5] !== null) ? (string) $row[$startcol + 5] : null; - $this->cueout = ($row[$startcol + 6] !== null) ? (string) $row[$startcol + 6] : null; - $this->fadein = ($row[$startcol + 7] !== null) ? (string) $row[$startcol + 7] : null; - $this->fadeout = ($row[$startcol + 8] !== null) ? (string) $row[$startcol + 8] : null; + $this->block_id = ($row[$startcol + 3] !== null) ? (int) $row[$startcol + 3] : null; + $this->stream_id = ($row[$startcol + 4] !== null) ? (int) $row[$startcol + 4] : null; + $this->type = ($row[$startcol + 5] !== null) ? (int) $row[$startcol + 5] : null; + $this->position = ($row[$startcol + 6] !== null) ? (int) $row[$startcol + 6] : null; + $this->cliplength = ($row[$startcol + 7] !== null) ? (string) $row[$startcol + 7] : null; + $this->cuein = ($row[$startcol + 8] !== null) ? (string) $row[$startcol + 8] : null; + $this->cueout = ($row[$startcol + 9] !== null) ? (string) $row[$startcol + 9] : null; + $this->fadein = ($row[$startcol + 10] !== null) ? (string) $row[$startcol + 10] : null; + $this->fadeout = ($row[$startcol + 11] !== null) ? (string) $row[$startcol + 11] : null; $this->resetModified(); $this->setNew(false); @@ -588,7 +714,7 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent $this->ensureConsistency(); } - return $startcol + 9; // 9 = CcPlaylistcontentsPeer::NUM_COLUMNS - CcPlaylistcontentsPeer::NUM_LAZY_LOAD_COLUMNS). + return $startcol + 12; // 12 = CcPlaylistcontentsPeer::NUM_COLUMNS - CcPlaylistcontentsPeer::NUM_LAZY_LOAD_COLUMNS). } catch (Exception $e) { throw new PropelException("Error populating CcPlaylistcontents object", $e); @@ -617,6 +743,9 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent if ($this->aCcFiles !== null && $this->file_id !== $this->aCcFiles->getDbId()) { $this->aCcFiles = null; } + if ($this->aCcBlock !== null && $this->block_id !== $this->aCcBlock->getDbId()) { + $this->aCcBlock = null; + } } // ensureConsistency /** @@ -657,6 +786,7 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent if ($deep) { // also de-associate any related objects? $this->aCcFiles = null; + $this->aCcBlock = null; $this->aCcPlaylist = null; } // if (deep) } @@ -782,6 +912,13 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent $this->setCcFiles($this->aCcFiles); } + 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); @@ -889,6 +1026,12 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent } } + 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()); @@ -944,21 +1087,30 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent return $this->getDbFileId(); break; case 3: - return $this->getDbPosition(); + return $this->getDbBlockId(); break; case 4: - return $this->getDbCliplength(); + return $this->getDbStreamId(); break; case 5: - return $this->getDbCuein(); + return $this->getDbType(); break; case 6: - return $this->getDbCueout(); + return $this->getDbPosition(); break; case 7: - return $this->getDbFadein(); + 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: @@ -988,17 +1140,23 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent $keys[0] => $this->getDbId(), $keys[1] => $this->getDbPlaylistId(), $keys[2] => $this->getDbFileId(), - $keys[3] => $this->getDbPosition(), - $keys[4] => $this->getDbCliplength(), - $keys[5] => $this->getDbCuein(), - $keys[6] => $this->getDbCueout(), - $keys[7] => $this->getDbFadein(), - $keys[8] => $this->getDbFadeout(), + $keys[3] => $this->getDbBlockId(), + $keys[4] => $this->getDbStreamId(), + $keys[5] => $this->getDbType(), + $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->aCcFiles) { $result['CcFiles'] = $this->aCcFiles->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); } @@ -1043,21 +1201,30 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent $this->setDbFileId($value); break; case 3: - $this->setDbPosition($value); + $this->setDbBlockId($value); break; case 4: - $this->setDbCliplength($value); + $this->setDbStreamId($value); break; case 5: - $this->setDbCuein($value); + $this->setDbType($value); break; case 6: - $this->setDbCueout($value); + $this->setDbPosition($value); break; case 7: - $this->setDbFadein($value); + $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() @@ -1087,12 +1254,15 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent if (array_key_exists($keys[0], $arr)) $this->setDbId($arr[$keys[0]]); if (array_key_exists($keys[1], $arr)) $this->setDbPlaylistId($arr[$keys[1]]); if (array_key_exists($keys[2], $arr)) $this->setDbFileId($arr[$keys[2]]); - if (array_key_exists($keys[3], $arr)) $this->setDbPosition($arr[$keys[3]]); - if (array_key_exists($keys[4], $arr)) $this->setDbCliplength($arr[$keys[4]]); - if (array_key_exists($keys[5], $arr)) $this->setDbCuein($arr[$keys[5]]); - if (array_key_exists($keys[6], $arr)) $this->setDbCueout($arr[$keys[6]]); - if (array_key_exists($keys[7], $arr)) $this->setDbFadein($arr[$keys[7]]); - if (array_key_exists($keys[8], $arr)) $this->setDbFadeout($arr[$keys[8]]); + if (array_key_exists($keys[3], $arr)) $this->setDbBlockId($arr[$keys[3]]); + if (array_key_exists($keys[4], $arr)) $this->setDbStreamId($arr[$keys[4]]); + if (array_key_exists($keys[5], $arr)) $this->setDbType($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]]); } /** @@ -1107,6 +1277,9 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent if ($this->isColumnModified(CcPlaylistcontentsPeer::ID)) $criteria->add(CcPlaylistcontentsPeer::ID, $this->id); if ($this->isColumnModified(CcPlaylistcontentsPeer::PLAYLIST_ID)) $criteria->add(CcPlaylistcontentsPeer::PLAYLIST_ID, $this->playlist_id); if ($this->isColumnModified(CcPlaylistcontentsPeer::FILE_ID)) $criteria->add(CcPlaylistcontentsPeer::FILE_ID, $this->file_id); + if ($this->isColumnModified(CcPlaylistcontentsPeer::BLOCK_ID)) $criteria->add(CcPlaylistcontentsPeer::BLOCK_ID, $this->block_id); + if ($this->isColumnModified(CcPlaylistcontentsPeer::STREAM_ID)) $criteria->add(CcPlaylistcontentsPeer::STREAM_ID, $this->stream_id); + if ($this->isColumnModified(CcPlaylistcontentsPeer::TYPE)) $criteria->add(CcPlaylistcontentsPeer::TYPE, $this->type); if ($this->isColumnModified(CcPlaylistcontentsPeer::POSITION)) $criteria->add(CcPlaylistcontentsPeer::POSITION, $this->position); if ($this->isColumnModified(CcPlaylistcontentsPeer::CLIPLENGTH)) $criteria->add(CcPlaylistcontentsPeer::CLIPLENGTH, $this->cliplength); if ($this->isColumnModified(CcPlaylistcontentsPeer::CUEIN)) $criteria->add(CcPlaylistcontentsPeer::CUEIN, $this->cuein); @@ -1176,6 +1349,9 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent { $copyObj->setDbPlaylistId($this->playlist_id); $copyObj->setDbFileId($this->file_id); + $copyObj->setDbBlockId($this->block_id); + $copyObj->setDbStreamId($this->stream_id); + $copyObj->setDbType($this->type); $copyObj->setDbPosition($this->position); $copyObj->setDbCliplength($this->cliplength); $copyObj->setDbCuein($this->cuein); @@ -1274,6 +1450,55 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent return $this->aCcFiles; } + /** + * Declares an association between this object and a CcBlock object. + * + * @param CcBlock $v + * @return CcPlaylistcontents 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->addCcPlaylistcontents($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->addCcPlaylistcontentss($this); + */ + } + return $this->aCcBlock; + } + /** * Declares an association between this object and a CcPlaylist object. * @@ -1335,6 +1560,9 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent $this->id = null; $this->playlist_id = null; $this->file_id = null; + $this->block_id = null; + $this->stream_id = null; + $this->type = null; $this->position = null; $this->cliplength = null; $this->cuein = null; @@ -1365,6 +1593,7 @@ abstract class BaseCcPlaylistcontents extends BaseObject implements Persistent } // if ($deep) $this->aCcFiles = null; + $this->aCcBlock = null; $this->aCcPlaylist = null; } diff --git a/airtime_mvc/application/models/airtime/om/BaseCcPlaylistcontentsPeer.php b/airtime_mvc/application/models/airtime/om/BaseCcPlaylistcontentsPeer.php index 0bb899b67..d90906568 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcPlaylistcontentsPeer.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcPlaylistcontentsPeer.php @@ -26,7 +26,7 @@ abstract class BaseCcPlaylistcontentsPeer { const TM_CLASS = 'CcPlaylistcontentsTableMap'; /** The total number of columns. */ - const NUM_COLUMNS = 9; + const NUM_COLUMNS = 12; /** The number of lazy-loaded columns. */ const NUM_LAZY_LOAD_COLUMNS = 0; @@ -40,6 +40,15 @@ abstract class BaseCcPlaylistcontentsPeer { /** the column name for the FILE_ID field */ const FILE_ID = 'cc_playlistcontents.FILE_ID'; + /** the column name for the BLOCK_ID field */ + const BLOCK_ID = 'cc_playlistcontents.BLOCK_ID'; + + /** the column name for the STREAM_ID field */ + const STREAM_ID = 'cc_playlistcontents.STREAM_ID'; + + /** the column name for the TYPE field */ + const TYPE = 'cc_playlistcontents.TYPE'; + /** the column name for the POSITION field */ const POSITION = 'cc_playlistcontents.POSITION'; @@ -74,12 +83,12 @@ abstract class BaseCcPlaylistcontentsPeer { * e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id' */ private static $fieldNames = array ( - BasePeer::TYPE_PHPNAME => array ('DbId', 'DbPlaylistId', 'DbFileId', 'DbPosition', 'DbCliplength', 'DbCuein', 'DbCueout', 'DbFadein', 'DbFadeout', ), - BasePeer::TYPE_STUDLYPHPNAME => array ('dbId', 'dbPlaylistId', 'dbFileId', 'dbPosition', 'dbCliplength', 'dbCuein', 'dbCueout', 'dbFadein', 'dbFadeout', ), - BasePeer::TYPE_COLNAME => array (self::ID, self::PLAYLIST_ID, self::FILE_ID, self::POSITION, self::CLIPLENGTH, self::CUEIN, self::CUEOUT, self::FADEIN, self::FADEOUT, ), - BasePeer::TYPE_RAW_COLNAME => array ('ID', 'PLAYLIST_ID', 'FILE_ID', 'POSITION', 'CLIPLENGTH', 'CUEIN', 'CUEOUT', 'FADEIN', 'FADEOUT', ), - BasePeer::TYPE_FIELDNAME => array ('id', 'playlist_id', 'file_id', 'position', 'cliplength', 'cuein', 'cueout', 'fadein', 'fadeout', ), - BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, ) + BasePeer::TYPE_PHPNAME => array ('DbId', 'DbPlaylistId', 'DbFileId', 'DbBlockId', 'DbStreamId', 'DbType', 'DbPosition', 'DbCliplength', 'DbCuein', 'DbCueout', 'DbFadein', 'DbFadeout', ), + BasePeer::TYPE_STUDLYPHPNAME => array ('dbId', 'dbPlaylistId', 'dbFileId', 'dbBlockId', 'dbStreamId', 'dbType', 'dbPosition', 'dbCliplength', 'dbCuein', 'dbCueout', 'dbFadein', 'dbFadeout', ), + BasePeer::TYPE_COLNAME => array (self::ID, self::PLAYLIST_ID, self::FILE_ID, self::BLOCK_ID, self::STREAM_ID, self::TYPE, self::POSITION, self::CLIPLENGTH, self::CUEIN, self::CUEOUT, self::FADEIN, self::FADEOUT, ), + BasePeer::TYPE_RAW_COLNAME => array ('ID', 'PLAYLIST_ID', 'FILE_ID', 'BLOCK_ID', 'STREAM_ID', 'TYPE', 'POSITION', 'CLIPLENGTH', 'CUEIN', 'CUEOUT', 'FADEIN', 'FADEOUT', ), + BasePeer::TYPE_FIELDNAME => array ('id', 'playlist_id', 'file_id', 'block_id', 'stream_id', 'type', 'position', 'cliplength', 'cuein', 'cueout', 'fadein', 'fadeout', ), + BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ) ); /** @@ -89,12 +98,12 @@ abstract class BaseCcPlaylistcontentsPeer { * e.g. self::$fieldNames[BasePeer::TYPE_PHPNAME]['Id'] = 0 */ private static $fieldKeys = array ( - BasePeer::TYPE_PHPNAME => array ('DbId' => 0, 'DbPlaylistId' => 1, 'DbFileId' => 2, 'DbPosition' => 3, 'DbCliplength' => 4, 'DbCuein' => 5, 'DbCueout' => 6, 'DbFadein' => 7, 'DbFadeout' => 8, ), - BasePeer::TYPE_STUDLYPHPNAME => array ('dbId' => 0, 'dbPlaylistId' => 1, 'dbFileId' => 2, 'dbPosition' => 3, 'dbCliplength' => 4, 'dbCuein' => 5, 'dbCueout' => 6, 'dbFadein' => 7, 'dbFadeout' => 8, ), - BasePeer::TYPE_COLNAME => array (self::ID => 0, self::PLAYLIST_ID => 1, self::FILE_ID => 2, self::POSITION => 3, self::CLIPLENGTH => 4, self::CUEIN => 5, self::CUEOUT => 6, self::FADEIN => 7, self::FADEOUT => 8, ), - BasePeer::TYPE_RAW_COLNAME => array ('ID' => 0, 'PLAYLIST_ID' => 1, 'FILE_ID' => 2, 'POSITION' => 3, 'CLIPLENGTH' => 4, 'CUEIN' => 5, 'CUEOUT' => 6, 'FADEIN' => 7, 'FADEOUT' => 8, ), - BasePeer::TYPE_FIELDNAME => array ('id' => 0, 'playlist_id' => 1, 'file_id' => 2, 'position' => 3, 'cliplength' => 4, 'cuein' => 5, 'cueout' => 6, 'fadein' => 7, 'fadeout' => 8, ), - BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, ) + BasePeer::TYPE_PHPNAME => array ('DbId' => 0, 'DbPlaylistId' => 1, 'DbFileId' => 2, 'DbBlockId' => 3, 'DbStreamId' => 4, 'DbType' => 5, 'DbPosition' => 6, 'DbCliplength' => 7, 'DbCuein' => 8, 'DbCueout' => 9, 'DbFadein' => 10, 'DbFadeout' => 11, ), + BasePeer::TYPE_STUDLYPHPNAME => array ('dbId' => 0, 'dbPlaylistId' => 1, 'dbFileId' => 2, 'dbBlockId' => 3, 'dbStreamId' => 4, 'dbType' => 5, 'dbPosition' => 6, 'dbCliplength' => 7, 'dbCuein' => 8, 'dbCueout' => 9, 'dbFadein' => 10, 'dbFadeout' => 11, ), + BasePeer::TYPE_COLNAME => array (self::ID => 0, self::PLAYLIST_ID => 1, self::FILE_ID => 2, self::BLOCK_ID => 3, self::STREAM_ID => 4, self::TYPE => 5, self::POSITION => 6, self::CLIPLENGTH => 7, self::CUEIN => 8, self::CUEOUT => 9, self::FADEIN => 10, self::FADEOUT => 11, ), + BasePeer::TYPE_RAW_COLNAME => array ('ID' => 0, 'PLAYLIST_ID' => 1, 'FILE_ID' => 2, 'BLOCK_ID' => 3, 'STREAM_ID' => 4, 'TYPE' => 5, 'POSITION' => 6, 'CLIPLENGTH' => 7, 'CUEIN' => 8, 'CUEOUT' => 9, 'FADEIN' => 10, 'FADEOUT' => 11, ), + BasePeer::TYPE_FIELDNAME => array ('id' => 0, 'playlist_id' => 1, 'file_id' => 2, 'block_id' => 3, 'stream_id' => 4, 'type' => 5, 'position' => 6, 'cliplength' => 7, 'cuein' => 8, 'cueout' => 9, 'fadein' => 10, 'fadeout' => 11, ), + BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ) ); /** @@ -169,6 +178,9 @@ abstract class BaseCcPlaylistcontentsPeer { $criteria->addSelectColumn(CcPlaylistcontentsPeer::ID); $criteria->addSelectColumn(CcPlaylistcontentsPeer::PLAYLIST_ID); $criteria->addSelectColumn(CcPlaylistcontentsPeer::FILE_ID); + $criteria->addSelectColumn(CcPlaylistcontentsPeer::BLOCK_ID); + $criteria->addSelectColumn(CcPlaylistcontentsPeer::STREAM_ID); + $criteria->addSelectColumn(CcPlaylistcontentsPeer::TYPE); $criteria->addSelectColumn(CcPlaylistcontentsPeer::POSITION); $criteria->addSelectColumn(CcPlaylistcontentsPeer::CLIPLENGTH); $criteria->addSelectColumn(CcPlaylistcontentsPeer::CUEIN); @@ -179,6 +191,9 @@ abstract class BaseCcPlaylistcontentsPeer { $criteria->addSelectColumn($alias . '.ID'); $criteria->addSelectColumn($alias . '.PLAYLIST_ID'); $criteria->addSelectColumn($alias . '.FILE_ID'); + $criteria->addSelectColumn($alias . '.BLOCK_ID'); + $criteria->addSelectColumn($alias . '.STREAM_ID'); + $criteria->addSelectColumn($alias . '.TYPE'); $criteria->addSelectColumn($alias . '.POSITION'); $criteria->addSelectColumn($alias . '.CLIPLENGTH'); $criteria->addSelectColumn($alias . '.CUEIN'); @@ -520,6 +535,56 @@ abstract class BaseCcPlaylistcontentsPeer { } + /** + * 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(CcPlaylistcontentsPeer::TABLE_NAME); + + if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->setDistinct(); + } + + if (!$criteria->hasSelectClause()) { + CcPlaylistcontentsPeer::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(CcPlaylistcontentsPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $criteria->addJoin(CcPlaylistcontentsPeer::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 * @@ -636,6 +701,72 @@ abstract class BaseCcPlaylistcontentsPeer { } + /** + * Selects a collection of CcPlaylistcontents 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 CcPlaylistcontents 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); + } + + CcPlaylistcontentsPeer::addSelectColumns($criteria); + $startcol = (CcPlaylistcontentsPeer::NUM_COLUMNS - CcPlaylistcontentsPeer::NUM_LAZY_LOAD_COLUMNS); + CcBlockPeer::addSelectColumns($criteria); + + $criteria->addJoin(CcPlaylistcontentsPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); + + $stmt = BasePeer::doSelect($criteria, $con); + $results = array(); + + while ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $key1 = CcPlaylistcontentsPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcPlaylistcontentsPeer::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 = CcPlaylistcontentsPeer::getOMClass(false); + + $obj1 = new $cls(); + $obj1->hydrate($row); + CcPlaylistcontentsPeer::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 (CcPlaylistcontents) to $obj2 (CcBlock) + $obj2->addCcPlaylistcontents($obj1); + + } // if joined row was not null + + $results[] = $obj1; + } + $stmt->closeCursor(); + return $results; + } + + /** * Selects a collection of CcPlaylistcontents objects pre-filled with their CcPlaylist objects. * @param Criteria $criteria @@ -740,6 +871,8 @@ abstract class BaseCcPlaylistcontentsPeer { $criteria->addJoin(CcPlaylistcontentsPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + $criteria->addJoin(CcPlaylistcontentsPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); + $criteria->addJoin(CcPlaylistcontentsPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); $stmt = BasePeer::doCount($criteria, $con); @@ -778,11 +911,16 @@ abstract class BaseCcPlaylistcontentsPeer { CcFilesPeer::addSelectColumns($criteria); $startcol3 = $startcol2 + (CcFilesPeer::NUM_COLUMNS - CcFilesPeer::NUM_LAZY_LOAD_COLUMNS); + CcBlockPeer::addSelectColumns($criteria); + $startcol4 = $startcol3 + (CcBlockPeer::NUM_COLUMNS - CcBlockPeer::NUM_LAZY_LOAD_COLUMNS); + CcPlaylistPeer::addSelectColumns($criteria); - $startcol4 = $startcol3 + (CcPlaylistPeer::NUM_COLUMNS - CcPlaylistPeer::NUM_LAZY_LOAD_COLUMNS); + $startcol5 = $startcol4 + (CcPlaylistPeer::NUM_COLUMNS - CcPlaylistPeer::NUM_LAZY_LOAD_COLUMNS); $criteria->addJoin(CcPlaylistcontentsPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + $criteria->addJoin(CcPlaylistcontentsPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); + $criteria->addJoin(CcPlaylistcontentsPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); $stmt = BasePeer::doSelect($criteria, $con); @@ -820,24 +958,42 @@ abstract class BaseCcPlaylistcontentsPeer { $obj2->addCcPlaylistcontents($obj1); } // if joined row not null - // Add objects for joined CcPlaylist rows + // Add objects for joined CcBlock rows - $key3 = CcPlaylistPeer::getPrimaryKeyHashFromRow($row, $startcol3); + $key3 = CcBlockPeer::getPrimaryKeyHashFromRow($row, $startcol3); if ($key3 !== null) { - $obj3 = CcPlaylistPeer::getInstanceFromPool($key3); + $obj3 = CcBlockPeer::getInstanceFromPool($key3); if (!$obj3) { - $cls = CcPlaylistPeer::getOMClass(false); + $cls = CcBlockPeer::getOMClass(false); $obj3 = new $cls(); $obj3->hydrate($row, $startcol3); - CcPlaylistPeer::addInstanceToPool($obj3, $key3); + CcBlockPeer::addInstanceToPool($obj3, $key3); } // if obj3 loaded - // Add the $obj1 (CcPlaylistcontents) to the collection in $obj3 (CcPlaylist) + // Add the $obj1 (CcPlaylistcontents) to the collection in $obj3 (CcBlock) $obj3->addCcPlaylistcontents($obj1); } // if joined row not null + // Add objects for joined CcPlaylist rows + + $key4 = CcPlaylistPeer::getPrimaryKeyHashFromRow($row, $startcol4); + if ($key4 !== null) { + $obj4 = CcPlaylistPeer::getInstanceFromPool($key4); + if (!$obj4) { + + $cls = CcPlaylistPeer::getOMClass(false); + + $obj4 = new $cls(); + $obj4->hydrate($row, $startcol4); + CcPlaylistPeer::addInstanceToPool($obj4, $key4); + } // if obj4 loaded + + // Add the $obj1 (CcPlaylistcontents) to the collection in $obj4 (CcPlaylist) + $obj4->addCcPlaylistcontents($obj1); + } // if joined row not null + $results[] = $obj1; } $stmt->closeCursor(); @@ -881,6 +1037,60 @@ abstract class BaseCcPlaylistcontentsPeer { $con = Propel::getConnection(CcPlaylistcontentsPeer::DATABASE_NAME, Propel::CONNECTION_READ); } + $criteria->addJoin(CcPlaylistcontentsPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); + + $criteria->addJoin(CcPlaylistcontentsPeer::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(CcPlaylistcontentsPeer::TABLE_NAME); + + if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->setDistinct(); + } + + if (!$criteria->hasSelectClause()) { + CcPlaylistcontentsPeer::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(CcPlaylistcontentsPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $criteria->addJoin(CcPlaylistcontentsPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + $criteria->addJoin(CcPlaylistcontentsPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); $stmt = BasePeer::doCount($criteria, $con); @@ -933,6 +1143,8 @@ abstract class BaseCcPlaylistcontentsPeer { $criteria->addJoin(CcPlaylistcontentsPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + $criteria->addJoin(CcPlaylistcontentsPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); + $stmt = BasePeer::doCount($criteria, $con); if ($row = $stmt->fetch(PDO::FETCH_NUM)) { @@ -969,8 +1181,13 @@ abstract class BaseCcPlaylistcontentsPeer { CcPlaylistcontentsPeer::addSelectColumns($criteria); $startcol2 = (CcPlaylistcontentsPeer::NUM_COLUMNS - CcPlaylistcontentsPeer::NUM_LAZY_LOAD_COLUMNS); + CcBlockPeer::addSelectColumns($criteria); + $startcol3 = $startcol2 + (CcBlockPeer::NUM_COLUMNS - CcBlockPeer::NUM_LAZY_LOAD_COLUMNS); + CcPlaylistPeer::addSelectColumns($criteria); - $startcol3 = $startcol2 + (CcPlaylistPeer::NUM_COLUMNS - CcPlaylistPeer::NUM_LAZY_LOAD_COLUMNS); + $startcol4 = $startcol3 + (CcPlaylistPeer::NUM_COLUMNS - CcPlaylistPeer::NUM_LAZY_LOAD_COLUMNS); + + $criteria->addJoin(CcPlaylistcontentsPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); $criteria->addJoin(CcPlaylistcontentsPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); @@ -992,23 +1209,139 @@ abstract class BaseCcPlaylistcontentsPeer { CcPlaylistcontentsPeer::addInstanceToPool($obj1, $key1); } // if obj1 already loaded - // Add objects for joined CcPlaylist rows + // Add objects for joined CcBlock rows - $key2 = CcPlaylistPeer::getPrimaryKeyHashFromRow($row, $startcol2); + $key2 = CcBlockPeer::getPrimaryKeyHashFromRow($row, $startcol2); if ($key2 !== null) { - $obj2 = CcPlaylistPeer::getInstanceFromPool($key2); + $obj2 = CcBlockPeer::getInstanceFromPool($key2); if (!$obj2) { - $cls = CcPlaylistPeer::getOMClass(false); + $cls = CcBlockPeer::getOMClass(false); $obj2 = new $cls(); $obj2->hydrate($row, $startcol2); - CcPlaylistPeer::addInstanceToPool($obj2, $key2); + CcBlockPeer::addInstanceToPool($obj2, $key2); } // if $obj2 already loaded - // Add the $obj1 (CcPlaylistcontents) to the collection in $obj2 (CcPlaylist) + // Add the $obj1 (CcPlaylistcontents) to the collection in $obj2 (CcBlock) $obj2->addCcPlaylistcontents($obj1); + } // if joined row is not null + + // Add objects for joined CcPlaylist rows + + $key3 = CcPlaylistPeer::getPrimaryKeyHashFromRow($row, $startcol3); + if ($key3 !== null) { + $obj3 = CcPlaylistPeer::getInstanceFromPool($key3); + if (!$obj3) { + + $cls = CcPlaylistPeer::getOMClass(false); + + $obj3 = new $cls(); + $obj3->hydrate($row, $startcol3); + CcPlaylistPeer::addInstanceToPool($obj3, $key3); + } // if $obj3 already loaded + + // Add the $obj1 (CcPlaylistcontents) to the collection in $obj3 (CcPlaylist) + $obj3->addCcPlaylistcontents($obj1); + + } // if joined row is not null + + $results[] = $obj1; + } + $stmt->closeCursor(); + return $results; + } + + + /** + * Selects a collection of CcPlaylistcontents 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 CcPlaylistcontents 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); + } + + CcPlaylistcontentsPeer::addSelectColumns($criteria); + $startcol2 = (CcPlaylistcontentsPeer::NUM_COLUMNS - CcPlaylistcontentsPeer::NUM_LAZY_LOAD_COLUMNS); + + CcFilesPeer::addSelectColumns($criteria); + $startcol3 = $startcol2 + (CcFilesPeer::NUM_COLUMNS - CcFilesPeer::NUM_LAZY_LOAD_COLUMNS); + + CcPlaylistPeer::addSelectColumns($criteria); + $startcol4 = $startcol3 + (CcPlaylistPeer::NUM_COLUMNS - CcPlaylistPeer::NUM_LAZY_LOAD_COLUMNS); + + $criteria->addJoin(CcPlaylistcontentsPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + + $criteria->addJoin(CcPlaylistcontentsPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); + + + $stmt = BasePeer::doSelect($criteria, $con); + $results = array(); + + while ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $key1 = CcPlaylistcontentsPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcPlaylistcontentsPeer::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 = CcPlaylistcontentsPeer::getOMClass(false); + + $obj1 = new $cls(); + $obj1->hydrate($row); + CcPlaylistcontentsPeer::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 (CcPlaylistcontents) to the collection in $obj2 (CcFiles) + $obj2->addCcPlaylistcontents($obj1); + + } // if joined row is not null + + // Add objects for joined CcPlaylist rows + + $key3 = CcPlaylistPeer::getPrimaryKeyHashFromRow($row, $startcol3); + if ($key3 !== null) { + $obj3 = CcPlaylistPeer::getInstanceFromPool($key3); + if (!$obj3) { + + $cls = CcPlaylistPeer::getOMClass(false); + + $obj3 = new $cls(); + $obj3->hydrate($row, $startcol3); + CcPlaylistPeer::addInstanceToPool($obj3, $key3); + } // if $obj3 already loaded + + // Add the $obj1 (CcPlaylistcontents) to the collection in $obj3 (CcPlaylist) + $obj3->addCcPlaylistcontents($obj1); + } // if joined row is not null $results[] = $obj1; @@ -1045,8 +1378,13 @@ abstract class BaseCcPlaylistcontentsPeer { CcFilesPeer::addSelectColumns($criteria); $startcol3 = $startcol2 + (CcFilesPeer::NUM_COLUMNS - CcFilesPeer::NUM_LAZY_LOAD_COLUMNS); + CcBlockPeer::addSelectColumns($criteria); + $startcol4 = $startcol3 + (CcBlockPeer::NUM_COLUMNS - CcBlockPeer::NUM_LAZY_LOAD_COLUMNS); + $criteria->addJoin(CcPlaylistcontentsPeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + $criteria->addJoin(CcPlaylistcontentsPeer::BLOCK_ID, CcBlockPeer::ID, $join_behavior); + $stmt = BasePeer::doSelect($criteria, $con); $results = array(); @@ -1082,6 +1420,25 @@ abstract class BaseCcPlaylistcontentsPeer { // Add the $obj1 (CcPlaylistcontents) to the collection in $obj2 (CcFiles) $obj2->addCcPlaylistcontents($obj1); + } // if joined row is not null + + // Add objects for joined CcBlock rows + + $key3 = CcBlockPeer::getPrimaryKeyHashFromRow($row, $startcol3); + if ($key3 !== null) { + $obj3 = CcBlockPeer::getInstanceFromPool($key3); + if (!$obj3) { + + $cls = CcBlockPeer::getOMClass(false); + + $obj3 = new $cls(); + $obj3->hydrate($row, $startcol3); + CcBlockPeer::addInstanceToPool($obj3, $key3); + } // if $obj3 already loaded + + // Add the $obj1 (CcPlaylistcontents) to the collection in $obj3 (CcBlock) + $obj3->addCcPlaylistcontents($obj1); + } // if joined row is not null $results[] = $obj1; diff --git a/airtime_mvc/application/models/airtime/om/BaseCcPlaylistcontentsQuery.php b/airtime_mvc/application/models/airtime/om/BaseCcPlaylistcontentsQuery.php index 8769dfe60..25ea29378 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcPlaylistcontentsQuery.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcPlaylistcontentsQuery.php @@ -9,6 +9,9 @@ * @method CcPlaylistcontentsQuery orderByDbId($order = Criteria::ASC) Order by the id column * @method CcPlaylistcontentsQuery orderByDbPlaylistId($order = Criteria::ASC) Order by the playlist_id column * @method CcPlaylistcontentsQuery orderByDbFileId($order = Criteria::ASC) Order by the file_id column + * @method CcPlaylistcontentsQuery orderByDbBlockId($order = Criteria::ASC) Order by the block_id column + * @method CcPlaylistcontentsQuery orderByDbStreamId($order = Criteria::ASC) Order by the stream_id column + * @method CcPlaylistcontentsQuery orderByDbType($order = Criteria::ASC) Order by the type column * @method CcPlaylistcontentsQuery orderByDbPosition($order = Criteria::ASC) Order by the position column * @method CcPlaylistcontentsQuery orderByDbCliplength($order = Criteria::ASC) Order by the cliplength column * @method CcPlaylistcontentsQuery orderByDbCuein($order = Criteria::ASC) Order by the cuein column @@ -19,6 +22,9 @@ * @method CcPlaylistcontentsQuery groupByDbId() Group by the id column * @method CcPlaylistcontentsQuery groupByDbPlaylistId() Group by the playlist_id column * @method CcPlaylistcontentsQuery groupByDbFileId() Group by the file_id column + * @method CcPlaylistcontentsQuery groupByDbBlockId() Group by the block_id column + * @method CcPlaylistcontentsQuery groupByDbStreamId() Group by the stream_id column + * @method CcPlaylistcontentsQuery groupByDbType() Group by the type column * @method CcPlaylistcontentsQuery groupByDbPosition() Group by the position column * @method CcPlaylistcontentsQuery groupByDbCliplength() Group by the cliplength column * @method CcPlaylistcontentsQuery groupByDbCuein() Group by the cuein column @@ -34,6 +40,10 @@ * @method CcPlaylistcontentsQuery rightJoinCcFiles($relationAlias = '') Adds a RIGHT JOIN clause to the query using the CcFiles relation * @method CcPlaylistcontentsQuery innerJoinCcFiles($relationAlias = '') Adds a INNER JOIN clause to the query using the CcFiles relation * + * @method CcPlaylistcontentsQuery leftJoinCcBlock($relationAlias = '') Adds a LEFT JOIN clause to the query using the CcBlock relation + * @method CcPlaylistcontentsQuery rightJoinCcBlock($relationAlias = '') Adds a RIGHT JOIN clause to the query using the CcBlock relation + * @method CcPlaylistcontentsQuery innerJoinCcBlock($relationAlias = '') Adds a INNER JOIN clause to the query using the CcBlock relation + * * @method CcPlaylistcontentsQuery leftJoinCcPlaylist($relationAlias = '') Adds a LEFT JOIN clause to the query using the CcPlaylist relation * @method CcPlaylistcontentsQuery rightJoinCcPlaylist($relationAlias = '') Adds a RIGHT JOIN clause to the query using the CcPlaylist relation * @method CcPlaylistcontentsQuery innerJoinCcPlaylist($relationAlias = '') Adds a INNER JOIN clause to the query using the CcPlaylist relation @@ -44,6 +54,9 @@ * @method CcPlaylistcontents findOneByDbId(int $id) Return the first CcPlaylistcontents filtered by the id column * @method CcPlaylistcontents findOneByDbPlaylistId(int $playlist_id) Return the first CcPlaylistcontents filtered by the playlist_id column * @method CcPlaylistcontents findOneByDbFileId(int $file_id) Return the first CcPlaylistcontents filtered by the file_id column + * @method CcPlaylistcontents findOneByDbBlockId(int $block_id) Return the first CcPlaylistcontents filtered by the block_id column + * @method CcPlaylistcontents findOneByDbStreamId(int $stream_id) Return the first CcPlaylistcontents filtered by the stream_id column + * @method CcPlaylistcontents findOneByDbType(int $type) Return the first CcPlaylistcontents filtered by the type column * @method CcPlaylistcontents findOneByDbPosition(int $position) Return the first CcPlaylistcontents filtered by the position column * @method CcPlaylistcontents findOneByDbCliplength(string $cliplength) Return the first CcPlaylistcontents filtered by the cliplength column * @method CcPlaylistcontents findOneByDbCuein(string $cuein) Return the first CcPlaylistcontents filtered by the cuein column @@ -54,6 +67,9 @@ * @method array findByDbId(int $id) Return CcPlaylistcontents objects filtered by the id column * @method array findByDbPlaylistId(int $playlist_id) Return CcPlaylistcontents objects filtered by the playlist_id column * @method array findByDbFileId(int $file_id) Return CcPlaylistcontents objects filtered by the file_id column + * @method array findByDbBlockId(int $block_id) Return CcPlaylistcontents objects filtered by the block_id column + * @method array findByDbStreamId(int $stream_id) Return CcPlaylistcontents objects filtered by the stream_id column + * @method array findByDbType(int $type) Return CcPlaylistcontents objects filtered by the type column * @method array findByDbPosition(int $position) Return CcPlaylistcontents objects filtered by the position column * @method array findByDbCliplength(string $cliplength) Return CcPlaylistcontents objects filtered by the cliplength column * @method array findByDbCuein(string $cuein) Return CcPlaylistcontents objects filtered by the cuein column @@ -248,6 +264,99 @@ abstract class BaseCcPlaylistcontentsQuery extends ModelCriteria return $this->addUsingAlias(CcPlaylistcontentsPeer::FILE_ID, $dbFileId, $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 CcPlaylistcontentsQuery 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(CcPlaylistcontentsPeer::BLOCK_ID, $dbBlockId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbBlockId['max'])) { + $this->addUsingAlias(CcPlaylistcontentsPeer::BLOCK_ID, $dbBlockId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcPlaylistcontentsPeer::BLOCK_ID, $dbBlockId, $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 CcPlaylistcontentsQuery 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(CcPlaylistcontentsPeer::STREAM_ID, $dbStreamId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbStreamId['max'])) { + $this->addUsingAlias(CcPlaylistcontentsPeer::STREAM_ID, $dbStreamId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcPlaylistcontentsPeer::STREAM_ID, $dbStreamId, $comparison); + } + + /** + * Filter the query on the type column + * + * @param int|array $dbType 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 CcPlaylistcontentsQuery The current query, for fluid interface + */ + public function filterByDbType($dbType = null, $comparison = null) + { + if (is_array($dbType)) { + $useMinMax = false; + if (isset($dbType['min'])) { + $this->addUsingAlias(CcPlaylistcontentsPeer::TYPE, $dbType['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbType['max'])) { + $this->addUsingAlias(CcPlaylistcontentsPeer::TYPE, $dbType['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcPlaylistcontentsPeer::TYPE, $dbType, $comparison); + } + /** * Filter the query on the position column * @@ -471,6 +580,70 @@ abstract class BaseCcPlaylistcontentsQuery extends ModelCriteria ->useQuery($relationAlias ? $relationAlias : 'CcFiles', 'CcFilesQuery'); } + /** + * 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 CcPlaylistcontentsQuery The current query, for fluid interface + */ + public function filterByCcBlock($ccBlock, $comparison = null) + { + return $this + ->addUsingAlias(CcPlaylistcontentsPeer::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 CcPlaylistcontentsQuery 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 * diff --git a/install_minimal/upgrades/airtime-1.9.0/propel/airtime/om/BaseCcShowSchedule.php b/airtime_mvc/application/models/airtime/om/BaseCcPlaylistcriteria.php similarity index 65% rename from install_minimal/upgrades/airtime-1.9.0/propel/airtime/om/BaseCcShowSchedule.php rename to airtime_mvc/application/models/airtime/om/BaseCcPlaylistcriteria.php index bf8b384e6..52359cc90 100644 --- a/install_minimal/upgrades/airtime-1.9.0/propel/airtime/om/BaseCcShowSchedule.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcPlaylistcriteria.php @@ -2,25 +2,25 @@ /** - * Base class that represents a row from the 'cc_show_schedule' table. + * Base class that represents a row from the 'cc_playlistcriteria' table. * * * * @package propel.generator.airtime.om */ -abstract class BaseCcShowSchedule extends BaseObject implements Persistent +abstract class BaseCcPlaylistcriteria extends BaseObject implements Persistent { /** * Peer class name */ - const PEER = 'CcShowSchedulePeer'; + const PEER = 'CcPlaylistcriteriaPeer'; /** * The Peer class. * Instance provides a convenient way of calling static methods on a class * that calling code may not be able to identify. - * @var CcShowSchedulePeer + * @var CcPlaylistcriteriaPeer */ protected static $peer; @@ -31,27 +31,45 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent protected $id; /** - * The value for the instance_id field. - * @var int + * The value for the criteria field. + * @var string */ - protected $instance_id; + protected $criteria; /** - * The value for the position field. - * @var int + * The value for the modifier field. + * @var string */ - protected $position; + protected $modifier; /** - * The value for the group_id field. - * @var int + * The value for the value field. + * @var string */ - protected $group_id; + protected $value; /** - * @var CcShowInstances + * The value for the extra field. + * @var string */ - protected $aCcShowInstances; + protected $extra; + + /** + * The value for the playlist_id field. + * @var int + */ + protected $playlist_id; + + /** + * The value for the set_number field. + * @var int + */ + protected $set_number; + + /** + * @var CcPlaylist + */ + protected $aCcPlaylist; /** * Flag to prevent endless save loop, if this object is referenced @@ -78,40 +96,70 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent } /** - * Get the [instance_id] column value. + * Get the [criteria] column value. * - * @return int + * @return string */ - public function getDbInstanceId() + public function getDbCriteria() { - return $this->instance_id; + return $this->criteria; } /** - * Get the [position] column value. + * Get the [modifier] column value. * - * @return int + * @return string */ - public function getDbPosition() + public function getDbModifier() { - return $this->position; + return $this->modifier; } /** - * Get the [group_id] column value. + * Get the [value] column value. + * + * @return string + */ + public function getDbValue() + { + return $this->value; + } + + /** + * Get the [extra] column value. + * + * @return string + */ + public function getDbExtra() + { + return $this->extra; + } + + /** + * Get the [playlist_id] column value. * * @return int */ - public function getDbGroupId() + public function getDbPlaylistId() { - return $this->group_id; + return $this->playlist_id; + } + + /** + * Get the [set_number] column value. + * + * @return int + */ + public function getDbSetNumber() + { + return $this->set_number; } /** * Set the value of [id] column. * * @param int $v new value - * @return CcShowSchedule The current object (for fluent API support) + * @return CcPlaylistcriteria The current object (for fluent API support) */ public function setDbId($v) { @@ -121,75 +169,135 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent if ($this->id !== $v) { $this->id = $v; - $this->modifiedColumns[] = CcShowSchedulePeer::ID; + $this->modifiedColumns[] = CcPlaylistcriteriaPeer::ID; } return $this; } // setDbId() /** - * Set the value of [instance_id] column. + * Set the value of [criteria] column. * - * @param int $v new value - * @return CcShowSchedule The current object (for fluent API support) + * @param string $v new value + * @return CcPlaylistcriteria The current object (for fluent API support) */ - public function setDbInstanceId($v) + public function setDbCriteria($v) { if ($v !== null) { - $v = (int) $v; + $v = (string) $v; } - if ($this->instance_id !== $v) { - $this->instance_id = $v; - $this->modifiedColumns[] = CcShowSchedulePeer::INSTANCE_ID; - } - - if ($this->aCcShowInstances !== null && $this->aCcShowInstances->getDbId() !== $v) { - $this->aCcShowInstances = null; + if ($this->criteria !== $v) { + $this->criteria = $v; + $this->modifiedColumns[] = CcPlaylistcriteriaPeer::CRITERIA; } return $this; - } // setDbInstanceId() + } // setDbCriteria() /** - * Set the value of [position] column. + * Set the value of [modifier] column. * - * @param int $v new value - * @return CcShowSchedule The current object (for fluent API support) + * @param string $v new value + * @return CcPlaylistcriteria The current object (for fluent API support) */ - public function setDbPosition($v) + public function setDbModifier($v) { if ($v !== null) { - $v = (int) $v; + $v = (string) $v; } - if ($this->position !== $v) { - $this->position = $v; - $this->modifiedColumns[] = CcShowSchedulePeer::POSITION; + if ($this->modifier !== $v) { + $this->modifier = $v; + $this->modifiedColumns[] = CcPlaylistcriteriaPeer::MODIFIER; } return $this; - } // setDbPosition() + } // setDbModifier() /** - * Set the value of [group_id] column. + * Set the value of [value] column. + * + * @param string $v new value + * @return CcPlaylistcriteria The current object (for fluent API support) + */ + public function setDbValue($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->value !== $v) { + $this->value = $v; + $this->modifiedColumns[] = CcPlaylistcriteriaPeer::VALUE; + } + + return $this; + } // setDbValue() + + /** + * Set the value of [extra] column. + * + * @param string $v new value + * @return CcPlaylistcriteria The current object (for fluent API support) + */ + public function setDbExtra($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->extra !== $v) { + $this->extra = $v; + $this->modifiedColumns[] = CcPlaylistcriteriaPeer::EXTRA; + } + + return $this; + } // setDbExtra() + + /** + * Set the value of [playlist_id] column. * * @param int $v new value - * @return CcShowSchedule The current object (for fluent API support) + * @return CcPlaylistcriteria The current object (for fluent API support) */ - public function setDbGroupId($v) + public function setDbPlaylistId($v) { if ($v !== null) { $v = (int) $v; } - if ($this->group_id !== $v) { - $this->group_id = $v; - $this->modifiedColumns[] = CcShowSchedulePeer::GROUP_ID; + if ($this->playlist_id !== $v) { + $this->playlist_id = $v; + $this->modifiedColumns[] = CcPlaylistcriteriaPeer::PLAYLIST_ID; + } + + if ($this->aCcPlaylist !== null && $this->aCcPlaylist->getDbId() !== $v) { + $this->aCcPlaylist = null; } return $this; - } // setDbGroupId() + } // setDbPlaylistId() + + /** + * Set the value of [set_number] column. + * + * @param int $v new value + * @return CcPlaylistcriteria The current object (for fluent API support) + */ + public function setDbSetNumber($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->set_number !== $v) { + $this->set_number = $v; + $this->modifiedColumns[] = CcPlaylistcriteriaPeer::SET_NUMBER; + } + + return $this; + } // setDbSetNumber() /** * Indicates whether the columns in this object are only set to default values. @@ -224,9 +332,12 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent try { $this->id = ($row[$startcol + 0] !== null) ? (int) $row[$startcol + 0] : null; - $this->instance_id = ($row[$startcol + 1] !== null) ? (int) $row[$startcol + 1] : null; - $this->position = ($row[$startcol + 2] !== null) ? (int) $row[$startcol + 2] : null; - $this->group_id = ($row[$startcol + 3] !== null) ? (int) $row[$startcol + 3] : null; + $this->criteria = ($row[$startcol + 1] !== null) ? (string) $row[$startcol + 1] : null; + $this->modifier = ($row[$startcol + 2] !== null) ? (string) $row[$startcol + 2] : null; + $this->value = ($row[$startcol + 3] !== null) ? (string) $row[$startcol + 3] : null; + $this->extra = ($row[$startcol + 4] !== null) ? (string) $row[$startcol + 4] : null; + $this->playlist_id = ($row[$startcol + 5] !== null) ? (int) $row[$startcol + 5] : null; + $this->set_number = ($row[$startcol + 6] !== null) ? (int) $row[$startcol + 6] : null; $this->resetModified(); $this->setNew(false); @@ -235,10 +346,10 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent $this->ensureConsistency(); } - return $startcol + 4; // 4 = CcShowSchedulePeer::NUM_COLUMNS - CcShowSchedulePeer::NUM_LAZY_LOAD_COLUMNS). + return $startcol + 7; // 7 = CcPlaylistcriteriaPeer::NUM_COLUMNS - CcPlaylistcriteriaPeer::NUM_LAZY_LOAD_COLUMNS). } catch (Exception $e) { - throw new PropelException("Error populating CcShowSchedule object", $e); + throw new PropelException("Error populating CcPlaylistcriteria object", $e); } } @@ -258,8 +369,8 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent public function ensureConsistency() { - if ($this->aCcShowInstances !== null && $this->instance_id !== $this->aCcShowInstances->getDbId()) { - $this->aCcShowInstances = null; + if ($this->aCcPlaylist !== null && $this->playlist_id !== $this->aCcPlaylist->getDbId()) { + $this->aCcPlaylist = null; } } // ensureConsistency @@ -284,13 +395,13 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent } if ($con === null) { - $con = Propel::getConnection(CcShowSchedulePeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcPlaylistcriteriaPeer::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 = CcShowSchedulePeer::doSelectStmt($this->buildPkeyCriteria(), $con); + $stmt = CcPlaylistcriteriaPeer::doSelectStmt($this->buildPkeyCriteria(), $con); $row = $stmt->fetch(PDO::FETCH_NUM); $stmt->closeCursor(); if (!$row) { @@ -300,7 +411,7 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent if ($deep) { // also de-associate any related objects? - $this->aCcShowInstances = null; + $this->aCcPlaylist = null; } // if (deep) } @@ -320,14 +431,14 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent } if ($con === null) { - $con = Propel::getConnection(CcShowSchedulePeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + $con = Propel::getConnection(CcPlaylistcriteriaPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); } $con->beginTransaction(); try { $ret = $this->preDelete($con); if ($ret) { - CcShowScheduleQuery::create() + CcPlaylistcriteriaQuery::create() ->filterByPrimaryKey($this->getPrimaryKey()) ->delete($con); $this->postDelete($con); @@ -362,7 +473,7 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent } if ($con === null) { - $con = Propel::getConnection(CcShowSchedulePeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + $con = Propel::getConnection(CcPlaylistcriteriaPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); } $con->beginTransaction(); @@ -382,7 +493,7 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent $this->postUpdate($con); } $this->postSave($con); - CcShowSchedulePeer::addInstanceToPool($this); + CcPlaylistcriteriaPeer::addInstanceToPool($this); } else { $affectedRows = 0; } @@ -416,23 +527,23 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent // method. This object relates to these object(s) by a // foreign key reference. - if ($this->aCcShowInstances !== null) { - if ($this->aCcShowInstances->isModified() || $this->aCcShowInstances->isNew()) { - $affectedRows += $this->aCcShowInstances->save($con); + if ($this->aCcPlaylist !== null) { + if ($this->aCcPlaylist->isModified() || $this->aCcPlaylist->isNew()) { + $affectedRows += $this->aCcPlaylist->save($con); } - $this->setCcShowInstances($this->aCcShowInstances); + $this->setCcPlaylist($this->aCcPlaylist); } if ($this->isNew() ) { - $this->modifiedColumns[] = CcShowSchedulePeer::ID; + $this->modifiedColumns[] = CcPlaylistcriteriaPeer::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(CcShowSchedulePeer::ID) ) { - throw new PropelException('Cannot insert a value for auto-increment primary key ('.CcShowSchedulePeer::ID.')'); + if ($criteria->keyContainsValue(CcPlaylistcriteriaPeer::ID) ) { + throw new PropelException('Cannot insert a value for auto-increment primary key ('.CcPlaylistcriteriaPeer::ID.')'); } $pk = BasePeer::doInsert($criteria, $con); @@ -440,7 +551,7 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent $this->setDbId($pk); //[IMV] update autoincrement primary key $this->setNew(false); } else { - $affectedRows += CcShowSchedulePeer::doUpdate($this, $con); + $affectedRows += CcPlaylistcriteriaPeer::doUpdate($this, $con); } $this->resetModified(); // [HL] After being saved an object is no longer 'modified' @@ -517,14 +628,14 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent // method. This object relates to these object(s) by a // foreign key reference. - if ($this->aCcShowInstances !== null) { - if (!$this->aCcShowInstances->validate($columns)) { - $failureMap = array_merge($failureMap, $this->aCcShowInstances->getValidationFailures()); + if ($this->aCcPlaylist !== null) { + if (!$this->aCcPlaylist->validate($columns)) { + $failureMap = array_merge($failureMap, $this->aCcPlaylist->getValidationFailures()); } } - if (($retval = CcShowSchedulePeer::doValidate($this, $columns)) !== true) { + if (($retval = CcPlaylistcriteriaPeer::doValidate($this, $columns)) !== true) { $failureMap = array_merge($failureMap, $retval); } @@ -547,7 +658,7 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent */ public function getByName($name, $type = BasePeer::TYPE_PHPNAME) { - $pos = CcShowSchedulePeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); + $pos = CcPlaylistcriteriaPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); $field = $this->getByPosition($pos); return $field; } @@ -566,13 +677,22 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent return $this->getDbId(); break; case 1: - return $this->getDbInstanceId(); + return $this->getDbCriteria(); break; case 2: - return $this->getDbPosition(); + return $this->getDbModifier(); break; case 3: - return $this->getDbGroupId(); + return $this->getDbValue(); + break; + case 4: + return $this->getDbExtra(); + break; + case 5: + return $this->getDbPlaylistId(); + break; + case 6: + return $this->getDbSetNumber(); break; default: return null; @@ -596,16 +716,19 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent */ public function toArray($keyType = BasePeer::TYPE_PHPNAME, $includeLazyLoadColumns = true, $includeForeignObjects = false) { - $keys = CcShowSchedulePeer::getFieldNames($keyType); + $keys = CcPlaylistcriteriaPeer::getFieldNames($keyType); $result = array( $keys[0] => $this->getDbId(), - $keys[1] => $this->getDbInstanceId(), - $keys[2] => $this->getDbPosition(), - $keys[3] => $this->getDbGroupId(), + $keys[1] => $this->getDbCriteria(), + $keys[2] => $this->getDbModifier(), + $keys[3] => $this->getDbValue(), + $keys[4] => $this->getDbExtra(), + $keys[5] => $this->getDbPlaylistId(), + $keys[6] => $this->getDbSetNumber(), ); if ($includeForeignObjects) { - if (null !== $this->aCcShowInstances) { - $result['CcShowInstances'] = $this->aCcShowInstances->toArray($keyType, $includeLazyLoadColumns, true); + if (null !== $this->aCcPlaylist) { + $result['CcPlaylist'] = $this->aCcPlaylist->toArray($keyType, $includeLazyLoadColumns, true); } } return $result; @@ -623,7 +746,7 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent */ public function setByName($name, $value, $type = BasePeer::TYPE_PHPNAME) { - $pos = CcShowSchedulePeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); + $pos = CcPlaylistcriteriaPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); return $this->setByPosition($pos, $value); } @@ -642,13 +765,22 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent $this->setDbId($value); break; case 1: - $this->setDbInstanceId($value); + $this->setDbCriteria($value); break; case 2: - $this->setDbPosition($value); + $this->setDbModifier($value); break; case 3: - $this->setDbGroupId($value); + $this->setDbValue($value); + break; + case 4: + $this->setDbExtra($value); + break; + case 5: + $this->setDbPlaylistId($value); + break; + case 6: + $this->setDbSetNumber($value); break; } // switch() } @@ -672,12 +804,15 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent */ public function fromArray($arr, $keyType = BasePeer::TYPE_PHPNAME) { - $keys = CcShowSchedulePeer::getFieldNames($keyType); + $keys = CcPlaylistcriteriaPeer::getFieldNames($keyType); if (array_key_exists($keys[0], $arr)) $this->setDbId($arr[$keys[0]]); - if (array_key_exists($keys[1], $arr)) $this->setDbInstanceId($arr[$keys[1]]); - if (array_key_exists($keys[2], $arr)) $this->setDbPosition($arr[$keys[2]]); - if (array_key_exists($keys[3], $arr)) $this->setDbGroupId($arr[$keys[3]]); + if (array_key_exists($keys[1], $arr)) $this->setDbCriteria($arr[$keys[1]]); + if (array_key_exists($keys[2], $arr)) $this->setDbModifier($arr[$keys[2]]); + if (array_key_exists($keys[3], $arr)) $this->setDbValue($arr[$keys[3]]); + if (array_key_exists($keys[4], $arr)) $this->setDbExtra($arr[$keys[4]]); + if (array_key_exists($keys[5], $arr)) $this->setDbPlaylistId($arr[$keys[5]]); + if (array_key_exists($keys[6], $arr)) $this->setDbSetNumber($arr[$keys[6]]); } /** @@ -687,12 +822,15 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent */ public function buildCriteria() { - $criteria = new Criteria(CcShowSchedulePeer::DATABASE_NAME); + $criteria = new Criteria(CcPlaylistcriteriaPeer::DATABASE_NAME); - if ($this->isColumnModified(CcShowSchedulePeer::ID)) $criteria->add(CcShowSchedulePeer::ID, $this->id); - if ($this->isColumnModified(CcShowSchedulePeer::INSTANCE_ID)) $criteria->add(CcShowSchedulePeer::INSTANCE_ID, $this->instance_id); - if ($this->isColumnModified(CcShowSchedulePeer::POSITION)) $criteria->add(CcShowSchedulePeer::POSITION, $this->position); - if ($this->isColumnModified(CcShowSchedulePeer::GROUP_ID)) $criteria->add(CcShowSchedulePeer::GROUP_ID, $this->group_id); + if ($this->isColumnModified(CcPlaylistcriteriaPeer::ID)) $criteria->add(CcPlaylistcriteriaPeer::ID, $this->id); + if ($this->isColumnModified(CcPlaylistcriteriaPeer::CRITERIA)) $criteria->add(CcPlaylistcriteriaPeer::CRITERIA, $this->criteria); + if ($this->isColumnModified(CcPlaylistcriteriaPeer::MODIFIER)) $criteria->add(CcPlaylistcriteriaPeer::MODIFIER, $this->modifier); + if ($this->isColumnModified(CcPlaylistcriteriaPeer::VALUE)) $criteria->add(CcPlaylistcriteriaPeer::VALUE, $this->value); + if ($this->isColumnModified(CcPlaylistcriteriaPeer::EXTRA)) $criteria->add(CcPlaylistcriteriaPeer::EXTRA, $this->extra); + if ($this->isColumnModified(CcPlaylistcriteriaPeer::PLAYLIST_ID)) $criteria->add(CcPlaylistcriteriaPeer::PLAYLIST_ID, $this->playlist_id); + if ($this->isColumnModified(CcPlaylistcriteriaPeer::SET_NUMBER)) $criteria->add(CcPlaylistcriteriaPeer::SET_NUMBER, $this->set_number); return $criteria; } @@ -707,8 +845,8 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent */ public function buildPkeyCriteria() { - $criteria = new Criteria(CcShowSchedulePeer::DATABASE_NAME); - $criteria->add(CcShowSchedulePeer::ID, $this->id); + $criteria = new Criteria(CcPlaylistcriteriaPeer::DATABASE_NAME); + $criteria->add(CcPlaylistcriteriaPeer::ID, $this->id); return $criteria; } @@ -748,15 +886,18 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent * If desired, this method can also make copies of all associated (fkey referrers) * objects. * - * @param object $copyObj An object of CcShowSchedule (or compatible) type. + * @param object $copyObj An object of CcPlaylistcriteria (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->setDbInstanceId($this->instance_id); - $copyObj->setDbPosition($this->position); - $copyObj->setDbGroupId($this->group_id); + $copyObj->setDbCriteria($this->criteria); + $copyObj->setDbModifier($this->modifier); + $copyObj->setDbValue($this->value); + $copyObj->setDbExtra($this->extra); + $copyObj->setDbPlaylistId($this->playlist_id); + $copyObj->setDbSetNumber($this->set_number); $copyObj->setNew(true); $copyObj->setDbId(NULL); // this is a auto-increment column, so set to default value @@ -771,7 +912,7 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent * objects. * * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. - * @return CcShowSchedule Clone of current object. + * @return CcPlaylistcriteria Clone of current object. * @throws PropelException */ public function copy($deepCopy = false) @@ -790,37 +931,37 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent * same instance for all member of this class. The method could therefore * be static, but this would prevent one from overriding the behavior. * - * @return CcShowSchedulePeer + * @return CcPlaylistcriteriaPeer */ public function getPeer() { if (self::$peer === null) { - self::$peer = new CcShowSchedulePeer(); + self::$peer = new CcPlaylistcriteriaPeer(); } return self::$peer; } /** - * Declares an association between this object and a CcShowInstances object. + * Declares an association between this object and a CcPlaylist object. * - * @param CcShowInstances $v - * @return CcShowSchedule The current object (for fluent API support) + * @param CcPlaylist $v + * @return CcPlaylistcriteria The current object (for fluent API support) * @throws PropelException */ - public function setCcShowInstances(CcShowInstances $v = null) + public function setCcPlaylist(CcPlaylist $v = null) { if ($v === null) { - $this->setDbInstanceId(NULL); + $this->setDbPlaylistId(NULL); } else { - $this->setDbInstanceId($v->getDbId()); + $this->setDbPlaylistId($v->getDbId()); } - $this->aCcShowInstances = $v; + $this->aCcPlaylist = $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 this object has already been added to the CcPlaylist object, it will not be re-added. if ($v !== null) { - $v->addCcShowSchedule($this); + $v->addCcPlaylistcriteria($this); } return $this; @@ -828,25 +969,25 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent /** - * Get the associated CcShowInstances object + * Get the associated CcPlaylist object * * @param PropelPDO Optional Connection object. - * @return CcShowInstances The associated CcShowInstances object. + * @return CcPlaylist The associated CcPlaylist object. * @throws PropelException */ - public function getCcShowInstances(PropelPDO $con = null) + public function getCcPlaylist(PropelPDO $con = null) { - if ($this->aCcShowInstances === null && ($this->instance_id !== null)) { - $this->aCcShowInstances = CcShowInstancesQuery::create()->findPk($this->instance_id, $con); + 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->aCcShowInstances->addCcShowSchedules($this); + $this->aCcPlaylist->addCcPlaylistcriterias($this); */ } - return $this->aCcShowInstances; + return $this->aCcPlaylist; } /** @@ -855,9 +996,12 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent public function clear() { $this->id = null; - $this->instance_id = null; - $this->position = null; - $this->group_id = null; + $this->criteria = null; + $this->modifier = null; + $this->value = null; + $this->extra = null; + $this->playlist_id = null; + $this->set_number = null; $this->alreadyInSave = false; $this->alreadyInValidation = false; $this->clearAllReferences(); @@ -880,7 +1024,7 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent if ($deep) { } // if ($deep) - $this->aCcShowInstances = null; + $this->aCcPlaylist = null; } /** @@ -902,4 +1046,4 @@ abstract class BaseCcShowSchedule extends BaseObject implements Persistent throw new PropelException('Call to undefined method: ' . $name); } -} // BaseCcShowSchedule +} // BaseCcPlaylistcriteria diff --git a/install_minimal/upgrades/airtime-1.9.0/propel/airtime/om/BaseCcPlaylistPeer.php b/airtime_mvc/application/models/airtime/om/BaseCcPlaylistcriteriaPeer.php similarity index 67% rename from install_minimal/upgrades/airtime-1.9.0/propel/airtime/om/BaseCcPlaylistPeer.php rename to airtime_mvc/application/models/airtime/om/BaseCcPlaylistcriteriaPeer.php index 0e338bc39..8ab217965 100644 --- a/install_minimal/upgrades/airtime-1.9.0/propel/airtime/om/BaseCcPlaylistPeer.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcPlaylistcriteriaPeer.php @@ -2,64 +2,61 @@ /** - * Base static class for performing query and update operations on the 'cc_playlist' table. + * Base static class for performing query and update operations on the 'cc_playlistcriteria' table. * * * * @package propel.generator.airtime.om */ -abstract class BaseCcPlaylistPeer { +abstract class BaseCcPlaylistcriteriaPeer { /** the default database name for this class */ const DATABASE_NAME = 'airtime'; /** the table name for this class */ - const TABLE_NAME = 'cc_playlist'; + const TABLE_NAME = 'cc_playlistcriteria'; /** the related Propel class for this table */ - const OM_CLASS = 'CcPlaylist'; + const OM_CLASS = 'CcPlaylistcriteria'; /** A class that can be returned by this peer. */ - const CLASS_DEFAULT = 'airtime.CcPlaylist'; + const CLASS_DEFAULT = 'airtime.CcPlaylistcriteria'; /** the related TableMap class for this table */ - const TM_CLASS = 'CcPlaylistTableMap'; + const TM_CLASS = 'CcPlaylistcriteriaTableMap'; /** The total number of columns. */ - const NUM_COLUMNS = 8; + const NUM_COLUMNS = 7; /** The number of lazy-loaded columns. */ const NUM_LAZY_LOAD_COLUMNS = 0; /** the column name for the ID field */ - const ID = 'cc_playlist.ID'; + const ID = 'cc_playlistcriteria.ID'; - /** the column name for the NAME field */ - const NAME = 'cc_playlist.NAME'; + /** the column name for the CRITERIA field */ + const CRITERIA = 'cc_playlistcriteria.CRITERIA'; - /** the column name for the STATE field */ - const STATE = 'cc_playlist.STATE'; + /** the column name for the MODIFIER field */ + const MODIFIER = 'cc_playlistcriteria.MODIFIER'; - /** the column name for the CURRENTLYACCESSING field */ - const CURRENTLYACCESSING = 'cc_playlist.CURRENTLYACCESSING'; + /** the column name for the VALUE field */ + const VALUE = 'cc_playlistcriteria.VALUE'; - /** the column name for the EDITEDBY field */ - const EDITEDBY = 'cc_playlist.EDITEDBY'; + /** the column name for the EXTRA field */ + const EXTRA = 'cc_playlistcriteria.EXTRA'; - /** the column name for the MTIME field */ - const MTIME = 'cc_playlist.MTIME'; + /** the column name for the PLAYLIST_ID field */ + const PLAYLIST_ID = 'cc_playlistcriteria.PLAYLIST_ID'; - /** the column name for the CREATOR field */ - const CREATOR = 'cc_playlist.CREATOR'; - - /** the column name for the DESCRIPTION field */ - const DESCRIPTION = 'cc_playlist.DESCRIPTION'; + /** the column name for the SET_NUMBER field */ + const SET_NUMBER = 'cc_playlistcriteria.SET_NUMBER'; /** - * An identiy map to hold any loaded instances of CcPlaylist objects. + * An identiy map to hold any loaded instances of CcPlaylistcriteria objects. * This must be public so that other peer classes can access this when hydrating from JOIN * queries. - * @var array CcPlaylist[] + * @var array CcPlaylistcriteria[] */ public static $instances = array(); @@ -71,12 +68,12 @@ abstract class BaseCcPlaylistPeer { * e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id' */ private static $fieldNames = array ( - BasePeer::TYPE_PHPNAME => array ('DbId', 'DbName', 'DbState', 'DbCurrentlyaccessing', 'DbEditedby', 'DbMtime', 'DbCreator', 'DbDescription', ), - BasePeer::TYPE_STUDLYPHPNAME => array ('dbId', 'dbName', 'dbState', 'dbCurrentlyaccessing', 'dbEditedby', 'dbMtime', 'dbCreator', 'dbDescription', ), - BasePeer::TYPE_COLNAME => array (self::ID, self::NAME, self::STATE, self::CURRENTLYACCESSING, self::EDITEDBY, self::MTIME, self::CREATOR, self::DESCRIPTION, ), - BasePeer::TYPE_RAW_COLNAME => array ('ID', 'NAME', 'STATE', 'CURRENTLYACCESSING', 'EDITEDBY', 'MTIME', 'CREATOR', 'DESCRIPTION', ), - BasePeer::TYPE_FIELDNAME => array ('id', 'name', 'state', 'currentlyaccessing', 'editedby', 'mtime', 'creator', 'description', ), - BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, ) + BasePeer::TYPE_PHPNAME => array ('DbId', 'DbCriteria', 'DbModifier', 'DbValue', 'DbExtra', 'DbPlaylistId', 'DbSetNumber', ), + BasePeer::TYPE_STUDLYPHPNAME => array ('dbId', 'dbCriteria', 'dbModifier', 'dbValue', 'dbExtra', 'dbPlaylistId', 'dbSetNumber', ), + BasePeer::TYPE_COLNAME => array (self::ID, self::CRITERIA, self::MODIFIER, self::VALUE, self::EXTRA, self::PLAYLIST_ID, self::SET_NUMBER, ), + BasePeer::TYPE_RAW_COLNAME => array ('ID', 'CRITERIA', 'MODIFIER', 'VALUE', 'EXTRA', 'PLAYLIST_ID', 'SET_NUMBER', ), + BasePeer::TYPE_FIELDNAME => array ('id', 'criteria', 'modifier', 'value', 'extra', 'playlist_id', 'set_number', ), + BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, ) ); /** @@ -86,12 +83,12 @@ abstract class BaseCcPlaylistPeer { * e.g. self::$fieldNames[BasePeer::TYPE_PHPNAME]['Id'] = 0 */ private static $fieldKeys = array ( - BasePeer::TYPE_PHPNAME => array ('DbId' => 0, 'DbName' => 1, 'DbState' => 2, 'DbCurrentlyaccessing' => 3, 'DbEditedby' => 4, 'DbMtime' => 5, 'DbCreator' => 6, 'DbDescription' => 7, ), - BasePeer::TYPE_STUDLYPHPNAME => array ('dbId' => 0, 'dbName' => 1, 'dbState' => 2, 'dbCurrentlyaccessing' => 3, 'dbEditedby' => 4, 'dbMtime' => 5, 'dbCreator' => 6, 'dbDescription' => 7, ), - BasePeer::TYPE_COLNAME => array (self::ID => 0, self::NAME => 1, self::STATE => 2, self::CURRENTLYACCESSING => 3, self::EDITEDBY => 4, self::MTIME => 5, self::CREATOR => 6, self::DESCRIPTION => 7, ), - BasePeer::TYPE_RAW_COLNAME => array ('ID' => 0, 'NAME' => 1, 'STATE' => 2, 'CURRENTLYACCESSING' => 3, 'EDITEDBY' => 4, 'MTIME' => 5, 'CREATOR' => 6, 'DESCRIPTION' => 7, ), - BasePeer::TYPE_FIELDNAME => array ('id' => 0, 'name' => 1, 'state' => 2, 'currentlyaccessing' => 3, 'editedby' => 4, 'mtime' => 5, 'creator' => 6, 'description' => 7, ), - BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, ) + BasePeer::TYPE_PHPNAME => array ('DbId' => 0, 'DbCriteria' => 1, 'DbModifier' => 2, 'DbValue' => 3, 'DbExtra' => 4, 'DbPlaylistId' => 5, 'DbSetNumber' => 6, ), + BasePeer::TYPE_STUDLYPHPNAME => array ('dbId' => 0, 'dbCriteria' => 1, 'dbModifier' => 2, 'dbValue' => 3, 'dbExtra' => 4, 'dbPlaylistId' => 5, 'dbSetNumber' => 6, ), + BasePeer::TYPE_COLNAME => array (self::ID => 0, self::CRITERIA => 1, self::MODIFIER => 2, self::VALUE => 3, self::EXTRA => 4, self::PLAYLIST_ID => 5, self::SET_NUMBER => 6, ), + BasePeer::TYPE_RAW_COLNAME => array ('ID' => 0, 'CRITERIA' => 1, 'MODIFIER' => 2, 'VALUE' => 3, 'EXTRA' => 4, 'PLAYLIST_ID' => 5, 'SET_NUMBER' => 6, ), + BasePeer::TYPE_FIELDNAME => array ('id' => 0, 'criteria' => 1, 'modifier' => 2, 'value' => 3, 'extra' => 4, 'playlist_id' => 5, 'set_number' => 6, ), + BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, ) ); /** @@ -140,12 +137,12 @@ abstract class BaseCcPlaylistPeer { * $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. CcPlaylistPeer::COLUMN_NAME). + * @param string $column The column name for current table. (i.e. CcPlaylistcriteriaPeer::COLUMN_NAME). * @return string */ public static function alias($alias, $column) { - return str_replace(CcPlaylistPeer::TABLE_NAME.'.', $alias.'.', $column); + return str_replace(CcPlaylistcriteriaPeer::TABLE_NAME.'.', $alias.'.', $column); } /** @@ -163,23 +160,21 @@ abstract class BaseCcPlaylistPeer { public static function addSelectColumns(Criteria $criteria, $alias = null) { if (null === $alias) { - $criteria->addSelectColumn(CcPlaylistPeer::ID); - $criteria->addSelectColumn(CcPlaylistPeer::NAME); - $criteria->addSelectColumn(CcPlaylistPeer::STATE); - $criteria->addSelectColumn(CcPlaylistPeer::CURRENTLYACCESSING); - $criteria->addSelectColumn(CcPlaylistPeer::EDITEDBY); - $criteria->addSelectColumn(CcPlaylistPeer::MTIME); - $criteria->addSelectColumn(CcPlaylistPeer::CREATOR); - $criteria->addSelectColumn(CcPlaylistPeer::DESCRIPTION); + $criteria->addSelectColumn(CcPlaylistcriteriaPeer::ID); + $criteria->addSelectColumn(CcPlaylistcriteriaPeer::CRITERIA); + $criteria->addSelectColumn(CcPlaylistcriteriaPeer::MODIFIER); + $criteria->addSelectColumn(CcPlaylistcriteriaPeer::VALUE); + $criteria->addSelectColumn(CcPlaylistcriteriaPeer::EXTRA); + $criteria->addSelectColumn(CcPlaylistcriteriaPeer::PLAYLIST_ID); + $criteria->addSelectColumn(CcPlaylistcriteriaPeer::SET_NUMBER); } else { $criteria->addSelectColumn($alias . '.ID'); - $criteria->addSelectColumn($alias . '.NAME'); - $criteria->addSelectColumn($alias . '.STATE'); - $criteria->addSelectColumn($alias . '.CURRENTLYACCESSING'); - $criteria->addSelectColumn($alias . '.EDITEDBY'); - $criteria->addSelectColumn($alias . '.MTIME'); - $criteria->addSelectColumn($alias . '.CREATOR'); - $criteria->addSelectColumn($alias . '.DESCRIPTION'); + $criteria->addSelectColumn($alias . '.CRITERIA'); + $criteria->addSelectColumn($alias . '.MODIFIER'); + $criteria->addSelectColumn($alias . '.VALUE'); + $criteria->addSelectColumn($alias . '.EXTRA'); + $criteria->addSelectColumn($alias . '.PLAYLIST_ID'); + $criteria->addSelectColumn($alias . '.SET_NUMBER'); } } @@ -199,21 +194,21 @@ abstract class BaseCcPlaylistPeer { // 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(CcPlaylistPeer::TABLE_NAME); + $criteria->setPrimaryTableName(CcPlaylistcriteriaPeer::TABLE_NAME); if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { $criteria->setDistinct(); } if (!$criteria->hasSelectClause()) { - CcPlaylistPeer::addSelectColumns($criteria); + CcPlaylistcriteriaPeer::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(CcPlaylistPeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcPlaylistcriteriaPeer::DATABASE_NAME, Propel::CONNECTION_READ); } // BasePeer returns a PDOStatement $stmt = BasePeer::doCount($criteria, $con); @@ -231,7 +226,7 @@ abstract class BaseCcPlaylistPeer { * * @param Criteria $criteria object used to create the SELECT statement. * @param PropelPDO $con - * @return CcPlaylist + * @return CcPlaylistcriteria * @throws PropelException Any exceptions caught during processing will be * rethrown wrapped into a PropelException. */ @@ -239,7 +234,7 @@ abstract class BaseCcPlaylistPeer { { $critcopy = clone $criteria; $critcopy->setLimit(1); - $objects = CcPlaylistPeer::doSelect($critcopy, $con); + $objects = CcPlaylistcriteriaPeer::doSelect($critcopy, $con); if ($objects) { return $objects[0]; } @@ -256,7 +251,7 @@ abstract class BaseCcPlaylistPeer { */ public static function doSelect(Criteria $criteria, PropelPDO $con = null) { - return CcPlaylistPeer::populateObjects(CcPlaylistPeer::doSelectStmt($criteria, $con)); + return CcPlaylistcriteriaPeer::populateObjects(CcPlaylistcriteriaPeer::doSelectStmt($criteria, $con)); } /** * Prepares the Criteria object and uses the parent doSelect() method to execute a PDOStatement. @@ -274,12 +269,12 @@ abstract class BaseCcPlaylistPeer { public static function doSelectStmt(Criteria $criteria, PropelPDO $con = null) { if ($con === null) { - $con = Propel::getConnection(CcPlaylistPeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcPlaylistcriteriaPeer::DATABASE_NAME, Propel::CONNECTION_READ); } if (!$criteria->hasSelectClause()) { $criteria = clone $criteria; - CcPlaylistPeer::addSelectColumns($criteria); + CcPlaylistcriteriaPeer::addSelectColumns($criteria); } // Set the correct dbName @@ -297,10 +292,10 @@ abstract class BaseCcPlaylistPeer { * to the cache in order to ensure that the same objects are always returned by doSelect*() * and retrieveByPK*() calls. * - * @param CcPlaylist $value A CcPlaylist object. + * @param CcPlaylistcriteria $value A CcPlaylistcriteria object. * @param string $key (optional) key to use for instance map (for performance boost if key was already calculated externally). */ - public static function addInstanceToPool(CcPlaylist $obj, $key = null) + public static function addInstanceToPool(CcPlaylistcriteria $obj, $key = null) { if (Propel::isInstancePoolingEnabled()) { if ($key === null) { @@ -318,18 +313,18 @@ abstract class BaseCcPlaylistPeer { * 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 CcPlaylist object or a primary key value. + * @param mixed $value A CcPlaylistcriteria object or a primary key value. */ public static function removeInstanceFromPool($value) { if (Propel::isInstancePoolingEnabled() && $value !== null) { - if (is_object($value) && $value instanceof CcPlaylist) { + if (is_object($value) && $value instanceof CcPlaylistcriteria) { $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 CcPlaylist object; got " . (is_object($value) ? get_class($value) . ' object.' : var_export($value,true))); + $e = new PropelException("Invalid value passed to removeInstanceFromPool(). Expected primary key or CcPlaylistcriteria object; got " . (is_object($value) ? get_class($value) . ' object.' : var_export($value,true))); throw $e; } @@ -344,7 +339,7 @@ abstract class BaseCcPlaylistPeer { * 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 CcPlaylist Found object or NULL if 1) no instance exists for specified key or 2) instance pooling has been disabled. + * @return CcPlaylistcriteria 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) @@ -368,14 +363,11 @@ abstract class BaseCcPlaylistPeer { } /** - * Method to invalidate the instance pool of all tables related to cc_playlist + * Method to invalidate the instance pool of all tables related to cc_playlistcriteria * by a foreign key with ON DELETE CASCADE */ public static function clearRelatedInstancePool() { - // Invalidate objects in CcPlaylistcontentsPeer instance pool, - // since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule. - CcPlaylistcontentsPeer::clearInstancePool(); } /** @@ -423,11 +415,11 @@ abstract class BaseCcPlaylistPeer { $results = array(); // set the class once to avoid overhead in the loop - $cls = CcPlaylistPeer::getOMClass(false); + $cls = CcPlaylistcriteriaPeer::getOMClass(false); // populate the object(s) while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $key = CcPlaylistPeer::getPrimaryKeyHashFromRow($row, 0); - if (null !== ($obj = CcPlaylistPeer::getInstanceFromPool($key))) { + $key = CcPlaylistcriteriaPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj = CcPlaylistcriteriaPeer::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 @@ -436,7 +428,7 @@ abstract class BaseCcPlaylistPeer { $obj = new $cls(); $obj->hydrate($row); $results[] = $obj; - CcPlaylistPeer::addInstanceToPool($obj, $key); + CcPlaylistcriteriaPeer::addInstanceToPool($obj, $key); } // if key exists } $stmt->closeCursor(); @@ -449,27 +441,27 @@ abstract class BaseCcPlaylistPeer { * @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 (CcPlaylist object, last column rank) + * @return array (CcPlaylistcriteria object, last column rank) */ public static function populateObject($row, $startcol = 0) { - $key = CcPlaylistPeer::getPrimaryKeyHashFromRow($row, $startcol); - if (null !== ($obj = CcPlaylistPeer::getInstanceFromPool($key))) { + $key = CcPlaylistcriteriaPeer::getPrimaryKeyHashFromRow($row, $startcol); + if (null !== ($obj = CcPlaylistcriteriaPeer::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 + CcPlaylistPeer::NUM_COLUMNS; + $col = $startcol + CcPlaylistcriteriaPeer::NUM_COLUMNS; } else { - $cls = CcPlaylistPeer::OM_CLASS; + $cls = CcPlaylistcriteriaPeer::OM_CLASS; $obj = new $cls(); $col = $obj->hydrate($row, $startcol); - CcPlaylistPeer::addInstanceToPool($obj, $key); + CcPlaylistcriteriaPeer::addInstanceToPool($obj, $key); } return array($obj, $col); } /** - * Returns the number of rows matching criteria, joining the related CcSubjs table + * 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. @@ -477,7 +469,7 @@ abstract class BaseCcPlaylistPeer { * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN * @return int Number of matching rows. */ - public static function doCountJoinCcSubjs(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) + 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; @@ -485,14 +477,14 @@ abstract class BaseCcPlaylistPeer { // 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(CcPlaylistPeer::TABLE_NAME); + $criteria->setPrimaryTableName(CcPlaylistcriteriaPeer::TABLE_NAME); if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { $criteria->setDistinct(); } if (!$criteria->hasSelectClause()) { - CcPlaylistPeer::addSelectColumns($criteria); + CcPlaylistcriteriaPeer::addSelectColumns($criteria); } $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count @@ -501,10 +493,10 @@ abstract class BaseCcPlaylistPeer { $criteria->setDbName(self::DATABASE_NAME); if ($con === null) { - $con = Propel::getConnection(CcPlaylistPeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcPlaylistcriteriaPeer::DATABASE_NAME, Propel::CONNECTION_READ); } - $criteria->addJoin(CcPlaylistPeer::EDITEDBY, CcSubjsPeer::ID, $join_behavior); + $criteria->addJoin(CcPlaylistcriteriaPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); $stmt = BasePeer::doCount($criteria, $con); @@ -519,15 +511,15 @@ abstract class BaseCcPlaylistPeer { /** - * Selects a collection of CcPlaylist objects pre-filled with their CcSubjs objects. + * Selects a collection of CcPlaylistcriteria 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 CcPlaylist objects. + * @return array Array of CcPlaylistcriteria objects. * @throws PropelException Any exceptions caught during processing will be * rethrown wrapped into a PropelException. */ - public static function doSelectJoinCcSubjs(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) + public static function doSelectJoinCcPlaylist(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) { $criteria = clone $criteria; @@ -536,44 +528,44 @@ abstract class BaseCcPlaylistPeer { $criteria->setDbName(self::DATABASE_NAME); } + CcPlaylistcriteriaPeer::addSelectColumns($criteria); + $startcol = (CcPlaylistcriteriaPeer::NUM_COLUMNS - CcPlaylistcriteriaPeer::NUM_LAZY_LOAD_COLUMNS); CcPlaylistPeer::addSelectColumns($criteria); - $startcol = (CcPlaylistPeer::NUM_COLUMNS - CcPlaylistPeer::NUM_LAZY_LOAD_COLUMNS); - CcSubjsPeer::addSelectColumns($criteria); - $criteria->addJoin(CcPlaylistPeer::EDITEDBY, CcSubjsPeer::ID, $join_behavior); + $criteria->addJoin(CcPlaylistcriteriaPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); $stmt = BasePeer::doSelect($criteria, $con); $results = array(); while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $key1 = CcPlaylistPeer::getPrimaryKeyHashFromRow($row, 0); - if (null !== ($obj1 = CcPlaylistPeer::getInstanceFromPool($key1))) { + $key1 = CcPlaylistcriteriaPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcPlaylistcriteriaPeer::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 = CcPlaylistPeer::getOMClass(false); + $cls = CcPlaylistcriteriaPeer::getOMClass(false); $obj1 = new $cls(); $obj1->hydrate($row); - CcPlaylistPeer::addInstanceToPool($obj1, $key1); + CcPlaylistcriteriaPeer::addInstanceToPool($obj1, $key1); } // if $obj1 already loaded - $key2 = CcSubjsPeer::getPrimaryKeyHashFromRow($row, $startcol); + $key2 = CcPlaylistPeer::getPrimaryKeyHashFromRow($row, $startcol); if ($key2 !== null) { - $obj2 = CcSubjsPeer::getInstanceFromPool($key2); + $obj2 = CcPlaylistPeer::getInstanceFromPool($key2); if (!$obj2) { - $cls = CcSubjsPeer::getOMClass(false); + $cls = CcPlaylistPeer::getOMClass(false); $obj2 = new $cls(); $obj2->hydrate($row, $startcol); - CcSubjsPeer::addInstanceToPool($obj2, $key2); + CcPlaylistPeer::addInstanceToPool($obj2, $key2); } // if obj2 already loaded - // Add the $obj1 (CcPlaylist) to $obj2 (CcSubjs) - $obj2->addCcPlaylist($obj1); + // Add the $obj1 (CcPlaylistcriteria) to $obj2 (CcPlaylist) + $obj2->addCcPlaylistcriteria($obj1); } // if joined row was not null @@ -601,14 +593,14 @@ abstract class BaseCcPlaylistPeer { // 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(CcPlaylistPeer::TABLE_NAME); + $criteria->setPrimaryTableName(CcPlaylistcriteriaPeer::TABLE_NAME); if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { $criteria->setDistinct(); } if (!$criteria->hasSelectClause()) { - CcPlaylistPeer::addSelectColumns($criteria); + CcPlaylistcriteriaPeer::addSelectColumns($criteria); } $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count @@ -617,10 +609,10 @@ abstract class BaseCcPlaylistPeer { $criteria->setDbName(self::DATABASE_NAME); if ($con === null) { - $con = Propel::getConnection(CcPlaylistPeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcPlaylistcriteriaPeer::DATABASE_NAME, Propel::CONNECTION_READ); } - $criteria->addJoin(CcPlaylistPeer::EDITEDBY, CcSubjsPeer::ID, $join_behavior); + $criteria->addJoin(CcPlaylistcriteriaPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); $stmt = BasePeer::doCount($criteria, $con); @@ -634,12 +626,12 @@ abstract class BaseCcPlaylistPeer { } /** - * Selects a collection of CcPlaylist objects pre-filled with all related objects. + * Selects a collection of CcPlaylistcriteria 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 CcPlaylist objects. + * @return array Array of CcPlaylistcriteria objects. * @throws PropelException Any exceptions caught during processing will be * rethrown wrapped into a PropelException. */ @@ -652,47 +644,47 @@ abstract class BaseCcPlaylistPeer { $criteria->setDbName(self::DATABASE_NAME); } + CcPlaylistcriteriaPeer::addSelectColumns($criteria); + $startcol2 = (CcPlaylistcriteriaPeer::NUM_COLUMNS - CcPlaylistcriteriaPeer::NUM_LAZY_LOAD_COLUMNS); + CcPlaylistPeer::addSelectColumns($criteria); - $startcol2 = (CcPlaylistPeer::NUM_COLUMNS - CcPlaylistPeer::NUM_LAZY_LOAD_COLUMNS); + $startcol3 = $startcol2 + (CcPlaylistPeer::NUM_COLUMNS - CcPlaylistPeer::NUM_LAZY_LOAD_COLUMNS); - CcSubjsPeer::addSelectColumns($criteria); - $startcol3 = $startcol2 + (CcSubjsPeer::NUM_COLUMNS - CcSubjsPeer::NUM_LAZY_LOAD_COLUMNS); - - $criteria->addJoin(CcPlaylistPeer::EDITEDBY, CcSubjsPeer::ID, $join_behavior); + $criteria->addJoin(CcPlaylistcriteriaPeer::PLAYLIST_ID, CcPlaylistPeer::ID, $join_behavior); $stmt = BasePeer::doSelect($criteria, $con); $results = array(); while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $key1 = CcPlaylistPeer::getPrimaryKeyHashFromRow($row, 0); - if (null !== ($obj1 = CcPlaylistPeer::getInstanceFromPool($key1))) { + $key1 = CcPlaylistcriteriaPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcPlaylistcriteriaPeer::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 = CcPlaylistPeer::getOMClass(false); + $cls = CcPlaylistcriteriaPeer::getOMClass(false); $obj1 = new $cls(); $obj1->hydrate($row); - CcPlaylistPeer::addInstanceToPool($obj1, $key1); + CcPlaylistcriteriaPeer::addInstanceToPool($obj1, $key1); } // if obj1 already loaded - // Add objects for joined CcSubjs rows + // Add objects for joined CcPlaylist rows - $key2 = CcSubjsPeer::getPrimaryKeyHashFromRow($row, $startcol2); + $key2 = CcPlaylistPeer::getPrimaryKeyHashFromRow($row, $startcol2); if ($key2 !== null) { - $obj2 = CcSubjsPeer::getInstanceFromPool($key2); + $obj2 = CcPlaylistPeer::getInstanceFromPool($key2); if (!$obj2) { - $cls = CcSubjsPeer::getOMClass(false); + $cls = CcPlaylistPeer::getOMClass(false); $obj2 = new $cls(); $obj2->hydrate($row, $startcol2); - CcSubjsPeer::addInstanceToPool($obj2, $key2); + CcPlaylistPeer::addInstanceToPool($obj2, $key2); } // if obj2 loaded - // Add the $obj1 (CcPlaylist) to the collection in $obj2 (CcSubjs) - $obj2->addCcPlaylist($obj1); + // Add the $obj1 (CcPlaylistcriteria) to the collection in $obj2 (CcPlaylist) + $obj2->addCcPlaylistcriteria($obj1); } // if joined row not null $results[] = $obj1; @@ -718,10 +710,10 @@ abstract class BaseCcPlaylistPeer { */ public static function buildTableMap() { - $dbMap = Propel::getDatabaseMap(BaseCcPlaylistPeer::DATABASE_NAME); - if (!$dbMap->hasTable(BaseCcPlaylistPeer::TABLE_NAME)) + $dbMap = Propel::getDatabaseMap(BaseCcPlaylistcriteriaPeer::DATABASE_NAME); + if (!$dbMap->hasTable(BaseCcPlaylistcriteriaPeer::TABLE_NAME)) { - $dbMap->addTableObject(new CcPlaylistTableMap()); + $dbMap->addTableObject(new CcPlaylistcriteriaTableMap()); } } @@ -738,13 +730,13 @@ abstract class BaseCcPlaylistPeer { */ public static function getOMClass($withPrefix = true) { - return $withPrefix ? CcPlaylistPeer::CLASS_DEFAULT : CcPlaylistPeer::OM_CLASS; + return $withPrefix ? CcPlaylistcriteriaPeer::CLASS_DEFAULT : CcPlaylistcriteriaPeer::OM_CLASS; } /** - * Method perform an INSERT on the database, given a CcPlaylist or Criteria object. + * Method perform an INSERT on the database, given a CcPlaylistcriteria or Criteria object. * - * @param mixed $values Criteria or CcPlaylist object containing data that is used to create the INSERT statement. + * @param mixed $values Criteria or CcPlaylistcriteria 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 @@ -753,17 +745,17 @@ abstract class BaseCcPlaylistPeer { public static function doInsert($values, PropelPDO $con = null) { if ($con === null) { - $con = Propel::getConnection(CcPlaylistPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + $con = Propel::getConnection(CcPlaylistcriteriaPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); } if ($values instanceof Criteria) { $criteria = clone $values; // rename for clarity } else { - $criteria = $values->buildCriteria(); // build Criteria from CcPlaylist object + $criteria = $values->buildCriteria(); // build Criteria from CcPlaylistcriteria object } - if ($criteria->containsKey(CcPlaylistPeer::ID) && $criteria->keyContainsValue(CcPlaylistPeer::ID) ) { - throw new PropelException('Cannot insert a value for auto-increment primary key ('.CcPlaylistPeer::ID.')'); + if ($criteria->containsKey(CcPlaylistcriteriaPeer::ID) && $criteria->keyContainsValue(CcPlaylistcriteriaPeer::ID) ) { + throw new PropelException('Cannot insert a value for auto-increment primary key ('.CcPlaylistcriteriaPeer::ID.')'); } @@ -785,9 +777,9 @@ abstract class BaseCcPlaylistPeer { } /** - * Method perform an UPDATE on the database, given a CcPlaylist or Criteria object. + * Method perform an UPDATE on the database, given a CcPlaylistcriteria or Criteria object. * - * @param mixed $values Criteria or CcPlaylist object containing data that is used to create the UPDATE statement. + * @param mixed $values Criteria or CcPlaylistcriteria 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 @@ -796,7 +788,7 @@ abstract class BaseCcPlaylistPeer { public static function doUpdate($values, PropelPDO $con = null) { if ($con === null) { - $con = Propel::getConnection(CcPlaylistPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + $con = Propel::getConnection(CcPlaylistcriteriaPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); } $selectCriteria = new Criteria(self::DATABASE_NAME); @@ -804,15 +796,15 @@ abstract class BaseCcPlaylistPeer { if ($values instanceof Criteria) { $criteria = clone $values; // rename for clarity - $comparison = $criteria->getComparison(CcPlaylistPeer::ID); - $value = $criteria->remove(CcPlaylistPeer::ID); + $comparison = $criteria->getComparison(CcPlaylistcriteriaPeer::ID); + $value = $criteria->remove(CcPlaylistcriteriaPeer::ID); if ($value) { - $selectCriteria->add(CcPlaylistPeer::ID, $value, $comparison); + $selectCriteria->add(CcPlaylistcriteriaPeer::ID, $value, $comparison); } else { - $selectCriteria->setPrimaryTableName(CcPlaylistPeer::TABLE_NAME); + $selectCriteria->setPrimaryTableName(CcPlaylistcriteriaPeer::TABLE_NAME); } - } else { // $values is CcPlaylist object + } else { // $values is CcPlaylistcriteria object $criteria = $values->buildCriteria(); // gets full criteria $selectCriteria = $values->buildPkeyCriteria(); // gets criteria w/ primary key(s) } @@ -824,26 +816,26 @@ abstract class BaseCcPlaylistPeer { } /** - * Method to DELETE all rows from the cc_playlist table. + * Method to DELETE all rows from the cc_playlistcriteria 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(CcPlaylistPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + $con = Propel::getConnection(CcPlaylistcriteriaPeer::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(CcPlaylistPeer::TABLE_NAME, $con, CcPlaylistPeer::DATABASE_NAME); + $affectedRows += BasePeer::doDeleteAll(CcPlaylistcriteriaPeer::TABLE_NAME, $con, CcPlaylistcriteriaPeer::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). - CcPlaylistPeer::clearInstancePool(); - CcPlaylistPeer::clearRelatedInstancePool(); + CcPlaylistcriteriaPeer::clearInstancePool(); + CcPlaylistcriteriaPeer::clearRelatedInstancePool(); $con->commit(); return $affectedRows; } catch (PropelException $e) { @@ -853,9 +845,9 @@ abstract class BaseCcPlaylistPeer { } /** - * Method perform a DELETE on the database, given a CcPlaylist or Criteria object OR a primary key value. + * Method perform a DELETE on the database, given a CcPlaylistcriteria or Criteria object OR a primary key value. * - * @param mixed $values Criteria or CcPlaylist object or primary key or array of primary keys + * @param mixed $values Criteria or CcPlaylistcriteria 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 @@ -866,27 +858,27 @@ abstract class BaseCcPlaylistPeer { public static function doDelete($values, PropelPDO $con = null) { if ($con === null) { - $con = Propel::getConnection(CcPlaylistPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + $con = Propel::getConnection(CcPlaylistcriteriaPeer::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. - CcPlaylistPeer::clearInstancePool(); + CcPlaylistcriteriaPeer::clearInstancePool(); // rename for clarity $criteria = clone $values; - } elseif ($values instanceof CcPlaylist) { // it's a model object + } elseif ($values instanceof CcPlaylistcriteria) { // it's a model object // invalidate the cache for this single object - CcPlaylistPeer::removeInstanceFromPool($values); + CcPlaylistcriteriaPeer::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(CcPlaylistPeer::ID, (array) $values, Criteria::IN); + $criteria->add(CcPlaylistcriteriaPeer::ID, (array) $values, Criteria::IN); // invalidate the cache for this object(s) foreach ((array) $values as $singleval) { - CcPlaylistPeer::removeInstanceFromPool($singleval); + CcPlaylistcriteriaPeer::removeInstanceFromPool($singleval); } } @@ -901,7 +893,7 @@ abstract class BaseCcPlaylistPeer { $con->beginTransaction(); $affectedRows += BasePeer::doDelete($criteria, $con); - CcPlaylistPeer::clearRelatedInstancePool(); + CcPlaylistcriteriaPeer::clearRelatedInstancePool(); $con->commit(); return $affectedRows; } catch (PropelException $e) { @@ -911,24 +903,24 @@ abstract class BaseCcPlaylistPeer { } /** - * Validates all modified columns of given CcPlaylist object. + * Validates all modified columns of given CcPlaylistcriteria 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 CcPlaylist $obj The object to validate. + * @param CcPlaylistcriteria $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(CcPlaylist $obj, $cols = null) + public static function doValidate(CcPlaylistcriteria $obj, $cols = null) { $columns = array(); if ($cols) { - $dbMap = Propel::getDatabaseMap(CcPlaylistPeer::DATABASE_NAME); - $tableMap = $dbMap->getTable(CcPlaylistPeer::TABLE_NAME); + $dbMap = Propel::getDatabaseMap(CcPlaylistcriteriaPeer::DATABASE_NAME); + $tableMap = $dbMap->getTable(CcPlaylistcriteriaPeer::TABLE_NAME); if (! is_array($cols)) { $cols = array($cols); @@ -944,7 +936,7 @@ abstract class BaseCcPlaylistPeer { } - return BasePeer::doValidate(CcPlaylistPeer::DATABASE_NAME, CcPlaylistPeer::TABLE_NAME, $columns); + return BasePeer::doValidate(CcPlaylistcriteriaPeer::DATABASE_NAME, CcPlaylistcriteriaPeer::TABLE_NAME, $columns); } /** @@ -952,23 +944,23 @@ abstract class BaseCcPlaylistPeer { * * @param int $pk the primary key. * @param PropelPDO $con the connection to use - * @return CcPlaylist + * @return CcPlaylistcriteria */ public static function retrieveByPK($pk, PropelPDO $con = null) { - if (null !== ($obj = CcPlaylistPeer::getInstanceFromPool((string) $pk))) { + if (null !== ($obj = CcPlaylistcriteriaPeer::getInstanceFromPool((string) $pk))) { return $obj; } if ($con === null) { - $con = Propel::getConnection(CcPlaylistPeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcPlaylistcriteriaPeer::DATABASE_NAME, Propel::CONNECTION_READ); } - $criteria = new Criteria(CcPlaylistPeer::DATABASE_NAME); - $criteria->add(CcPlaylistPeer::ID, $pk); + $criteria = new Criteria(CcPlaylistcriteriaPeer::DATABASE_NAME); + $criteria->add(CcPlaylistcriteriaPeer::ID, $pk); - $v = CcPlaylistPeer::doSelect($criteria, $con); + $v = CcPlaylistcriteriaPeer::doSelect($criteria, $con); return !empty($v) > 0 ? $v[0] : null; } @@ -984,23 +976,23 @@ abstract class BaseCcPlaylistPeer { public static function retrieveByPKs($pks, PropelPDO $con = null) { if ($con === null) { - $con = Propel::getConnection(CcPlaylistPeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcPlaylistcriteriaPeer::DATABASE_NAME, Propel::CONNECTION_READ); } $objs = null; if (empty($pks)) { $objs = array(); } else { - $criteria = new Criteria(CcPlaylistPeer::DATABASE_NAME); - $criteria->add(CcPlaylistPeer::ID, $pks, Criteria::IN); - $objs = CcPlaylistPeer::doSelect($criteria, $con); + $criteria = new Criteria(CcPlaylistcriteriaPeer::DATABASE_NAME); + $criteria->add(CcPlaylistcriteriaPeer::ID, $pks, Criteria::IN); + $objs = CcPlaylistcriteriaPeer::doSelect($criteria, $con); } return $objs; } -} // BaseCcPlaylistPeer +} // BaseCcPlaylistcriteriaPeer // This is the static code needed to register the TableMap for this table with the main Propel class. // -BaseCcPlaylistPeer::buildTableMap(); +BaseCcPlaylistcriteriaPeer::buildTableMap(); diff --git a/airtime_mvc/application/models/airtime/om/BaseCcPlaylistcriteriaQuery.php b/airtime_mvc/application/models/airtime/om/BaseCcPlaylistcriteriaQuery.php new file mode 100644 index 000000000..42cd8ecbd --- /dev/null +++ b/airtime_mvc/application/models/airtime/om/BaseCcPlaylistcriteriaQuery.php @@ -0,0 +1,407 @@ +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 CcPlaylistcriteria|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ((null !== ($obj = CcPlaylistcriteriaPeer::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 CcPlaylistcriteriaQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + return $this->addUsingAlias(CcPlaylistcriteriaPeer::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 CcPlaylistcriteriaQuery The current query, for fluid interface + */ + public function filterByPrimaryKeys($keys) + { + return $this->addUsingAlias(CcPlaylistcriteriaPeer::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 CcPlaylistcriteriaQuery 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(CcPlaylistcriteriaPeer::ID, $dbId, $comparison); + } + + /** + * Filter the query on the criteria column + * + * @param string $dbCriteria 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 CcPlaylistcriteriaQuery The current query, for fluid interface + */ + public function filterByDbCriteria($dbCriteria = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($dbCriteria)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $dbCriteria)) { + $dbCriteria = str_replace('*', '%', $dbCriteria); + $comparison = Criteria::LIKE; + } + } + return $this->addUsingAlias(CcPlaylistcriteriaPeer::CRITERIA, $dbCriteria, $comparison); + } + + /** + * Filter the query on the modifier column + * + * @param string $dbModifier 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 CcPlaylistcriteriaQuery The current query, for fluid interface + */ + public function filterByDbModifier($dbModifier = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($dbModifier)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $dbModifier)) { + $dbModifier = str_replace('*', '%', $dbModifier); + $comparison = Criteria::LIKE; + } + } + return $this->addUsingAlias(CcPlaylistcriteriaPeer::MODIFIER, $dbModifier, $comparison); + } + + /** + * Filter the query on the value column + * + * @param string $dbValue 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 CcPlaylistcriteriaQuery The current query, for fluid interface + */ + public function filterByDbValue($dbValue = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($dbValue)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $dbValue)) { + $dbValue = str_replace('*', '%', $dbValue); + $comparison = Criteria::LIKE; + } + } + return $this->addUsingAlias(CcPlaylistcriteriaPeer::VALUE, $dbValue, $comparison); + } + + /** + * Filter the query on the extra column + * + * @param string $dbExtra 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 CcPlaylistcriteriaQuery The current query, for fluid interface + */ + public function filterByDbExtra($dbExtra = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($dbExtra)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $dbExtra)) { + $dbExtra = str_replace('*', '%', $dbExtra); + $comparison = Criteria::LIKE; + } + } + return $this->addUsingAlias(CcPlaylistcriteriaPeer::EXTRA, $dbExtra, $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 CcPlaylistcriteriaQuery 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(CcPlaylistcriteriaPeer::PLAYLIST_ID, $dbPlaylistId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbPlaylistId['max'])) { + $this->addUsingAlias(CcPlaylistcriteriaPeer::PLAYLIST_ID, $dbPlaylistId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcPlaylistcriteriaPeer::PLAYLIST_ID, $dbPlaylistId, $comparison); + } + + /** + * Filter the query on the set_number column + * + * @param int|array $dbSetNumber 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 CcPlaylistcriteriaQuery The current query, for fluid interface + */ + public function filterByDbSetNumber($dbSetNumber = null, $comparison = null) + { + if (is_array($dbSetNumber)) { + $useMinMax = false; + if (isset($dbSetNumber['min'])) { + $this->addUsingAlias(CcPlaylistcriteriaPeer::SET_NUMBER, $dbSetNumber['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbSetNumber['max'])) { + $this->addUsingAlias(CcPlaylistcriteriaPeer::SET_NUMBER, $dbSetNumber['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcPlaylistcriteriaPeer::SET_NUMBER, $dbSetNumber, $comparison); + } + + /** + * 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 CcPlaylistcriteriaQuery The current query, for fluid interface + */ + public function filterByCcPlaylist($ccPlaylist, $comparison = null) + { + return $this + ->addUsingAlias(CcPlaylistcriteriaPeer::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 CcPlaylistcriteriaQuery The current query, for fluid interface + */ + public function joinCcPlaylist($relationAlias = '', $joinType = Criteria::INNER_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::INNER_JOIN) + { + return $this + ->joinCcPlaylist($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'CcPlaylist', 'CcPlaylistQuery'); + } + + /** + * Exclude object from result + * + * @param CcPlaylistcriteria $ccPlaylistcriteria Object to remove from the list of results + * + * @return CcPlaylistcriteriaQuery The current query, for fluid interface + */ + public function prune($ccPlaylistcriteria = null) + { + if ($ccPlaylistcriteria) { + $this->addUsingAlias(CcPlaylistcriteriaPeer::ID, $ccPlaylistcriteria->getDbId(), Criteria::NOT_EQUAL); + } + + return $this; + } + +} // BaseCcPlaylistcriteriaQuery diff --git a/airtime_mvc/application/models/airtime/om/BaseCcSchedule.php b/airtime_mvc/application/models/airtime/om/BaseCcSchedule.php index 9556499bb..4f7edcebf 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcSchedule.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcSchedule.php @@ -48,6 +48,12 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent */ protected $file_id; + /** + * The value for the stream_id field. + * @var int + */ + protected $stream_id; + /** * The value for the clip_length field. * Note: this column has a database default value of: '00:00:00' @@ -120,6 +126,16 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent */ protected $aCcFiles; + /** + * @var CcWebstream + */ + protected $aCcWebstream; + + /** + * @var array CcWebstreamMetadata[] Collection to store aggregation of CcWebstreamMetadata objects. + */ + protected $collCcWebstreamMetadatas; + /** * Flag to prevent endless save loop, if this object is referenced * by another object which falls in this transaction. @@ -248,6 +264,16 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent return $this->file_id; } + /** + * Get the [stream_id] column value. + * + * @return int + */ + public function getDbStreamId() + { + return $this->stream_id; + } + /** * Get the [clip_length] column value. * @@ -526,6 +552,30 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent return $this; } // setDbFileId() + /** + * Set the value of [stream_id] column. + * + * @param int $v new value + * @return CcSchedule 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[] = CcSchedulePeer::STREAM_ID; + } + + if ($this->aCcWebstream !== null && $this->aCcWebstream->getDbId() !== $v) { + $this->aCcWebstream = null; + } + + return $this; + } // setDbStreamId() + /** * Set the value of [clip_length] column. * @@ -838,15 +888,16 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent $this->starts = ($row[$startcol + 1] !== null) ? (string) $row[$startcol + 1] : null; $this->ends = ($row[$startcol + 2] !== null) ? (string) $row[$startcol + 2] : null; $this->file_id = ($row[$startcol + 3] !== null) ? (int) $row[$startcol + 3] : null; - $this->clip_length = ($row[$startcol + 4] !== null) ? (string) $row[$startcol + 4] : null; - $this->fade_in = ($row[$startcol + 5] !== null) ? (string) $row[$startcol + 5] : null; - $this->fade_out = ($row[$startcol + 6] !== null) ? (string) $row[$startcol + 6] : null; - $this->cue_in = ($row[$startcol + 7] !== null) ? (string) $row[$startcol + 7] : null; - $this->cue_out = ($row[$startcol + 8] !== null) ? (string) $row[$startcol + 8] : null; - $this->media_item_played = ($row[$startcol + 9] !== null) ? (boolean) $row[$startcol + 9] : null; - $this->instance_id = ($row[$startcol + 10] !== null) ? (int) $row[$startcol + 10] : null; - $this->playout_status = ($row[$startcol + 11] !== null) ? (int) $row[$startcol + 11] : null; - $this->broadcasted = ($row[$startcol + 12] !== null) ? (int) $row[$startcol + 12] : null; + $this->stream_id = ($row[$startcol + 4] !== null) ? (int) $row[$startcol + 4] : null; + $this->clip_length = ($row[$startcol + 5] !== null) ? (string) $row[$startcol + 5] : null; + $this->fade_in = ($row[$startcol + 6] !== null) ? (string) $row[$startcol + 6] : null; + $this->fade_out = ($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->media_item_played = ($row[$startcol + 10] !== null) ? (boolean) $row[$startcol + 10] : null; + $this->instance_id = ($row[$startcol + 11] !== null) ? (int) $row[$startcol + 11] : null; + $this->playout_status = ($row[$startcol + 12] !== null) ? (int) $row[$startcol + 12] : null; + $this->broadcasted = ($row[$startcol + 13] !== null) ? (int) $row[$startcol + 13] : null; $this->resetModified(); $this->setNew(false); @@ -855,7 +906,7 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent $this->ensureConsistency(); } - return $startcol + 13; // 13 = CcSchedulePeer::NUM_COLUMNS - CcSchedulePeer::NUM_LAZY_LOAD_COLUMNS). + return $startcol + 14; // 14 = CcSchedulePeer::NUM_COLUMNS - CcSchedulePeer::NUM_LAZY_LOAD_COLUMNS). } catch (Exception $e) { throw new PropelException("Error populating CcSchedule object", $e); @@ -881,6 +932,9 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent 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->aCcShowInstances !== null && $this->instance_id !== $this->aCcShowInstances->getDbId()) { $this->aCcShowInstances = null; } @@ -925,6 +979,9 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent $this->aCcShowInstances = null; $this->aCcFiles = null; + $this->aCcWebstream = null; + $this->collCcWebstreamMetadatas = null; + } // if (deep) } @@ -1054,6 +1111,13 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent $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->isNew() ) { $this->modifiedColumns[] = CcSchedulePeer::ID; } @@ -1077,6 +1141,14 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent $this->resetModified(); // [HL] After being saved an object is no longer 'modified' } + if ($this->collCcWebstreamMetadatas !== null) { + foreach ($this->collCcWebstreamMetadatas as $referrerFK) { + if (!$referrerFK->isDeleted()) { + $affectedRows += $referrerFK->save($con); + } + } + } + $this->alreadyInSave = false; } @@ -1160,12 +1232,26 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent } } + if ($this->aCcWebstream !== null) { + if (!$this->aCcWebstream->validate($columns)) { + $failureMap = array_merge($failureMap, $this->aCcWebstream->getValidationFailures()); + } + } + if (($retval = CcSchedulePeer::doValidate($this, $columns)) !== true) { $failureMap = array_merge($failureMap, $retval); } + if ($this->collCcWebstreamMetadatas !== null) { + foreach ($this->collCcWebstreamMetadatas as $referrerFK) { + if (!$referrerFK->validate($columns)) { + $failureMap = array_merge($failureMap, $referrerFK->getValidationFailures()); + } + } + } + $this->alreadyInValidation = false; } @@ -1212,30 +1298,33 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent return $this->getDbFileId(); break; case 4: - return $this->getDbClipLength(); + return $this->getDbStreamId(); break; case 5: - return $this->getDbFadeIn(); + return $this->getDbClipLength(); break; case 6: - return $this->getDbFadeOut(); + return $this->getDbFadeIn(); break; case 7: - return $this->getDbCueIn(); + return $this->getDbFadeOut(); break; case 8: - return $this->getDbCueOut(); + return $this->getDbCueIn(); break; case 9: - return $this->getDbMediaItemPlayed(); + return $this->getDbCueOut(); break; case 10: - return $this->getDbInstanceId(); + return $this->getDbMediaItemPlayed(); break; case 11: - return $this->getDbPlayoutStatus(); + return $this->getDbInstanceId(); break; case 12: + return $this->getDbPlayoutStatus(); + break; + case 13: return $this->getDbBroadcasted(); break; default: @@ -1266,15 +1355,16 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent $keys[1] => $this->getDbStarts(), $keys[2] => $this->getDbEnds(), $keys[3] => $this->getDbFileId(), - $keys[4] => $this->getDbClipLength(), - $keys[5] => $this->getDbFadeIn(), - $keys[6] => $this->getDbFadeOut(), - $keys[7] => $this->getDbCueIn(), - $keys[8] => $this->getDbCueOut(), - $keys[9] => $this->getDbMediaItemPlayed(), - $keys[10] => $this->getDbInstanceId(), - $keys[11] => $this->getDbPlayoutStatus(), - $keys[12] => $this->getDbBroadcasted(), + $keys[4] => $this->getDbStreamId(), + $keys[5] => $this->getDbClipLength(), + $keys[6] => $this->getDbFadeIn(), + $keys[7] => $this->getDbFadeOut(), + $keys[8] => $this->getDbCueIn(), + $keys[9] => $this->getDbCueOut(), + $keys[10] => $this->getDbMediaItemPlayed(), + $keys[11] => $this->getDbInstanceId(), + $keys[12] => $this->getDbPlayoutStatus(), + $keys[13] => $this->getDbBroadcasted(), ); if ($includeForeignObjects) { if (null !== $this->aCcShowInstances) { @@ -1283,6 +1373,9 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent if (null !== $this->aCcFiles) { $result['CcFiles'] = $this->aCcFiles->toArray($keyType, $includeLazyLoadColumns, true); } + if (null !== $this->aCcWebstream) { + $result['CcWebstream'] = $this->aCcWebstream->toArray($keyType, $includeLazyLoadColumns, true); + } } return $result; } @@ -1327,30 +1420,33 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent $this->setDbFileId($value); break; case 4: - $this->setDbClipLength($value); + $this->setDbStreamId($value); break; case 5: - $this->setDbFadeIn($value); + $this->setDbClipLength($value); break; case 6: - $this->setDbFadeOut($value); + $this->setDbFadeIn($value); break; case 7: - $this->setDbCueIn($value); + $this->setDbFadeOut($value); break; case 8: - $this->setDbCueOut($value); + $this->setDbCueIn($value); break; case 9: - $this->setDbMediaItemPlayed($value); + $this->setDbCueOut($value); break; case 10: - $this->setDbInstanceId($value); + $this->setDbMediaItemPlayed($value); break; case 11: - $this->setDbPlayoutStatus($value); + $this->setDbInstanceId($value); break; case 12: + $this->setDbPlayoutStatus($value); + break; + case 13: $this->setDbBroadcasted($value); break; } // switch() @@ -1381,15 +1477,16 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent if (array_key_exists($keys[1], $arr)) $this->setDbStarts($arr[$keys[1]]); if (array_key_exists($keys[2], $arr)) $this->setDbEnds($arr[$keys[2]]); if (array_key_exists($keys[3], $arr)) $this->setDbFileId($arr[$keys[3]]); - if (array_key_exists($keys[4], $arr)) $this->setDbClipLength($arr[$keys[4]]); - if (array_key_exists($keys[5], $arr)) $this->setDbFadeIn($arr[$keys[5]]); - if (array_key_exists($keys[6], $arr)) $this->setDbFadeOut($arr[$keys[6]]); - if (array_key_exists($keys[7], $arr)) $this->setDbCueIn($arr[$keys[7]]); - if (array_key_exists($keys[8], $arr)) $this->setDbCueOut($arr[$keys[8]]); - if (array_key_exists($keys[9], $arr)) $this->setDbMediaItemPlayed($arr[$keys[9]]); - if (array_key_exists($keys[10], $arr)) $this->setDbInstanceId($arr[$keys[10]]); - if (array_key_exists($keys[11], $arr)) $this->setDbPlayoutStatus($arr[$keys[11]]); - if (array_key_exists($keys[12], $arr)) $this->setDbBroadcasted($arr[$keys[12]]); + if (array_key_exists($keys[4], $arr)) $this->setDbStreamId($arr[$keys[4]]); + if (array_key_exists($keys[5], $arr)) $this->setDbClipLength($arr[$keys[5]]); + if (array_key_exists($keys[6], $arr)) $this->setDbFadeIn($arr[$keys[6]]); + if (array_key_exists($keys[7], $arr)) $this->setDbFadeOut($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->setDbMediaItemPlayed($arr[$keys[10]]); + if (array_key_exists($keys[11], $arr)) $this->setDbInstanceId($arr[$keys[11]]); + if (array_key_exists($keys[12], $arr)) $this->setDbPlayoutStatus($arr[$keys[12]]); + if (array_key_exists($keys[13], $arr)) $this->setDbBroadcasted($arr[$keys[13]]); } /** @@ -1405,6 +1502,7 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent if ($this->isColumnModified(CcSchedulePeer::STARTS)) $criteria->add(CcSchedulePeer::STARTS, $this->starts); if ($this->isColumnModified(CcSchedulePeer::ENDS)) $criteria->add(CcSchedulePeer::ENDS, $this->ends); if ($this->isColumnModified(CcSchedulePeer::FILE_ID)) $criteria->add(CcSchedulePeer::FILE_ID, $this->file_id); + if ($this->isColumnModified(CcSchedulePeer::STREAM_ID)) $criteria->add(CcSchedulePeer::STREAM_ID, $this->stream_id); if ($this->isColumnModified(CcSchedulePeer::CLIP_LENGTH)) $criteria->add(CcSchedulePeer::CLIP_LENGTH, $this->clip_length); if ($this->isColumnModified(CcSchedulePeer::FADE_IN)) $criteria->add(CcSchedulePeer::FADE_IN, $this->fade_in); if ($this->isColumnModified(CcSchedulePeer::FADE_OUT)) $criteria->add(CcSchedulePeer::FADE_OUT, $this->fade_out); @@ -1478,6 +1576,7 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent $copyObj->setDbStarts($this->starts); $copyObj->setDbEnds($this->ends); $copyObj->setDbFileId($this->file_id); + $copyObj->setDbStreamId($this->stream_id); $copyObj->setDbClipLength($this->clip_length); $copyObj->setDbFadeIn($this->fade_in); $copyObj->setDbFadeOut($this->fade_out); @@ -1488,6 +1587,20 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent $copyObj->setDbPlayoutStatus($this->playout_status); $copyObj->setDbBroadcasted($this->broadcasted); + 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->getCcWebstreamMetadatas() as $relObj) { + if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves + $copyObj->addCcWebstreamMetadata($relObj->copy($deepCopy)); + } + } + + } // if ($deepCopy) + + $copyObj->setNew(true); $copyObj->setDbId(NULL); // this is a auto-increment column, so set to default value } @@ -1628,6 +1741,164 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent return $this->aCcFiles; } + /** + * Declares an association between this object and a CcWebstream object. + * + * @param CcWebstream $v + * @return CcSchedule 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->addCcSchedule($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->addCcSchedules($this); + */ + } + return $this->aCcWebstream; + } + + /** + * Clears out the collCcWebstreamMetadatas 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 addCcWebstreamMetadatas() + */ + public function clearCcWebstreamMetadatas() + { + $this->collCcWebstreamMetadatas = null; // important to set this to NULL since that means it is uninitialized + } + + /** + * Initializes the collCcWebstreamMetadatas collection. + * + * By default this just sets the collCcWebstreamMetadatas collection to an empty array (like clearcollCcWebstreamMetadatas()); + * 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 initCcWebstreamMetadatas() + { + $this->collCcWebstreamMetadatas = new PropelObjectCollection(); + $this->collCcWebstreamMetadatas->setModel('CcWebstreamMetadata'); + } + + /** + * Gets an array of CcWebstreamMetadata 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 CcSchedule 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 CcWebstreamMetadata[] List of CcWebstreamMetadata objects + * @throws PropelException + */ + public function getCcWebstreamMetadatas($criteria = null, PropelPDO $con = null) + { + if(null === $this->collCcWebstreamMetadatas || null !== $criteria) { + if ($this->isNew() && null === $this->collCcWebstreamMetadatas) { + // return empty collection + $this->initCcWebstreamMetadatas(); + } else { + $collCcWebstreamMetadatas = CcWebstreamMetadataQuery::create(null, $criteria) + ->filterByCcSchedule($this) + ->find($con); + if (null !== $criteria) { + return $collCcWebstreamMetadatas; + } + $this->collCcWebstreamMetadatas = $collCcWebstreamMetadatas; + } + } + return $this->collCcWebstreamMetadatas; + } + + /** + * Returns the number of related CcWebstreamMetadata objects. + * + * @param Criteria $criteria + * @param boolean $distinct + * @param PropelPDO $con + * @return int Count of related CcWebstreamMetadata objects. + * @throws PropelException + */ + public function countCcWebstreamMetadatas(Criteria $criteria = null, $distinct = false, PropelPDO $con = null) + { + if(null === $this->collCcWebstreamMetadatas || null !== $criteria) { + if ($this->isNew() && null === $this->collCcWebstreamMetadatas) { + return 0; + } else { + $query = CcWebstreamMetadataQuery::create(null, $criteria); + if($distinct) { + $query->distinct(); + } + return $query + ->filterByCcSchedule($this) + ->count($con); + } + } else { + return count($this->collCcWebstreamMetadatas); + } + } + + /** + * Method called to associate a CcWebstreamMetadata object to this object + * through the CcWebstreamMetadata foreign key attribute. + * + * @param CcWebstreamMetadata $l CcWebstreamMetadata + * @return void + * @throws PropelException + */ + public function addCcWebstreamMetadata(CcWebstreamMetadata $l) + { + if ($this->collCcWebstreamMetadatas === null) { + $this->initCcWebstreamMetadatas(); + } + if (!$this->collCcWebstreamMetadatas->contains($l)) { // only add it if the **same** object is not already associated + $this->collCcWebstreamMetadatas[]= $l; + $l->setCcSchedule($this); + } + } + /** * Clears the current object and sets all attributes to their default values */ @@ -1637,6 +1908,7 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent $this->starts = null; $this->ends = null; $this->file_id = null; + $this->stream_id = null; $this->clip_length = null; $this->fade_in = null; $this->fade_out = null; @@ -1667,10 +1939,17 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent public function clearAllReferences($deep = false) { if ($deep) { + if ($this->collCcWebstreamMetadatas) { + foreach ((array) $this->collCcWebstreamMetadatas as $o) { + $o->clearAllReferences($deep); + } + } } // if ($deep) + $this->collCcWebstreamMetadatas = null; $this->aCcShowInstances = null; $this->aCcFiles = null; + $this->aCcWebstream = null; } /** diff --git a/airtime_mvc/application/models/airtime/om/BaseCcSchedulePeer.php b/airtime_mvc/application/models/airtime/om/BaseCcSchedulePeer.php index c73ee915d..8cca53863 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 = 13; + const NUM_COLUMNS = 14; /** The number of lazy-loaded columns. */ const NUM_LAZY_LOAD_COLUMNS = 0; @@ -43,6 +43,9 @@ abstract class BaseCcSchedulePeer { /** the column name for the FILE_ID field */ const FILE_ID = 'cc_schedule.FILE_ID'; + /** the column name for the STREAM_ID field */ + const STREAM_ID = 'cc_schedule.STREAM_ID'; + /** the column name for the CLIP_LENGTH field */ const CLIP_LENGTH = 'cc_schedule.CLIP_LENGTH'; @@ -86,12 +89,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', 'DbClipLength', 'DbFadeIn', 'DbFadeOut', 'DbCueIn', 'DbCueOut', 'DbMediaItemPlayed', 'DbInstanceId', 'DbPlayoutStatus', 'DbBroadcasted', ), - BasePeer::TYPE_STUDLYPHPNAME => array ('dbId', 'dbStarts', 'dbEnds', 'dbFileId', 'dbClipLength', 'dbFadeIn', 'dbFadeOut', 'dbCueIn', 'dbCueOut', 'dbMediaItemPlayed', 'dbInstanceId', 'dbPlayoutStatus', 'dbBroadcasted', ), - BasePeer::TYPE_COLNAME => array (self::ID, self::STARTS, self::ENDS, self::FILE_ID, self::CLIP_LENGTH, self::FADE_IN, self::FADE_OUT, self::CUE_IN, self::CUE_OUT, self::MEDIA_ITEM_PLAYED, self::INSTANCE_ID, self::PLAYOUT_STATUS, self::BROADCASTED, ), - BasePeer::TYPE_RAW_COLNAME => array ('ID', 'STARTS', 'ENDS', 'FILE_ID', 'CLIP_LENGTH', 'FADE_IN', 'FADE_OUT', 'CUE_IN', 'CUE_OUT', 'MEDIA_ITEM_PLAYED', 'INSTANCE_ID', 'PLAYOUT_STATUS', 'BROADCASTED', ), - BasePeer::TYPE_FIELDNAME => array ('id', 'starts', 'ends', 'file_id', 'clip_length', 'fade_in', 'fade_out', 'cue_in', 'cue_out', 'media_item_played', 'instance_id', 'playout_status', 'broadcasted', ), - BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, ) + BasePeer::TYPE_PHPNAME => array ('DbId', 'DbStarts', 'DbEnds', 'DbFileId', 'DbStreamId', 'DbClipLength', 'DbFadeIn', 'DbFadeOut', 'DbCueIn', 'DbCueOut', 'DbMediaItemPlayed', 'DbInstanceId', 'DbPlayoutStatus', 'DbBroadcasted', ), + BasePeer::TYPE_STUDLYPHPNAME => array ('dbId', 'dbStarts', 'dbEnds', 'dbFileId', 'dbStreamId', 'dbClipLength', 'dbFadeIn', 'dbFadeOut', 'dbCueIn', 'dbCueOut', 'dbMediaItemPlayed', 'dbInstanceId', 'dbPlayoutStatus', 'dbBroadcasted', ), + BasePeer::TYPE_COLNAME => array (self::ID, self::STARTS, self::ENDS, self::FILE_ID, self::STREAM_ID, self::CLIP_LENGTH, self::FADE_IN, self::FADE_OUT, self::CUE_IN, self::CUE_OUT, self::MEDIA_ITEM_PLAYED, self::INSTANCE_ID, self::PLAYOUT_STATUS, self::BROADCASTED, ), + BasePeer::TYPE_RAW_COLNAME => array ('ID', 'STARTS', 'ENDS', 'FILE_ID', 'STREAM_ID', 'CLIP_LENGTH', 'FADE_IN', 'FADE_OUT', 'CUE_IN', 'CUE_OUT', 'MEDIA_ITEM_PLAYED', 'INSTANCE_ID', 'PLAYOUT_STATUS', 'BROADCASTED', ), + BasePeer::TYPE_FIELDNAME => array ('id', 'starts', 'ends', 'file_id', 'stream_id', 'clip_length', 'fade_in', 'fade_out', 'cue_in', 'cue_out', 'media_item_played', 'instance_id', 'playout_status', 'broadcasted', ), + BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, ) ); /** @@ -101,12 +104,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, 'DbClipLength' => 4, 'DbFadeIn' => 5, 'DbFadeOut' => 6, 'DbCueIn' => 7, 'DbCueOut' => 8, 'DbMediaItemPlayed' => 9, 'DbInstanceId' => 10, 'DbPlayoutStatus' => 11, 'DbBroadcasted' => 12, ), - BasePeer::TYPE_STUDLYPHPNAME => array ('dbId' => 0, 'dbStarts' => 1, 'dbEnds' => 2, 'dbFileId' => 3, 'dbClipLength' => 4, 'dbFadeIn' => 5, 'dbFadeOut' => 6, 'dbCueIn' => 7, 'dbCueOut' => 8, 'dbMediaItemPlayed' => 9, 'dbInstanceId' => 10, 'dbPlayoutStatus' => 11, 'dbBroadcasted' => 12, ), - BasePeer::TYPE_COLNAME => array (self::ID => 0, self::STARTS => 1, self::ENDS => 2, self::FILE_ID => 3, self::CLIP_LENGTH => 4, self::FADE_IN => 5, self::FADE_OUT => 6, self::CUE_IN => 7, self::CUE_OUT => 8, self::MEDIA_ITEM_PLAYED => 9, self::INSTANCE_ID => 10, self::PLAYOUT_STATUS => 11, self::BROADCASTED => 12, ), - BasePeer::TYPE_RAW_COLNAME => array ('ID' => 0, 'STARTS' => 1, 'ENDS' => 2, 'FILE_ID' => 3, 'CLIP_LENGTH' => 4, 'FADE_IN' => 5, 'FADE_OUT' => 6, 'CUE_IN' => 7, 'CUE_OUT' => 8, 'MEDIA_ITEM_PLAYED' => 9, 'INSTANCE_ID' => 10, 'PLAYOUT_STATUS' => 11, 'BROADCASTED' => 12, ), - BasePeer::TYPE_FIELDNAME => array ('id' => 0, 'starts' => 1, 'ends' => 2, 'file_id' => 3, 'clip_length' => 4, 'fade_in' => 5, 'fade_out' => 6, 'cue_in' => 7, 'cue_out' => 8, 'media_item_played' => 9, 'instance_id' => 10, 'playout_status' => 11, 'broadcasted' => 12, ), - BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, ) + BasePeer::TYPE_PHPNAME => array ('DbId' => 0, 'DbStarts' => 1, 'DbEnds' => 2, 'DbFileId' => 3, 'DbStreamId' => 4, 'DbClipLength' => 5, 'DbFadeIn' => 6, 'DbFadeOut' => 7, 'DbCueIn' => 8, 'DbCueOut' => 9, 'DbMediaItemPlayed' => 10, 'DbInstanceId' => 11, 'DbPlayoutStatus' => 12, 'DbBroadcasted' => 13, ), + BasePeer::TYPE_STUDLYPHPNAME => array ('dbId' => 0, 'dbStarts' => 1, 'dbEnds' => 2, 'dbFileId' => 3, 'dbStreamId' => 4, 'dbClipLength' => 5, 'dbFadeIn' => 6, 'dbFadeOut' => 7, 'dbCueIn' => 8, 'dbCueOut' => 9, 'dbMediaItemPlayed' => 10, 'dbInstanceId' => 11, 'dbPlayoutStatus' => 12, 'dbBroadcasted' => 13, ), + BasePeer::TYPE_COLNAME => array (self::ID => 0, self::STARTS => 1, self::ENDS => 2, self::FILE_ID => 3, self::STREAM_ID => 4, self::CLIP_LENGTH => 5, self::FADE_IN => 6, self::FADE_OUT => 7, self::CUE_IN => 8, self::CUE_OUT => 9, self::MEDIA_ITEM_PLAYED => 10, self::INSTANCE_ID => 11, self::PLAYOUT_STATUS => 12, self::BROADCASTED => 13, ), + BasePeer::TYPE_RAW_COLNAME => array ('ID' => 0, 'STARTS' => 1, 'ENDS' => 2, 'FILE_ID' => 3, 'STREAM_ID' => 4, 'CLIP_LENGTH' => 5, 'FADE_IN' => 6, 'FADE_OUT' => 7, 'CUE_IN' => 8, 'CUE_OUT' => 9, 'MEDIA_ITEM_PLAYED' => 10, 'INSTANCE_ID' => 11, 'PLAYOUT_STATUS' => 12, 'BROADCASTED' => 13, ), + BasePeer::TYPE_FIELDNAME => array ('id' => 0, 'starts' => 1, 'ends' => 2, 'file_id' => 3, 'stream_id' => 4, 'clip_length' => 5, 'fade_in' => 6, 'fade_out' => 7, 'cue_in' => 8, 'cue_out' => 9, 'media_item_played' => 10, 'instance_id' => 11, 'playout_status' => 12, 'broadcasted' => 13, ), + BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, ) ); /** @@ -182,6 +185,7 @@ abstract class BaseCcSchedulePeer { $criteria->addSelectColumn(CcSchedulePeer::STARTS); $criteria->addSelectColumn(CcSchedulePeer::ENDS); $criteria->addSelectColumn(CcSchedulePeer::FILE_ID); + $criteria->addSelectColumn(CcSchedulePeer::STREAM_ID); $criteria->addSelectColumn(CcSchedulePeer::CLIP_LENGTH); $criteria->addSelectColumn(CcSchedulePeer::FADE_IN); $criteria->addSelectColumn(CcSchedulePeer::FADE_OUT); @@ -196,6 +200,7 @@ abstract class BaseCcSchedulePeer { $criteria->addSelectColumn($alias . '.STARTS'); $criteria->addSelectColumn($alias . '.ENDS'); $criteria->addSelectColumn($alias . '.FILE_ID'); + $criteria->addSelectColumn($alias . '.STREAM_ID'); $criteria->addSelectColumn($alias . '.CLIP_LENGTH'); $criteria->addSelectColumn($alias . '.FADE_IN'); $criteria->addSelectColumn($alias . '.FADE_OUT'); @@ -398,6 +403,9 @@ abstract class BaseCcSchedulePeer { */ public static function clearRelatedInstancePool() { + // Invalidate objects in CcWebstreamMetadataPeer instance pool, + // since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule. + CcWebstreamMetadataPeer::clearInstancePool(); } /** @@ -590,6 +598,56 @@ abstract class BaseCcSchedulePeer { } + /** + * 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(CcSchedulePeer::TABLE_NAME); + + if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->setDistinct(); + } + + if (!$criteria->hasSelectClause()) { + CcSchedulePeer::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(CcSchedulePeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $criteria->addJoin(CcSchedulePeer::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; + } + + /** * Selects a collection of CcSchedule objects pre-filled with their CcShowInstances objects. * @param Criteria $criteria @@ -722,6 +780,72 @@ abstract class BaseCcSchedulePeer { } + /** + * Selects a collection of CcSchedule 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 CcSchedule 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); + } + + CcSchedulePeer::addSelectColumns($criteria); + $startcol = (CcSchedulePeer::NUM_COLUMNS - CcSchedulePeer::NUM_LAZY_LOAD_COLUMNS); + CcWebstreamPeer::addSelectColumns($criteria); + + $criteria->addJoin(CcSchedulePeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); + + $stmt = BasePeer::doSelect($criteria, $con); + $results = array(); + + while ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $key1 = CcSchedulePeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcSchedulePeer::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 = CcSchedulePeer::getOMClass(false); + + $obj1 = new $cls(); + $obj1->hydrate($row); + CcSchedulePeer::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 (CcSchedule) to $obj2 (CcWebstream) + $obj2->addCcSchedule($obj1); + + } // if joined row was not null + + $results[] = $obj1; + } + $stmt->closeCursor(); + return $results; + } + + /** * Returns the number of rows matching criteria, joining all related tables * @@ -762,6 +886,8 @@ abstract class BaseCcSchedulePeer { $criteria->addJoin(CcSchedulePeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + $criteria->addJoin(CcSchedulePeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); + $stmt = BasePeer::doCount($criteria, $con); if ($row = $stmt->fetch(PDO::FETCH_NUM)) { @@ -801,10 +927,15 @@ abstract class BaseCcSchedulePeer { 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); + $criteria->addJoin(CcSchedulePeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); $criteria->addJoin(CcSchedulePeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + $criteria->addJoin(CcSchedulePeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); + $stmt = BasePeer::doSelect($criteria, $con); $results = array(); @@ -858,6 +989,24 @@ abstract class BaseCcSchedulePeer { $obj3->addCcSchedule($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 (CcSchedule) to the collection in $obj4 (CcWebstream) + $obj4->addCcSchedule($obj1); + } // if joined row not null + $results[] = $obj1; } $stmt->closeCursor(); @@ -903,6 +1052,8 @@ abstract class BaseCcSchedulePeer { $criteria->addJoin(CcSchedulePeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + $criteria->addJoin(CcSchedulePeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); + $stmt = BasePeer::doCount($criteria, $con); if ($row = $stmt->fetch(PDO::FETCH_NUM)) { @@ -953,6 +1104,60 @@ abstract class BaseCcSchedulePeer { $criteria->addJoin(CcSchedulePeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); + $criteria->addJoin(CcSchedulePeer::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 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(CcSchedulePeer::TABLE_NAME); + + if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->setDistinct(); + } + + if (!$criteria->hasSelectClause()) { + CcSchedulePeer::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(CcSchedulePeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $criteria->addJoin(CcSchedulePeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); + + $criteria->addJoin(CcSchedulePeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + $stmt = BasePeer::doCount($criteria, $con); if ($row = $stmt->fetch(PDO::FETCH_NUM)) { @@ -992,8 +1197,13 @@ abstract class BaseCcSchedulePeer { 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); + $criteria->addJoin(CcSchedulePeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + $criteria->addJoin(CcSchedulePeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); + $stmt = BasePeer::doSelect($criteria, $con); $results = array(); @@ -1029,6 +1239,25 @@ abstract class BaseCcSchedulePeer { // Add the $obj1 (CcSchedule) to the collection in $obj2 (CcFiles) $obj2->addCcSchedule($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 (CcSchedule) to the collection in $obj3 (CcWebstream) + $obj3->addCcSchedule($obj1); + } // if joined row is not null $results[] = $obj1; @@ -1065,8 +1294,13 @@ abstract class BaseCcSchedulePeer { CcShowInstancesPeer::addSelectColumns($criteria); $startcol3 = $startcol2 + (CcShowInstancesPeer::NUM_COLUMNS - CcShowInstancesPeer::NUM_LAZY_LOAD_COLUMNS); + CcWebstreamPeer::addSelectColumns($criteria); + $startcol4 = $startcol3 + (CcWebstreamPeer::NUM_COLUMNS - CcWebstreamPeer::NUM_LAZY_LOAD_COLUMNS); + $criteria->addJoin(CcSchedulePeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); + $criteria->addJoin(CcSchedulePeer::STREAM_ID, CcWebstreamPeer::ID, $join_behavior); + $stmt = BasePeer::doSelect($criteria, $con); $results = array(); @@ -1102,6 +1336,122 @@ abstract class BaseCcSchedulePeer { // Add the $obj1 (CcSchedule) to the collection in $obj2 (CcShowInstances) $obj2->addCcSchedule($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 (CcSchedule) to the collection in $obj3 (CcWebstream) + $obj3->addCcSchedule($obj1); + + } // if joined row is not null + + $results[] = $obj1; + } + $stmt->closeCursor(); + return $results; + } + + + /** + * Selects a collection of CcSchedule 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 CcSchedule 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); + } + + CcSchedulePeer::addSelectColumns($criteria); + $startcol2 = (CcSchedulePeer::NUM_COLUMNS - CcSchedulePeer::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); + + $criteria->addJoin(CcSchedulePeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); + + $criteria->addJoin(CcSchedulePeer::FILE_ID, CcFilesPeer::ID, $join_behavior); + + + $stmt = BasePeer::doSelect($criteria, $con); + $results = array(); + + while ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $key1 = CcSchedulePeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcSchedulePeer::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 = CcSchedulePeer::getOMClass(false); + + $obj1 = new $cls(); + $obj1->hydrate($row); + CcSchedulePeer::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 (CcSchedule) to the collection in $obj2 (CcShowInstances) + $obj2->addCcSchedule($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 (CcSchedule) to the collection in $obj3 (CcFiles) + $obj3->addCcSchedule($obj1); + } // if joined row is not null $results[] = $obj1; diff --git a/airtime_mvc/application/models/airtime/om/BaseCcScheduleQuery.php b/airtime_mvc/application/models/airtime/om/BaseCcScheduleQuery.php index 236e3cb26..890a8cab9 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcScheduleQuery.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcScheduleQuery.php @@ -10,6 +10,7 @@ * @method CcScheduleQuery orderByDbStarts($order = Criteria::ASC) Order by the starts column * @method CcScheduleQuery orderByDbEnds($order = Criteria::ASC) Order by the ends column * @method CcScheduleQuery orderByDbFileId($order = Criteria::ASC) Order by the file_id column + * @method CcScheduleQuery orderByDbStreamId($order = Criteria::ASC) Order by the stream_id column * @method CcScheduleQuery orderByDbClipLength($order = Criteria::ASC) Order by the clip_length column * @method CcScheduleQuery orderByDbFadeIn($order = Criteria::ASC) Order by the fade_in column * @method CcScheduleQuery orderByDbFadeOut($order = Criteria::ASC) Order by the fade_out column @@ -24,6 +25,7 @@ * @method CcScheduleQuery groupByDbStarts() Group by the starts column * @method CcScheduleQuery groupByDbEnds() Group by the ends column * @method CcScheduleQuery groupByDbFileId() Group by the file_id column + * @method CcScheduleQuery groupByDbStreamId() Group by the stream_id column * @method CcScheduleQuery groupByDbClipLength() Group by the clip_length column * @method CcScheduleQuery groupByDbFadeIn() Group by the fade_in column * @method CcScheduleQuery groupByDbFadeOut() Group by the fade_out column @@ -46,6 +48,14 @@ * @method CcScheduleQuery rightJoinCcFiles($relationAlias = '') Adds a RIGHT JOIN clause to the query using the CcFiles relation * @method CcScheduleQuery innerJoinCcFiles($relationAlias = '') Adds a INNER JOIN clause to the query using the CcFiles relation * + * @method CcScheduleQuery leftJoinCcWebstream($relationAlias = '') Adds a LEFT JOIN clause to the query using the CcWebstream relation + * @method CcScheduleQuery rightJoinCcWebstream($relationAlias = '') Adds a RIGHT JOIN clause to the query using the CcWebstream relation + * @method CcScheduleQuery innerJoinCcWebstream($relationAlias = '') Adds a INNER JOIN clause to the query using the CcWebstream relation + * + * @method CcScheduleQuery leftJoinCcWebstreamMetadata($relationAlias = '') Adds a LEFT JOIN clause to the query using the CcWebstreamMetadata relation + * @method CcScheduleQuery rightJoinCcWebstreamMetadata($relationAlias = '') Adds a RIGHT JOIN clause to the query using the CcWebstreamMetadata relation + * @method CcScheduleQuery innerJoinCcWebstreamMetadata($relationAlias = '') Adds a INNER JOIN clause to the query using the CcWebstreamMetadata relation + * * @method CcSchedule findOne(PropelPDO $con = null) Return the first CcSchedule matching the query * @method CcSchedule findOneOrCreate(PropelPDO $con = null) Return the first CcSchedule matching the query, or a new CcSchedule object populated from the query conditions when no match is found * @@ -53,6 +63,7 @@ * @method CcSchedule findOneByDbStarts(string $starts) Return the first CcSchedule filtered by the starts column * @method CcSchedule findOneByDbEnds(string $ends) Return the first CcSchedule filtered by the ends column * @method CcSchedule findOneByDbFileId(int $file_id) Return the first CcSchedule filtered by the file_id column + * @method CcSchedule findOneByDbStreamId(int $stream_id) Return the first CcSchedule filtered by the stream_id column * @method CcSchedule findOneByDbClipLength(string $clip_length) Return the first CcSchedule filtered by the clip_length column * @method CcSchedule findOneByDbFadeIn(string $fade_in) Return the first CcSchedule filtered by the fade_in column * @method CcSchedule findOneByDbFadeOut(string $fade_out) Return the first CcSchedule filtered by the fade_out column @@ -67,6 +78,7 @@ * @method array findByDbStarts(string $starts) Return CcSchedule objects filtered by the starts column * @method array findByDbEnds(string $ends) Return CcSchedule objects filtered by the ends column * @method array findByDbFileId(int $file_id) Return CcSchedule objects filtered by the file_id column + * @method array findByDbStreamId(int $stream_id) Return CcSchedule objects filtered by the stream_id column * @method array findByDbClipLength(string $clip_length) Return CcSchedule objects filtered by the clip_length column * @method array findByDbFadeIn(string $fade_in) Return CcSchedule objects filtered by the fade_in column * @method array findByDbFadeOut(string $fade_out) Return CcSchedule objects filtered by the fade_out column @@ -295,6 +307,37 @@ abstract class BaseCcScheduleQuery extends ModelCriteria return $this->addUsingAlias(CcSchedulePeer::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 CcScheduleQuery 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(CcSchedulePeer::STREAM_ID, $dbStreamId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbStreamId['max'])) { + $this->addUsingAlias(CcSchedulePeer::STREAM_ID, $dbStreamId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcSchedulePeer::STREAM_ID, $dbStreamId, $comparison); + } + /** * Filter the query on the clip_length column * @@ -661,6 +704,134 @@ abstract class BaseCcScheduleQuery extends ModelCriteria ->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 CcScheduleQuery The current query, for fluid interface + */ + public function filterByCcWebstream($ccWebstream, $comparison = null) + { + return $this + ->addUsingAlias(CcSchedulePeer::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 CcScheduleQuery 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 CcWebstreamMetadata object + * + * @param CcWebstreamMetadata $ccWebstreamMetadata the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return CcScheduleQuery The current query, for fluid interface + */ + public function filterByCcWebstreamMetadata($ccWebstreamMetadata, $comparison = null) + { + return $this + ->addUsingAlias(CcSchedulePeer::ID, $ccWebstreamMetadata->getDbInstanceId(), $comparison); + } + + /** + * Adds a JOIN clause to the query using the CcWebstreamMetadata relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return CcScheduleQuery The current query, for fluid interface + */ + public function joinCcWebstreamMetadata($relationAlias = '', $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('CcWebstreamMetadata'); + + // 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, 'CcWebstreamMetadata'); + } + + return $this; + } + + /** + * Use the CcWebstreamMetadata relation CcWebstreamMetadata 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 CcWebstreamMetadataQuery A secondary query class using the current class as primary query + */ + public function useCcWebstreamMetadataQuery($relationAlias = '', $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinCcWebstreamMetadata($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'CcWebstreamMetadata', 'CcWebstreamMetadataQuery'); + } + /** * Exclude object from result * diff --git a/airtime_mvc/application/models/airtime/om/BaseCcShowInstances.php b/airtime_mvc/application/models/airtime/om/BaseCcShowInstances.php index 7bea16463..1caf7df62 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcShowInstances.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcShowInstances.php @@ -1992,6 +1992,31 @@ abstract class BaseCcShowInstances extends BaseObject implements Persistent return $this->getCcSchedules($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 CcSchedules 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 CcSchedule[] List of CcSchedule objects + */ + public function getCcSchedulesJoinCcWebstream($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $query = CcScheduleQuery::create(null, $criteria); + $query->joinWith('CcWebstream', $join_behavior); + + return $this->getCcSchedules($query, $con); + } + /** * Clears the current object and sets all attributes to their default values */ diff --git a/airtime_mvc/application/models/airtime/om/BaseCcSubjs.php b/airtime_mvc/application/models/airtime/om/BaseCcSubjs.php index 40cd181bf..c335d7158 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcSubjs.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcSubjs.php @@ -109,14 +109,14 @@ abstract class BaseCcSubjs extends BaseObject implements Persistent protected $login_attempts; /** - * @var array CcAccess[] Collection to store aggregation of CcAccess objects. + * @var array CcFiles[] Collection to store aggregation of CcFiles objects. */ - protected $collCcAccesss; + protected $collCcFilessRelatedByDbOwnerId; /** * @var array CcFiles[] Collection to store aggregation of CcFiles objects. */ - protected $collCcFiless; + protected $collCcFilessRelatedByDbEditedby; /** * @var array CcPerms[] Collection to store aggregation of CcPerms objects. @@ -133,6 +133,11 @@ abstract class BaseCcSubjs extends BaseObject implements Persistent */ protected $collCcPlaylists; + /** + * @var array CcBlock[] Collection to store aggregation of CcBlock objects. + */ + protected $collCcBlocks; + /** * @var array CcPref[] Collection to store aggregation of CcPref objects. */ @@ -821,9 +826,9 @@ abstract class BaseCcSubjs extends BaseObject implements Persistent if ($deep) { // also de-associate any related objects? - $this->collCcAccesss = null; + $this->collCcFilessRelatedByDbOwnerId = null; - $this->collCcFiless = null; + $this->collCcFilessRelatedByDbEditedby = null; $this->collCcPermss = null; @@ -831,6 +836,8 @@ abstract class BaseCcSubjs extends BaseObject implements Persistent $this->collCcPlaylists = null; + $this->collCcBlocks = null; + $this->collCcPrefs = null; $this->collCcSesss = null; @@ -970,16 +977,16 @@ abstract class BaseCcSubjs extends BaseObject implements Persistent $this->resetModified(); // [HL] After being saved an object is no longer 'modified' } - if ($this->collCcAccesss !== null) { - foreach ($this->collCcAccesss as $referrerFK) { + if ($this->collCcFilessRelatedByDbOwnerId !== null) { + foreach ($this->collCcFilessRelatedByDbOwnerId as $referrerFK) { if (!$referrerFK->isDeleted()) { $affectedRows += $referrerFK->save($con); } } } - if ($this->collCcFiless !== null) { - foreach ($this->collCcFiless as $referrerFK) { + if ($this->collCcFilessRelatedByDbEditedby !== null) { + foreach ($this->collCcFilessRelatedByDbEditedby as $referrerFK) { if (!$referrerFK->isDeleted()) { $affectedRows += $referrerFK->save($con); } @@ -1010,6 +1017,14 @@ abstract class BaseCcSubjs extends BaseObject implements Persistent } } + if ($this->collCcBlocks !== null) { + foreach ($this->collCcBlocks as $referrerFK) { + if (!$referrerFK->isDeleted()) { + $affectedRows += $referrerFK->save($con); + } + } + } + if ($this->collCcPrefs !== null) { foreach ($this->collCcPrefs as $referrerFK) { if (!$referrerFK->isDeleted()) { @@ -1105,16 +1120,16 @@ abstract class BaseCcSubjs extends BaseObject implements Persistent } - if ($this->collCcAccesss !== null) { - foreach ($this->collCcAccesss as $referrerFK) { + if ($this->collCcFilessRelatedByDbOwnerId !== null) { + foreach ($this->collCcFilessRelatedByDbOwnerId as $referrerFK) { if (!$referrerFK->validate($columns)) { $failureMap = array_merge($failureMap, $referrerFK->getValidationFailures()); } } } - if ($this->collCcFiless !== null) { - foreach ($this->collCcFiless as $referrerFK) { + if ($this->collCcFilessRelatedByDbEditedby !== null) { + foreach ($this->collCcFilessRelatedByDbEditedby as $referrerFK) { if (!$referrerFK->validate($columns)) { $failureMap = array_merge($failureMap, $referrerFK->getValidationFailures()); } @@ -1145,6 +1160,14 @@ abstract class BaseCcSubjs extends BaseObject implements Persistent } } + if ($this->collCcBlocks !== null) { + foreach ($this->collCcBlocks as $referrerFK) { + if (!$referrerFK->validate($columns)) { + $failureMap = array_merge($failureMap, $referrerFK->getValidationFailures()); + } + } + } + if ($this->collCcPrefs !== null) { foreach ($this->collCcPrefs as $referrerFK) { if (!$referrerFK->validate($columns)) { @@ -1487,15 +1510,15 @@ abstract class BaseCcSubjs extends BaseObject implements Persistent // the getter/setter methods for fkey referrer objects. $copyObj->setNew(false); - foreach ($this->getCcAccesss() as $relObj) { + foreach ($this->getCcFilessRelatedByDbOwnerId() as $relObj) { if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves - $copyObj->addCcAccess($relObj->copy($deepCopy)); + $copyObj->addCcFilesRelatedByDbOwnerId($relObj->copy($deepCopy)); } } - foreach ($this->getCcFiless() as $relObj) { + foreach ($this->getCcFilessRelatedByDbEditedby() as $relObj) { if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves - $copyObj->addCcFiles($relObj->copy($deepCopy)); + $copyObj->addCcFilesRelatedByDbEditedby($relObj->copy($deepCopy)); } } @@ -1517,6 +1540,12 @@ abstract class BaseCcSubjs extends BaseObject implements Persistent } } + foreach ($this->getCcBlocks() as $relObj) { + if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves + $copyObj->addCcBlock($relObj->copy($deepCopy)); + } + } + foreach ($this->getCcPrefs() as $relObj) { if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves $copyObj->addCcPref($relObj->copy($deepCopy)); @@ -1581,141 +1610,32 @@ abstract class BaseCcSubjs extends BaseObject implements Persistent } /** - * Clears out the collCcAccesss collection + * Clears out the collCcFilessRelatedByDbOwnerId 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 addCcAccesss() + * @see addCcFilessRelatedByDbOwnerId() */ - public function clearCcAccesss() + public function clearCcFilessRelatedByDbOwnerId() { - $this->collCcAccesss = null; // important to set this to NULL since that means it is uninitialized + $this->collCcFilessRelatedByDbOwnerId = null; // important to set this to NULL since that means it is uninitialized } /** - * Initializes the collCcAccesss collection. + * Initializes the collCcFilessRelatedByDbOwnerId collection. * - * By default this just sets the collCcAccesss collection to an empty array (like clearcollCcAccesss()); + * By default this just sets the collCcFilessRelatedByDbOwnerId collection to an empty array (like clearcollCcFilessRelatedByDbOwnerId()); * 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 initCcAccesss() + public function initCcFilessRelatedByDbOwnerId() { - $this->collCcAccesss = new PropelObjectCollection(); - $this->collCcAccesss->setModel('CcAccess'); - } - - /** - * Gets an array of CcAccess 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 CcSubjs 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 CcAccess[] List of CcAccess objects - * @throws PropelException - */ - public function getCcAccesss($criteria = null, PropelPDO $con = null) - { - if(null === $this->collCcAccesss || null !== $criteria) { - if ($this->isNew() && null === $this->collCcAccesss) { - // return empty collection - $this->initCcAccesss(); - } else { - $collCcAccesss = CcAccessQuery::create(null, $criteria) - ->filterByCcSubjs($this) - ->find($con); - if (null !== $criteria) { - return $collCcAccesss; - } - $this->collCcAccesss = $collCcAccesss; - } - } - return $this->collCcAccesss; - } - - /** - * Returns the number of related CcAccess objects. - * - * @param Criteria $criteria - * @param boolean $distinct - * @param PropelPDO $con - * @return int Count of related CcAccess objects. - * @throws PropelException - */ - public function countCcAccesss(Criteria $criteria = null, $distinct = false, PropelPDO $con = null) - { - if(null === $this->collCcAccesss || null !== $criteria) { - if ($this->isNew() && null === $this->collCcAccesss) { - return 0; - } else { - $query = CcAccessQuery::create(null, $criteria); - if($distinct) { - $query->distinct(); - } - return $query - ->filterByCcSubjs($this) - ->count($con); - } - } else { - return count($this->collCcAccesss); - } - } - - /** - * Method called to associate a CcAccess object to this object - * through the CcAccess foreign key attribute. - * - * @param CcAccess $l CcAccess - * @return void - * @throws PropelException - */ - public function addCcAccess(CcAccess $l) - { - if ($this->collCcAccesss === null) { - $this->initCcAccesss(); - } - if (!$this->collCcAccesss->contains($l)) { // only add it if the **same** object is not already associated - $this->collCcAccesss[]= $l; - $l->setCcSubjs($this); - } - } - - /** - * Clears out the collCcFiless 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 addCcFiless() - */ - public function clearCcFiless() - { - $this->collCcFiless = null; // important to set this to NULL since that means it is uninitialized - } - - /** - * Initializes the collCcFiless collection. - * - * By default this just sets the collCcFiless collection to an empty array (like clearcollCcFiless()); - * 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 initCcFiless() - { - $this->collCcFiless = new PropelObjectCollection(); - $this->collCcFiless->setModel('CcFiles'); + $this->collCcFilessRelatedByDbOwnerId = new PropelObjectCollection(); + $this->collCcFilessRelatedByDbOwnerId->setModel('CcFiles'); } /** @@ -1732,23 +1652,23 @@ abstract class BaseCcSubjs extends BaseObject implements Persistent * @return PropelCollection|array CcFiles[] List of CcFiles objects * @throws PropelException */ - public function getCcFiless($criteria = null, PropelPDO $con = null) + public function getCcFilessRelatedByDbOwnerId($criteria = null, PropelPDO $con = null) { - if(null === $this->collCcFiless || null !== $criteria) { - if ($this->isNew() && null === $this->collCcFiless) { + if(null === $this->collCcFilessRelatedByDbOwnerId || null !== $criteria) { + if ($this->isNew() && null === $this->collCcFilessRelatedByDbOwnerId) { // return empty collection - $this->initCcFiless(); + $this->initCcFilessRelatedByDbOwnerId(); } else { - $collCcFiless = CcFilesQuery::create(null, $criteria) - ->filterByCcSubjs($this) + $collCcFilessRelatedByDbOwnerId = CcFilesQuery::create(null, $criteria) + ->filterByFkOwner($this) ->find($con); if (null !== $criteria) { - return $collCcFiless; + return $collCcFilessRelatedByDbOwnerId; } - $this->collCcFiless = $collCcFiless; + $this->collCcFilessRelatedByDbOwnerId = $collCcFilessRelatedByDbOwnerId; } } - return $this->collCcFiless; + return $this->collCcFilessRelatedByDbOwnerId; } /** @@ -1760,10 +1680,10 @@ abstract class BaseCcSubjs extends BaseObject implements Persistent * @return int Count of related CcFiles objects. * @throws PropelException */ - public function countCcFiless(Criteria $criteria = null, $distinct = false, PropelPDO $con = null) + public function countCcFilessRelatedByDbOwnerId(Criteria $criteria = null, $distinct = false, PropelPDO $con = null) { - if(null === $this->collCcFiless || null !== $criteria) { - if ($this->isNew() && null === $this->collCcFiless) { + if(null === $this->collCcFilessRelatedByDbOwnerId || null !== $criteria) { + if ($this->isNew() && null === $this->collCcFilessRelatedByDbOwnerId) { return 0; } else { $query = CcFilesQuery::create(null, $criteria); @@ -1771,11 +1691,11 @@ abstract class BaseCcSubjs extends BaseObject implements Persistent $query->distinct(); } return $query - ->filterByCcSubjs($this) + ->filterByFkOwner($this) ->count($con); } } else { - return count($this->collCcFiless); + return count($this->collCcFilessRelatedByDbOwnerId); } } @@ -1787,14 +1707,14 @@ abstract class BaseCcSubjs extends BaseObject implements Persistent * @return void * @throws PropelException */ - public function addCcFiles(CcFiles $l) + public function addCcFilesRelatedByDbOwnerId(CcFiles $l) { - if ($this->collCcFiless === null) { - $this->initCcFiless(); + if ($this->collCcFilessRelatedByDbOwnerId === null) { + $this->initCcFilessRelatedByDbOwnerId(); } - if (!$this->collCcFiless->contains($l)) { // only add it if the **same** object is not already associated - $this->collCcFiless[]= $l; - $l->setCcSubjs($this); + if (!$this->collCcFilessRelatedByDbOwnerId->contains($l)) { // only add it if the **same** object is not already associated + $this->collCcFilessRelatedByDbOwnerId[]= $l; + $l->setFkOwner($this); } } @@ -1804,7 +1724,7 @@ abstract class BaseCcSubjs extends BaseObject implements Persistent * an identical criteria, it returns the collection. * Otherwise if this CcSubjs is new, it will return * an empty collection; or if this CcSubjs has previously - * been saved, it will retrieve related CcFiless from storage. + * been saved, it will retrieve related CcFilessRelatedByDbOwnerId from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you @@ -1815,12 +1735,146 @@ abstract class BaseCcSubjs extends BaseObject implements Persistent * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) * @return PropelCollection|array CcFiles[] List of CcFiles objects */ - public function getCcFilessJoinCcMusicDirs($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) + public function getCcFilessRelatedByDbOwnerIdJoinCcMusicDirs($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { $query = CcFilesQuery::create(null, $criteria); $query->joinWith('CcMusicDirs', $join_behavior); - return $this->getCcFiless($query, $con); + return $this->getCcFilessRelatedByDbOwnerId($query, $con); + } + + /** + * Clears out the collCcFilessRelatedByDbEditedby 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 addCcFilessRelatedByDbEditedby() + */ + public function clearCcFilessRelatedByDbEditedby() + { + $this->collCcFilessRelatedByDbEditedby = null; // important to set this to NULL since that means it is uninitialized + } + + /** + * Initializes the collCcFilessRelatedByDbEditedby collection. + * + * By default this just sets the collCcFilessRelatedByDbEditedby collection to an empty array (like clearcollCcFilessRelatedByDbEditedby()); + * 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 initCcFilessRelatedByDbEditedby() + { + $this->collCcFilessRelatedByDbEditedby = new PropelObjectCollection(); + $this->collCcFilessRelatedByDbEditedby->setModel('CcFiles'); + } + + /** + * Gets an array of CcFiles 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 CcSubjs 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 CcFiles[] List of CcFiles objects + * @throws PropelException + */ + public function getCcFilessRelatedByDbEditedby($criteria = null, PropelPDO $con = null) + { + if(null === $this->collCcFilessRelatedByDbEditedby || null !== $criteria) { + if ($this->isNew() && null === $this->collCcFilessRelatedByDbEditedby) { + // return empty collection + $this->initCcFilessRelatedByDbEditedby(); + } else { + $collCcFilessRelatedByDbEditedby = CcFilesQuery::create(null, $criteria) + ->filterByCcSubjsRelatedByDbEditedby($this) + ->find($con); + if (null !== $criteria) { + return $collCcFilessRelatedByDbEditedby; + } + $this->collCcFilessRelatedByDbEditedby = $collCcFilessRelatedByDbEditedby; + } + } + return $this->collCcFilessRelatedByDbEditedby; + } + + /** + * Returns the number of related CcFiles objects. + * + * @param Criteria $criteria + * @param boolean $distinct + * @param PropelPDO $con + * @return int Count of related CcFiles objects. + * @throws PropelException + */ + public function countCcFilessRelatedByDbEditedby(Criteria $criteria = null, $distinct = false, PropelPDO $con = null) + { + if(null === $this->collCcFilessRelatedByDbEditedby || null !== $criteria) { + if ($this->isNew() && null === $this->collCcFilessRelatedByDbEditedby) { + return 0; + } else { + $query = CcFilesQuery::create(null, $criteria); + if($distinct) { + $query->distinct(); + } + return $query + ->filterByCcSubjsRelatedByDbEditedby($this) + ->count($con); + } + } else { + return count($this->collCcFilessRelatedByDbEditedby); + } + } + + /** + * Method called to associate a CcFiles object to this object + * through the CcFiles foreign key attribute. + * + * @param CcFiles $l CcFiles + * @return void + * @throws PropelException + */ + public function addCcFilesRelatedByDbEditedby(CcFiles $l) + { + if ($this->collCcFilessRelatedByDbEditedby === null) { + $this->initCcFilessRelatedByDbEditedby(); + } + if (!$this->collCcFilessRelatedByDbEditedby->contains($l)) { // only add it if the **same** object is not already associated + $this->collCcFilessRelatedByDbEditedby[]= $l; + $l->setCcSubjsRelatedByDbEditedby($this); + } + } + + + /** + * If this collection has already been initialized with + * an identical criteria, it returns the collection. + * Otherwise if this CcSubjs is new, it will return + * an empty collection; or if this CcSubjs has previously + * been saved, it will retrieve related CcFilessRelatedByDbEditedby 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 CcSubjs. + * + * @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 CcFiles[] List of CcFiles objects + */ + public function getCcFilessRelatedByDbEditedbyJoinCcMusicDirs($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $query = CcFilesQuery::create(null, $criteria); + $query->joinWith('CcMusicDirs', $join_behavior); + + return $this->getCcFilessRelatedByDbEditedby($query, $con); } /** @@ -2175,6 +2229,115 @@ abstract class BaseCcSubjs extends BaseObject implements Persistent } } + /** + * Clears out the collCcBlocks 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 addCcBlocks() + */ + public function clearCcBlocks() + { + $this->collCcBlocks = null; // important to set this to NULL since that means it is uninitialized + } + + /** + * Initializes the collCcBlocks collection. + * + * By default this just sets the collCcBlocks collection to an empty array (like clearcollCcBlocks()); + * 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 initCcBlocks() + { + $this->collCcBlocks = new PropelObjectCollection(); + $this->collCcBlocks->setModel('CcBlock'); + } + + /** + * Gets an array of CcBlock 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 CcSubjs 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 CcBlock[] List of CcBlock objects + * @throws PropelException + */ + public function getCcBlocks($criteria = null, PropelPDO $con = null) + { + if(null === $this->collCcBlocks || null !== $criteria) { + if ($this->isNew() && null === $this->collCcBlocks) { + // return empty collection + $this->initCcBlocks(); + } else { + $collCcBlocks = CcBlockQuery::create(null, $criteria) + ->filterByCcSubjs($this) + ->find($con); + if (null !== $criteria) { + return $collCcBlocks; + } + $this->collCcBlocks = $collCcBlocks; + } + } + return $this->collCcBlocks; + } + + /** + * Returns the number of related CcBlock objects. + * + * @param Criteria $criteria + * @param boolean $distinct + * @param PropelPDO $con + * @return int Count of related CcBlock objects. + * @throws PropelException + */ + public function countCcBlocks(Criteria $criteria = null, $distinct = false, PropelPDO $con = null) + { + if(null === $this->collCcBlocks || null !== $criteria) { + if ($this->isNew() && null === $this->collCcBlocks) { + return 0; + } else { + $query = CcBlockQuery::create(null, $criteria); + if($distinct) { + $query->distinct(); + } + return $query + ->filterByCcSubjs($this) + ->count($con); + } + } else { + return count($this->collCcBlocks); + } + } + + /** + * Method called to associate a CcBlock object to this object + * through the CcBlock foreign key attribute. + * + * @param CcBlock $l CcBlock + * @return void + * @throws PropelException + */ + public function addCcBlock(CcBlock $l) + { + if ($this->collCcBlocks === null) { + $this->initCcBlocks(); + } + if (!$this->collCcBlocks->contains($l)) { // only add it if the **same** object is not already associated + $this->collCcBlocks[]= $l; + $l->setCcSubjs($this); + } + } + /** * Clears out the collCcPrefs collection * @@ -2541,13 +2704,13 @@ abstract class BaseCcSubjs extends BaseObject implements Persistent public function clearAllReferences($deep = false) { if ($deep) { - if ($this->collCcAccesss) { - foreach ((array) $this->collCcAccesss as $o) { + if ($this->collCcFilessRelatedByDbOwnerId) { + foreach ((array) $this->collCcFilessRelatedByDbOwnerId as $o) { $o->clearAllReferences($deep); } } - if ($this->collCcFiless) { - foreach ((array) $this->collCcFiless as $o) { + if ($this->collCcFilessRelatedByDbEditedby) { + foreach ((array) $this->collCcFilessRelatedByDbEditedby as $o) { $o->clearAllReferences($deep); } } @@ -2566,6 +2729,11 @@ abstract class BaseCcSubjs extends BaseObject implements Persistent $o->clearAllReferences($deep); } } + if ($this->collCcBlocks) { + foreach ((array) $this->collCcBlocks as $o) { + $o->clearAllReferences($deep); + } + } if ($this->collCcPrefs) { foreach ((array) $this->collCcPrefs as $o) { $o->clearAllReferences($deep); @@ -2583,11 +2751,12 @@ abstract class BaseCcSubjs extends BaseObject implements Persistent } } // if ($deep) - $this->collCcAccesss = null; - $this->collCcFiless = null; + $this->collCcFilessRelatedByDbOwnerId = null; + $this->collCcFilessRelatedByDbEditedby = null; $this->collCcPermss = null; $this->collCcShowHostss = null; $this->collCcPlaylists = null; + $this->collCcBlocks = null; $this->collCcPrefs = null; $this->collCcSesss = null; $this->collCcSubjsTokens = null; diff --git a/airtime_mvc/application/models/airtime/om/BaseCcSubjsPeer.php b/airtime_mvc/application/models/airtime/om/BaseCcSubjsPeer.php index 68403579f..dbd9978d7 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcSubjsPeer.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcSubjsPeer.php @@ -404,6 +404,9 @@ abstract class BaseCcSubjsPeer { // 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 CcPlaylistPeer instance pool, + // since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule. + CcPlaylistPeer::clearInstancePool(); // Invalidate objects in CcPrefPeer instance pool, // since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule. CcPrefPeer::clearInstancePool(); diff --git a/airtime_mvc/application/models/airtime/om/BaseCcSubjsQuery.php b/airtime_mvc/application/models/airtime/om/BaseCcSubjsQuery.php index c76e2a1f8..38703d208 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcSubjsQuery.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcSubjsQuery.php @@ -38,13 +38,13 @@ * @method CcSubjsQuery rightJoin($relation) Adds a RIGHT JOIN clause to the query * @method CcSubjsQuery innerJoin($relation) Adds a INNER JOIN clause to the query * - * @method CcSubjsQuery leftJoinCcAccess($relationAlias = '') Adds a LEFT JOIN clause to the query using the CcAccess relation - * @method CcSubjsQuery rightJoinCcAccess($relationAlias = '') Adds a RIGHT JOIN clause to the query using the CcAccess relation - * @method CcSubjsQuery innerJoinCcAccess($relationAlias = '') Adds a INNER JOIN clause to the query using the CcAccess relation + * @method CcSubjsQuery leftJoinCcFilesRelatedByDbOwnerId($relationAlias = '') Adds a LEFT JOIN clause to the query using the CcFilesRelatedByDbOwnerId relation + * @method CcSubjsQuery rightJoinCcFilesRelatedByDbOwnerId($relationAlias = '') Adds a RIGHT JOIN clause to the query using the CcFilesRelatedByDbOwnerId relation + * @method CcSubjsQuery innerJoinCcFilesRelatedByDbOwnerId($relationAlias = '') Adds a INNER JOIN clause to the query using the CcFilesRelatedByDbOwnerId relation * - * @method CcSubjsQuery leftJoinCcFiles($relationAlias = '') Adds a LEFT JOIN clause to the query using the CcFiles relation - * @method CcSubjsQuery rightJoinCcFiles($relationAlias = '') Adds a RIGHT JOIN clause to the query using the CcFiles relation - * @method CcSubjsQuery innerJoinCcFiles($relationAlias = '') Adds a INNER JOIN clause to the query using the CcFiles relation + * @method CcSubjsQuery leftJoinCcFilesRelatedByDbEditedby($relationAlias = '') Adds a LEFT JOIN clause to the query using the CcFilesRelatedByDbEditedby relation + * @method CcSubjsQuery rightJoinCcFilesRelatedByDbEditedby($relationAlias = '') Adds a RIGHT JOIN clause to the query using the CcFilesRelatedByDbEditedby relation + * @method CcSubjsQuery innerJoinCcFilesRelatedByDbEditedby($relationAlias = '') Adds a INNER JOIN clause to the query using the CcFilesRelatedByDbEditedby relation * * @method CcSubjsQuery leftJoinCcPerms($relationAlias = '') Adds a LEFT JOIN clause to the query using the CcPerms relation * @method CcSubjsQuery rightJoinCcPerms($relationAlias = '') Adds a RIGHT JOIN clause to the query using the CcPerms relation @@ -58,6 +58,10 @@ * @method CcSubjsQuery rightJoinCcPlaylist($relationAlias = '') Adds a RIGHT JOIN clause to the query using the CcPlaylist relation * @method CcSubjsQuery innerJoinCcPlaylist($relationAlias = '') Adds a INNER JOIN clause to the query using the CcPlaylist relation * + * @method CcSubjsQuery leftJoinCcBlock($relationAlias = '') Adds a LEFT JOIN clause to the query using the CcBlock relation + * @method CcSubjsQuery rightJoinCcBlock($relationAlias = '') Adds a RIGHT JOIN clause to the query using the CcBlock relation + * @method CcSubjsQuery innerJoinCcBlock($relationAlias = '') Adds a INNER JOIN clause to the query using the CcBlock relation + * * @method CcSubjsQuery leftJoinCcPref($relationAlias = '') Adds a LEFT JOIN clause to the query using the CcPref relation * @method CcSubjsQuery rightJoinCcPref($relationAlias = '') Adds a RIGHT JOIN clause to the query using the CcPref relation * @method CcSubjsQuery innerJoinCcPref($relationAlias = '') Adds a INNER JOIN clause to the query using the CcPref relation @@ -518,31 +522,31 @@ abstract class BaseCcSubjsQuery extends ModelCriteria } /** - * Filter the query by a related CcAccess object + * Filter the query by a related CcFiles object * - * @param CcAccess $ccAccess the related object to use as filter + * @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 CcSubjsQuery The current query, for fluid interface */ - public function filterByCcAccess($ccAccess, $comparison = null) + public function filterByCcFilesRelatedByDbOwnerId($ccFiles, $comparison = null) { return $this - ->addUsingAlias(CcSubjsPeer::ID, $ccAccess->getOwner(), $comparison); + ->addUsingAlias(CcSubjsPeer::ID, $ccFiles->getDbOwnerId(), $comparison); } /** - * Adds a JOIN clause to the query using the CcAccess relation + * Adds a JOIN clause to the query using the CcFilesRelatedByDbOwnerId relation * * @param string $relationAlias optional alias for the relation * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' * * @return CcSubjsQuery The current query, for fluid interface */ - public function joinCcAccess($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + public function joinCcFilesRelatedByDbOwnerId($relationAlias = '', $joinType = Criteria::LEFT_JOIN) { $tableMap = $this->getTableMap(); - $relationMap = $tableMap->getRelation('CcAccess'); + $relationMap = $tableMap->getRelation('CcFilesRelatedByDbOwnerId'); // create a ModelJoin object for this join $join = new ModelJoin(); @@ -557,14 +561,14 @@ abstract class BaseCcSubjsQuery extends ModelCriteria $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); $this->addJoinObject($join, $relationAlias); } else { - $this->addJoinObject($join, 'CcAccess'); + $this->addJoinObject($join, 'CcFilesRelatedByDbOwnerId'); } return $this; } /** - * Use the CcAccess relation CcAccess object + * Use the CcFilesRelatedByDbOwnerId relation CcFiles object * * @see useQuery() * @@ -572,13 +576,13 @@ abstract class BaseCcSubjsQuery 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 CcAccessQuery A secondary query class using the current class as primary query + * @return CcFilesQuery A secondary query class using the current class as primary query */ - public function useCcAccessQuery($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + public function useCcFilesRelatedByDbOwnerIdQuery($relationAlias = '', $joinType = Criteria::LEFT_JOIN) { return $this - ->joinCcAccess($relationAlias, $joinType) - ->useQuery($relationAlias ? $relationAlias : 'CcAccess', 'CcAccessQuery'); + ->joinCcFilesRelatedByDbOwnerId($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'CcFilesRelatedByDbOwnerId', 'CcFilesQuery'); } /** @@ -589,24 +593,24 @@ abstract class BaseCcSubjsQuery extends ModelCriteria * * @return CcSubjsQuery The current query, for fluid interface */ - public function filterByCcFiles($ccFiles, $comparison = null) + public function filterByCcFilesRelatedByDbEditedby($ccFiles, $comparison = null) { return $this ->addUsingAlias(CcSubjsPeer::ID, $ccFiles->getDbEditedby(), $comparison); } /** - * Adds a JOIN clause to the query using the CcFiles relation + * Adds a JOIN clause to the query using the CcFilesRelatedByDbEditedby relation * * @param string $relationAlias optional alias for the relation * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' * * @return CcSubjsQuery The current query, for fluid interface */ - public function joinCcFiles($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + public function joinCcFilesRelatedByDbEditedby($relationAlias = '', $joinType = Criteria::LEFT_JOIN) { $tableMap = $this->getTableMap(); - $relationMap = $tableMap->getRelation('CcFiles'); + $relationMap = $tableMap->getRelation('CcFilesRelatedByDbEditedby'); // create a ModelJoin object for this join $join = new ModelJoin(); @@ -621,14 +625,14 @@ abstract class BaseCcSubjsQuery extends ModelCriteria $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); $this->addJoinObject($join, $relationAlias); } else { - $this->addJoinObject($join, 'CcFiles'); + $this->addJoinObject($join, 'CcFilesRelatedByDbEditedby'); } return $this; } /** - * Use the CcFiles relation CcFiles object + * Use the CcFilesRelatedByDbEditedby relation CcFiles object * * @see useQuery() * @@ -638,11 +642,11 @@ abstract class BaseCcSubjsQuery extends ModelCriteria * * @return CcFilesQuery A secondary query class using the current class as primary query */ - public function useCcFilesQuery($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + public function useCcFilesRelatedByDbEditedbyQuery($relationAlias = '', $joinType = Criteria::LEFT_JOIN) { return $this - ->joinCcFiles($relationAlias, $joinType) - ->useQuery($relationAlias ? $relationAlias : 'CcFiles', 'CcFilesQuery'); + ->joinCcFilesRelatedByDbEditedby($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'CcFilesRelatedByDbEditedby', 'CcFilesQuery'); } /** @@ -837,6 +841,70 @@ abstract class BaseCcSubjsQuery extends ModelCriteria ->useQuery($relationAlias ? $relationAlias : 'CcPlaylist', 'CcPlaylistQuery'); } + /** + * 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 CcSubjsQuery The current query, for fluid interface + */ + public function filterByCcBlock($ccBlock, $comparison = null) + { + return $this + ->addUsingAlias(CcSubjsPeer::ID, $ccBlock->getDbCreatorId(), $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 CcSubjsQuery 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 CcPref object * diff --git a/install_minimal/upgrades/airtime-2.0.0/propel/airtime/om/BaseCcPlaylist.php b/airtime_mvc/application/models/airtime/om/BaseCcWebstream.php similarity index 59% rename from install_minimal/upgrades/airtime-2.0.0/propel/airtime/om/BaseCcPlaylist.php rename to airtime_mvc/application/models/airtime/om/BaseCcWebstream.php index 222c1c6f4..6f6e16e2b 100644 --- a/install_minimal/upgrades/airtime-2.0.0/propel/airtime/om/BaseCcPlaylist.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcWebstream.php @@ -2,25 +2,25 @@ /** - * Base class that represents a row from the 'cc_playlist' table. + * Base class that represents a row from the 'cc_webstream' table. * * * * @package propel.generator.airtime.om */ -abstract class BaseCcPlaylist extends BaseObject implements Persistent +abstract class BaseCcWebstream extends BaseObject implements Persistent { /** * Peer class name */ - const PEER = 'CcPlaylistPeer'; + const PEER = 'CcWebstreamPeer'; /** * The Peer class. * Instance provides a convenient way of calling static methods on a class * that calling code may not be able to identify. - * @var CcPlaylistPeer + * @var CcWebstreamPeer */ protected static $peer; @@ -32,43 +32,10 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent /** * The value for the name field. - * Note: this column has a database default value of: '' * @var string */ protected $name; - /** - * The value for the state field. - * Note: this column has a database default value of: 'empty' - * @var string - */ - protected $state; - - /** - * The value for the currentlyaccessing field. - * Note: this column has a database default value of: 0 - * @var int - */ - protected $currentlyaccessing; - - /** - * The value for the editedby field. - * @var int - */ - protected $editedby; - - /** - * The value for the mtime field. - * @var string - */ - protected $mtime; - - /** - * The value for the creator field. - * @var string - */ - protected $creator; - /** * The value for the description field. * @var string @@ -76,14 +43,52 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent protected $description; /** - * @var CcSubjs + * The value for the url field. + * @var string */ - protected $aCcSubjs; + protected $url; /** - * @var array CcPlaylistcontents[] Collection to store aggregation of CcPlaylistcontents objects. + * The value for the length field. + * Note: this column has a database default value of: '00:00:00' + * @var string */ - protected $collCcPlaylistcontentss; + protected $length; + + /** + * The value for the creator_id field. + * @var int + */ + protected $creator_id; + + /** + * The value for the mtime field. + * @var string + */ + protected $mtime; + + /** + * The value for the utime field. + * @var string + */ + protected $utime; + + /** + * The value for the lptime field. + * @var string + */ + protected $lptime; + + /** + * The value for the mime field. + * @var string + */ + protected $mime; + + /** + * @var array CcSchedule[] Collection to store aggregation of CcSchedule objects. + */ + protected $collCcSchedules; /** * Flag to prevent endless save loop, if this object is referenced @@ -107,13 +112,11 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent */ public function applyDefaultValues() { - $this->name = ''; - $this->state = 'empty'; - $this->currentlyaccessing = 0; + $this->length = '00:00:00'; } /** - * Initializes internal state of BaseCcPlaylist object. + * Initializes internal state of BaseCcWebstream object. * @see applyDefaults() */ public function __construct() @@ -143,33 +146,43 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent } /** - * Get the [state] column value. + * Get the [description] column value. * * @return string */ - public function getDbState() + public function getDbDescription() { - return $this->state; + return $this->description; } /** - * Get the [currentlyaccessing] column value. + * Get the [url] column value. * - * @return int + * @return string */ - public function getDbCurrentlyaccessing() + public function getDbUrl() { - return $this->currentlyaccessing; + return $this->url; } /** - * Get the [editedby] column value. + * Get the [length] column value. + * + * @return string + */ + public function getDbLength() + { + return $this->length; + } + + /** + * Get the [creator_id] column value. * * @return int */ - public function getDbEditedby() + public function getDbCreatorId() { - return $this->editedby; + return $this->creator_id; } /** @@ -206,30 +219,86 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent } /** - * Get the [creator] column value. + * Get the [optionally formatted] temporal [utime] column value. * - * @return string + * + * @param string $format The date/time format string (either date()-style or strftime()-style). + * If format is NULL, then the raw DateTime object will be returned. + * @return mixed Formatted date/time value as string or DateTime object (if format is NULL), NULL if column is NULL + * @throws PropelException - if unable to parse/validate the date/time value. */ - public function getDbCreator() + public function getDbUtime($format = 'Y-m-d H:i:s') { - return $this->creator; + if ($this->utime === null) { + return null; + } + + + + try { + $dt = new DateTime($this->utime); + } catch (Exception $x) { + throw new PropelException("Internally stored date/time/timestamp value could not be converted to DateTime: " . var_export($this->utime, true), $x); + } + + if ($format === null) { + // Because propel.useDateTimeClass is TRUE, we return a DateTime object. + return $dt; + } elseif (strpos($format, '%') !== false) { + return strftime($format, $dt->format('U')); + } else { + return $dt->format($format); + } } /** - * Get the [description] column value. + * Get the [optionally formatted] temporal [lptime] column value. + * + * + * @param string $format The date/time format string (either date()-style or strftime()-style). + * If format is NULL, then the raw DateTime object will be returned. + * @return mixed Formatted date/time value as string or DateTime object (if format is NULL), NULL if column is NULL + * @throws PropelException - if unable to parse/validate the date/time value. + */ + public function getDbLPtime($format = 'Y-m-d H:i:s') + { + if ($this->lptime === null) { + return null; + } + + + + try { + $dt = new DateTime($this->lptime); + } catch (Exception $x) { + throw new PropelException("Internally stored date/time/timestamp value could not be converted to DateTime: " . var_export($this->lptime, true), $x); + } + + if ($format === null) { + // Because propel.useDateTimeClass is TRUE, we return a DateTime object. + return $dt; + } elseif (strpos($format, '%') !== false) { + return strftime($format, $dt->format('U')); + } else { + return $dt->format($format); + } + } + + /** + * Get the [mime] column value. * * @return string */ - public function getDbDescription() + public function getDbMime() { - return $this->description; + return $this->mime; } /** * Set the value of [id] column. * * @param int $v new value - * @return CcPlaylist The current object (for fluent API support) + * @return CcWebstream The current object (for fluent API support) */ public function setDbId($v) { @@ -239,7 +308,7 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent if ($this->id !== $v) { $this->id = $v; - $this->modifiedColumns[] = CcPlaylistPeer::ID; + $this->modifiedColumns[] = CcWebstreamPeer::ID; } return $this; @@ -249,7 +318,7 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent * Set the value of [name] column. * * @param string $v new value - * @return CcPlaylist The current object (for fluent API support) + * @return CcWebstream The current object (for fluent API support) */ public function setDbName($v) { @@ -257,84 +326,100 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent $v = (string) $v; } - if ($this->name !== $v || $this->isNew()) { + if ($this->name !== $v) { $this->name = $v; - $this->modifiedColumns[] = CcPlaylistPeer::NAME; + $this->modifiedColumns[] = CcWebstreamPeer::NAME; } return $this; } // setDbName() /** - * Set the value of [state] column. + * Set the value of [description] column. * * @param string $v new value - * @return CcPlaylist The current object (for fluent API support) + * @return CcWebstream The current object (for fluent API support) */ - public function setDbState($v) + public function setDbDescription($v) { if ($v !== null) { $v = (string) $v; } - if ($this->state !== $v || $this->isNew()) { - $this->state = $v; - $this->modifiedColumns[] = CcPlaylistPeer::STATE; + if ($this->description !== $v) { + $this->description = $v; + $this->modifiedColumns[] = CcWebstreamPeer::DESCRIPTION; } return $this; - } // setDbState() + } // setDbDescription() /** - * Set the value of [currentlyaccessing] column. + * Set the value of [url] column. + * + * @param string $v new value + * @return CcWebstream The current object (for fluent API support) + */ + public function setDbUrl($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->url !== $v) { + $this->url = $v; + $this->modifiedColumns[] = CcWebstreamPeer::URL; + } + + return $this; + } // setDbUrl() + + /** + * Set the value of [length] column. + * + * @param string $v new value + * @return CcWebstream The current object (for fluent API support) + */ + public function setDbLength($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->length !== $v || $this->isNew()) { + $this->length = $v; + $this->modifiedColumns[] = CcWebstreamPeer::LENGTH; + } + + return $this; + } // setDbLength() + + /** + * Set the value of [creator_id] column. * * @param int $v new value - * @return CcPlaylist The current object (for fluent API support) + * @return CcWebstream The current object (for fluent API support) */ - public function setDbCurrentlyaccessing($v) + public function setDbCreatorId($v) { if ($v !== null) { $v = (int) $v; } - if ($this->currentlyaccessing !== $v || $this->isNew()) { - $this->currentlyaccessing = $v; - $this->modifiedColumns[] = CcPlaylistPeer::CURRENTLYACCESSING; + if ($this->creator_id !== $v) { + $this->creator_id = $v; + $this->modifiedColumns[] = CcWebstreamPeer::CREATOR_ID; } return $this; - } // setDbCurrentlyaccessing() - - /** - * Set the value of [editedby] column. - * - * @param int $v new value - * @return CcPlaylist The current object (for fluent API support) - */ - public function setDbEditedby($v) - { - if ($v !== null) { - $v = (int) $v; - } - - if ($this->editedby !== $v) { - $this->editedby = $v; - $this->modifiedColumns[] = CcPlaylistPeer::EDITEDBY; - } - - if ($this->aCcSubjs !== null && $this->aCcSubjs->getDbId() !== $v) { - $this->aCcSubjs = null; - } - - return $this; - } // setDbEditedby() + } // setDbCreatorId() /** * Sets the value of [mtime] column to a normalized version of the date/time value specified. * * @param mixed $v string, integer (timestamp), or DateTime value. Empty string will * be treated as NULL for temporal objects. - * @return CcPlaylist The current object (for fluent API support) + * @return CcWebstream The current object (for fluent API support) */ public function setDbMtime($v) { @@ -371,7 +456,7 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent ) { $this->mtime = ($dt ? $dt->format('Y-m-d\\TH:i:sO') : null); - $this->modifiedColumns[] = CcPlaylistPeer::MTIME; + $this->modifiedColumns[] = CcWebstreamPeer::MTIME; } } // if either are not null @@ -379,44 +464,122 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent } // setDbMtime() /** - * Set the value of [creator] column. + * Sets the value of [utime] column to a normalized version of the date/time value specified. * - * @param string $v new value - * @return CcPlaylist The current object (for fluent API support) + * @param mixed $v string, integer (timestamp), or DateTime value. Empty string will + * be treated as NULL for temporal objects. + * @return CcWebstream The current object (for fluent API support) */ - public function setDbCreator($v) + public function setDbUtime($v) { - if ($v !== null) { - $v = (string) $v; + // we treat '' as NULL for temporal objects because DateTime('') == DateTime('now') + // -- which is unexpected, to say the least. + if ($v === null || $v === '') { + $dt = null; + } elseif ($v instanceof DateTime) { + $dt = $v; + } else { + // some string/numeric value passed; we normalize that so that we can + // validate it. + try { + if (is_numeric($v)) { // if it's a unix timestamp + $dt = new DateTime('@'.$v, new DateTimeZone('UTC')); + // We have to explicitly specify and then change the time zone because of a + // DateTime bug: http://bugs.php.net/bug.php?id=43003 + $dt->setTimeZone(new DateTimeZone(date_default_timezone_get())); + } else { + $dt = new DateTime($v); + } + } catch (Exception $x) { + throw new PropelException('Error parsing date/time value: ' . var_export($v, true), $x); + } } - if ($this->creator !== $v) { - $this->creator = $v; - $this->modifiedColumns[] = CcPlaylistPeer::CREATOR; - } + if ( $this->utime !== null || $dt !== null ) { + // (nested ifs are a little easier to read in this case) + + $currNorm = ($this->utime !== null && $tmpDt = new DateTime($this->utime)) ? $tmpDt->format('Y-m-d\\TH:i:sO') : null; + $newNorm = ($dt !== null) ? $dt->format('Y-m-d\\TH:i:sO') : null; + + if ( ($currNorm !== $newNorm) // normalized values don't match + ) + { + $this->utime = ($dt ? $dt->format('Y-m-d\\TH:i:sO') : null); + $this->modifiedColumns[] = CcWebstreamPeer::UTIME; + } + } // if either are not null return $this; - } // setDbCreator() + } // setDbUtime() /** - * Set the value of [description] column. + * Sets the value of [lptime] column to a normalized version of the date/time value specified. + * + * @param mixed $v string, integer (timestamp), or DateTime value. Empty string will + * be treated as NULL for temporal objects. + * @return CcWebstream The current object (for fluent API support) + */ + public function setDbLPtime($v) + { + // we treat '' as NULL for temporal objects because DateTime('') == DateTime('now') + // -- which is unexpected, to say the least. + if ($v === null || $v === '') { + $dt = null; + } elseif ($v instanceof DateTime) { + $dt = $v; + } else { + // some string/numeric value passed; we normalize that so that we can + // validate it. + try { + if (is_numeric($v)) { // if it's a unix timestamp + $dt = new DateTime('@'.$v, new DateTimeZone('UTC')); + // We have to explicitly specify and then change the time zone because of a + // DateTime bug: http://bugs.php.net/bug.php?id=43003 + $dt->setTimeZone(new DateTimeZone(date_default_timezone_get())); + } else { + $dt = new DateTime($v); + } + } catch (Exception $x) { + throw new PropelException('Error parsing date/time value: ' . var_export($v, true), $x); + } + } + + if ( $this->lptime !== null || $dt !== null ) { + // (nested ifs are a little easier to read in this case) + + $currNorm = ($this->lptime !== null && $tmpDt = new DateTime($this->lptime)) ? $tmpDt->format('Y-m-d\\TH:i:sO') : null; + $newNorm = ($dt !== null) ? $dt->format('Y-m-d\\TH:i:sO') : null; + + if ( ($currNorm !== $newNorm) // normalized values don't match + ) + { + $this->lptime = ($dt ? $dt->format('Y-m-d\\TH:i:sO') : null); + $this->modifiedColumns[] = CcWebstreamPeer::LPTIME; + } + } // if either are not null + + return $this; + } // setDbLPtime() + + /** + * Set the value of [mime] column. * * @param string $v new value - * @return CcPlaylist The current object (for fluent API support) + * @return CcWebstream The current object (for fluent API support) */ - public function setDbDescription($v) + public function setDbMime($v) { if ($v !== null) { $v = (string) $v; } - if ($this->description !== $v) { - $this->description = $v; - $this->modifiedColumns[] = CcPlaylistPeer::DESCRIPTION; + if ($this->mime !== $v) { + $this->mime = $v; + $this->modifiedColumns[] = CcWebstreamPeer::MIME; } return $this; - } // setDbDescription() + } // setDbMime() /** * Indicates whether the columns in this object are only set to default values. @@ -428,15 +591,7 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent */ public function hasOnlyDefaultValues() { - if ($this->name !== '') { - return false; - } - - if ($this->state !== 'empty') { - return false; - } - - if ($this->currentlyaccessing !== 0) { + if ($this->length !== '00:00:00') { return false; } @@ -464,12 +619,14 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent $this->id = ($row[$startcol + 0] !== null) ? (int) $row[$startcol + 0] : null; $this->name = ($row[$startcol + 1] !== null) ? (string) $row[$startcol + 1] : null; - $this->state = ($row[$startcol + 2] !== null) ? (string) $row[$startcol + 2] : null; - $this->currentlyaccessing = ($row[$startcol + 3] !== null) ? (int) $row[$startcol + 3] : null; - $this->editedby = ($row[$startcol + 4] !== null) ? (int) $row[$startcol + 4] : null; - $this->mtime = ($row[$startcol + 5] !== null) ? (string) $row[$startcol + 5] : null; - $this->creator = ($row[$startcol + 6] !== null) ? (string) $row[$startcol + 6] : null; - $this->description = ($row[$startcol + 7] !== null) ? (string) $row[$startcol + 7] : null; + $this->description = ($row[$startcol + 2] !== null) ? (string) $row[$startcol + 2] : null; + $this->url = ($row[$startcol + 3] !== null) ? (string) $row[$startcol + 3] : null; + $this->length = ($row[$startcol + 4] !== null) ? (string) $row[$startcol + 4] : null; + $this->creator_id = ($row[$startcol + 5] !== null) ? (int) $row[$startcol + 5] : null; + $this->mtime = ($row[$startcol + 6] !== null) ? (string) $row[$startcol + 6] : null; + $this->utime = ($row[$startcol + 7] !== null) ? (string) $row[$startcol + 7] : null; + $this->lptime = ($row[$startcol + 8] !== null) ? (string) $row[$startcol + 8] : null; + $this->mime = ($row[$startcol + 9] !== null) ? (string) $row[$startcol + 9] : null; $this->resetModified(); $this->setNew(false); @@ -478,10 +635,10 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent $this->ensureConsistency(); } - return $startcol + 8; // 8 = CcPlaylistPeer::NUM_COLUMNS - CcPlaylistPeer::NUM_LAZY_LOAD_COLUMNS). + return $startcol + 10; // 10 = CcWebstreamPeer::NUM_COLUMNS - CcWebstreamPeer::NUM_LAZY_LOAD_COLUMNS). } catch (Exception $e) { - throw new PropelException("Error populating CcPlaylist object", $e); + throw new PropelException("Error populating CcWebstream object", $e); } } @@ -501,9 +658,6 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent public function ensureConsistency() { - if ($this->aCcSubjs !== null && $this->editedby !== $this->aCcSubjs->getDbId()) { - $this->aCcSubjs = null; - } } // ensureConsistency /** @@ -527,13 +681,13 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent } if ($con === null) { - $con = Propel::getConnection(CcPlaylistPeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcWebstreamPeer::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 = CcPlaylistPeer::doSelectStmt($this->buildPkeyCriteria(), $con); + $stmt = CcWebstreamPeer::doSelectStmt($this->buildPkeyCriteria(), $con); $row = $stmt->fetch(PDO::FETCH_NUM); $stmt->closeCursor(); if (!$row) { @@ -543,8 +697,7 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent if ($deep) { // also de-associate any related objects? - $this->aCcSubjs = null; - $this->collCcPlaylistcontentss = null; + $this->collCcSchedules = null; } // if (deep) } @@ -565,14 +718,14 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent } if ($con === null) { - $con = Propel::getConnection(CcPlaylistPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + $con = Propel::getConnection(CcWebstreamPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); } $con->beginTransaction(); try { $ret = $this->preDelete($con); if ($ret) { - CcPlaylistQuery::create() + CcWebstreamQuery::create() ->filterByPrimaryKey($this->getPrimaryKey()) ->delete($con); $this->postDelete($con); @@ -607,7 +760,7 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent } if ($con === null) { - $con = Propel::getConnection(CcPlaylistPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + $con = Propel::getConnection(CcWebstreamPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); } $con->beginTransaction(); @@ -627,7 +780,7 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent $this->postUpdate($con); } $this->postSave($con); - CcPlaylistPeer::addInstanceToPool($this); + CcWebstreamPeer::addInstanceToPool($this); } else { $affectedRows = 0; } @@ -656,43 +809,31 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent 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->aCcSubjs !== null) { - if ($this->aCcSubjs->isModified() || $this->aCcSubjs->isNew()) { - $affectedRows += $this->aCcSubjs->save($con); - } - $this->setCcSubjs($this->aCcSubjs); - } - if ($this->isNew() ) { - $this->modifiedColumns[] = CcPlaylistPeer::ID; + $this->modifiedColumns[] = CcWebstreamPeer::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(CcPlaylistPeer::ID) ) { - throw new PropelException('Cannot insert a value for auto-increment primary key ('.CcPlaylistPeer::ID.')'); + if ($criteria->keyContainsValue(CcWebstreamPeer::ID) ) { + throw new PropelException('Cannot insert a value for auto-increment primary key ('.CcWebstreamPeer::ID.')'); } $pk = BasePeer::doInsert($criteria, $con); - $affectedRows += 1; + $affectedRows = 1; $this->setDbId($pk); //[IMV] update autoincrement primary key $this->setNew(false); } else { - $affectedRows += CcPlaylistPeer::doUpdate($this, $con); + $affectedRows = CcWebstreamPeer::doUpdate($this, $con); } $this->resetModified(); // [HL] After being saved an object is no longer 'modified' } - if ($this->collCcPlaylistcontentss !== null) { - foreach ($this->collCcPlaylistcontentss as $referrerFK) { + if ($this->collCcSchedules !== null) { + foreach ($this->collCcSchedules as $referrerFK) { if (!$referrerFK->isDeleted()) { $affectedRows += $referrerFK->save($con); } @@ -765,25 +906,13 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent $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->aCcSubjs !== null) { - if (!$this->aCcSubjs->validate($columns)) { - $failureMap = array_merge($failureMap, $this->aCcSubjs->getValidationFailures()); - } - } - - - if (($retval = CcPlaylistPeer::doValidate($this, $columns)) !== true) { + if (($retval = CcWebstreamPeer::doValidate($this, $columns)) !== true) { $failureMap = array_merge($failureMap, $retval); } - if ($this->collCcPlaylistcontentss !== null) { - foreach ($this->collCcPlaylistcontentss as $referrerFK) { + if ($this->collCcSchedules !== null) { + foreach ($this->collCcSchedules as $referrerFK) { if (!$referrerFK->validate($columns)) { $failureMap = array_merge($failureMap, $referrerFK->getValidationFailures()); } @@ -808,7 +937,7 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent */ public function getByName($name, $type = BasePeer::TYPE_PHPNAME) { - $pos = CcPlaylistPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); + $pos = CcWebstreamPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); $field = $this->getByPosition($pos); return $field; } @@ -830,22 +959,28 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent return $this->getDbName(); break; case 2: - return $this->getDbState(); + return $this->getDbDescription(); break; case 3: - return $this->getDbCurrentlyaccessing(); + return $this->getDbUrl(); break; case 4: - return $this->getDbEditedby(); + return $this->getDbLength(); break; case 5: - return $this->getDbMtime(); + return $this->getDbCreatorId(); break; case 6: - return $this->getDbCreator(); + return $this->getDbMtime(); break; case 7: - return $this->getDbDescription(); + return $this->getDbUtime(); + break; + case 8: + return $this->getDbLPtime(); + break; + case 9: + return $this->getDbMime(); break; default: return null; @@ -863,28 +998,24 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent * 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) + public function toArray($keyType = BasePeer::TYPE_PHPNAME, $includeLazyLoadColumns = true) { - $keys = CcPlaylistPeer::getFieldNames($keyType); + $keys = CcWebstreamPeer::getFieldNames($keyType); $result = array( $keys[0] => $this->getDbId(), $keys[1] => $this->getDbName(), - $keys[2] => $this->getDbState(), - $keys[3] => $this->getDbCurrentlyaccessing(), - $keys[4] => $this->getDbEditedby(), - $keys[5] => $this->getDbMtime(), - $keys[6] => $this->getDbCreator(), - $keys[7] => $this->getDbDescription(), + $keys[2] => $this->getDbDescription(), + $keys[3] => $this->getDbUrl(), + $keys[4] => $this->getDbLength(), + $keys[5] => $this->getDbCreatorId(), + $keys[6] => $this->getDbMtime(), + $keys[7] => $this->getDbUtime(), + $keys[8] => $this->getDbLPtime(), + $keys[9] => $this->getDbMime(), ); - if ($includeForeignObjects) { - if (null !== $this->aCcSubjs) { - $result['CcSubjs'] = $this->aCcSubjs->toArray($keyType, $includeLazyLoadColumns, true); - } - } return $result; } @@ -900,7 +1031,7 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent */ public function setByName($name, $value, $type = BasePeer::TYPE_PHPNAME) { - $pos = CcPlaylistPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); + $pos = CcWebstreamPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); return $this->setByPosition($pos, $value); } @@ -922,22 +1053,28 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent $this->setDbName($value); break; case 2: - $this->setDbState($value); + $this->setDbDescription($value); break; case 3: - $this->setDbCurrentlyaccessing($value); + $this->setDbUrl($value); break; case 4: - $this->setDbEditedby($value); + $this->setDbLength($value); break; case 5: - $this->setDbMtime($value); + $this->setDbCreatorId($value); break; case 6: - $this->setDbCreator($value); + $this->setDbMtime($value); break; case 7: - $this->setDbDescription($value); + $this->setDbUtime($value); + break; + case 8: + $this->setDbLPtime($value); + break; + case 9: + $this->setDbMime($value); break; } // switch() } @@ -961,16 +1098,18 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent */ public function fromArray($arr, $keyType = BasePeer::TYPE_PHPNAME) { - $keys = CcPlaylistPeer::getFieldNames($keyType); + $keys = CcWebstreamPeer::getFieldNames($keyType); if (array_key_exists($keys[0], $arr)) $this->setDbId($arr[$keys[0]]); if (array_key_exists($keys[1], $arr)) $this->setDbName($arr[$keys[1]]); - if (array_key_exists($keys[2], $arr)) $this->setDbState($arr[$keys[2]]); - if (array_key_exists($keys[3], $arr)) $this->setDbCurrentlyaccessing($arr[$keys[3]]); - if (array_key_exists($keys[4], $arr)) $this->setDbEditedby($arr[$keys[4]]); - if (array_key_exists($keys[5], $arr)) $this->setDbMtime($arr[$keys[5]]); - if (array_key_exists($keys[6], $arr)) $this->setDbCreator($arr[$keys[6]]); - if (array_key_exists($keys[7], $arr)) $this->setDbDescription($arr[$keys[7]]); + if (array_key_exists($keys[2], $arr)) $this->setDbDescription($arr[$keys[2]]); + if (array_key_exists($keys[3], $arr)) $this->setDbUrl($arr[$keys[3]]); + if (array_key_exists($keys[4], $arr)) $this->setDbLength($arr[$keys[4]]); + if (array_key_exists($keys[5], $arr)) $this->setDbCreatorId($arr[$keys[5]]); + if (array_key_exists($keys[6], $arr)) $this->setDbMtime($arr[$keys[6]]); + if (array_key_exists($keys[7], $arr)) $this->setDbUtime($arr[$keys[7]]); + if (array_key_exists($keys[8], $arr)) $this->setDbLPtime($arr[$keys[8]]); + if (array_key_exists($keys[9], $arr)) $this->setDbMime($arr[$keys[9]]); } /** @@ -980,16 +1119,18 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent */ public function buildCriteria() { - $criteria = new Criteria(CcPlaylistPeer::DATABASE_NAME); + $criteria = new Criteria(CcWebstreamPeer::DATABASE_NAME); - if ($this->isColumnModified(CcPlaylistPeer::ID)) $criteria->add(CcPlaylistPeer::ID, $this->id); - if ($this->isColumnModified(CcPlaylistPeer::NAME)) $criteria->add(CcPlaylistPeer::NAME, $this->name); - if ($this->isColumnModified(CcPlaylistPeer::STATE)) $criteria->add(CcPlaylistPeer::STATE, $this->state); - if ($this->isColumnModified(CcPlaylistPeer::CURRENTLYACCESSING)) $criteria->add(CcPlaylistPeer::CURRENTLYACCESSING, $this->currentlyaccessing); - if ($this->isColumnModified(CcPlaylistPeer::EDITEDBY)) $criteria->add(CcPlaylistPeer::EDITEDBY, $this->editedby); - if ($this->isColumnModified(CcPlaylistPeer::MTIME)) $criteria->add(CcPlaylistPeer::MTIME, $this->mtime); - if ($this->isColumnModified(CcPlaylistPeer::CREATOR)) $criteria->add(CcPlaylistPeer::CREATOR, $this->creator); - if ($this->isColumnModified(CcPlaylistPeer::DESCRIPTION)) $criteria->add(CcPlaylistPeer::DESCRIPTION, $this->description); + if ($this->isColumnModified(CcWebstreamPeer::ID)) $criteria->add(CcWebstreamPeer::ID, $this->id); + if ($this->isColumnModified(CcWebstreamPeer::NAME)) $criteria->add(CcWebstreamPeer::NAME, $this->name); + if ($this->isColumnModified(CcWebstreamPeer::DESCRIPTION)) $criteria->add(CcWebstreamPeer::DESCRIPTION, $this->description); + if ($this->isColumnModified(CcWebstreamPeer::URL)) $criteria->add(CcWebstreamPeer::URL, $this->url); + if ($this->isColumnModified(CcWebstreamPeer::LENGTH)) $criteria->add(CcWebstreamPeer::LENGTH, $this->length); + if ($this->isColumnModified(CcWebstreamPeer::CREATOR_ID)) $criteria->add(CcWebstreamPeer::CREATOR_ID, $this->creator_id); + if ($this->isColumnModified(CcWebstreamPeer::MTIME)) $criteria->add(CcWebstreamPeer::MTIME, $this->mtime); + if ($this->isColumnModified(CcWebstreamPeer::UTIME)) $criteria->add(CcWebstreamPeer::UTIME, $this->utime); + if ($this->isColumnModified(CcWebstreamPeer::LPTIME)) $criteria->add(CcWebstreamPeer::LPTIME, $this->lptime); + if ($this->isColumnModified(CcWebstreamPeer::MIME)) $criteria->add(CcWebstreamPeer::MIME, $this->mime); return $criteria; } @@ -1004,8 +1145,8 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent */ public function buildPkeyCriteria() { - $criteria = new Criteria(CcPlaylistPeer::DATABASE_NAME); - $criteria->add(CcPlaylistPeer::ID, $this->id); + $criteria = new Criteria(CcWebstreamPeer::DATABASE_NAME); + $criteria->add(CcWebstreamPeer::ID, $this->id); return $criteria; } @@ -1045,28 +1186,30 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent * If desired, this method can also make copies of all associated (fkey referrers) * objects. * - * @param object $copyObj An object of CcPlaylist (or compatible) type. + * @param object $copyObj An object of CcWebstream (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->setDbName($this->name); - $copyObj->setDbState($this->state); - $copyObj->setDbCurrentlyaccessing($this->currentlyaccessing); - $copyObj->setDbEditedby($this->editedby); - $copyObj->setDbMtime($this->mtime); - $copyObj->setDbCreator($this->creator); $copyObj->setDbDescription($this->description); + $copyObj->setDbUrl($this->url); + $copyObj->setDbLength($this->length); + $copyObj->setDbCreatorId($this->creator_id); + $copyObj->setDbMtime($this->mtime); + $copyObj->setDbUtime($this->utime); + $copyObj->setDbLPtime($this->lptime); + $copyObj->setDbMime($this->mime); 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->getCcPlaylistcontentss() as $relObj) { + foreach ($this->getCcSchedules() as $relObj) { if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves - $copyObj->addCcPlaylistcontents($relObj->copy($deepCopy)); + $copyObj->addCcSchedule($relObj->copy($deepCopy)); } } @@ -1086,7 +1229,7 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent * objects. * * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. - * @return CcPlaylist Clone of current object. + * @return CcWebstream Clone of current object. * @throws PropelException */ public function copy($deepCopy = false) @@ -1105,171 +1248,122 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent * same instance for all member of this class. The method could therefore * be static, but this would prevent one from overriding the behavior. * - * @return CcPlaylistPeer + * @return CcWebstreamPeer */ public function getPeer() { if (self::$peer === null) { - self::$peer = new CcPlaylistPeer(); + self::$peer = new CcWebstreamPeer(); } return self::$peer; } /** - * Declares an association between this object and a CcSubjs object. - * - * @param CcSubjs $v - * @return CcPlaylist The current object (for fluent API support) - * @throws PropelException - */ - public function setCcSubjs(CcSubjs $v = null) - { - if ($v === null) { - $this->setDbEditedby(NULL); - } else { - $this->setDbEditedby($v->getDbId()); - } - - $this->aCcSubjs = $v; - - // Add binding for other direction of this n:n relationship. - // If this object has already been added to the CcSubjs object, it will not be re-added. - if ($v !== null) { - $v->addCcPlaylist($this); - } - - return $this; - } - - - /** - * Get the associated CcSubjs object - * - * @param PropelPDO Optional Connection object. - * @return CcSubjs The associated CcSubjs object. - * @throws PropelException - */ - public function getCcSubjs(PropelPDO $con = null) - { - if ($this->aCcSubjs === null && ($this->editedby !== null)) { - $this->aCcSubjs = CcSubjsQuery::create()->findPk($this->editedby, $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->aCcSubjs->addCcPlaylists($this); - */ - } - return $this->aCcSubjs; - } - - /** - * Clears out the collCcPlaylistcontentss collection + * Clears out the collCcSchedules 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 addCcPlaylistcontentss() + * @see addCcSchedules() */ - public function clearCcPlaylistcontentss() + public function clearCcSchedules() { - $this->collCcPlaylistcontentss = null; // important to set this to NULL since that means it is uninitialized + $this->collCcSchedules = null; // important to set this to NULL since that means it is uninitialized } /** - * Initializes the collCcPlaylistcontentss collection. + * Initializes the collCcSchedules collection. * - * By default this just sets the collCcPlaylistcontentss collection to an empty array (like clearcollCcPlaylistcontentss()); + * By default this just sets the collCcSchedules collection to an empty array (like clearcollCcSchedules()); * 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 initCcPlaylistcontentss() + public function initCcSchedules() { - $this->collCcPlaylistcontentss = new PropelObjectCollection(); - $this->collCcPlaylistcontentss->setModel('CcPlaylistcontents'); + $this->collCcSchedules = new PropelObjectCollection(); + $this->collCcSchedules->setModel('CcSchedule'); } /** - * Gets an array of CcPlaylistcontents objects which contain a foreign key that references this object. + * Gets an array of CcSchedule 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 CcPlaylist is new, it will return + * If this CcWebstream 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 CcPlaylistcontents[] List of CcPlaylistcontents objects + * @return PropelCollection|array CcSchedule[] List of CcSchedule objects * @throws PropelException */ - public function getCcPlaylistcontentss($criteria = null, PropelPDO $con = null) + public function getCcSchedules($criteria = null, PropelPDO $con = null) { - if(null === $this->collCcPlaylistcontentss || null !== $criteria) { - if ($this->isNew() && null === $this->collCcPlaylistcontentss) { + if(null === $this->collCcSchedules || null !== $criteria) { + if ($this->isNew() && null === $this->collCcSchedules) { // return empty collection - $this->initCcPlaylistcontentss(); + $this->initCcSchedules(); } else { - $collCcPlaylistcontentss = CcPlaylistcontentsQuery::create(null, $criteria) - ->filterByCcPlaylist($this) + $collCcSchedules = CcScheduleQuery::create(null, $criteria) + ->filterByCcWebstream($this) ->find($con); if (null !== $criteria) { - return $collCcPlaylistcontentss; + return $collCcSchedules; } - $this->collCcPlaylistcontentss = $collCcPlaylistcontentss; + $this->collCcSchedules = $collCcSchedules; } } - return $this->collCcPlaylistcontentss; + return $this->collCcSchedules; } /** - * Returns the number of related CcPlaylistcontents objects. + * Returns the number of related CcSchedule objects. * * @param Criteria $criteria * @param boolean $distinct * @param PropelPDO $con - * @return int Count of related CcPlaylistcontents objects. + * @return int Count of related CcSchedule objects. * @throws PropelException */ - public function countCcPlaylistcontentss(Criteria $criteria = null, $distinct = false, PropelPDO $con = null) + public function countCcSchedules(Criteria $criteria = null, $distinct = false, PropelPDO $con = null) { - if(null === $this->collCcPlaylistcontentss || null !== $criteria) { - if ($this->isNew() && null === $this->collCcPlaylistcontentss) { + if(null === $this->collCcSchedules || null !== $criteria) { + if ($this->isNew() && null === $this->collCcSchedules) { return 0; } else { - $query = CcPlaylistcontentsQuery::create(null, $criteria); + $query = CcScheduleQuery::create(null, $criteria); if($distinct) { $query->distinct(); } return $query - ->filterByCcPlaylist($this) + ->filterByCcWebstream($this) ->count($con); } } else { - return count($this->collCcPlaylistcontentss); + return count($this->collCcSchedules); } } /** - * Method called to associate a CcPlaylistcontents object to this object - * through the CcPlaylistcontents foreign key attribute. + * Method called to associate a CcSchedule object to this object + * through the CcSchedule foreign key attribute. * - * @param CcPlaylistcontents $l CcPlaylistcontents + * @param CcSchedule $l CcSchedule * @return void * @throws PropelException */ - public function addCcPlaylistcontents(CcPlaylistcontents $l) + public function addCcSchedule(CcSchedule $l) { - if ($this->collCcPlaylistcontentss === null) { - $this->initCcPlaylistcontentss(); + if ($this->collCcSchedules === null) { + $this->initCcSchedules(); } - if (!$this->collCcPlaylistcontentss->contains($l)) { // only add it if the **same** object is not already associated - $this->collCcPlaylistcontentss[]= $l; - $l->setCcPlaylist($this); + if (!$this->collCcSchedules->contains($l)) { // only add it if the **same** object is not already associated + $this->collCcSchedules[]= $l; + $l->setCcWebstream($this); } } @@ -1277,25 +1371,50 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent /** * 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 CcPlaylistcontentss from storage. + * Otherwise if this CcWebstream is new, it will return + * an empty collection; or if this CcWebstream has previously + * been saved, it will retrieve related CcSchedules 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. + * 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 CcPlaylistcontents[] List of CcPlaylistcontents objects + * @return PropelCollection|array CcSchedule[] List of CcSchedule objects */ - public function getCcPlaylistcontentssJoinCcFiles($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) + public function getCcSchedulesJoinCcShowInstances($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { - $query = CcPlaylistcontentsQuery::create(null, $criteria); + $query = CcScheduleQuery::create(null, $criteria); + $query->joinWith('CcShowInstances', $join_behavior); + + return $this->getCcSchedules($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 CcSchedules 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 CcSchedule[] List of CcSchedule objects + */ + public function getCcSchedulesJoinCcFiles($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $query = CcScheduleQuery::create(null, $criteria); $query->joinWith('CcFiles', $join_behavior); - return $this->getCcPlaylistcontentss($query, $con); + return $this->getCcSchedules($query, $con); } /** @@ -1305,12 +1424,14 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent { $this->id = null; $this->name = null; - $this->state = null; - $this->currentlyaccessing = null; - $this->editedby = null; - $this->mtime = null; - $this->creator = null; $this->description = null; + $this->url = null; + $this->length = null; + $this->creator_id = null; + $this->mtime = null; + $this->utime = null; + $this->lptime = null; + $this->mime = null; $this->alreadyInSave = false; $this->alreadyInValidation = false; $this->clearAllReferences(); @@ -1332,15 +1453,14 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent public function clearAllReferences($deep = false) { if ($deep) { - if ($this->collCcPlaylistcontentss) { - foreach ((array) $this->collCcPlaylistcontentss as $o) { + if ($this->collCcSchedules) { + foreach ((array) $this->collCcSchedules as $o) { $o->clearAllReferences($deep); } } } // if ($deep) - $this->collCcPlaylistcontentss = null; - $this->aCcSubjs = null; + $this->collCcSchedules = null; } /** @@ -1362,4 +1482,4 @@ abstract class BaseCcPlaylist extends BaseObject implements Persistent throw new PropelException('Call to undefined method: ' . $name); } -} // BaseCcPlaylist +} // BaseCcWebstream diff --git a/install_minimal/upgrades/airtime-2.0.0/propel/airtime/om/BaseCcShowRebroadcast.php b/airtime_mvc/application/models/airtime/om/BaseCcWebstreamMetadata.php similarity index 76% rename from install_minimal/upgrades/airtime-2.0.0/propel/airtime/om/BaseCcShowRebroadcast.php rename to airtime_mvc/application/models/airtime/om/BaseCcWebstreamMetadata.php index aabd37d79..f5730573c 100644 --- a/install_minimal/upgrades/airtime-2.0.0/propel/airtime/om/BaseCcShowRebroadcast.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcWebstreamMetadata.php @@ -2,25 +2,25 @@ /** - * Base class that represents a row from the 'cc_show_rebroadcast' table. + * Base class that represents a row from the 'cc_webstream_metadata' table. * * * * @package propel.generator.airtime.om */ -abstract class BaseCcShowRebroadcast extends BaseObject implements Persistent +abstract class BaseCcWebstreamMetadata extends BaseObject implements Persistent { /** * Peer class name */ - const PEER = 'CcShowRebroadcastPeer'; + const PEER = 'CcWebstreamMetadataPeer'; /** * The Peer class. * Instance provides a convenient way of calling static methods on a class * that calling code may not be able to identify. - * @var CcShowRebroadcastPeer + * @var CcWebstreamMetadataPeer */ protected static $peer; @@ -31,10 +31,10 @@ abstract class BaseCcShowRebroadcast extends BaseObject implements Persistent protected $id; /** - * The value for the day_offset field. - * @var string + * The value for the instance_id field. + * @var int */ - protected $day_offset; + protected $instance_id; /** * The value for the start_time field. @@ -43,15 +43,15 @@ abstract class BaseCcShowRebroadcast extends BaseObject implements Persistent protected $start_time; /** - * The value for the show_id field. - * @var int + * The value for the liquidsoap_data field. + * @var string */ - protected $show_id; + protected $liquidsoap_data; /** - * @var CcShow + * @var CcSchedule */ - protected $aCcShow; + protected $aCcSchedule; /** * Flag to prevent endless save loop, if this object is referenced @@ -78,13 +78,13 @@ abstract class BaseCcShowRebroadcast extends BaseObject implements Persistent } /** - * Get the [day_offset] column value. + * Get the [instance_id] column value. * - * @return string + * @return int */ - public function getDbDayOffset() + public function getDbInstanceId() { - return $this->day_offset; + return $this->instance_id; } /** @@ -96,7 +96,7 @@ abstract class BaseCcShowRebroadcast extends BaseObject implements Persistent * @return mixed Formatted date/time value as string or DateTime object (if format is NULL), NULL if column is NULL * @throws PropelException - if unable to parse/validate the date/time value. */ - public function getDbStartTime($format = '%X') + public function getDbStartTime($format = 'Y-m-d H:i:s') { if ($this->start_time === null) { return null; @@ -121,20 +121,20 @@ abstract class BaseCcShowRebroadcast extends BaseObject implements Persistent } /** - * Get the [show_id] column value. + * Get the [liquidsoap_data] column value. * - * @return int + * @return string */ - public function getDbShowId() + public function getDbLiquidsoapData() { - return $this->show_id; + return $this->liquidsoap_data; } /** * Set the value of [id] column. * * @param int $v new value - * @return CcShowRebroadcast The current object (for fluent API support) + * @return CcWebstreamMetadata The current object (for fluent API support) */ public function setDbId($v) { @@ -144,38 +144,42 @@ abstract class BaseCcShowRebroadcast extends BaseObject implements Persistent if ($this->id !== $v) { $this->id = $v; - $this->modifiedColumns[] = CcShowRebroadcastPeer::ID; + $this->modifiedColumns[] = CcWebstreamMetadataPeer::ID; } return $this; } // setDbId() /** - * Set the value of [day_offset] column. + * Set the value of [instance_id] column. * - * @param string $v new value - * @return CcShowRebroadcast The current object (for fluent API support) + * @param int $v new value + * @return CcWebstreamMetadata The current object (for fluent API support) */ - public function setDbDayOffset($v) + public function setDbInstanceId($v) { if ($v !== null) { - $v = (string) $v; + $v = (int) $v; } - if ($this->day_offset !== $v) { - $this->day_offset = $v; - $this->modifiedColumns[] = CcShowRebroadcastPeer::DAY_OFFSET; + if ($this->instance_id !== $v) { + $this->instance_id = $v; + $this->modifiedColumns[] = CcWebstreamMetadataPeer::INSTANCE_ID; + } + + if ($this->aCcSchedule !== null && $this->aCcSchedule->getDbId() !== $v) { + $this->aCcSchedule = null; } return $this; - } // setDbDayOffset() + } // setDbInstanceId() /** * Sets the value of [start_time] column to a normalized version of the date/time value specified. * * @param mixed $v string, integer (timestamp), or DateTime value. Empty string will * be treated as NULL for temporal objects. - * @return CcShowRebroadcast The current object (for fluent API support) + * @return CcWebstreamMetadata The current object (for fluent API support) */ public function setDbStartTime($v) { @@ -205,14 +209,14 @@ abstract class BaseCcShowRebroadcast extends BaseObject implements Persistent if ( $this->start_time !== null || $dt !== null ) { // (nested ifs are a little easier to read in this case) - $currNorm = ($this->start_time !== null && $tmpDt = new DateTime($this->start_time)) ? $tmpDt->format('H:i:s') : null; - $newNorm = ($dt !== null) ? $dt->format('H:i:s') : null; + $currNorm = ($this->start_time !== null && $tmpDt = new DateTime($this->start_time)) ? $tmpDt->format('Y-m-d\\TH:i:sO') : null; + $newNorm = ($dt !== null) ? $dt->format('Y-m-d\\TH:i:sO') : null; if ( ($currNorm !== $newNorm) // normalized values don't match ) { - $this->start_time = ($dt ? $dt->format('H:i:s') : null); - $this->modifiedColumns[] = CcShowRebroadcastPeer::START_TIME; + $this->start_time = ($dt ? $dt->format('Y-m-d\\TH:i:sO') : null); + $this->modifiedColumns[] = CcWebstreamMetadataPeer::START_TIME; } } // if either are not null @@ -220,28 +224,24 @@ abstract class BaseCcShowRebroadcast extends BaseObject implements Persistent } // setDbStartTime() /** - * Set the value of [show_id] column. + * Set the value of [liquidsoap_data] column. * - * @param int $v new value - * @return CcShowRebroadcast The current object (for fluent API support) + * @param string $v new value + * @return CcWebstreamMetadata The current object (for fluent API support) */ - public function setDbShowId($v) + public function setDbLiquidsoapData($v) { if ($v !== null) { - $v = (int) $v; + $v = (string) $v; } - if ($this->show_id !== $v) { - $this->show_id = $v; - $this->modifiedColumns[] = CcShowRebroadcastPeer::SHOW_ID; - } - - if ($this->aCcShow !== null && $this->aCcShow->getDbId() !== $v) { - $this->aCcShow = null; + if ($this->liquidsoap_data !== $v) { + $this->liquidsoap_data = $v; + $this->modifiedColumns[] = CcWebstreamMetadataPeer::LIQUIDSOAP_DATA; } return $this; - } // setDbShowId() + } // setDbLiquidsoapData() /** * Indicates whether the columns in this object are only set to default values. @@ -276,9 +276,9 @@ abstract class BaseCcShowRebroadcast extends BaseObject implements Persistent try { $this->id = ($row[$startcol + 0] !== null) ? (int) $row[$startcol + 0] : null; - $this->day_offset = ($row[$startcol + 1] !== null) ? (string) $row[$startcol + 1] : null; + $this->instance_id = ($row[$startcol + 1] !== null) ? (int) $row[$startcol + 1] : null; $this->start_time = ($row[$startcol + 2] !== null) ? (string) $row[$startcol + 2] : null; - $this->show_id = ($row[$startcol + 3] !== null) ? (int) $row[$startcol + 3] : null; + $this->liquidsoap_data = ($row[$startcol + 3] !== null) ? (string) $row[$startcol + 3] : null; $this->resetModified(); $this->setNew(false); @@ -287,10 +287,10 @@ abstract class BaseCcShowRebroadcast extends BaseObject implements Persistent $this->ensureConsistency(); } - return $startcol + 4; // 4 = CcShowRebroadcastPeer::NUM_COLUMNS - CcShowRebroadcastPeer::NUM_LAZY_LOAD_COLUMNS). + return $startcol + 4; // 4 = CcWebstreamMetadataPeer::NUM_COLUMNS - CcWebstreamMetadataPeer::NUM_LAZY_LOAD_COLUMNS). } catch (Exception $e) { - throw new PropelException("Error populating CcShowRebroadcast object", $e); + throw new PropelException("Error populating CcWebstreamMetadata object", $e); } } @@ -310,8 +310,8 @@ abstract class BaseCcShowRebroadcast extends BaseObject implements Persistent public function ensureConsistency() { - if ($this->aCcShow !== null && $this->show_id !== $this->aCcShow->getDbId()) { - $this->aCcShow = null; + if ($this->aCcSchedule !== null && $this->instance_id !== $this->aCcSchedule->getDbId()) { + $this->aCcSchedule = null; } } // ensureConsistency @@ -336,13 +336,13 @@ abstract class BaseCcShowRebroadcast extends BaseObject implements Persistent } if ($con === null) { - $con = Propel::getConnection(CcShowRebroadcastPeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcWebstreamMetadataPeer::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 = CcShowRebroadcastPeer::doSelectStmt($this->buildPkeyCriteria(), $con); + $stmt = CcWebstreamMetadataPeer::doSelectStmt($this->buildPkeyCriteria(), $con); $row = $stmt->fetch(PDO::FETCH_NUM); $stmt->closeCursor(); if (!$row) { @@ -352,7 +352,7 @@ abstract class BaseCcShowRebroadcast extends BaseObject implements Persistent if ($deep) { // also de-associate any related objects? - $this->aCcShow = null; + $this->aCcSchedule = null; } // if (deep) } @@ -372,14 +372,14 @@ abstract class BaseCcShowRebroadcast extends BaseObject implements Persistent } if ($con === null) { - $con = Propel::getConnection(CcShowRebroadcastPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + $con = Propel::getConnection(CcWebstreamMetadataPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); } $con->beginTransaction(); try { $ret = $this->preDelete($con); if ($ret) { - CcShowRebroadcastQuery::create() + CcWebstreamMetadataQuery::create() ->filterByPrimaryKey($this->getPrimaryKey()) ->delete($con); $this->postDelete($con); @@ -414,7 +414,7 @@ abstract class BaseCcShowRebroadcast extends BaseObject implements Persistent } if ($con === null) { - $con = Propel::getConnection(CcShowRebroadcastPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + $con = Propel::getConnection(CcWebstreamMetadataPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); } $con->beginTransaction(); @@ -434,7 +434,7 @@ abstract class BaseCcShowRebroadcast extends BaseObject implements Persistent $this->postUpdate($con); } $this->postSave($con); - CcShowRebroadcastPeer::addInstanceToPool($this); + CcWebstreamMetadataPeer::addInstanceToPool($this); } else { $affectedRows = 0; } @@ -468,23 +468,23 @@ abstract class BaseCcShowRebroadcast extends BaseObject implements Persistent // 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); + if ($this->aCcSchedule !== null) { + if ($this->aCcSchedule->isModified() || $this->aCcSchedule->isNew()) { + $affectedRows += $this->aCcSchedule->save($con); } - $this->setCcShow($this->aCcShow); + $this->setCcSchedule($this->aCcSchedule); } if ($this->isNew() ) { - $this->modifiedColumns[] = CcShowRebroadcastPeer::ID; + $this->modifiedColumns[] = CcWebstreamMetadataPeer::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(CcShowRebroadcastPeer::ID) ) { - throw new PropelException('Cannot insert a value for auto-increment primary key ('.CcShowRebroadcastPeer::ID.')'); + if ($criteria->keyContainsValue(CcWebstreamMetadataPeer::ID) ) { + throw new PropelException('Cannot insert a value for auto-increment primary key ('.CcWebstreamMetadataPeer::ID.')'); } $pk = BasePeer::doInsert($criteria, $con); @@ -492,7 +492,7 @@ abstract class BaseCcShowRebroadcast extends BaseObject implements Persistent $this->setDbId($pk); //[IMV] update autoincrement primary key $this->setNew(false); } else { - $affectedRows += CcShowRebroadcastPeer::doUpdate($this, $con); + $affectedRows += CcWebstreamMetadataPeer::doUpdate($this, $con); } $this->resetModified(); // [HL] After being saved an object is no longer 'modified' @@ -569,14 +569,14 @@ abstract class BaseCcShowRebroadcast extends BaseObject implements Persistent // 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->aCcSchedule !== null) { + if (!$this->aCcSchedule->validate($columns)) { + $failureMap = array_merge($failureMap, $this->aCcSchedule->getValidationFailures()); } } - if (($retval = CcShowRebroadcastPeer::doValidate($this, $columns)) !== true) { + if (($retval = CcWebstreamMetadataPeer::doValidate($this, $columns)) !== true) { $failureMap = array_merge($failureMap, $retval); } @@ -599,7 +599,7 @@ abstract class BaseCcShowRebroadcast extends BaseObject implements Persistent */ public function getByName($name, $type = BasePeer::TYPE_PHPNAME) { - $pos = CcShowRebroadcastPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); + $pos = CcWebstreamMetadataPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); $field = $this->getByPosition($pos); return $field; } @@ -618,13 +618,13 @@ abstract class BaseCcShowRebroadcast extends BaseObject implements Persistent return $this->getDbId(); break; case 1: - return $this->getDbDayOffset(); + return $this->getDbInstanceId(); break; case 2: return $this->getDbStartTime(); break; case 3: - return $this->getDbShowId(); + return $this->getDbLiquidsoapData(); break; default: return null; @@ -648,16 +648,16 @@ abstract class BaseCcShowRebroadcast extends BaseObject implements Persistent */ public function toArray($keyType = BasePeer::TYPE_PHPNAME, $includeLazyLoadColumns = true, $includeForeignObjects = false) { - $keys = CcShowRebroadcastPeer::getFieldNames($keyType); + $keys = CcWebstreamMetadataPeer::getFieldNames($keyType); $result = array( $keys[0] => $this->getDbId(), - $keys[1] => $this->getDbDayOffset(), + $keys[1] => $this->getDbInstanceId(), $keys[2] => $this->getDbStartTime(), - $keys[3] => $this->getDbShowId(), + $keys[3] => $this->getDbLiquidsoapData(), ); if ($includeForeignObjects) { - if (null !== $this->aCcShow) { - $result['CcShow'] = $this->aCcShow->toArray($keyType, $includeLazyLoadColumns, true); + if (null !== $this->aCcSchedule) { + $result['CcSchedule'] = $this->aCcSchedule->toArray($keyType, $includeLazyLoadColumns, true); } } return $result; @@ -675,7 +675,7 @@ abstract class BaseCcShowRebroadcast extends BaseObject implements Persistent */ public function setByName($name, $value, $type = BasePeer::TYPE_PHPNAME) { - $pos = CcShowRebroadcastPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); + $pos = CcWebstreamMetadataPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); return $this->setByPosition($pos, $value); } @@ -694,13 +694,13 @@ abstract class BaseCcShowRebroadcast extends BaseObject implements Persistent $this->setDbId($value); break; case 1: - $this->setDbDayOffset($value); + $this->setDbInstanceId($value); break; case 2: $this->setDbStartTime($value); break; case 3: - $this->setDbShowId($value); + $this->setDbLiquidsoapData($value); break; } // switch() } @@ -724,12 +724,12 @@ abstract class BaseCcShowRebroadcast extends BaseObject implements Persistent */ public function fromArray($arr, $keyType = BasePeer::TYPE_PHPNAME) { - $keys = CcShowRebroadcastPeer::getFieldNames($keyType); + $keys = CcWebstreamMetadataPeer::getFieldNames($keyType); if (array_key_exists($keys[0], $arr)) $this->setDbId($arr[$keys[0]]); - if (array_key_exists($keys[1], $arr)) $this->setDbDayOffset($arr[$keys[1]]); + if (array_key_exists($keys[1], $arr)) $this->setDbInstanceId($arr[$keys[1]]); if (array_key_exists($keys[2], $arr)) $this->setDbStartTime($arr[$keys[2]]); - if (array_key_exists($keys[3], $arr)) $this->setDbShowId($arr[$keys[3]]); + if (array_key_exists($keys[3], $arr)) $this->setDbLiquidsoapData($arr[$keys[3]]); } /** @@ -739,12 +739,12 @@ abstract class BaseCcShowRebroadcast extends BaseObject implements Persistent */ public function buildCriteria() { - $criteria = new Criteria(CcShowRebroadcastPeer::DATABASE_NAME); + $criteria = new Criteria(CcWebstreamMetadataPeer::DATABASE_NAME); - if ($this->isColumnModified(CcShowRebroadcastPeer::ID)) $criteria->add(CcShowRebroadcastPeer::ID, $this->id); - if ($this->isColumnModified(CcShowRebroadcastPeer::DAY_OFFSET)) $criteria->add(CcShowRebroadcastPeer::DAY_OFFSET, $this->day_offset); - if ($this->isColumnModified(CcShowRebroadcastPeer::START_TIME)) $criteria->add(CcShowRebroadcastPeer::START_TIME, $this->start_time); - if ($this->isColumnModified(CcShowRebroadcastPeer::SHOW_ID)) $criteria->add(CcShowRebroadcastPeer::SHOW_ID, $this->show_id); + if ($this->isColumnModified(CcWebstreamMetadataPeer::ID)) $criteria->add(CcWebstreamMetadataPeer::ID, $this->id); + if ($this->isColumnModified(CcWebstreamMetadataPeer::INSTANCE_ID)) $criteria->add(CcWebstreamMetadataPeer::INSTANCE_ID, $this->instance_id); + if ($this->isColumnModified(CcWebstreamMetadataPeer::START_TIME)) $criteria->add(CcWebstreamMetadataPeer::START_TIME, $this->start_time); + if ($this->isColumnModified(CcWebstreamMetadataPeer::LIQUIDSOAP_DATA)) $criteria->add(CcWebstreamMetadataPeer::LIQUIDSOAP_DATA, $this->liquidsoap_data); return $criteria; } @@ -759,8 +759,8 @@ abstract class BaseCcShowRebroadcast extends BaseObject implements Persistent */ public function buildPkeyCriteria() { - $criteria = new Criteria(CcShowRebroadcastPeer::DATABASE_NAME); - $criteria->add(CcShowRebroadcastPeer::ID, $this->id); + $criteria = new Criteria(CcWebstreamMetadataPeer::DATABASE_NAME); + $criteria->add(CcWebstreamMetadataPeer::ID, $this->id); return $criteria; } @@ -800,15 +800,15 @@ abstract class BaseCcShowRebroadcast extends BaseObject implements Persistent * If desired, this method can also make copies of all associated (fkey referrers) * objects. * - * @param object $copyObj An object of CcShowRebroadcast (or compatible) type. + * @param object $copyObj An object of CcWebstreamMetadata (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->setDbDayOffset($this->day_offset); + $copyObj->setDbInstanceId($this->instance_id); $copyObj->setDbStartTime($this->start_time); - $copyObj->setDbShowId($this->show_id); + $copyObj->setDbLiquidsoapData($this->liquidsoap_data); $copyObj->setNew(true); $copyObj->setDbId(NULL); // this is a auto-increment column, so set to default value @@ -823,7 +823,7 @@ abstract class BaseCcShowRebroadcast extends BaseObject implements Persistent * objects. * * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. - * @return CcShowRebroadcast Clone of current object. + * @return CcWebstreamMetadata Clone of current object. * @throws PropelException */ public function copy($deepCopy = false) @@ -842,37 +842,37 @@ abstract class BaseCcShowRebroadcast extends BaseObject implements Persistent * same instance for all member of this class. The method could therefore * be static, but this would prevent one from overriding the behavior. * - * @return CcShowRebroadcastPeer + * @return CcWebstreamMetadataPeer */ public function getPeer() { if (self::$peer === null) { - self::$peer = new CcShowRebroadcastPeer(); + self::$peer = new CcWebstreamMetadataPeer(); } return self::$peer; } /** - * Declares an association between this object and a CcShow object. + * Declares an association between this object and a CcSchedule object. * - * @param CcShow $v - * @return CcShowRebroadcast The current object (for fluent API support) + * @param CcSchedule $v + * @return CcWebstreamMetadata The current object (for fluent API support) * @throws PropelException */ - public function setCcShow(CcShow $v = null) + public function setCcSchedule(CcSchedule $v = null) { if ($v === null) { - $this->setDbShowId(NULL); + $this->setDbInstanceId(NULL); } else { - $this->setDbShowId($v->getDbId()); + $this->setDbInstanceId($v->getDbId()); } - $this->aCcShow = $v; + $this->aCcSchedule = $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 this object has already been added to the CcSchedule object, it will not be re-added. if ($v !== null) { - $v->addCcShowRebroadcast($this); + $v->addCcWebstreamMetadata($this); } return $this; @@ -880,25 +880,25 @@ abstract class BaseCcShowRebroadcast extends BaseObject implements Persistent /** - * Get the associated CcShow object + * Get the associated CcSchedule object * * @param PropelPDO Optional Connection object. - * @return CcShow The associated CcShow object. + * @return CcSchedule The associated CcSchedule object. * @throws PropelException */ - public function getCcShow(PropelPDO $con = null) + public function getCcSchedule(PropelPDO $con = null) { - if ($this->aCcShow === null && ($this->show_id !== null)) { - $this->aCcShow = CcShowQuery::create()->findPk($this->show_id, $con); + if ($this->aCcSchedule === null && ($this->instance_id !== null)) { + $this->aCcSchedule = CcScheduleQuery::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->aCcShow->addCcShowRebroadcasts($this); + $this->aCcSchedule->addCcWebstreamMetadatas($this); */ } - return $this->aCcShow; + return $this->aCcSchedule; } /** @@ -907,9 +907,9 @@ abstract class BaseCcShowRebroadcast extends BaseObject implements Persistent public function clear() { $this->id = null; - $this->day_offset = null; + $this->instance_id = null; $this->start_time = null; - $this->show_id = null; + $this->liquidsoap_data = null; $this->alreadyInSave = false; $this->alreadyInValidation = false; $this->clearAllReferences(); @@ -932,7 +932,7 @@ abstract class BaseCcShowRebroadcast extends BaseObject implements Persistent if ($deep) { } // if ($deep) - $this->aCcShow = null; + $this->aCcSchedule = null; } /** @@ -954,4 +954,4 @@ abstract class BaseCcShowRebroadcast extends BaseObject implements Persistent throw new PropelException('Call to undefined method: ' . $name); } -} // BaseCcShowRebroadcast +} // BaseCcWebstreamMetadata diff --git a/install_minimal/upgrades/airtime-1.9.0/propel/airtime/om/BaseCcShowSchedulePeer.php b/airtime_mvc/application/models/airtime/om/BaseCcWebstreamMetadataPeer.php similarity index 70% rename from install_minimal/upgrades/airtime-1.9.0/propel/airtime/om/BaseCcShowSchedulePeer.php rename to airtime_mvc/application/models/airtime/om/BaseCcWebstreamMetadataPeer.php index 677ff8447..445e9793c 100644 --- a/install_minimal/upgrades/airtime-1.9.0/propel/airtime/om/BaseCcShowSchedulePeer.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcWebstreamMetadataPeer.php @@ -2,28 +2,28 @@ /** - * Base static class for performing query and update operations on the 'cc_show_schedule' table. + * Base static class for performing query and update operations on the 'cc_webstream_metadata' table. * * * * @package propel.generator.airtime.om */ -abstract class BaseCcShowSchedulePeer { +abstract class BaseCcWebstreamMetadataPeer { /** the default database name for this class */ const DATABASE_NAME = 'airtime'; /** the table name for this class */ - const TABLE_NAME = 'cc_show_schedule'; + const TABLE_NAME = 'cc_webstream_metadata'; /** the related Propel class for this table */ - const OM_CLASS = 'CcShowSchedule'; + const OM_CLASS = 'CcWebstreamMetadata'; /** A class that can be returned by this peer. */ - const CLASS_DEFAULT = 'airtime.CcShowSchedule'; + const CLASS_DEFAULT = 'airtime.CcWebstreamMetadata'; /** the related TableMap class for this table */ - const TM_CLASS = 'CcShowScheduleTableMap'; + const TM_CLASS = 'CcWebstreamMetadataTableMap'; /** The total number of columns. */ const NUM_COLUMNS = 4; @@ -32,22 +32,22 @@ abstract class BaseCcShowSchedulePeer { const NUM_LAZY_LOAD_COLUMNS = 0; /** the column name for the ID field */ - const ID = 'cc_show_schedule.ID'; + const ID = 'cc_webstream_metadata.ID'; /** the column name for the INSTANCE_ID field */ - const INSTANCE_ID = 'cc_show_schedule.INSTANCE_ID'; + const INSTANCE_ID = 'cc_webstream_metadata.INSTANCE_ID'; - /** the column name for the POSITION field */ - const POSITION = 'cc_show_schedule.POSITION'; + /** the column name for the START_TIME field */ + const START_TIME = 'cc_webstream_metadata.START_TIME'; - /** the column name for the GROUP_ID field */ - const GROUP_ID = 'cc_show_schedule.GROUP_ID'; + /** the column name for the LIQUIDSOAP_DATA field */ + const LIQUIDSOAP_DATA = 'cc_webstream_metadata.LIQUIDSOAP_DATA'; /** - * An identiy map to hold any loaded instances of CcShowSchedule objects. + * An identiy map to hold any loaded instances of CcWebstreamMetadata objects. * This must be public so that other peer classes can access this when hydrating from JOIN * queries. - * @var array CcShowSchedule[] + * @var array CcWebstreamMetadata[] */ public static $instances = array(); @@ -59,11 +59,11 @@ abstract class BaseCcShowSchedulePeer { * e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id' */ private static $fieldNames = array ( - BasePeer::TYPE_PHPNAME => array ('DbId', 'DbInstanceId', 'DbPosition', 'DbGroupId', ), - BasePeer::TYPE_STUDLYPHPNAME => array ('dbId', 'dbInstanceId', 'dbPosition', 'dbGroupId', ), - BasePeer::TYPE_COLNAME => array (self::ID, self::INSTANCE_ID, self::POSITION, self::GROUP_ID, ), - BasePeer::TYPE_RAW_COLNAME => array ('ID', 'INSTANCE_ID', 'POSITION', 'GROUP_ID', ), - BasePeer::TYPE_FIELDNAME => array ('id', 'instance_id', 'position', 'group_id', ), + BasePeer::TYPE_PHPNAME => array ('DbId', 'DbInstanceId', 'DbStartTime', 'DbLiquidsoapData', ), + BasePeer::TYPE_STUDLYPHPNAME => array ('dbId', 'dbInstanceId', 'dbStartTime', 'dbLiquidsoapData', ), + BasePeer::TYPE_COLNAME => array (self::ID, self::INSTANCE_ID, self::START_TIME, self::LIQUIDSOAP_DATA, ), + BasePeer::TYPE_RAW_COLNAME => array ('ID', 'INSTANCE_ID', 'START_TIME', 'LIQUIDSOAP_DATA', ), + BasePeer::TYPE_FIELDNAME => array ('id', 'instance_id', 'start_time', 'liquidsoap_data', ), BasePeer::TYPE_NUM => array (0, 1, 2, 3, ) ); @@ -74,11 +74,11 @@ abstract class BaseCcShowSchedulePeer { * e.g. self::$fieldNames[BasePeer::TYPE_PHPNAME]['Id'] = 0 */ private static $fieldKeys = array ( - BasePeer::TYPE_PHPNAME => array ('DbId' => 0, 'DbInstanceId' => 1, 'DbPosition' => 2, 'DbGroupId' => 3, ), - BasePeer::TYPE_STUDLYPHPNAME => array ('dbId' => 0, 'dbInstanceId' => 1, 'dbPosition' => 2, 'dbGroupId' => 3, ), - BasePeer::TYPE_COLNAME => array (self::ID => 0, self::INSTANCE_ID => 1, self::POSITION => 2, self::GROUP_ID => 3, ), - BasePeer::TYPE_RAW_COLNAME => array ('ID' => 0, 'INSTANCE_ID' => 1, 'POSITION' => 2, 'GROUP_ID' => 3, ), - BasePeer::TYPE_FIELDNAME => array ('id' => 0, 'instance_id' => 1, 'position' => 2, 'group_id' => 3, ), + BasePeer::TYPE_PHPNAME => array ('DbId' => 0, 'DbInstanceId' => 1, 'DbStartTime' => 2, 'DbLiquidsoapData' => 3, ), + BasePeer::TYPE_STUDLYPHPNAME => array ('dbId' => 0, 'dbInstanceId' => 1, 'dbStartTime' => 2, 'dbLiquidsoapData' => 3, ), + BasePeer::TYPE_COLNAME => array (self::ID => 0, self::INSTANCE_ID => 1, self::START_TIME => 2, self::LIQUIDSOAP_DATA => 3, ), + BasePeer::TYPE_RAW_COLNAME => array ('ID' => 0, 'INSTANCE_ID' => 1, 'START_TIME' => 2, 'LIQUIDSOAP_DATA' => 3, ), + BasePeer::TYPE_FIELDNAME => array ('id' => 0, 'instance_id' => 1, 'start_time' => 2, 'liquidsoap_data' => 3, ), BasePeer::TYPE_NUM => array (0, 1, 2, 3, ) ); @@ -128,12 +128,12 @@ abstract class BaseCcShowSchedulePeer { * $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. CcShowSchedulePeer::COLUMN_NAME). + * @param string $column The column name for current table. (i.e. CcWebstreamMetadataPeer::COLUMN_NAME). * @return string */ public static function alias($alias, $column) { - return str_replace(CcShowSchedulePeer::TABLE_NAME.'.', $alias.'.', $column); + return str_replace(CcWebstreamMetadataPeer::TABLE_NAME.'.', $alias.'.', $column); } /** @@ -151,15 +151,15 @@ abstract class BaseCcShowSchedulePeer { public static function addSelectColumns(Criteria $criteria, $alias = null) { if (null === $alias) { - $criteria->addSelectColumn(CcShowSchedulePeer::ID); - $criteria->addSelectColumn(CcShowSchedulePeer::INSTANCE_ID); - $criteria->addSelectColumn(CcShowSchedulePeer::POSITION); - $criteria->addSelectColumn(CcShowSchedulePeer::GROUP_ID); + $criteria->addSelectColumn(CcWebstreamMetadataPeer::ID); + $criteria->addSelectColumn(CcWebstreamMetadataPeer::INSTANCE_ID); + $criteria->addSelectColumn(CcWebstreamMetadataPeer::START_TIME); + $criteria->addSelectColumn(CcWebstreamMetadataPeer::LIQUIDSOAP_DATA); } else { $criteria->addSelectColumn($alias . '.ID'); $criteria->addSelectColumn($alias . '.INSTANCE_ID'); - $criteria->addSelectColumn($alias . '.POSITION'); - $criteria->addSelectColumn($alias . '.GROUP_ID'); + $criteria->addSelectColumn($alias . '.START_TIME'); + $criteria->addSelectColumn($alias . '.LIQUIDSOAP_DATA'); } } @@ -179,21 +179,21 @@ abstract class BaseCcShowSchedulePeer { // 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(CcShowSchedulePeer::TABLE_NAME); + $criteria->setPrimaryTableName(CcWebstreamMetadataPeer::TABLE_NAME); if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { $criteria->setDistinct(); } if (!$criteria->hasSelectClause()) { - CcShowSchedulePeer::addSelectColumns($criteria); + CcWebstreamMetadataPeer::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(CcShowSchedulePeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcWebstreamMetadataPeer::DATABASE_NAME, Propel::CONNECTION_READ); } // BasePeer returns a PDOStatement $stmt = BasePeer::doCount($criteria, $con); @@ -211,7 +211,7 @@ abstract class BaseCcShowSchedulePeer { * * @param Criteria $criteria object used to create the SELECT statement. * @param PropelPDO $con - * @return CcShowSchedule + * @return CcWebstreamMetadata * @throws PropelException Any exceptions caught during processing will be * rethrown wrapped into a PropelException. */ @@ -219,7 +219,7 @@ abstract class BaseCcShowSchedulePeer { { $critcopy = clone $criteria; $critcopy->setLimit(1); - $objects = CcShowSchedulePeer::doSelect($critcopy, $con); + $objects = CcWebstreamMetadataPeer::doSelect($critcopy, $con); if ($objects) { return $objects[0]; } @@ -236,7 +236,7 @@ abstract class BaseCcShowSchedulePeer { */ public static function doSelect(Criteria $criteria, PropelPDO $con = null) { - return CcShowSchedulePeer::populateObjects(CcShowSchedulePeer::doSelectStmt($criteria, $con)); + return CcWebstreamMetadataPeer::populateObjects(CcWebstreamMetadataPeer::doSelectStmt($criteria, $con)); } /** * Prepares the Criteria object and uses the parent doSelect() method to execute a PDOStatement. @@ -254,12 +254,12 @@ abstract class BaseCcShowSchedulePeer { public static function doSelectStmt(Criteria $criteria, PropelPDO $con = null) { if ($con === null) { - $con = Propel::getConnection(CcShowSchedulePeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcWebstreamMetadataPeer::DATABASE_NAME, Propel::CONNECTION_READ); } if (!$criteria->hasSelectClause()) { $criteria = clone $criteria; - CcShowSchedulePeer::addSelectColumns($criteria); + CcWebstreamMetadataPeer::addSelectColumns($criteria); } // Set the correct dbName @@ -277,10 +277,10 @@ abstract class BaseCcShowSchedulePeer { * to the cache in order to ensure that the same objects are always returned by doSelect*() * and retrieveByPK*() calls. * - * @param CcShowSchedule $value A CcShowSchedule object. + * @param CcWebstreamMetadata $value A CcWebstreamMetadata object. * @param string $key (optional) key to use for instance map (for performance boost if key was already calculated externally). */ - public static function addInstanceToPool(CcShowSchedule $obj, $key = null) + public static function addInstanceToPool(CcWebstreamMetadata $obj, $key = null) { if (Propel::isInstancePoolingEnabled()) { if ($key === null) { @@ -298,18 +298,18 @@ abstract class BaseCcShowSchedulePeer { * 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 CcShowSchedule object or a primary key value. + * @param mixed $value A CcWebstreamMetadata object or a primary key value. */ public static function removeInstanceFromPool($value) { if (Propel::isInstancePoolingEnabled() && $value !== null) { - if (is_object($value) && $value instanceof CcShowSchedule) { + if (is_object($value) && $value instanceof CcWebstreamMetadata) { $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 CcShowSchedule object; got " . (is_object($value) ? get_class($value) . ' object.' : var_export($value,true))); + $e = new PropelException("Invalid value passed to removeInstanceFromPool(). Expected primary key or CcWebstreamMetadata object; got " . (is_object($value) ? get_class($value) . ' object.' : var_export($value,true))); throw $e; } @@ -324,7 +324,7 @@ abstract class BaseCcShowSchedulePeer { * 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 CcShowSchedule Found object or NULL if 1) no instance exists for specified key or 2) instance pooling has been disabled. + * @return CcWebstreamMetadata 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) @@ -348,7 +348,7 @@ abstract class BaseCcShowSchedulePeer { } /** - * Method to invalidate the instance pool of all tables related to cc_show_schedule + * Method to invalidate the instance pool of all tables related to cc_webstream_metadata * by a foreign key with ON DELETE CASCADE */ public static function clearRelatedInstancePool() @@ -400,11 +400,11 @@ abstract class BaseCcShowSchedulePeer { $results = array(); // set the class once to avoid overhead in the loop - $cls = CcShowSchedulePeer::getOMClass(false); + $cls = CcWebstreamMetadataPeer::getOMClass(false); // populate the object(s) while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $key = CcShowSchedulePeer::getPrimaryKeyHashFromRow($row, 0); - if (null !== ($obj = CcShowSchedulePeer::getInstanceFromPool($key))) { + $key = CcWebstreamMetadataPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj = CcWebstreamMetadataPeer::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 @@ -413,7 +413,7 @@ abstract class BaseCcShowSchedulePeer { $obj = new $cls(); $obj->hydrate($row); $results[] = $obj; - CcShowSchedulePeer::addInstanceToPool($obj, $key); + CcWebstreamMetadataPeer::addInstanceToPool($obj, $key); } // if key exists } $stmt->closeCursor(); @@ -426,27 +426,27 @@ abstract class BaseCcShowSchedulePeer { * @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 (CcShowSchedule object, last column rank) + * @return array (CcWebstreamMetadata object, last column rank) */ public static function populateObject($row, $startcol = 0) { - $key = CcShowSchedulePeer::getPrimaryKeyHashFromRow($row, $startcol); - if (null !== ($obj = CcShowSchedulePeer::getInstanceFromPool($key))) { + $key = CcWebstreamMetadataPeer::getPrimaryKeyHashFromRow($row, $startcol); + if (null !== ($obj = CcWebstreamMetadataPeer::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 + CcShowSchedulePeer::NUM_COLUMNS; + $col = $startcol + CcWebstreamMetadataPeer::NUM_COLUMNS; } else { - $cls = CcShowSchedulePeer::OM_CLASS; + $cls = CcWebstreamMetadataPeer::OM_CLASS; $obj = new $cls(); $col = $obj->hydrate($row, $startcol); - CcShowSchedulePeer::addInstanceToPool($obj, $key); + CcWebstreamMetadataPeer::addInstanceToPool($obj, $key); } return array($obj, $col); } /** - * Returns the number of rows matching criteria, joining the related CcShowInstances table + * Returns the number of rows matching criteria, joining the related CcSchedule table * * @param Criteria $criteria * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. @@ -454,7 +454,7 @@ abstract class BaseCcShowSchedulePeer { * @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) + public static function doCountJoinCcSchedule(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; @@ -462,14 +462,14 @@ abstract class BaseCcShowSchedulePeer { // 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(CcShowSchedulePeer::TABLE_NAME); + $criteria->setPrimaryTableName(CcWebstreamMetadataPeer::TABLE_NAME); if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { $criteria->setDistinct(); } if (!$criteria->hasSelectClause()) { - CcShowSchedulePeer::addSelectColumns($criteria); + CcWebstreamMetadataPeer::addSelectColumns($criteria); } $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count @@ -478,10 +478,10 @@ abstract class BaseCcShowSchedulePeer { $criteria->setDbName(self::DATABASE_NAME); if ($con === null) { - $con = Propel::getConnection(CcShowSchedulePeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcWebstreamMetadataPeer::DATABASE_NAME, Propel::CONNECTION_READ); } - $criteria->addJoin(CcShowSchedulePeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); + $criteria->addJoin(CcWebstreamMetadataPeer::INSTANCE_ID, CcSchedulePeer::ID, $join_behavior); $stmt = BasePeer::doCount($criteria, $con); @@ -496,15 +496,15 @@ abstract class BaseCcShowSchedulePeer { /** - * Selects a collection of CcShowSchedule objects pre-filled with their CcShowInstances objects. + * Selects a collection of CcWebstreamMetadata objects pre-filled with their CcSchedule 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 CcShowSchedule objects. + * @return array Array of CcWebstreamMetadata 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) + public static function doSelectJoinCcSchedule(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) { $criteria = clone $criteria; @@ -513,44 +513,44 @@ abstract class BaseCcShowSchedulePeer { $criteria->setDbName(self::DATABASE_NAME); } - CcShowSchedulePeer::addSelectColumns($criteria); - $startcol = (CcShowSchedulePeer::NUM_COLUMNS - CcShowSchedulePeer::NUM_LAZY_LOAD_COLUMNS); - CcShowInstancesPeer::addSelectColumns($criteria); + CcWebstreamMetadataPeer::addSelectColumns($criteria); + $startcol = (CcWebstreamMetadataPeer::NUM_COLUMNS - CcWebstreamMetadataPeer::NUM_LAZY_LOAD_COLUMNS); + CcSchedulePeer::addSelectColumns($criteria); - $criteria->addJoin(CcShowSchedulePeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); + $criteria->addJoin(CcWebstreamMetadataPeer::INSTANCE_ID, CcSchedulePeer::ID, $join_behavior); $stmt = BasePeer::doSelect($criteria, $con); $results = array(); while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $key1 = CcShowSchedulePeer::getPrimaryKeyHashFromRow($row, 0); - if (null !== ($obj1 = CcShowSchedulePeer::getInstanceFromPool($key1))) { + $key1 = CcWebstreamMetadataPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcWebstreamMetadataPeer::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 = CcShowSchedulePeer::getOMClass(false); + $cls = CcWebstreamMetadataPeer::getOMClass(false); $obj1 = new $cls(); $obj1->hydrate($row); - CcShowSchedulePeer::addInstanceToPool($obj1, $key1); + CcWebstreamMetadataPeer::addInstanceToPool($obj1, $key1); } // if $obj1 already loaded - $key2 = CcShowInstancesPeer::getPrimaryKeyHashFromRow($row, $startcol); + $key2 = CcSchedulePeer::getPrimaryKeyHashFromRow($row, $startcol); if ($key2 !== null) { - $obj2 = CcShowInstancesPeer::getInstanceFromPool($key2); + $obj2 = CcSchedulePeer::getInstanceFromPool($key2); if (!$obj2) { - $cls = CcShowInstancesPeer::getOMClass(false); + $cls = CcSchedulePeer::getOMClass(false); $obj2 = new $cls(); $obj2->hydrate($row, $startcol); - CcShowInstancesPeer::addInstanceToPool($obj2, $key2); + CcSchedulePeer::addInstanceToPool($obj2, $key2); } // if obj2 already loaded - // Add the $obj1 (CcShowSchedule) to $obj2 (CcShowInstances) - $obj2->addCcShowSchedule($obj1); + // Add the $obj1 (CcWebstreamMetadata) to $obj2 (CcSchedule) + $obj2->addCcWebstreamMetadata($obj1); } // if joined row was not null @@ -578,14 +578,14 @@ abstract class BaseCcShowSchedulePeer { // 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(CcShowSchedulePeer::TABLE_NAME); + $criteria->setPrimaryTableName(CcWebstreamMetadataPeer::TABLE_NAME); if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { $criteria->setDistinct(); } if (!$criteria->hasSelectClause()) { - CcShowSchedulePeer::addSelectColumns($criteria); + CcWebstreamMetadataPeer::addSelectColumns($criteria); } $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count @@ -594,10 +594,10 @@ abstract class BaseCcShowSchedulePeer { $criteria->setDbName(self::DATABASE_NAME); if ($con === null) { - $con = Propel::getConnection(CcShowSchedulePeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcWebstreamMetadataPeer::DATABASE_NAME, Propel::CONNECTION_READ); } - $criteria->addJoin(CcShowSchedulePeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); + $criteria->addJoin(CcWebstreamMetadataPeer::INSTANCE_ID, CcSchedulePeer::ID, $join_behavior); $stmt = BasePeer::doCount($criteria, $con); @@ -611,12 +611,12 @@ abstract class BaseCcShowSchedulePeer { } /** - * Selects a collection of CcShowSchedule objects pre-filled with all related objects. + * Selects a collection of CcWebstreamMetadata 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 CcShowSchedule objects. + * @return array Array of CcWebstreamMetadata objects. * @throws PropelException Any exceptions caught during processing will be * rethrown wrapped into a PropelException. */ @@ -629,47 +629,47 @@ abstract class BaseCcShowSchedulePeer { $criteria->setDbName(self::DATABASE_NAME); } - CcShowSchedulePeer::addSelectColumns($criteria); - $startcol2 = (CcShowSchedulePeer::NUM_COLUMNS - CcShowSchedulePeer::NUM_LAZY_LOAD_COLUMNS); + CcWebstreamMetadataPeer::addSelectColumns($criteria); + $startcol2 = (CcWebstreamMetadataPeer::NUM_COLUMNS - CcWebstreamMetadataPeer::NUM_LAZY_LOAD_COLUMNS); - CcShowInstancesPeer::addSelectColumns($criteria); - $startcol3 = $startcol2 + (CcShowInstancesPeer::NUM_COLUMNS - CcShowInstancesPeer::NUM_LAZY_LOAD_COLUMNS); + CcSchedulePeer::addSelectColumns($criteria); + $startcol3 = $startcol2 + (CcSchedulePeer::NUM_COLUMNS - CcSchedulePeer::NUM_LAZY_LOAD_COLUMNS); - $criteria->addJoin(CcShowSchedulePeer::INSTANCE_ID, CcShowInstancesPeer::ID, $join_behavior); + $criteria->addJoin(CcWebstreamMetadataPeer::INSTANCE_ID, CcSchedulePeer::ID, $join_behavior); $stmt = BasePeer::doSelect($criteria, $con); $results = array(); while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $key1 = CcShowSchedulePeer::getPrimaryKeyHashFromRow($row, 0); - if (null !== ($obj1 = CcShowSchedulePeer::getInstanceFromPool($key1))) { + $key1 = CcWebstreamMetadataPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcWebstreamMetadataPeer::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 = CcShowSchedulePeer::getOMClass(false); + $cls = CcWebstreamMetadataPeer::getOMClass(false); $obj1 = new $cls(); $obj1->hydrate($row); - CcShowSchedulePeer::addInstanceToPool($obj1, $key1); + CcWebstreamMetadataPeer::addInstanceToPool($obj1, $key1); } // if obj1 already loaded - // Add objects for joined CcShowInstances rows + // Add objects for joined CcSchedule rows - $key2 = CcShowInstancesPeer::getPrimaryKeyHashFromRow($row, $startcol2); + $key2 = CcSchedulePeer::getPrimaryKeyHashFromRow($row, $startcol2); if ($key2 !== null) { - $obj2 = CcShowInstancesPeer::getInstanceFromPool($key2); + $obj2 = CcSchedulePeer::getInstanceFromPool($key2); if (!$obj2) { - $cls = CcShowInstancesPeer::getOMClass(false); + $cls = CcSchedulePeer::getOMClass(false); $obj2 = new $cls(); $obj2->hydrate($row, $startcol2); - CcShowInstancesPeer::addInstanceToPool($obj2, $key2); + CcSchedulePeer::addInstanceToPool($obj2, $key2); } // if obj2 loaded - // Add the $obj1 (CcShowSchedule) to the collection in $obj2 (CcShowInstances) - $obj2->addCcShowSchedule($obj1); + // Add the $obj1 (CcWebstreamMetadata) to the collection in $obj2 (CcSchedule) + $obj2->addCcWebstreamMetadata($obj1); } // if joined row not null $results[] = $obj1; @@ -695,10 +695,10 @@ abstract class BaseCcShowSchedulePeer { */ public static function buildTableMap() { - $dbMap = Propel::getDatabaseMap(BaseCcShowSchedulePeer::DATABASE_NAME); - if (!$dbMap->hasTable(BaseCcShowSchedulePeer::TABLE_NAME)) + $dbMap = Propel::getDatabaseMap(BaseCcWebstreamMetadataPeer::DATABASE_NAME); + if (!$dbMap->hasTable(BaseCcWebstreamMetadataPeer::TABLE_NAME)) { - $dbMap->addTableObject(new CcShowScheduleTableMap()); + $dbMap->addTableObject(new CcWebstreamMetadataTableMap()); } } @@ -715,13 +715,13 @@ abstract class BaseCcShowSchedulePeer { */ public static function getOMClass($withPrefix = true) { - return $withPrefix ? CcShowSchedulePeer::CLASS_DEFAULT : CcShowSchedulePeer::OM_CLASS; + return $withPrefix ? CcWebstreamMetadataPeer::CLASS_DEFAULT : CcWebstreamMetadataPeer::OM_CLASS; } /** - * Method perform an INSERT on the database, given a CcShowSchedule or Criteria object. + * Method perform an INSERT on the database, given a CcWebstreamMetadata or Criteria object. * - * @param mixed $values Criteria or CcShowSchedule object containing data that is used to create the INSERT statement. + * @param mixed $values Criteria or CcWebstreamMetadata 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 @@ -730,17 +730,17 @@ abstract class BaseCcShowSchedulePeer { public static function doInsert($values, PropelPDO $con = null) { if ($con === null) { - $con = Propel::getConnection(CcShowSchedulePeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + $con = Propel::getConnection(CcWebstreamMetadataPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); } if ($values instanceof Criteria) { $criteria = clone $values; // rename for clarity } else { - $criteria = $values->buildCriteria(); // build Criteria from CcShowSchedule object + $criteria = $values->buildCriteria(); // build Criteria from CcWebstreamMetadata object } - if ($criteria->containsKey(CcShowSchedulePeer::ID) && $criteria->keyContainsValue(CcShowSchedulePeer::ID) ) { - throw new PropelException('Cannot insert a value for auto-increment primary key ('.CcShowSchedulePeer::ID.')'); + if ($criteria->containsKey(CcWebstreamMetadataPeer::ID) && $criteria->keyContainsValue(CcWebstreamMetadataPeer::ID) ) { + throw new PropelException('Cannot insert a value for auto-increment primary key ('.CcWebstreamMetadataPeer::ID.')'); } @@ -762,9 +762,9 @@ abstract class BaseCcShowSchedulePeer { } /** - * Method perform an UPDATE on the database, given a CcShowSchedule or Criteria object. + * Method perform an UPDATE on the database, given a CcWebstreamMetadata or Criteria object. * - * @param mixed $values Criteria or CcShowSchedule object containing data that is used to create the UPDATE statement. + * @param mixed $values Criteria or CcWebstreamMetadata 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 @@ -773,7 +773,7 @@ abstract class BaseCcShowSchedulePeer { public static function doUpdate($values, PropelPDO $con = null) { if ($con === null) { - $con = Propel::getConnection(CcShowSchedulePeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + $con = Propel::getConnection(CcWebstreamMetadataPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); } $selectCriteria = new Criteria(self::DATABASE_NAME); @@ -781,15 +781,15 @@ abstract class BaseCcShowSchedulePeer { if ($values instanceof Criteria) { $criteria = clone $values; // rename for clarity - $comparison = $criteria->getComparison(CcShowSchedulePeer::ID); - $value = $criteria->remove(CcShowSchedulePeer::ID); + $comparison = $criteria->getComparison(CcWebstreamMetadataPeer::ID); + $value = $criteria->remove(CcWebstreamMetadataPeer::ID); if ($value) { - $selectCriteria->add(CcShowSchedulePeer::ID, $value, $comparison); + $selectCriteria->add(CcWebstreamMetadataPeer::ID, $value, $comparison); } else { - $selectCriteria->setPrimaryTableName(CcShowSchedulePeer::TABLE_NAME); + $selectCriteria->setPrimaryTableName(CcWebstreamMetadataPeer::TABLE_NAME); } - } else { // $values is CcShowSchedule object + } else { // $values is CcWebstreamMetadata object $criteria = $values->buildCriteria(); // gets full criteria $selectCriteria = $values->buildPkeyCriteria(); // gets criteria w/ primary key(s) } @@ -801,26 +801,26 @@ abstract class BaseCcShowSchedulePeer { } /** - * Method to DELETE all rows from the cc_show_schedule table. + * Method to DELETE all rows from the cc_webstream_metadata 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(CcShowSchedulePeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + $con = Propel::getConnection(CcWebstreamMetadataPeer::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(CcShowSchedulePeer::TABLE_NAME, $con, CcShowSchedulePeer::DATABASE_NAME); + $affectedRows += BasePeer::doDeleteAll(CcWebstreamMetadataPeer::TABLE_NAME, $con, CcWebstreamMetadataPeer::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). - CcShowSchedulePeer::clearInstancePool(); - CcShowSchedulePeer::clearRelatedInstancePool(); + CcWebstreamMetadataPeer::clearInstancePool(); + CcWebstreamMetadataPeer::clearRelatedInstancePool(); $con->commit(); return $affectedRows; } catch (PropelException $e) { @@ -830,9 +830,9 @@ abstract class BaseCcShowSchedulePeer { } /** - * Method perform a DELETE on the database, given a CcShowSchedule or Criteria object OR a primary key value. + * Method perform a DELETE on the database, given a CcWebstreamMetadata or Criteria object OR a primary key value. * - * @param mixed $values Criteria or CcShowSchedule object or primary key or array of primary keys + * @param mixed $values Criteria or CcWebstreamMetadata 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 @@ -843,27 +843,27 @@ abstract class BaseCcShowSchedulePeer { public static function doDelete($values, PropelPDO $con = null) { if ($con === null) { - $con = Propel::getConnection(CcShowSchedulePeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + $con = Propel::getConnection(CcWebstreamMetadataPeer::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. - CcShowSchedulePeer::clearInstancePool(); + CcWebstreamMetadataPeer::clearInstancePool(); // rename for clarity $criteria = clone $values; - } elseif ($values instanceof CcShowSchedule) { // it's a model object + } elseif ($values instanceof CcWebstreamMetadata) { // it's a model object // invalidate the cache for this single object - CcShowSchedulePeer::removeInstanceFromPool($values); + CcWebstreamMetadataPeer::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(CcShowSchedulePeer::ID, (array) $values, Criteria::IN); + $criteria->add(CcWebstreamMetadataPeer::ID, (array) $values, Criteria::IN); // invalidate the cache for this object(s) foreach ((array) $values as $singleval) { - CcShowSchedulePeer::removeInstanceFromPool($singleval); + CcWebstreamMetadataPeer::removeInstanceFromPool($singleval); } } @@ -878,7 +878,7 @@ abstract class BaseCcShowSchedulePeer { $con->beginTransaction(); $affectedRows += BasePeer::doDelete($criteria, $con); - CcShowSchedulePeer::clearRelatedInstancePool(); + CcWebstreamMetadataPeer::clearRelatedInstancePool(); $con->commit(); return $affectedRows; } catch (PropelException $e) { @@ -888,24 +888,24 @@ abstract class BaseCcShowSchedulePeer { } /** - * Validates all modified columns of given CcShowSchedule object. + * Validates all modified columns of given CcWebstreamMetadata 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 CcShowSchedule $obj The object to validate. + * @param CcWebstreamMetadata $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(CcShowSchedule $obj, $cols = null) + public static function doValidate(CcWebstreamMetadata $obj, $cols = null) { $columns = array(); if ($cols) { - $dbMap = Propel::getDatabaseMap(CcShowSchedulePeer::DATABASE_NAME); - $tableMap = $dbMap->getTable(CcShowSchedulePeer::TABLE_NAME); + $dbMap = Propel::getDatabaseMap(CcWebstreamMetadataPeer::DATABASE_NAME); + $tableMap = $dbMap->getTable(CcWebstreamMetadataPeer::TABLE_NAME); if (! is_array($cols)) { $cols = array($cols); @@ -921,7 +921,7 @@ abstract class BaseCcShowSchedulePeer { } - return BasePeer::doValidate(CcShowSchedulePeer::DATABASE_NAME, CcShowSchedulePeer::TABLE_NAME, $columns); + return BasePeer::doValidate(CcWebstreamMetadataPeer::DATABASE_NAME, CcWebstreamMetadataPeer::TABLE_NAME, $columns); } /** @@ -929,23 +929,23 @@ abstract class BaseCcShowSchedulePeer { * * @param int $pk the primary key. * @param PropelPDO $con the connection to use - * @return CcShowSchedule + * @return CcWebstreamMetadata */ public static function retrieveByPK($pk, PropelPDO $con = null) { - if (null !== ($obj = CcShowSchedulePeer::getInstanceFromPool((string) $pk))) { + if (null !== ($obj = CcWebstreamMetadataPeer::getInstanceFromPool((string) $pk))) { return $obj; } if ($con === null) { - $con = Propel::getConnection(CcShowSchedulePeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcWebstreamMetadataPeer::DATABASE_NAME, Propel::CONNECTION_READ); } - $criteria = new Criteria(CcShowSchedulePeer::DATABASE_NAME); - $criteria->add(CcShowSchedulePeer::ID, $pk); + $criteria = new Criteria(CcWebstreamMetadataPeer::DATABASE_NAME); + $criteria->add(CcWebstreamMetadataPeer::ID, $pk); - $v = CcShowSchedulePeer::doSelect($criteria, $con); + $v = CcWebstreamMetadataPeer::doSelect($criteria, $con); return !empty($v) > 0 ? $v[0] : null; } @@ -961,23 +961,23 @@ abstract class BaseCcShowSchedulePeer { public static function retrieveByPKs($pks, PropelPDO $con = null) { if ($con === null) { - $con = Propel::getConnection(CcShowSchedulePeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcWebstreamMetadataPeer::DATABASE_NAME, Propel::CONNECTION_READ); } $objs = null; if (empty($pks)) { $objs = array(); } else { - $criteria = new Criteria(CcShowSchedulePeer::DATABASE_NAME); - $criteria->add(CcShowSchedulePeer::ID, $pks, Criteria::IN); - $objs = CcShowSchedulePeer::doSelect($criteria, $con); + $criteria = new Criteria(CcWebstreamMetadataPeer::DATABASE_NAME); + $criteria->add(CcWebstreamMetadataPeer::ID, $pks, Criteria::IN); + $objs = CcWebstreamMetadataPeer::doSelect($criteria, $con); } return $objs; } -} // BaseCcShowSchedulePeer +} // BaseCcWebstreamMetadataPeer // This is the static code needed to register the TableMap for this table with the main Propel class. // -BaseCcShowSchedulePeer::buildTableMap(); +BaseCcWebstreamMetadataPeer::buildTableMap(); diff --git a/airtime_mvc/application/models/airtime/om/BaseCcWebstreamMetadataQuery.php b/airtime_mvc/application/models/airtime/om/BaseCcWebstreamMetadataQuery.php new file mode 100644 index 000000000..ba5bfcb12 --- /dev/null +++ b/airtime_mvc/application/models/airtime/om/BaseCcWebstreamMetadataQuery.php @@ -0,0 +1,329 @@ +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 CcWebstreamMetadata|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ((null !== ($obj = CcWebstreamMetadataPeer::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 CcWebstreamMetadataQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + return $this->addUsingAlias(CcWebstreamMetadataPeer::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 CcWebstreamMetadataQuery The current query, for fluid interface + */ + public function filterByPrimaryKeys($keys) + { + return $this->addUsingAlias(CcWebstreamMetadataPeer::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 CcWebstreamMetadataQuery 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(CcWebstreamMetadataPeer::ID, $dbId, $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 CcWebstreamMetadataQuery 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(CcWebstreamMetadataPeer::INSTANCE_ID, $dbInstanceId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbInstanceId['max'])) { + $this->addUsingAlias(CcWebstreamMetadataPeer::INSTANCE_ID, $dbInstanceId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcWebstreamMetadataPeer::INSTANCE_ID, $dbInstanceId, $comparison); + } + + /** + * Filter the query on the start_time column + * + * @param string|array $dbStartTime 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 CcWebstreamMetadataQuery The current query, for fluid interface + */ + public function filterByDbStartTime($dbStartTime = null, $comparison = null) + { + if (is_array($dbStartTime)) { + $useMinMax = false; + if (isset($dbStartTime['min'])) { + $this->addUsingAlias(CcWebstreamMetadataPeer::START_TIME, $dbStartTime['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbStartTime['max'])) { + $this->addUsingAlias(CcWebstreamMetadataPeer::START_TIME, $dbStartTime['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcWebstreamMetadataPeer::START_TIME, $dbStartTime, $comparison); + } + + /** + * Filter the query on the liquidsoap_data column + * + * @param string $dbLiquidsoapData 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 CcWebstreamMetadataQuery The current query, for fluid interface + */ + public function filterByDbLiquidsoapData($dbLiquidsoapData = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($dbLiquidsoapData)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $dbLiquidsoapData)) { + $dbLiquidsoapData = str_replace('*', '%', $dbLiquidsoapData); + $comparison = Criteria::LIKE; + } + } + return $this->addUsingAlias(CcWebstreamMetadataPeer::LIQUIDSOAP_DATA, $dbLiquidsoapData, $comparison); + } + + /** + * Filter the query by a related CcSchedule object + * + * @param CcSchedule $ccSchedule the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return CcWebstreamMetadataQuery The current query, for fluid interface + */ + public function filterByCcSchedule($ccSchedule, $comparison = null) + { + return $this + ->addUsingAlias(CcWebstreamMetadataPeer::INSTANCE_ID, $ccSchedule->getDbId(), $comparison); + } + + /** + * Adds a JOIN clause to the query using the CcSchedule relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return CcWebstreamMetadataQuery The current query, for fluid interface + */ + public function joinCcSchedule($relationAlias = '', $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('CcSchedule'); + + // 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, 'CcSchedule'); + } + + return $this; + } + + /** + * Use the CcSchedule relation CcSchedule 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 CcScheduleQuery A secondary query class using the current class as primary query + */ + public function useCcScheduleQuery($relationAlias = '', $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinCcSchedule($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'CcSchedule', 'CcScheduleQuery'); + } + + /** + * Exclude object from result + * + * @param CcWebstreamMetadata $ccWebstreamMetadata Object to remove from the list of results + * + * @return CcWebstreamMetadataQuery The current query, for fluid interface + */ + public function prune($ccWebstreamMetadata = null) + { + if ($ccWebstreamMetadata) { + $this->addUsingAlias(CcWebstreamMetadataPeer::ID, $ccWebstreamMetadata->getDbId(), Criteria::NOT_EQUAL); + } + + return $this; + } + +} // BaseCcWebstreamMetadataQuery diff --git a/install_minimal/upgrades/airtime-1.9.0/propel/airtime/om/BaseCcMusicDirsPeer.php b/airtime_mvc/application/models/airtime/om/BaseCcWebstreamPeer.php similarity index 70% rename from install_minimal/upgrades/airtime-1.9.0/propel/airtime/om/BaseCcMusicDirsPeer.php rename to airtime_mvc/application/models/airtime/om/BaseCcWebstreamPeer.php index 5d06e270d..c1b2f7221 100644 --- a/install_minimal/upgrades/airtime-1.9.0/propel/airtime/om/BaseCcMusicDirsPeer.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcWebstreamPeer.php @@ -2,49 +2,70 @@ /** - * Base static class for performing query and update operations on the 'cc_music_dirs' table. + * Base static class for performing query and update operations on the 'cc_webstream' table. * * * * @package propel.generator.airtime.om */ -abstract class BaseCcMusicDirsPeer { +abstract class BaseCcWebstreamPeer { /** the default database name for this class */ const DATABASE_NAME = 'airtime'; /** the table name for this class */ - const TABLE_NAME = 'cc_music_dirs'; + const TABLE_NAME = 'cc_webstream'; /** the related Propel class for this table */ - const OM_CLASS = 'CcMusicDirs'; + const OM_CLASS = 'CcWebstream'; /** A class that can be returned by this peer. */ - const CLASS_DEFAULT = 'airtime.CcMusicDirs'; + const CLASS_DEFAULT = 'airtime.CcWebstream'; /** the related TableMap class for this table */ - const TM_CLASS = 'CcMusicDirsTableMap'; + const TM_CLASS = 'CcWebstreamTableMap'; /** The total number of columns. */ - const NUM_COLUMNS = 3; + const NUM_COLUMNS = 10; /** The number of lazy-loaded columns. */ const NUM_LAZY_LOAD_COLUMNS = 0; /** the column name for the ID field */ - const ID = 'cc_music_dirs.ID'; + const ID = 'cc_webstream.ID'; - /** the column name for the DIRECTORY field */ - const DIRECTORY = 'cc_music_dirs.DIRECTORY'; + /** the column name for the NAME field */ + const NAME = 'cc_webstream.NAME'; - /** the column name for the TYPE field */ - const TYPE = 'cc_music_dirs.TYPE'; + /** the column name for the DESCRIPTION field */ + const DESCRIPTION = 'cc_webstream.DESCRIPTION'; + + /** the column name for the URL field */ + const URL = 'cc_webstream.URL'; + + /** the column name for the LENGTH field */ + const LENGTH = 'cc_webstream.LENGTH'; + + /** the column name for the CREATOR_ID field */ + const CREATOR_ID = 'cc_webstream.CREATOR_ID'; + + /** the column name for the MTIME field */ + const MTIME = 'cc_webstream.MTIME'; + + /** the column name for the UTIME field */ + const UTIME = 'cc_webstream.UTIME'; + + /** the column name for the LPTIME field */ + const LPTIME = 'cc_webstream.LPTIME'; + + /** the column name for the MIME field */ + const MIME = 'cc_webstream.MIME'; /** - * An identiy map to hold any loaded instances of CcMusicDirs objects. + * An identiy map to hold any loaded instances of CcWebstream objects. * This must be public so that other peer classes can access this when hydrating from JOIN * queries. - * @var array CcMusicDirs[] + * @var array CcWebstream[] */ public static $instances = array(); @@ -56,12 +77,12 @@ abstract class BaseCcMusicDirsPeer { * e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id' */ private static $fieldNames = array ( - BasePeer::TYPE_PHPNAME => array ('Id', 'Directory', 'Type', ), - BasePeer::TYPE_STUDLYPHPNAME => array ('id', 'directory', 'type', ), - BasePeer::TYPE_COLNAME => array (self::ID, self::DIRECTORY, self::TYPE, ), - BasePeer::TYPE_RAW_COLNAME => array ('ID', 'DIRECTORY', 'TYPE', ), - BasePeer::TYPE_FIELDNAME => array ('id', 'directory', 'type', ), - BasePeer::TYPE_NUM => array (0, 1, 2, ) + BasePeer::TYPE_PHPNAME => array ('DbId', 'DbName', 'DbDescription', 'DbUrl', 'DbLength', 'DbCreatorId', 'DbMtime', 'DbUtime', 'DbLPtime', 'DbMime', ), + BasePeer::TYPE_STUDLYPHPNAME => array ('dbId', 'dbName', 'dbDescription', 'dbUrl', 'dbLength', 'dbCreatorId', 'dbMtime', 'dbUtime', 'dbLPtime', 'dbMime', ), + BasePeer::TYPE_COLNAME => array (self::ID, self::NAME, self::DESCRIPTION, self::URL, self::LENGTH, self::CREATOR_ID, self::MTIME, self::UTIME, self::LPTIME, self::MIME, ), + BasePeer::TYPE_RAW_COLNAME => array ('ID', 'NAME', 'DESCRIPTION', 'URL', 'LENGTH', 'CREATOR_ID', 'MTIME', 'UTIME', 'LPTIME', 'MIME', ), + BasePeer::TYPE_FIELDNAME => array ('id', 'name', 'description', 'url', 'length', 'creator_id', 'mtime', 'utime', 'lptime', 'mime', ), + BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ) ); /** @@ -71,12 +92,12 @@ abstract class BaseCcMusicDirsPeer { * e.g. self::$fieldNames[BasePeer::TYPE_PHPNAME]['Id'] = 0 */ private static $fieldKeys = array ( - BasePeer::TYPE_PHPNAME => array ('Id' => 0, 'Directory' => 1, 'Type' => 2, ), - BasePeer::TYPE_STUDLYPHPNAME => array ('id' => 0, 'directory' => 1, 'type' => 2, ), - BasePeer::TYPE_COLNAME => array (self::ID => 0, self::DIRECTORY => 1, self::TYPE => 2, ), - BasePeer::TYPE_RAW_COLNAME => array ('ID' => 0, 'DIRECTORY' => 1, 'TYPE' => 2, ), - BasePeer::TYPE_FIELDNAME => array ('id' => 0, 'directory' => 1, 'type' => 2, ), - BasePeer::TYPE_NUM => array (0, 1, 2, ) + BasePeer::TYPE_PHPNAME => array ('DbId' => 0, 'DbName' => 1, 'DbDescription' => 2, 'DbUrl' => 3, 'DbLength' => 4, 'DbCreatorId' => 5, 'DbMtime' => 6, 'DbUtime' => 7, 'DbLPtime' => 8, 'DbMime' => 9, ), + BasePeer::TYPE_STUDLYPHPNAME => array ('dbId' => 0, 'dbName' => 1, 'dbDescription' => 2, 'dbUrl' => 3, 'dbLength' => 4, 'dbCreatorId' => 5, 'dbMtime' => 6, 'dbUtime' => 7, 'dbLPtime' => 8, 'dbMime' => 9, ), + BasePeer::TYPE_COLNAME => array (self::ID => 0, self::NAME => 1, self::DESCRIPTION => 2, self::URL => 3, self::LENGTH => 4, self::CREATOR_ID => 5, self::MTIME => 6, self::UTIME => 7, self::LPTIME => 8, self::MIME => 9, ), + BasePeer::TYPE_RAW_COLNAME => array ('ID' => 0, 'NAME' => 1, 'DESCRIPTION' => 2, 'URL' => 3, 'LENGTH' => 4, 'CREATOR_ID' => 5, 'MTIME' => 6, 'UTIME' => 7, 'LPTIME' => 8, 'MIME' => 9, ), + BasePeer::TYPE_FIELDNAME => array ('id' => 0, 'name' => 1, 'description' => 2, 'url' => 3, 'length' => 4, 'creator_id' => 5, 'mtime' => 6, 'utime' => 7, 'lptime' => 8, 'mime' => 9, ), + BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ) ); /** @@ -125,12 +146,12 @@ abstract class BaseCcMusicDirsPeer { * $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. CcMusicDirsPeer::COLUMN_NAME). + * @param string $column The column name for current table. (i.e. CcWebstreamPeer::COLUMN_NAME). * @return string */ public static function alias($alias, $column) { - return str_replace(CcMusicDirsPeer::TABLE_NAME.'.', $alias.'.', $column); + return str_replace(CcWebstreamPeer::TABLE_NAME.'.', $alias.'.', $column); } /** @@ -148,13 +169,27 @@ abstract class BaseCcMusicDirsPeer { public static function addSelectColumns(Criteria $criteria, $alias = null) { if (null === $alias) { - $criteria->addSelectColumn(CcMusicDirsPeer::ID); - $criteria->addSelectColumn(CcMusicDirsPeer::DIRECTORY); - $criteria->addSelectColumn(CcMusicDirsPeer::TYPE); + $criteria->addSelectColumn(CcWebstreamPeer::ID); + $criteria->addSelectColumn(CcWebstreamPeer::NAME); + $criteria->addSelectColumn(CcWebstreamPeer::DESCRIPTION); + $criteria->addSelectColumn(CcWebstreamPeer::URL); + $criteria->addSelectColumn(CcWebstreamPeer::LENGTH); + $criteria->addSelectColumn(CcWebstreamPeer::CREATOR_ID); + $criteria->addSelectColumn(CcWebstreamPeer::MTIME); + $criteria->addSelectColumn(CcWebstreamPeer::UTIME); + $criteria->addSelectColumn(CcWebstreamPeer::LPTIME); + $criteria->addSelectColumn(CcWebstreamPeer::MIME); } else { $criteria->addSelectColumn($alias . '.ID'); - $criteria->addSelectColumn($alias . '.DIRECTORY'); - $criteria->addSelectColumn($alias . '.TYPE'); + $criteria->addSelectColumn($alias . '.NAME'); + $criteria->addSelectColumn($alias . '.DESCRIPTION'); + $criteria->addSelectColumn($alias . '.URL'); + $criteria->addSelectColumn($alias . '.LENGTH'); + $criteria->addSelectColumn($alias . '.CREATOR_ID'); + $criteria->addSelectColumn($alias . '.MTIME'); + $criteria->addSelectColumn($alias . '.UTIME'); + $criteria->addSelectColumn($alias . '.LPTIME'); + $criteria->addSelectColumn($alias . '.MIME'); } } @@ -174,21 +209,21 @@ abstract class BaseCcMusicDirsPeer { // 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(CcMusicDirsPeer::TABLE_NAME); + $criteria->setPrimaryTableName(CcWebstreamPeer::TABLE_NAME); if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { $criteria->setDistinct(); } if (!$criteria->hasSelectClause()) { - CcMusicDirsPeer::addSelectColumns($criteria); + CcWebstreamPeer::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(CcMusicDirsPeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcWebstreamPeer::DATABASE_NAME, Propel::CONNECTION_READ); } // BasePeer returns a PDOStatement $stmt = BasePeer::doCount($criteria, $con); @@ -206,7 +241,7 @@ abstract class BaseCcMusicDirsPeer { * * @param Criteria $criteria object used to create the SELECT statement. * @param PropelPDO $con - * @return CcMusicDirs + * @return CcWebstream * @throws PropelException Any exceptions caught during processing will be * rethrown wrapped into a PropelException. */ @@ -214,7 +249,7 @@ abstract class BaseCcMusicDirsPeer { { $critcopy = clone $criteria; $critcopy->setLimit(1); - $objects = CcMusicDirsPeer::doSelect($critcopy, $con); + $objects = CcWebstreamPeer::doSelect($critcopy, $con); if ($objects) { return $objects[0]; } @@ -231,7 +266,7 @@ abstract class BaseCcMusicDirsPeer { */ public static function doSelect(Criteria $criteria, PropelPDO $con = null) { - return CcMusicDirsPeer::populateObjects(CcMusicDirsPeer::doSelectStmt($criteria, $con)); + return CcWebstreamPeer::populateObjects(CcWebstreamPeer::doSelectStmt($criteria, $con)); } /** * Prepares the Criteria object and uses the parent doSelect() method to execute a PDOStatement. @@ -249,12 +284,12 @@ abstract class BaseCcMusicDirsPeer { public static function doSelectStmt(Criteria $criteria, PropelPDO $con = null) { if ($con === null) { - $con = Propel::getConnection(CcMusicDirsPeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcWebstreamPeer::DATABASE_NAME, Propel::CONNECTION_READ); } if (!$criteria->hasSelectClause()) { $criteria = clone $criteria; - CcMusicDirsPeer::addSelectColumns($criteria); + CcWebstreamPeer::addSelectColumns($criteria); } // Set the correct dbName @@ -272,14 +307,14 @@ abstract class BaseCcMusicDirsPeer { * to the cache in order to ensure that the same objects are always returned by doSelect*() * and retrieveByPK*() calls. * - * @param CcMusicDirs $value A CcMusicDirs object. + * @param CcWebstream $value A CcWebstream object. * @param string $key (optional) key to use for instance map (for performance boost if key was already calculated externally). */ - public static function addInstanceToPool(CcMusicDirs $obj, $key = null) + public static function addInstanceToPool(CcWebstream $obj, $key = null) { if (Propel::isInstancePoolingEnabled()) { if ($key === null) { - $key = (string) $obj->getId(); + $key = (string) $obj->getDbId(); } // if key === null self::$instances[$key] = $obj; } @@ -293,18 +328,18 @@ abstract class BaseCcMusicDirsPeer { * 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 CcMusicDirs object or a primary key value. + * @param mixed $value A CcWebstream object or a primary key value. */ public static function removeInstanceFromPool($value) { if (Propel::isInstancePoolingEnabled() && $value !== null) { - if (is_object($value) && $value instanceof CcMusicDirs) { - $key = (string) $value->getId(); + if (is_object($value) && $value instanceof CcWebstream) { + $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 CcMusicDirs object; got " . (is_object($value) ? get_class($value) . ' object.' : var_export($value,true))); + $e = new PropelException("Invalid value passed to removeInstanceFromPool(). Expected primary key or CcWebstream object; got " . (is_object($value) ? get_class($value) . ' object.' : var_export($value,true))); throw $e; } @@ -319,7 +354,7 @@ abstract class BaseCcMusicDirsPeer { * 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 CcMusicDirs Found object or NULL if 1) no instance exists for specified key or 2) instance pooling has been disabled. + * @return CcWebstream 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) @@ -343,14 +378,14 @@ abstract class BaseCcMusicDirsPeer { } /** - * Method to invalidate the instance pool of all tables related to cc_music_dirs + * Method to invalidate the instance pool of all tables related to cc_webstream * by a foreign key with ON DELETE CASCADE */ public static function clearRelatedInstancePool() { - // Invalidate objects in CcFilesPeer instance pool, + // Invalidate objects in CcSchedulePeer instance pool, // since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule. - CcFilesPeer::clearInstancePool(); + CcSchedulePeer::clearInstancePool(); } /** @@ -398,11 +433,11 @@ abstract class BaseCcMusicDirsPeer { $results = array(); // set the class once to avoid overhead in the loop - $cls = CcMusicDirsPeer::getOMClass(false); + $cls = CcWebstreamPeer::getOMClass(false); // populate the object(s) while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $key = CcMusicDirsPeer::getPrimaryKeyHashFromRow($row, 0); - if (null !== ($obj = CcMusicDirsPeer::getInstanceFromPool($key))) { + $key = CcWebstreamPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj = CcWebstreamPeer::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 @@ -411,7 +446,7 @@ abstract class BaseCcMusicDirsPeer { $obj = new $cls(); $obj->hydrate($row); $results[] = $obj; - CcMusicDirsPeer::addInstanceToPool($obj, $key); + CcWebstreamPeer::addInstanceToPool($obj, $key); } // if key exists } $stmt->closeCursor(); @@ -424,21 +459,21 @@ abstract class BaseCcMusicDirsPeer { * @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 (CcMusicDirs object, last column rank) + * @return array (CcWebstream object, last column rank) */ public static function populateObject($row, $startcol = 0) { - $key = CcMusicDirsPeer::getPrimaryKeyHashFromRow($row, $startcol); - if (null !== ($obj = CcMusicDirsPeer::getInstanceFromPool($key))) { + $key = CcWebstreamPeer::getPrimaryKeyHashFromRow($row, $startcol); + if (null !== ($obj = CcWebstreamPeer::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 + CcMusicDirsPeer::NUM_COLUMNS; + $col = $startcol + CcWebstreamPeer::NUM_COLUMNS; } else { - $cls = CcMusicDirsPeer::OM_CLASS; + $cls = CcWebstreamPeer::OM_CLASS; $obj = new $cls(); $col = $obj->hydrate($row, $startcol); - CcMusicDirsPeer::addInstanceToPool($obj, $key); + CcWebstreamPeer::addInstanceToPool($obj, $key); } return array($obj, $col); } @@ -459,10 +494,10 @@ abstract class BaseCcMusicDirsPeer { */ public static function buildTableMap() { - $dbMap = Propel::getDatabaseMap(BaseCcMusicDirsPeer::DATABASE_NAME); - if (!$dbMap->hasTable(BaseCcMusicDirsPeer::TABLE_NAME)) + $dbMap = Propel::getDatabaseMap(BaseCcWebstreamPeer::DATABASE_NAME); + if (!$dbMap->hasTable(BaseCcWebstreamPeer::TABLE_NAME)) { - $dbMap->addTableObject(new CcMusicDirsTableMap()); + $dbMap->addTableObject(new CcWebstreamTableMap()); } } @@ -479,13 +514,13 @@ abstract class BaseCcMusicDirsPeer { */ public static function getOMClass($withPrefix = true) { - return $withPrefix ? CcMusicDirsPeer::CLASS_DEFAULT : CcMusicDirsPeer::OM_CLASS; + return $withPrefix ? CcWebstreamPeer::CLASS_DEFAULT : CcWebstreamPeer::OM_CLASS; } /** - * Method perform an INSERT on the database, given a CcMusicDirs or Criteria object. + * Method perform an INSERT on the database, given a CcWebstream or Criteria object. * - * @param mixed $values Criteria or CcMusicDirs object containing data that is used to create the INSERT statement. + * @param mixed $values Criteria or CcWebstream 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 @@ -494,17 +529,17 @@ abstract class BaseCcMusicDirsPeer { public static function doInsert($values, PropelPDO $con = null) { if ($con === null) { - $con = Propel::getConnection(CcMusicDirsPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + $con = Propel::getConnection(CcWebstreamPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); } if ($values instanceof Criteria) { $criteria = clone $values; // rename for clarity } else { - $criteria = $values->buildCriteria(); // build Criteria from CcMusicDirs object + $criteria = $values->buildCriteria(); // build Criteria from CcWebstream object } - if ($criteria->containsKey(CcMusicDirsPeer::ID) && $criteria->keyContainsValue(CcMusicDirsPeer::ID) ) { - throw new PropelException('Cannot insert a value for auto-increment primary key ('.CcMusicDirsPeer::ID.')'); + if ($criteria->containsKey(CcWebstreamPeer::ID) && $criteria->keyContainsValue(CcWebstreamPeer::ID) ) { + throw new PropelException('Cannot insert a value for auto-increment primary key ('.CcWebstreamPeer::ID.')'); } @@ -526,9 +561,9 @@ abstract class BaseCcMusicDirsPeer { } /** - * Method perform an UPDATE on the database, given a CcMusicDirs or Criteria object. + * Method perform an UPDATE on the database, given a CcWebstream or Criteria object. * - * @param mixed $values Criteria or CcMusicDirs object containing data that is used to create the UPDATE statement. + * @param mixed $values Criteria or CcWebstream 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 @@ -537,7 +572,7 @@ abstract class BaseCcMusicDirsPeer { public static function doUpdate($values, PropelPDO $con = null) { if ($con === null) { - $con = Propel::getConnection(CcMusicDirsPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + $con = Propel::getConnection(CcWebstreamPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); } $selectCriteria = new Criteria(self::DATABASE_NAME); @@ -545,15 +580,15 @@ abstract class BaseCcMusicDirsPeer { if ($values instanceof Criteria) { $criteria = clone $values; // rename for clarity - $comparison = $criteria->getComparison(CcMusicDirsPeer::ID); - $value = $criteria->remove(CcMusicDirsPeer::ID); + $comparison = $criteria->getComparison(CcWebstreamPeer::ID); + $value = $criteria->remove(CcWebstreamPeer::ID); if ($value) { - $selectCriteria->add(CcMusicDirsPeer::ID, $value, $comparison); + $selectCriteria->add(CcWebstreamPeer::ID, $value, $comparison); } else { - $selectCriteria->setPrimaryTableName(CcMusicDirsPeer::TABLE_NAME); + $selectCriteria->setPrimaryTableName(CcWebstreamPeer::TABLE_NAME); } - } else { // $values is CcMusicDirs object + } else { // $values is CcWebstream object $criteria = $values->buildCriteria(); // gets full criteria $selectCriteria = $values->buildPkeyCriteria(); // gets criteria w/ primary key(s) } @@ -565,26 +600,26 @@ abstract class BaseCcMusicDirsPeer { } /** - * Method to DELETE all rows from the cc_music_dirs table. + * Method to DELETE all rows from the cc_webstream 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(CcMusicDirsPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + $con = Propel::getConnection(CcWebstreamPeer::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(CcMusicDirsPeer::TABLE_NAME, $con, CcMusicDirsPeer::DATABASE_NAME); + $affectedRows += BasePeer::doDeleteAll(CcWebstreamPeer::TABLE_NAME, $con, CcWebstreamPeer::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). - CcMusicDirsPeer::clearInstancePool(); - CcMusicDirsPeer::clearRelatedInstancePool(); + CcWebstreamPeer::clearInstancePool(); + CcWebstreamPeer::clearRelatedInstancePool(); $con->commit(); return $affectedRows; } catch (PropelException $e) { @@ -594,9 +629,9 @@ abstract class BaseCcMusicDirsPeer { } /** - * Method perform a DELETE on the database, given a CcMusicDirs or Criteria object OR a primary key value. + * Method perform a DELETE on the database, given a CcWebstream or Criteria object OR a primary key value. * - * @param mixed $values Criteria or CcMusicDirs object or primary key or array of primary keys + * @param mixed $values Criteria or CcWebstream 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 @@ -607,27 +642,27 @@ abstract class BaseCcMusicDirsPeer { public static function doDelete($values, PropelPDO $con = null) { if ($con === null) { - $con = Propel::getConnection(CcMusicDirsPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + $con = Propel::getConnection(CcWebstreamPeer::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. - CcMusicDirsPeer::clearInstancePool(); + CcWebstreamPeer::clearInstancePool(); // rename for clarity $criteria = clone $values; - } elseif ($values instanceof CcMusicDirs) { // it's a model object + } elseif ($values instanceof CcWebstream) { // it's a model object // invalidate the cache for this single object - CcMusicDirsPeer::removeInstanceFromPool($values); + CcWebstreamPeer::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(CcMusicDirsPeer::ID, (array) $values, Criteria::IN); + $criteria->add(CcWebstreamPeer::ID, (array) $values, Criteria::IN); // invalidate the cache for this object(s) foreach ((array) $values as $singleval) { - CcMusicDirsPeer::removeInstanceFromPool($singleval); + CcWebstreamPeer::removeInstanceFromPool($singleval); } } @@ -642,7 +677,7 @@ abstract class BaseCcMusicDirsPeer { $con->beginTransaction(); $affectedRows += BasePeer::doDelete($criteria, $con); - CcMusicDirsPeer::clearRelatedInstancePool(); + CcWebstreamPeer::clearRelatedInstancePool(); $con->commit(); return $affectedRows; } catch (PropelException $e) { @@ -652,24 +687,24 @@ abstract class BaseCcMusicDirsPeer { } /** - * Validates all modified columns of given CcMusicDirs object. + * Validates all modified columns of given CcWebstream 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 CcMusicDirs $obj The object to validate. + * @param CcWebstream $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(CcMusicDirs $obj, $cols = null) + public static function doValidate(CcWebstream $obj, $cols = null) { $columns = array(); if ($cols) { - $dbMap = Propel::getDatabaseMap(CcMusicDirsPeer::DATABASE_NAME); - $tableMap = $dbMap->getTable(CcMusicDirsPeer::TABLE_NAME); + $dbMap = Propel::getDatabaseMap(CcWebstreamPeer::DATABASE_NAME); + $tableMap = $dbMap->getTable(CcWebstreamPeer::TABLE_NAME); if (! is_array($cols)) { $cols = array($cols); @@ -685,7 +720,7 @@ abstract class BaseCcMusicDirsPeer { } - return BasePeer::doValidate(CcMusicDirsPeer::DATABASE_NAME, CcMusicDirsPeer::TABLE_NAME, $columns); + return BasePeer::doValidate(CcWebstreamPeer::DATABASE_NAME, CcWebstreamPeer::TABLE_NAME, $columns); } /** @@ -693,23 +728,23 @@ abstract class BaseCcMusicDirsPeer { * * @param int $pk the primary key. * @param PropelPDO $con the connection to use - * @return CcMusicDirs + * @return CcWebstream */ public static function retrieveByPK($pk, PropelPDO $con = null) { - if (null !== ($obj = CcMusicDirsPeer::getInstanceFromPool((string) $pk))) { + if (null !== ($obj = CcWebstreamPeer::getInstanceFromPool((string) $pk))) { return $obj; } if ($con === null) { - $con = Propel::getConnection(CcMusicDirsPeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcWebstreamPeer::DATABASE_NAME, Propel::CONNECTION_READ); } - $criteria = new Criteria(CcMusicDirsPeer::DATABASE_NAME); - $criteria->add(CcMusicDirsPeer::ID, $pk); + $criteria = new Criteria(CcWebstreamPeer::DATABASE_NAME); + $criteria->add(CcWebstreamPeer::ID, $pk); - $v = CcMusicDirsPeer::doSelect($criteria, $con); + $v = CcWebstreamPeer::doSelect($criteria, $con); return !empty($v) > 0 ? $v[0] : null; } @@ -725,23 +760,23 @@ abstract class BaseCcMusicDirsPeer { public static function retrieveByPKs($pks, PropelPDO $con = null) { if ($con === null) { - $con = Propel::getConnection(CcMusicDirsPeer::DATABASE_NAME, Propel::CONNECTION_READ); + $con = Propel::getConnection(CcWebstreamPeer::DATABASE_NAME, Propel::CONNECTION_READ); } $objs = null; if (empty($pks)) { $objs = array(); } else { - $criteria = new Criteria(CcMusicDirsPeer::DATABASE_NAME); - $criteria->add(CcMusicDirsPeer::ID, $pks, Criteria::IN); - $objs = CcMusicDirsPeer::doSelect($criteria, $con); + $criteria = new Criteria(CcWebstreamPeer::DATABASE_NAME); + $criteria->add(CcWebstreamPeer::ID, $pks, Criteria::IN); + $objs = CcWebstreamPeer::doSelect($criteria, $con); } return $objs; } -} // BaseCcMusicDirsPeer +} // BaseCcWebstreamPeer // This is the static code needed to register the TableMap for this table with the main Propel class. // -BaseCcMusicDirsPeer::buildTableMap(); +BaseCcWebstreamPeer::buildTableMap(); diff --git a/airtime_mvc/application/models/airtime/om/BaseCcWebstreamQuery.php b/airtime_mvc/application/models/airtime/om/BaseCcWebstreamQuery.php new file mode 100644 index 000000000..6f5becfb6 --- /dev/null +++ b/airtime_mvc/application/models/airtime/om/BaseCcWebstreamQuery.php @@ -0,0 +1,503 @@ +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 CcWebstream|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ((null !== ($obj = CcWebstreamPeer::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 CcWebstreamQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + return $this->addUsingAlias(CcWebstreamPeer::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 CcWebstreamQuery The current query, for fluid interface + */ + public function filterByPrimaryKeys($keys) + { + return $this->addUsingAlias(CcWebstreamPeer::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 CcWebstreamQuery 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(CcWebstreamPeer::ID, $dbId, $comparison); + } + + /** + * Filter the query on the name column + * + * @param string $dbName 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 CcWebstreamQuery The current query, for fluid interface + */ + public function filterByDbName($dbName = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($dbName)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $dbName)) { + $dbName = str_replace('*', '%', $dbName); + $comparison = Criteria::LIKE; + } + } + return $this->addUsingAlias(CcWebstreamPeer::NAME, $dbName, $comparison); + } + + /** + * Filter the query on the description column + * + * @param string $dbDescription 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 CcWebstreamQuery The current query, for fluid interface + */ + public function filterByDbDescription($dbDescription = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($dbDescription)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $dbDescription)) { + $dbDescription = str_replace('*', '%', $dbDescription); + $comparison = Criteria::LIKE; + } + } + return $this->addUsingAlias(CcWebstreamPeer::DESCRIPTION, $dbDescription, $comparison); + } + + /** + * Filter the query on the url column + * + * @param string $dbUrl 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 CcWebstreamQuery The current query, for fluid interface + */ + public function filterByDbUrl($dbUrl = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($dbUrl)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $dbUrl)) { + $dbUrl = str_replace('*', '%', $dbUrl); + $comparison = Criteria::LIKE; + } + } + return $this->addUsingAlias(CcWebstreamPeer::URL, $dbUrl, $comparison); + } + + /** + * Filter the query on the length column + * + * @param string $dbLength 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 CcWebstreamQuery The current query, for fluid interface + */ + public function filterByDbLength($dbLength = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($dbLength)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $dbLength)) { + $dbLength = str_replace('*', '%', $dbLength); + $comparison = Criteria::LIKE; + } + } + return $this->addUsingAlias(CcWebstreamPeer::LENGTH, $dbLength, $comparison); + } + + /** + * Filter the query on the creator_id column + * + * @param int|array $dbCreatorId 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 CcWebstreamQuery The current query, for fluid interface + */ + public function filterByDbCreatorId($dbCreatorId = null, $comparison = null) + { + if (is_array($dbCreatorId)) { + $useMinMax = false; + if (isset($dbCreatorId['min'])) { + $this->addUsingAlias(CcWebstreamPeer::CREATOR_ID, $dbCreatorId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbCreatorId['max'])) { + $this->addUsingAlias(CcWebstreamPeer::CREATOR_ID, $dbCreatorId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcWebstreamPeer::CREATOR_ID, $dbCreatorId, $comparison); + } + + /** + * Filter the query on the mtime column + * + * @param string|array $dbMtime 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 CcWebstreamQuery The current query, for fluid interface + */ + public function filterByDbMtime($dbMtime = null, $comparison = null) + { + if (is_array($dbMtime)) { + $useMinMax = false; + if (isset($dbMtime['min'])) { + $this->addUsingAlias(CcWebstreamPeer::MTIME, $dbMtime['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbMtime['max'])) { + $this->addUsingAlias(CcWebstreamPeer::MTIME, $dbMtime['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcWebstreamPeer::MTIME, $dbMtime, $comparison); + } + + /** + * Filter the query on the utime column + * + * @param string|array $dbUtime 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 CcWebstreamQuery The current query, for fluid interface + */ + public function filterByDbUtime($dbUtime = null, $comparison = null) + { + if (is_array($dbUtime)) { + $useMinMax = false; + if (isset($dbUtime['min'])) { + $this->addUsingAlias(CcWebstreamPeer::UTIME, $dbUtime['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbUtime['max'])) { + $this->addUsingAlias(CcWebstreamPeer::UTIME, $dbUtime['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcWebstreamPeer::UTIME, $dbUtime, $comparison); + } + + /** + * Filter the query on the lptime column + * + * @param string|array $dbLPtime 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 CcWebstreamQuery The current query, for fluid interface + */ + public function filterByDbLPtime($dbLPtime = null, $comparison = null) + { + if (is_array($dbLPtime)) { + $useMinMax = false; + if (isset($dbLPtime['min'])) { + $this->addUsingAlias(CcWebstreamPeer::LPTIME, $dbLPtime['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbLPtime['max'])) { + $this->addUsingAlias(CcWebstreamPeer::LPTIME, $dbLPtime['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcWebstreamPeer::LPTIME, $dbLPtime, $comparison); + } + + /** + * Filter the query on the mime column + * + * @param string $dbMime 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 CcWebstreamQuery The current query, for fluid interface + */ + public function filterByDbMime($dbMime = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($dbMime)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $dbMime)) { + $dbMime = str_replace('*', '%', $dbMime); + $comparison = Criteria::LIKE; + } + } + return $this->addUsingAlias(CcWebstreamPeer::MIME, $dbMime, $comparison); + } + + /** + * Filter the query by a related CcSchedule object + * + * @param CcSchedule $ccSchedule 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 filterByCcSchedule($ccSchedule, $comparison = null) + { + return $this + ->addUsingAlias(CcWebstreamPeer::ID, $ccSchedule->getDbStreamId(), $comparison); + } + + /** + * Adds a JOIN clause to the query using the CcSchedule 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 joinCcSchedule($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('CcSchedule'); + + // 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, 'CcSchedule'); + } + + return $this; + } + + /** + * Use the CcSchedule relation CcSchedule 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 CcScheduleQuery A secondary query class using the current class as primary query + */ + public function useCcScheduleQuery($relationAlias = '', $joinType = Criteria::LEFT_JOIN) + { + return $this + ->joinCcSchedule($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'CcSchedule', 'CcScheduleQuery'); + } + + /** + * Exclude object from result + * + * @param CcWebstream $ccWebstream Object to remove from the list of results + * + * @return CcWebstreamQuery The current query, for fluid interface + */ + public function prune($ccWebstream = null) + { + if ($ccWebstream) { + $this->addUsingAlias(CcWebstreamPeer::ID, $ccWebstream->getDbId(), Criteria::NOT_EQUAL); + } + + return $this; + } + +} // BaseCcWebstreamQuery diff --git a/airtime_mvc/application/models/formatters/BitrateFormatter.php b/airtime_mvc/application/models/formatters/BitrateFormatter.php index 00828a672..f1455ca74 100644 --- a/airtime_mvc/application/models/formatters/BitrateFormatter.php +++ b/airtime_mvc/application/models/formatters/BitrateFormatter.php @@ -1,7 +1,7 @@ _bitrate, 1000, 0); + $kbps = bcdiv($this->_bitrate, 1000, 0); - return "{$Kbps} Kbps"; + if ($kbps == 0) { + return ""; + } else { + return "$kbps Kbps"; + } } -} \ No newline at end of file +} diff --git a/airtime_mvc/application/models/formatters/LengthFormatter.php b/airtime_mvc/application/models/formatters/LengthFormatter.php index 4551e4680..140d69b1c 100644 --- a/airtime_mvc/application/models/formatters/LengthFormatter.php +++ b/airtime_mvc/application/models/formatters/LengthFormatter.php @@ -1,7 +1,7 @@ _length = $length; } - public function format() { + public function format() + { + if (!preg_match("/^[0-9]{2}:[0-9]{2}:[0-9]{2}/", $this->_length)) { + return $this->_length; + } $pieces = explode(":", $this->_length); @@ -42,15 +46,13 @@ class LengthFormatter { if (isset($hours) && isset($minutes) && isset($seconds)) { $time = sprintf("%d:%02d:%02d.%s", $hours, $minutes, $seconds, $milliStr); - } - else if (isset($minutes) && isset($seconds)) { + } elseif (isset($minutes) && isset($seconds)) { $time = sprintf("%d:%02d.%s", $minutes, $seconds, $milliStr); - } - else { + } else { $time = sprintf("%d.%s", $seconds, $milliStr); } return $time; } -} \ No newline at end of file +} diff --git a/airtime_mvc/application/models/formatters/SamplerateFormatter.php b/airtime_mvc/application/models/formatters/SamplerateFormatter.php index aeabe8c2f..f3c436f30 100644 --- a/airtime_mvc/application/models/formatters/SamplerateFormatter.php +++ b/airtime_mvc/application/models/formatters/SamplerateFormatter.php @@ -1,7 +1,7 @@ _seconds < 0) ? "-" : "+"; $perfect = true; - $time = Application_Model_Playlist::secondsToPlaylistTime(abs($this->_seconds)); + $time = Application_Common_DateHelper::secondsToPlaylistTime(abs($this->_seconds)); $info = explode(":", $time); $formatted .= $sign; @@ -51,4 +51,4 @@ class TimeFilledFormatter { return $formatted; } -} \ No newline at end of file +} diff --git a/airtime_mvc/application/models/tests/SchedulerTests.php b/airtime_mvc/application/models/tests/SchedulerTests.php index 40235e786..0122ee981 100644 --- a/airtime_mvc/application/models/tests/SchedulerTests.php +++ b/airtime_mvc/application/models/tests/SchedulerTests.php @@ -104,7 +104,7 @@ class SchedulerTests extends PHPUnit_TestCase { $groupId1 = $i1->add('2008-01-01 12:00:00.000', $this->storedFile->getId()); $i2 = new Application_Model_ScheduleGroup(); $i2->addAfter($groupId1, $this->storedFile->getId()); - $items = Application_Model_Schedule::GetItems("2008-01-01", "2008-01-02"); + $items = Application_Model_Schedule::getItems("2008-01-01", "2008-01-02"); if (count($items) != 2) { $this->fail("Wrong number of items returned."); return; diff --git a/airtime_mvc/application/models/tests/StoredFileTests.php b/airtime_mvc/application/models/tests/StoredFileTests.php index 851c62741..a41163bda 100644 --- a/airtime_mvc/application/models/tests/StoredFileTests.php +++ b/airtime_mvc/application/models/tests/StoredFileTests.php @@ -17,8 +17,8 @@ class StoredFileTest extends PHPUnit_TestCase { || ($metadata["audio"]["dataformat"] != "mp3") || ($metadata["dc:type"] != "Speech")) { $str = " [dc:description] = " . $metadata["dc:description"] ."\n" - . " [audio][dataformat] = " . $metadata["audio"]["dataformat"]."\n" - . " [dc:type] = ".$metadata["dc:type"]."\n"; + . " [audio][dataformat] = " . $metadata["audio"]["dataformat"]."\n" + . " [dc:type] = ".$metadata["dc:type"]."\n"; $this->fail("Metadata has unexpected values:\n".$str); } //var_dump($metadata); diff --git a/airtime_mvc/application/models/tests/populator.php b/airtime_mvc/application/models/tests/populator.php index 1ad1b2806..3b85d76bb 100644 --- a/airtime_mvc/application/models/tests/populator.php +++ b/airtime_mvc/application/models/tests/populator.php @@ -99,7 +99,7 @@ while ($showTime < $endDate) { } if (Application_Model_RabbitMq::$doPush) { - $md = array('schedule' => Application_Model_Schedule::GetScheduledPlaylists()); + $md = array('schedule' => Application_Model_Schedule::getSchedule()); Application_Model_RabbitMq::SendMessageToPypo("update_schedule", $md); } diff --git a/airtime_mvc/application/views/scripts/audiopreview/audio-preview.phtml b/airtime_mvc/application/views/scripts/audiopreview/audio-preview.phtml index d5d1b2dc4..f76249b9f 100644 --- a/airtime_mvc/application/views/scripts/audiopreview/audio-preview.phtml +++ b/airtime_mvc/application/views/scripts/audiopreview/audio-preview.phtml @@ -3,8 +3,12 @@ playlistID)): ?> playlistID" ?> playlistIndex" ?> -audioFileID)): ?> - audioFileID" ?> +blockId)): ?> + + +uri)): ?> + + audioFileTitle" ?> audioFileArtist" ?> showID)): ?> @@ -38,7 +42,7 @@ + diff --git a/airtime_mvc/application/views/scripts/dashboard/help.phtml b/airtime_mvc/application/views/scripts/dashboard/help.phtml index e6a4c4824..0ac5f80dc 100644 --- a/airtime_mvc/application/views/scripts/dashboard/help.phtml +++ b/airtime_mvc/application/views/scripts/dashboard/help.phtml @@ -4,7 +4,7 @@

Here's how you can get started using Airtime to automate your broadcasts:

    -
  1. Add your files to the library using the "Add Media" button. You can drag and drop your files to this window too.
  2. +
  3. Begin by adding your files to the library using the "Add Media" menu button. You can drag and drop your files to this window too.
  4. Create a show by going to "Calendar" in the menu bar, and then clicking the "+ Show" icon. This can be either a one-time or repeating show. Only admins and program managers can add shows.
  5. Add media to the show by going to your show in the Schedule calendar, left-clicking on it and selecting "Add / Remove Content".
  6. Select your media from the left pane and drag them to your show in the right pane.
  7. diff --git a/airtime_mvc/application/views/scripts/form/password-restore.phtml b/airtime_mvc/application/views/scripts/form/password-restore.phtml index a617ec971..a43b9fe36 100644 --- a/airtime_mvc/application/views/scripts/form/password-restore.phtml +++ b/airtime_mvc/application/views/scripts/form/password-restore.phtml @@ -1,11 +1,20 @@
    -
    +
    + element->getElement('username') ?> +
    + +
    + +
    +
    element->getElement('email') ?>
    element->getElement('email')->hasErrors()): ?> @@ -15,7 +24,6 @@ -
     
    diff --git a/airtime_mvc/application/views/scripts/form/preferences_email_server.phtml b/airtime_mvc/application/views/scripts/form/preferences_email_server.phtml index 555cbdded..9aba8a052 100644 --- a/airtime_mvc/application/views/scripts/form/preferences_email_server.phtml +++ b/airtime_mvc/application/views/scripts/form/preferences_email_server.phtml @@ -44,7 +44,13 @@ + + +
    element->getElement('mailServer') ?> element->getElement('mailServer')->hasErrors()) : ?> @@ -56,6 +62,14 @@
    +
    + +
    +
    + element->getElement('port') ?> +
    +
    - -
    -
    - element->getElement('port') ?> -
    -
    diff --git a/airtime_mvc/application/views/scripts/form/preferences_livestream.phtml b/airtime_mvc/application/views/scripts/form/preferences_livestream.phtml index 00221bf4e..e2dd5d7dc 100644 --- a/airtime_mvc/application/views/scripts/form/preferences_livestream.phtml +++ b/airtime_mvc/application/views/scripts/form/preferences_livestream.phtml @@ -49,7 +49,7 @@
    diff --git a/airtime_mvc/application/views/scripts/form/preferences_watched_dirs.phtml b/airtime_mvc/application/views/scripts/form/preferences_watched_dirs.phtml index 21cb6b0a4..93210b570 100644 --- a/airtime_mvc/application/views/scripts/form/preferences_watched_dirs.phtml +++ b/airtime_mvc/application/views/scripts/form/preferences_watched_dirs.phtml @@ -39,7 +39,7 @@ 0): ?>
    - getExistsFlag())?"":""?>getDirectory();?> + getExistsFlag())?"":""?>getDirectory();?> diff --git a/airtime_mvc/application/views/scripts/form/showbuilder.phtml b/airtime_mvc/application/views/scripts/form/showbuilder.phtml index ddca06770..a0193b664 100644 --- a/airtime_mvc/application/views/scripts/form/showbuilder.phtml +++ b/airtime_mvc/application/views/scripts/form/showbuilder.phtml @@ -2,9 +2,9 @@ element->getElement('sb_time_start'); ?> element->getElement('sb_date_end'); ?> element->getElement('sb_time_end'); ?> -
    - -
    + + + Find Shows
    @@ -22,4 +22,4 @@
    - \ No newline at end of file + diff --git a/airtime_mvc/application/views/scripts/form/smart-block-criteria.phtml b/airtime_mvc/application/views/scripts/form/smart-block-criteria.phtml new file mode 100644 index 000000000..0f27248ca --- /dev/null +++ b/airtime_mvc/application/views/scripts/form/smart-block-criteria.phtml @@ -0,0 +1,108 @@ + +
    +Smart Block Options + +
    +
    +
    + element->getElement('generate_button') ?> +
    +
    + element->getElement('shuffle_button') ?> +
    +
    + +
    + + element->getElement('sp_type')->getValue(); + foreach ($this->element->getElement('sp_type')->getMultiOptions() as $radio) : ?> + + + + +
    + +
    + criteriasLength; $i++) {?> + modRowMap[$i]; $j++) {?> +
    0) && ($this->element->getElement("sp_criteria_field_".$i."_".$j)->getAttrib('disabled') == 'disabled')) { + echo 'style=display:none'; + } ?>> + element->getElement("sp_criteria_field_".$i."_".$j) ?> + + + + element->getElement("sp_criteria_modifier_".$i."_".$j) ?> + element->getElement("sp_criteria_value_".$i."_".$j) ?> + element->getElement("sp_criteria_extra_".$i."_".$j)->getAttrib("disabled") == "disabled"?'style="display:none;"':""?>> to element->getElement('sp_criteria_extra_'.$i."_".$j) ?> + + + + + element->getElement("sp_criteria_field_".$i."_".$j)->hasErrors()) : ?> + element->getElement("sp_criteria_field_".$i."_".$j)->getMessages() as $error): ?> + + + + + +
    + + + +
    +
    + +
    + element->getElement('sp_limit_value')->getLabel() ?> + element->getElement('sp_limit_value')?> + element->getElement('sp_limit_options') ?> + element->getElement("sp_limit_value")->hasErrors()) : ?> + element->getElement("sp_limit_value")->getMessages() as $error): ?> + + + + + +
    +
    + + showPoolCount) { ?> +
    + + poolCount > 1) { + echo $this->poolCount; + ?> + files meet the criteria + + + poolCount == 1) { + echo $this->poolCount; + ?> + file meets the criteria + + + + 0 files meet the criteria + + + +
    + + +
    + +
    +
    diff --git a/airtime_mvc/application/views/scripts/form/stream-setting-form.phtml b/airtime_mvc/application/views/scripts/form/stream-setting-form.phtml index 0f746d4c3..088fc7aa2 100644 --- a/airtime_mvc/application/views/scripts/form/stream-setting-form.phtml +++ b/airtime_mvc/application/views/scripts/form/stream-setting-form.phtml @@ -1,7 +1,7 @@ stream_number; ?> -

    ">Stream stream_number?>

    +

    ">Stream stream_number?>

    enabled == 0?'style="display: none;':''?> id="-config">
    @@ -60,7 +60,14 @@
    element->getElement('output')?>
    - + +
    + +
    +
    + element->getElement('channels')?> +
    +
    diff --git a/airtime_mvc/application/views/scripts/form/support-setting.phtml b/airtime_mvc/application/views/scripts/form/support-setting.phtml index 46b93bb6c..f35a6eab1 100644 --- a/airtime_mvc/application/views/scripts/form/support-setting.phtml +++ b/airtime_mvc/application/views/scripts/form/support-setting.phtml @@ -3,9 +3,9 @@
    - Help Airtime improve by letting us know how you are using it. This info - will be collected regularly in order to enhance your user experience.

    - Click "Yes, help Airtime" and we'll make sure the features you use are + Help Airtime improve by letting Sourcefabric know how you are using it. This information + will be collected regularly in order to enhance your user experience.
    + Click the "Send support feedback" box and we'll make sure the features you use are constantly improving.
    -
    Click the box below to advertise your station on - Sourcefabric.org. - In order to promote your station, "Send support feedback" must be enabled. This data will be collected in addition to the support feedback.
    +
    Click the box below to promote your station on + Sourcefabric.org. +
    -

    Note: In order to promote your station, "Send support feedback" must be enabled

    +
    (In order to promote your station, "Send support feedback" must be enabled).

    ;">
    @@ -179,7 +179,7 @@ - Terms and Conditions + Sourcefabric Privacy Policy
    diff --git a/airtime_mvc/application/views/scripts/library/get-file-meta-data.ajax.phtml b/airtime_mvc/application/views/scripts/library/get-file-meta-data.ajax.phtml deleted file mode 100644 index 45bf68c0c..000000000 --- a/airtime_mvc/application/views/scripts/library/get-file-meta-data.ajax.phtml +++ /dev/null @@ -1,39 +0,0 @@ -type == "audioclip") : ?> -
    Title:md["MDATA_KEY_TITLE"]);?>
    -
    Creator:md["MDATA_KEY_CREATOR"]);?>
    -
    Album:md["MDATA_KEY_SOURCE"]);?>
    -
    Track:md["MDATA_KEY_TRACKNUMBER"]);?>
    -
    Length:md["MDATA_KEY_DURATION"]);?>
    -
    Sample Rate:md["MDATA_KEY_SAMPLERATE"]);?>
    -
    Bit Rate:md["MDATA_KEY_BITRATE"]);?>
    -
    Mood:md["MDATA_KEY_MOOD"]);?>
    -
    Genre:md["MDATA_KEY_GENRE"]);?>
    -
    Year:md["MDATA_KEY_YEAR"]);?>
    -
    Label:md["MDATA_KEY_LABEL"]);?>
    -
    BPM:md["MDATA_KEY_BPM"]);?>
    -
    Composer:md["MDATA_KEY_COMPOSER"]);?>
    -
    Conductor:md["MDATA_KEY_CONDUCTOR"]);?>
    -
    Copyright:md["MDATA_KEY_COPYRIGHT"]);?>
    -
    Isrc Number:md["MDATA_KEY_ISRC"]);?>
    -
    Website:md["MDATA_KEY_URL"]);?>
    -
    Language:md["MDATA_KEY_LANGUAGE"]);?>
    -
    File Path:md["MDATA_KEY_FILEPATH"]);?>
    - - - -type == "playlist") : ?> -
    Name:md["dc:title"]);?>
    -
    Creator:md["dc:creator"]);?>
    -
    Length:md["dcterms:extent"]);?>
    -
    Description:md["dc:description"]);?>
    -
    Contents: - contents as $row) : ?> -
    - - - - -
    - -
    - diff --git a/airtime_mvc/application/views/scripts/library/get-file-metadata.ajax.phtml b/airtime_mvc/application/views/scripts/library/get-file-metadata.ajax.phtml new file mode 100644 index 000000000..ad65f2417 --- /dev/null +++ b/airtime_mvc/application/views/scripts/library/get-file-metadata.ajax.phtml @@ -0,0 +1,134 @@ +type == "audioclip") : ?> + + + + + + + + + + + + + + + + + + + + +
    Title:md["MDATA_KEY_TITLE"]);?>
    Creator:md["MDATA_KEY_CREATOR"]);?>
    Album:md["MDATA_KEY_SOURCE"]);?>
    Track:md["MDATA_KEY_TRACKNUMBER"]);?>
    Length:md["MDATA_KEY_DURATION"]);?>
    Sample Rate:md["MDATA_KEY_SAMPLERATE"]);?>
    Bit Rate:md["MDATA_KEY_BITRATE"]);?>
    Mood:md["MDATA_KEY_MOOD"]);?>
    Genre:md["MDATA_KEY_GENRE"]);?>
    Year:md["MDATA_KEY_YEAR"]);?>
    Label:md["MDATA_KEY_LABEL"]);?>
    BPM:md["MDATA_KEY_BPM"]);?>
    Composer:md["MDATA_KEY_COMPOSER"]);?>
    Conductor:md["MDATA_KEY_CONDUCTOR"]);?>
    Copyright:md["MDATA_KEY_COPYRIGHT"]);?>
    Isrc Number:md["MDATA_KEY_ISRC"]);?>
    Website:md["MDATA_KEY_URL"]);?>
    Language:md["MDATA_KEY_LANGUAGE"]);?>
    File Path:md["MDATA_KEY_FILEPATH"]);?>
    + + +type == "playlist" || $this->type == "block") : ?> +
    + Name:md["dc:title"]);?>
    + Creator:md["dc:creator"]);?>
    + type == "block" && $this->blType == "Dynamic") { ?> + Length:block->getLength();?>
    + + Length:md["dcterms:extent"]);?>
    + + Description:md["dc:description"]);?> +
    + +type == "playlist") { ?> +
    +o Web Stream
    +o Dynamic Smart Block
    +o Static Smart Block
    +o Audio Track +
    + + + type == "playlist" || ($this->type == "block" && $this->blType == "Static")) {?> + type == "playlist") { ?> +
    Playlist Contents:
    + +
    Static Smart Block Contents:
    + + + contents as $row) : ?> + $titleMaxStrLen) { + $row["track_title"] = mb_substr($row["track_title"], 0, 34, 'UTF-8')."..."; + } + $artistMaxStrLen = 22; + if (mb_strlen($row["creator"], 'UTF-8') > $artistMaxStrLen) { + $row["creator"] = mb_substr($row["creator"], 0, 21, 'UTF-8')."..."; + } + ?> + isStatic(); ?> + '> + + + + + + + + + + + + + + + + + + +
    getLength(); ?>
    + + blType == "Dynamic") { ?> +
    Dynamic Smart Block Criteria:
    + + contents["crit"] as $criterias) : ?> + + $valMaxStrLen) { + $crit["value"] = substr($crit["value"], 0, 24)."..."; + } + $critMaxStrLen = 13; + if (strlen($crit["display_name"]) > $critMaxStrLen) { + $crit["display_name"] = substr($crit["display_name"], 0, 12)."..."; + } + $modMaxStrLen = 16; + if (strlen($crit["modifier"]) > $modMaxStrLen) { + $crit["modifier"] = substr($crit["modifier"], 0, 15)."..."; + } + ?> + + + + + + + + + + + + +
    + + to
    Limit to contents["limit"]["value"] ?> contents["limit"]["modifier"] ?>
    + + + +type == "stream") : ?> + +
    Name:md["name"]);?>
    +
    Length:md["length"]);?>
    +
    Creator:md["login"]);?>
    +
    Description:md["description"]);?>
    +
    URL:md["url"]);?>
    + + + diff --git a/airtime_mvc/application/views/scripts/library/index.phtml b/airtime_mvc/application/views/scripts/library/index.phtml new file mode 100644 index 000000000..30c18e365 --- /dev/null +++ b/airtime_mvc/application/views/scripts/library/index.phtml @@ -0,0 +1,19 @@ +
    + render('library/library.phtml') ?> +
    + +
    + type == 'block') { + echo $this->render('playlist/smart-block.phtml'); + } else if ($this->type == 'playlist') { + echo $this->render('playlist/playlist.phtml'); + } else if ($this->type == 'stream') { + echo $this->render('webstream/webstream.phtml'); + } else { + echo $this->render('webstream/webstream.phtml'); + //throw new Exception("Unrecognized type: '{$this->type}'"); + } + + +?> +
    diff --git a/airtime_mvc/application/views/scripts/library/library.phtml b/airtime_mvc/application/views/scripts/library/library.phtml index 9bdb1c387..0b60020c5 100644 --- a/airtime_mvc/application/views/scripts/library/library.phtml +++ b/airtime_mvc/application/views/scripts/library/library.phtml @@ -1,2 +1,7 @@ -
    \ No newline at end of file +
    + Advanced Search Options + +
    + +
    \ No newline at end of file diff --git a/airtime_mvc/application/views/scripts/login/password-restore.phtml b/airtime_mvc/application/views/scripts/login/password-restore.phtml index 63d265c65..bf65b2114 100644 --- a/airtime_mvc/application/views/scripts/login/password-restore.phtml +++ b/airtime_mvc/application/views/scripts/login/password-restore.phtml @@ -3,7 +3,7 @@

    Reset password

    - \ No newline at end of file + diff --git a/airtime_mvc/application/views/scripts/playlist/index.phtml b/airtime_mvc/application/views/scripts/playlist/index.phtml deleted file mode 100644 index e4e9991e7..000000000 --- a/airtime_mvc/application/views/scripts/playlist/index.phtml +++ /dev/null @@ -1,7 +0,0 @@ -
    - render('library/library.phtml') ?> -
    - -
    - render('playlist/playlist.phtml') ?> -
    \ No newline at end of file diff --git a/airtime_mvc/application/views/scripts/playlist/playlist.phtml b/airtime_mvc/application/views/scripts/playlist/playlist.phtml index b01309bcf..6f962b97b 100644 --- a/airtime_mvc/application/views/scripts/playlist/playlist.phtml +++ b/airtime_mvc/application/views/scripts/playlist/playlist.phtml @@ -1,43 +1,66 @@ - -pl)) : ?> - - - Playlist crossfade - - - -pl)) : ?> - - -
    -

    - pl->getName(); ?> -

    -

    length; ?>

    +obj)) { + $contents = $this->obj->getContents(); + $count = count($contents); +} +?> +
    + +obj)) : ?> +
    + +
    +
    + +
    + + +
    + +obj)) : ?> + + + +
    +

    + obj->getName(); ?> +

    +

    length; ?>

    +
    +
    View / edit description
    - -
    - -
    - - +
    + + form; ?>