From 458aae33a1df34b223d579e469d114e388c2ca65 Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Thu, 19 Apr 2012 15:03:17 -0400 Subject: [PATCH 01/15] CC-3429: Firefox does not natively support mp3 file playing so preview does nothing. -Removed use of filemtime -audiopreview is now in correct directory --- .../controllers/AudiopreviewController.php | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/airtime_mvc/application/controllers/AudiopreviewController.php b/airtime_mvc/application/controllers/AudiopreviewController.php index 8203adade..cc3a06e83 100644 --- a/airtime_mvc/application/controllers/AudiopreviewController.php +++ b/airtime_mvc/application/controllers/AudiopreviewController.php @@ -28,9 +28,9 @@ class AudiopreviewController extends Zend_Controller_Action $baseDir = dirname($_SERVER['SCRIPT_FILENAME']); - $this->view->headScript()->appendFile($baseUrl.'/js/audiopreview/preview_jplayer.js?'.filemtime($baseDir.'/js/audiopreview/preview_jplayer.js'),'text/javascript'); - $this->view->headScript()->appendFile($baseUrl.'/js/jplayer/jplayer.playlist.min.js?'.filemtime($baseDir.'/js/jplayer/jplayer.playlist.min.js'),'text/javascript'); - $this->view->headLink()->appendStylesheet($baseUrl.'/js/jplayer/skin/jplayer.audio-preview.blue.monday.css?'.filemtime($baseDir.'/js/jplayer/skin/jplayer.audio-preview.blue.monday.css')); + $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.audio-preview.blue.monday.css?'.$CC_CONFIG['airtime_version']); $this->_helper->layout->setLayout('audioPlayer'); $logo = Application_Model_Preference::GetStationLogo(); @@ -60,9 +60,9 @@ class AudiopreviewController extends Zend_Controller_Action $baseDir = dirname($_SERVER['SCRIPT_FILENAME']); - $this->view->headScript()->appendFile($baseUrl.'/js/audiopreview/preview_jplayer.js?'.filemtime($baseDir.'/js/audiopreview/preview_jplayer.js'),'text/javascript'); - $this->view->headScript()->appendFile($baseUrl.'/js/jplayer/jplayer.playlist.min.js?'.filemtime($baseDir.'/js/jplayer/jplayer.playlist.min.js'),'text/javascript'); - $this->view->headLink()->appendStylesheet($baseUrl.'/js/jplayer/skin/jplayer.audio-preview.blue.monday.css?'.filemtime($baseDir.'/js/jplayer/skin/jplayer.audio-preview.blue.monday.css')); + $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.audio-preview.blue.monday.css?'.$CC_CONFIG['airtime_version']); $this->_helper->layout->setLayout('audioPlayer'); $logo = Application_Model_Preference::GetStationLogo(); @@ -129,9 +129,9 @@ class AudiopreviewController extends Zend_Controller_Action $baseDir = dirname($_SERVER['SCRIPT_FILENAME']); - $this->view->headScript()->appendFile($baseUrl.'/js/audiopreview/preview_jplayer.js?'.filemtime($baseDir.'/js/audiopreview/preview_jplayer.js'),'text/javascript'); - $this->view->headScript()->appendFile($baseUrl.'/js/jplayer/jplayer.playlist.min.js?'.filemtime($baseDir.'/js/jplayer/jplayer.playlist.min.js'),'text/javascript'); - $this->view->headLink()->appendStylesheet($baseUrl.'/js/jplayer/skin/jplayer.audio-preview.blue.monday.css?'.filemtime($baseDir.'/js/jplayer/skin/jplayer.audio-preview.blue.monday.css')); + $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.audio-preview.blue.monday.css?'.$CC_CONFIG['airtime_version']); $this->_helper->layout->setLayout('audioPlayer'); $logo = Application_Model_Preference::GetStationLogo(); From 92f2027fc4711fefed91fdc8a3d9674308237f5e Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Thu, 19 Apr 2012 15:06:15 -0400 Subject: [PATCH 02/15] -missing CC_CONFIG global.. --- .../application/controllers/AudiopreviewController.php | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/airtime_mvc/application/controllers/AudiopreviewController.php b/airtime_mvc/application/controllers/AudiopreviewController.php index cc3a06e83..607d39dd8 100644 --- a/airtime_mvc/application/controllers/AudiopreviewController.php +++ b/airtime_mvc/application/controllers/AudiopreviewController.php @@ -19,6 +19,8 @@ class AudiopreviewController extends Zend_Controller_Action */ public function audioPreviewAction() { + global $CC_CONFIG; + $audioFileID = $this->_getParam('audioFileID'); $audioFileArtist = $this->_getParam('audioFileArtist'); $audioFileTitle = $this->_getParam('audioFileTitle'); @@ -52,6 +54,8 @@ class AudiopreviewController extends Zend_Controller_Action */ public function playlistPreviewAction() { + global $CC_CONFIG; + $playlistIndex = $this->_getParam('playlistIndex'); $playlistID = $this->_getParam('playlistID'); @@ -121,6 +125,8 @@ class AudiopreviewController extends Zend_Controller_Action */ public function showPreviewAction() { + global $CC_CONFIG; + $showID = $this->_getParam('showID'); $showIndex = $this->_getParam('showIndex'); From 92671f572370a48c595b2db454be769e69d87e83 Mon Sep 17 00:00:00 2001 From: James Date: Thu, 19 Apr 2012 15:18:53 -0400 Subject: [PATCH 03/15] CC-3681: the value range for the Master, Show Source posrts should be corrected (shrinked) - added validator that check if the value is between 1024 and 49151 --- .../forms/LiveStreamingPreferences.php | 44 +++++++++++-------- 1 file changed, 26 insertions(+), 18 deletions(-) diff --git a/airtime_mvc/application/forms/LiveStreamingPreferences.php b/airtime_mvc/application/forms/LiveStreamingPreferences.php index 7d22f6383..1818d1e6d 100644 --- a/airtime_mvc/application/forms/LiveStreamingPreferences.php +++ b/airtime_mvc/application/forms/LiveStreamingPreferences.php @@ -46,7 +46,7 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm $master_dj_port = new Zend_Form_Element_Text('master_harbor_input_port'); $master_dj_port->setLabel("Master Source Port") ->setValue($m_port) - ->setValidators(array(new Zend_Validate_Between(array('min'=>0, 'max'=>99999)))) + ->setValidators(array(new Zend_Validate_Between(array('min'=>1024, 'max'=>49151)))) ->addValidator('regex', false, array('pattern'=>'/^[0-9]+$/', 'messages'=>array('regexNotMatch'=>'Only numbers are allowed.'))) ->setDecorators(array('ViewHelper')); $this->addElement($master_dj_port); @@ -65,7 +65,7 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm $live_dj_port = new Zend_Form_Element_Text('dj_harbor_input_port'); $live_dj_port->setLabel("Show Source Port") ->setValue($l_port) - ->setValidators(array(new Zend_Validate_Between(array('min'=>0, 'max'=>99999)))) + ->setValidators(array(new Zend_Validate_Between(array('min'=>1024, 'max'=>49151)))) ->addValidator('regex', false, array('pattern'=>'/^[0-9]+$/', 'messages'=>array('regexNotMatch'=>'Only numbers are allowed.'))) ->setDecorators(array('ViewHelper')); $this->addElement($live_dj_port); @@ -117,27 +117,35 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm $element->addError("You cannot use same port as Master DJ port."); } if($master_harbor_input_port != ""){ - if($master_harbor_input_port != Application_Model_StreamSetting::GetMasterLiveSteamPort()){ - $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); - $res = socket_bind($sock, 0, $master_harbor_input_port); - if(!$res){ - $element = $this->getElement("master_harbor_input_port"); - $element->addError("Port '$master_harbor_input_port' is not available."); - $isValid = false; + if(is_numeric($master_harbor_input_port)){ + if($master_harbor_input_port != Application_Model_StreamSetting::GetMasterLiveSteamPort()){ + $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); + $res = socket_bind($sock, 0, $master_harbor_input_port); + if(!$res){ + $element = $this->getElement("master_harbor_input_port"); + $element->addError("Port '$master_harbor_input_port' is not available."); + $isValid = false; + } + socket_close($sock); } - socket_close($sock); + }else{ + $isValid = false; } } if($dj_harbor_input_port != ""){ - if($dj_harbor_input_port != Application_Model_StreamSetting::GetDJLiveSteamPort()){ - $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); - $res = socket_bind($sock, 0, $dj_harbor_input_port); - if(!$res){ - $element = $this->getElement("dj_harbor_input_port"); - $element->addError("Port '$dj_harbor_input_port' is not available."); - $isValid = false; + if(is_numeric($dj_harbor_input_port)){ + if($dj_harbor_input_port != Application_Model_StreamSetting::GetDJLiveSteamPort()){ + $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); + $res = socket_bind($sock, 0, $dj_harbor_input_port); + if(!$res){ + $element = $this->getElement("dj_harbor_input_port"); + $element->addError("Port '$dj_harbor_input_port' is not available."); + $isValid = false; + } + socket_close($sock); } - socket_close($sock); + }else{ + $isValid = false; } } return $isValid; From 3849e944cfba64ee4c14ea195fd29cf99f24d92e Mon Sep 17 00:00:00 2001 From: James Date: Thu, 19 Apr 2012 15:22:02 -0400 Subject: [PATCH 04/15] CC-3682: System-> Stream - Tooltips on port ranges should be introduced - fixed --- airtime_mvc/application/forms/LiveStreamingPreferences.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/airtime_mvc/application/forms/LiveStreamingPreferences.php b/airtime_mvc/application/forms/LiveStreamingPreferences.php index 1818d1e6d..9e89cae92 100644 --- a/airtime_mvc/application/forms/LiveStreamingPreferences.php +++ b/airtime_mvc/application/forms/LiveStreamingPreferences.php @@ -99,7 +99,7 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm $live_dj_connection_url = "N/A"; } - $overrideDescription = "If Airtime is behind a router or firewall, you may need to configure port forwarding and this field information will be incorrect. In this case you will need to manually update this field so it shows the correct host/port/mount that your DJ's need to connect to. For more detail, please read the Airtime manual."; + $overrideDescription = "If Airtime is behind a router or firewall, you may need to configure port forwarding and this field information will be incorrect. In this case you will need to manually update this field so it shows the correct host/port/mount that your DJ's need to connect to. The allowed range is between 1024 and 49151. For more detail, please read the Airtime manual."; $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,'overrideDescription' => $overrideDescription)) From 295eab430a4b0b4565a4e253e125dfa6cf85a821 Mon Sep 17 00:00:00 2001 From: James Date: Thu, 19 Apr 2012 15:45:13 -0400 Subject: [PATCH 05/15] CC-3671: add show on week/day view doesn't get start time/end time filled in - fixed in both day and week view --- .../schedule/full-calendar-functions.js | 23 +++++++++++++++---- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/airtime_mvc/public/js/airtime/schedule/full-calendar-functions.js b/airtime_mvc/public/js/airtime/schedule/full-calendar-functions.js index 976b69441..847784903 100644 --- a/airtime_mvc/public/js/airtime/schedule/full-calendar-functions.js +++ b/airtime_mvc/public/js/airtime/schedule/full-calendar-functions.js @@ -107,7 +107,7 @@ function dayClick(date, allDay, jsEvent, view){ today = new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours(), now.getMinutes()); selected = new Date(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes()); } - + if(selected >= today) { var addShow = $('.add-button'); @@ -131,11 +131,19 @@ function dayClick(date, allDay, jsEvent, view){ } // duration in milisec var duration = (duration_h * 60 * 60 * 1000) + (duration_m * 60 * 1000); - + + var startTime_string, startTime // get start time value on the form - var startTime_string = $("#add_show_start_time").val(); - var startTime_info = startTime_string.split(':'); - var startTime = (parseInt(startTime_info[0],10) * 60 * 60 * 1000) + (parseInt(startTime_info[1], 10) * 60 * 1000); + if(view.name === "month") { + startTime_string = $("#add_show_start_time").val(); + var startTime_info = startTime_string.split(':'); + startTime = (parseInt(startTime_info[0],10) * 60 * 60 * 1000) + (parseInt(startTime_info[1], 10) * 60 * 1000); + }else{ + // if in day or week view, selected has all the time info as well + // so we don't ahve to calculate it explicitly + startTime_string = selected.getHours()+":"+selected.getMinutes() + startTime = 0 + } // calculate endDateTime var endDateTime = new Date(selected.getTime() + startTime + duration); @@ -146,6 +154,11 @@ function dayClick(date, allDay, jsEvent, view){ $("#add_show_start_date").val(chosenDate); $("#add_show_end_date_no_repeat").val(endDateFormat); $("#add_show_end_date").val(endDateFormat); + if(view.name !== "month") { + var endTimeString = endDateTime.getHours()+":"+endDateTime.getMinutes(); + $("#add_show_start_time").val(startTime_string) + $("#add_show_end_time").val(endTimeString) + } $("#schedule-show-when").show(); openAddShowForm(); From a482a8fe078ee9bd7de008c16424ece4a6c9be9f Mon Sep 17 00:00:00 2001 From: James Date: Thu, 19 Apr 2012 15:55:55 -0400 Subject: [PATCH 06/15] CC-3590: Calendar GUI->DJ user should not be able to invoke "Add Show" window - done --- .../public/js/airtime/schedule/full-calendar-functions.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/airtime_mvc/public/js/airtime/schedule/full-calendar-functions.js b/airtime_mvc/public/js/airtime/schedule/full-calendar-functions.js index 847784903..ac06b6962 100644 --- a/airtime_mvc/public/js/airtime/schedule/full-calendar-functions.js +++ b/airtime_mvc/public/js/airtime/schedule/full-calendar-functions.js @@ -212,7 +212,9 @@ function viewDisplay( view ) { } if(($("#add-show-form").length == 1) && ($("#add-show-form").css('display')=='none') && ($('.fc-header-left > span').length == 5)) { - makeAddShowButton(); + if($.trim($("#add-show-form").html()) != ""){ + makeAddShowButton(); + } } //save view name to db From f69a172ee1da126e4398393805ad661e640baad5 Mon Sep 17 00:00:00 2001 From: "paul.baranowski" Date: Sun, 25 Mar 2012 12:57:20 -0400 Subject: [PATCH 07/15] Commented out a bunch of Logging debug lines. There was a lot of output being logged in the Zend log file. --- .../controllers/ShowbuilderController.php | 2 +- airtime_mvc/application/models/Datatables.php | 5 +---- airtime_mvc/application/models/Schedule.php | 2 -- airtime_mvc/application/models/Show.php | 22 +++++++++---------- .../application/models/ShowBuilder.php | 2 +- .../application/models/ShowInstance.php | 2 +- 6 files changed, 15 insertions(+), 20 deletions(-) diff --git a/airtime_mvc/application/controllers/ShowbuilderController.php b/airtime_mvc/application/controllers/ShowbuilderController.php index 3f42efdf8..e61838ba6 100644 --- a/airtime_mvc/application/controllers/ShowbuilderController.php +++ b/airtime_mvc/application/controllers/ShowbuilderController.php @@ -361,4 +361,4 @@ class ShowbuilderController extends Zend_Controller_Action $showInstance = $request->getParam("instanceId"); } -} \ No newline at end of file +} diff --git a/airtime_mvc/application/models/Datatables.php b/airtime_mvc/application/models/Datatables.php index d44bace5f..84b47ec6b 100644 --- a/airtime_mvc/application/models/Datatables.php +++ b/airtime_mvc/application/models/Datatables.php @@ -93,10 +93,7 @@ class Application_Model_Datatables { catch (Exception $e) { Logging::debug($e->getMessage()); } - - //display sql executed in airtime log for testing - Logging::debug($sql); - + return array( "sEcho" => intval($data["sEcho"]), "iTotalDisplayRecords" => intval($totalDisplayRows), diff --git a/airtime_mvc/application/models/Schedule.php b/airtime_mvc/application/models/Schedule.php index 4f5983a35..ba65f4a22 100644 --- a/airtime_mvc/application/models/Schedule.php +++ b/airtime_mvc/application/models/Schedule.php @@ -272,8 +272,6 @@ class Application_Model_Schedule { } $sql .= " ORDER BY si.starts, sched.starts;"; - - Logging::debug($sql); $rows = $CC_DBC->GetAll($sql); return $rows; diff --git a/airtime_mvc/application/models/Show.php b/airtime_mvc/application/models/Show.php index cb9a446e6..a3cf0588a 100644 --- a/airtime_mvc/application/models/Show.php +++ b/airtime_mvc/application/models/Show.php @@ -273,9 +273,9 @@ class Application_Model_Show { } 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()}"); + //Logging::log("Local show day is: {$showDay->getDbDay()}"); + //Logging::log("First show day is: {$showDay->getDbFirstShow()}"); + //Logging::log("Id show days is: {$showDay->getDbId()}"); if (in_array($showDay->getDbDay(), $p_uncheckedDays)) { $showDay->reload(); @@ -283,11 +283,11 @@ class Application_Model_Show { //Logging::log("First show day is: {$showDay->getDbFirstShow()}"); //Logging::log("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::log("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::log("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::log("UTC show day is: {$startDay->format('w')}"); } } @@ -301,7 +301,7 @@ class Application_Model_Show { ." AND starts > TIMESTAMP '$timestamp'" ." AND show_id = $showId"; - Logging::log($sql); + //Logging::log($sql); $CC_DBC->query($sql); } @@ -359,7 +359,7 @@ class Application_Model_Show { ."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); + //Logging::log($sql); $rebroadcasts = $CC_DBC->GetAll($sql); @@ -1263,7 +1263,7 @@ class Application_Model_Show { $sql = "SELECT * FROM cc_show_rebroadcast WHERE show_id={$show_id}"; $rebroadcasts = $CC_DBC->GetAll($sql); - Logging::log('$start time of non repeating record '.$start); + //Logging::log('$start time of non repeating record '.$start); self::createRebroadcastInstances($rebroadcasts, $currentUtcTimestamp, $show_id, $show_instance_id, $start, $duration, $timezone); } @@ -1569,7 +1569,7 @@ class Application_Model_Show { WHERE last_show IS NULL OR first_show < '{$endTimeString}' AND last_show > '{$startTimeString}'"; - Logging::log($sql); + //Logging::log($sql); $res = $CC_DBC->GetAll($sql); @@ -1689,7 +1689,7 @@ class Application_Model_Show { $showDay->setDbFirstShow($dt)->setDbStartTime($dt) ->save(); - Logging::log("setting show's first show."); + //Logging::log("setting show's first show."); } /* Takes in a UTC DateTime object diff --git a/airtime_mvc/application/models/ShowBuilder.php b/airtime_mvc/application/models/ShowBuilder.php index 1d1b05817..d34e9f0cb 100644 --- a/airtime_mvc/application/models/ShowBuilder.php +++ b/airtime_mvc/application/models/ShowBuilder.php @@ -381,4 +381,4 @@ class Application_Model_ShowBuilder { return $display_items; } -} \ No newline at end of file +} diff --git a/airtime_mvc/application/models/ShowInstance.php b/airtime_mvc/application/models/ShowInstance.php index c25f1e2c3..a6361dac0 100644 --- a/airtime_mvc/application/models/ShowInstance.php +++ b/airtime_mvc/application/models/ShowInstance.php @@ -638,7 +638,7 @@ class Application_Model_ShowInstance { WHERE s.instance_id = '{$this->_instanceId}' AND s.playout_status >= 0 ORDER BY starts"; - Logging::log($sql); + //Logging::log($sql); $results = $CC_DBC->GetAll($sql); From 7f78a7f663d2947956a914db7faec0900f859bef Mon Sep 17 00:00:00 2001 From: "paul.baranowski" Date: Sun, 1 Apr 2012 15:51:03 -0400 Subject: [PATCH 08/15] CC-1927: Remove PEAR DB First pass through the model classes to remove use of $CC_DBC. Web application is working. There are still other parts of the app that use PEAR DB. --- airtime_mvc/application/Bootstrap.php | 36 ++- .../application/controllers/ApiController.php | 2 +- .../application/models/LoginAttempts.php | 43 ++- airtime_mvc/application/models/MusicDir.php | 25 +- airtime_mvc/application/models/Playlist.php | 10 +- airtime_mvc/application/models/Preference.php | 138 +++++----- airtime_mvc/application/models/Schedule.php | 146 +++++----- airtime_mvc/application/models/Show.php | 229 +++++++++------- .../application/models/ShowInstance.php | 128 +++++---- airtime_mvc/application/models/StoredFile.php | 51 ++-- .../application/models/StreamSetting.php | 258 +++++++++--------- airtime_mvc/application/models/Subjects.php | 89 +++--- airtime_mvc/application/models/User.php | 40 ++- 13 files changed, 630 insertions(+), 565 deletions(-) diff --git a/airtime_mvc/application/Bootstrap.php b/airtime_mvc/application/Bootstrap.php index 4b0f7e35d..e7f4ac90e 100644 --- a/airtime_mvc/application/Bootstrap.php +++ b/airtime_mvc/application/Bootstrap.php @@ -10,7 +10,7 @@ require_once 'propel/runtime/lib/Propel.php'; Propel::init(__DIR__."/configs/airtime-conf-production.php"); require_once __DIR__."/configs/constants.php"; -require_once 'DB.php'; +// require_once 'DB.php'; require_once 'Preference.php'; require_once "DateHelper.php"; @@ -20,12 +20,34 @@ require_once __DIR__.'/controllers/plugins/RabbitMqPlugin.php'; global $CC_CONFIG, $CC_DBC; $dsn = $CC_CONFIG['dsn']; -$CC_DBC = DB::connect($dsn, FALSE); -if (PEAR::isError($CC_DBC)) { - echo "ERROR: ".$CC_DBC->getMessage()." ".$CC_DBC->getUserInfo()."\n"; - exit(1); -} -$CC_DBC->setFetchMode(DB_FETCHMODE_ASSOC); +// ****************************************************************** +// Differences between PEAR DB & Propel/PDO: +// When selecting a single value from a null return set, +// PEAR returns NULL +// PDO returns false +// ****************************************************************** + +// $CC_DBC = DB::connect($dsn, FALSE); +// if (PEAR::isError($CC_DBC)) { +// echo "ERROR: ".$CC_DBC->getMessage()." ".$CC_DBC->getUserInfo()."\n"; +// exit(1); +// } +// $CC_DBC->setFetchMode(DB_FETCHMODE_ASSOC); + +// $sql = "SELECT column_name, character_maximum_length FROM information_schema.columns" +// ." WHERE table_name = 'cc_show' AND character_maximum_length > 0 and table_name=''"; +// // $sql = "SELECT * FROM cc_files WHERE id=1"; +// // $result = $CC_DBC->GetAll($sql); +// $result = $CC_DBC->GetOne($sql); +// var_dump($result); + +// $con = Propel::getConnection(); +// $q = $con->query($sql); +// //var_dump($q); +// //var_dump($q->fetchAll()); +// var_dump($q->fetchColumn(0)); + +// exit; $CC_CONFIG['airtime_version'] = Application_Model_Preference::GetAirtimeVersion(); diff --git a/airtime_mvc/application/controllers/ApiController.php b/airtime_mvc/application/controllers/ApiController.php index 1ef9b3aa1..232577ae5 100644 --- a/airtime_mvc/application/controllers/ApiController.php +++ b/airtime_mvc/application/controllers/ApiController.php @@ -342,7 +342,7 @@ class ApiController extends Zend_Controller_Action exit; } - PEAR::setErrorHandling(PEAR_ERROR_RETURN); + //PEAR::setErrorHandling(PEAR_ERROR_RETURN); $data = Application_Model_Schedule::GetScheduledPlaylists(); echo json_encode($data, JSON_FORCE_OBJECT); diff --git a/airtime_mvc/application/models/LoginAttempts.php b/airtime_mvc/application/models/LoginAttempts.php index 18b16df9b..6ebeafff6 100644 --- a/airtime_mvc/application/models/LoginAttempts.php +++ b/airtime_mvc/application/models/LoginAttempts.php @@ -1,45 +1,36 @@ GetOne($sql); - if($res){ + $res = $con->query($sql)->fetchColumn(0); + if ($res) { $sql = "UPDATE cc_login_attempts SET attempts=attempts+1 WHERE ip='$ip'"; - $res = $CC_DBC->query($sql); - if (PEAR::isError($res)) { - return $res; - } - }else{ + $con->exec($sql); + } else { $sql = "INSERT INTO cc_login_attempts (ip, attempts) values ('$ip', '1')"; - $res = $CC_DBC->query($sql); - if (PEAR::isError($res)) { - return $res; - } + $con->exec($sql); } } - + public static function getAttempts($ip){ - global $CC_DBC; + $con = Propel::getConnection(); $sql = "select attempts from cc_login_attempts WHERE ip='$ip'"; - $res = $CC_DBC->GetOne($sql); - return $res; + $res = $con->query($sql)->fetchColumn(0); + return $res ? $res : 0; } - + public static function resetAttempts($ip){ - global $CC_DBC; + $con = Propel::getConnection(); $sql = "select count(*) from cc_login_attempts WHERE ip='$ip'"; - $res = $CC_DBC->GetOne($sql); - if($res){ + $res = $con->query($sql)->fetchColumn(0); + if ($res > 0) { $sql = "DELETE FROM cc_login_attempts WHERE ip='$ip'"; - $res = $CC_DBC->query($sql); - if (PEAR::isError($res)) { - return $res; - } + $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 b07ffff75..3c8b64e01 100644 --- a/airtime_mvc/application/models/MusicDir.php +++ b/airtime_mvc/application/models/MusicDir.php @@ -58,7 +58,8 @@ class Application_Model_MusicDir { return $this->_dir->getExists(); } - /** There are 2 cases where this function can be called. + /** + * 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 * @@ -67,24 +68,26 @@ class Application_Model_MusicDir { * * When $userAddedWatchedDir is true, it will set "Watched" flag to false * otherwise, it will set "Exists" flag to true - **/ + */ public function remove($userAddedWatchedDir=true) { - global $CC_DBC; + $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 = "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"; - $show_instances = $CC_DBC->GetAll($sql); + $show_instances = $con->query($sql)->fetchAll(); // get all the files on this dir - $sql = "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"; - $files = $CC_DBC->GetAll($sql); + $sql = "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"; + $files = $con->query($sql)->fetchAll(); // set file_exist flag to false - foreach( $files as $file_row ){ + foreach ($files as $file_row) { $temp_file = Application_Model_StoredFile::Recall($file_row['id']); if($temp_file != null){ $temp_file->setFileExistsFlag(false); @@ -92,9 +95,9 @@ class Application_Model_MusicDir { } // set RemovedFlag to true - if($userAddedWatchedDir){ + if ($userAddedWatchedDir) { self::setWatchedFlag(false); - }else{ + } else { self::setExistsFlag(false); } //$res = $this->_dir->delete(); diff --git a/airtime_mvc/application/models/Playlist.php b/airtime_mvc/application/models/Playlist.php index 92063218c..bc48bb2d0 100644 --- a/airtime_mvc/application/models/Playlist.php +++ b/airtime_mvc/application/models/Playlist.php @@ -541,7 +541,7 @@ class Application_Model_Playlist { ->filterByDbPlaylistId($this->id) ->filterByDbPosition($this->getSize()-1) ->findOne($this->con); - + $this->changeFadeInfo($row->getDbId(), null, $fadeout); } } @@ -769,10 +769,12 @@ class Application_Model_Playlist { return $res; } - public static function getPlaylistCount(){ - global $CC_CONFIG, $CC_DBC; + public static function getPlaylistCount() + { + global $CC_CONFIG; + $con = Propel::getConnection(); $sql = 'SELECT count(*) as cnt FROM '.$CC_CONFIG["playListTable"]; - return $CC_DBC->GetOne($sql); + return $con->query($sql)->fetchColumn(0); } /** diff --git a/airtime_mvc/application/models/Preference.php b/airtime_mvc/application/models/Preference.php index 0786152c3..5601a6158 100644 --- a/airtime_mvc/application/models/Preference.php +++ b/airtime_mvc/application/models/Preference.php @@ -4,7 +4,8 @@ class Application_Model_Preference { public static function SetValue($key, $value, $isUserValue = false){ - global $CC_CONFIG, $CC_DBC; + global $CC_CONFIG; + $con = Propel::getConnection(); //called from a daemon process if(!class_exists("Zend_Auth", false) || !Zend_Auth::getInstance()->hasIdentity()) { @@ -21,13 +22,13 @@ class Application_Model_Preference //Check if key already exists $sql = "SELECT COUNT(*) FROM cc_pref" ." WHERE keystr = '$key'"; - + //For user specific preference, check if id matches as well if($isUserValue) { $sql .= " AND subjid = '$id'"; } - - $result = $CC_DBC->GetOne($sql); + + $result = $con->query($sql)->fetchColumn(0); if($result == 1) { // result found @@ -38,8 +39,8 @@ class Application_Model_Preference ." WHERE keystr = '$key'"; } else { // user pref - $sql = "UPDATE cc_pref" - . " SET valstr = '$value'" + $sql = "UPDATE cc_pref" + . " SET valstr = '$value'" . " WHERE keystr = '$key' AND subjid = $id"; } } else { @@ -54,39 +55,39 @@ class Application_Model_Preference ." VALUES ($id, '$key', '$value')"; } } - - return $CC_DBC->query($sql); + + return $con->exec($sql); } public static function GetValue($key, $isUserValue = false){ - global $CC_CONFIG, $CC_DBC; - + global $CC_CONFIG; + $con = Propel::getConnection(); + //Check if key already exists $sql = "SELECT COUNT(*) FROM cc_pref" ." WHERE keystr = '$key'"; //For user specific preference, check if id matches as well - if($isUserValue) { + if ($isUserValue) { $auth = Zend_Auth::getInstance(); if($auth->hasIdentity()) { $id = $auth->getIdentity()->id; $sql .= " AND subjid = '$id'"; } } - $result = $CC_DBC->GetOne($sql); - + $result = $con->query($sql)->fetchColumn(0); if ($result == 0) return ""; else { $sql = "SELECT valstr FROM cc_pref" ." WHERE keystr = '$key'"; - + //For user specific preference, check if id matches as well if($isUserValue && $auth->hasIdentity()) { $sql .= " AND subjid = '$id'"; } - - $result = $CC_DBC->GetOne($sql); - return $result; + + $result = $con->query($sql)->fetchColumn(0); + return $result ? $result : ""; } } @@ -109,36 +110,36 @@ class Application_Model_Preference $view->headTitle()->exchangeArray(array()); //clear headTitle ArrayObject $view->headTitle(self::GetHeadTitle()); } - + $eventType = "update_station_name"; $md = array("station_name"=>$title); - + Application_Model_RabbitMq::SendMessageToPypo($eventType, $md); } /** - * Set the furthest date that a never-ending show + * Set the furthest date that a never-ending show * should be populated until. - * + * * @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")); } /** - * Get the furthest date that a never-ending show + * Get the furthest date that a never-ending show * should be populated until. * * Returns null if the value hasn't been set, otherwise returns - * a DateTime object representing the date. - * + * a DateTime object representing the date. + * * @return DateTime (in UTC Timezone) */ public static function GetShowsPopulatedUntil() { $date = self::GetValue("shows_populated_until"); - + if ($date == ""){ return null; } else { @@ -163,15 +164,15 @@ class Application_Model_Preference $fade = str_pad($fade, 9, "0", STR_PAD_LEFT); return $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 == ""){ @@ -182,10 +183,10 @@ class Application_Model_Preference public static function SetStreamLabelFormat($type){ self::SetValue("stream_label_format", $type); - + $eventType = "update_stream_format"; $md = array("stream_format"=>$type); - + Application_Model_RabbitMq::SendMessageToPypo($eventType, $md); } @@ -365,10 +366,11 @@ class Application_Model_Preference return self::GetValue("uniqueId"); } - public static function GetCountryList(){ - global $CC_DBC; + public static function GetCountryList() + { + $con = Propel::getConnection(); $sql = "SELECT * FROM cc_country"; - $res = $CC_DBC->GetAll($sql); + $res = $con->query($sql)->fetchAll(); $out = array(); $out[""] = "Select Country"; foreach($res as $r){ @@ -401,7 +403,7 @@ class Application_Model_Preference $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"])){ @@ -438,7 +440,7 @@ class Application_Model_Preference foreach($s_info as $k => $v){ $outputString .= "\t".strtoupper($k)." : ".$v."\n"; } - } + } }else{ $outputString .= $key.' : '.$out."\n"; } @@ -452,7 +454,7 @@ class Application_Model_Preference return $outputString; } } - + public static function GetInstallMethod(){ $easy_install = file_exists('/usr/bin/airtime-easy-setup'); $debian_install = file_exists('/var/lib/dpkg/info/airtime.config'); @@ -559,7 +561,7 @@ class Application_Model_Preference return self::GetValue("system_version"); } } - + public static function GetLatestVersion(){ $latest = self::GetValue("latest_version"); if($latest == null || strlen($latest) == 0) { @@ -568,14 +570,14 @@ class Application_Model_Preference return $latest; } } - + public static function SetLatestVersion($version){ $pattern = "/^[0-9]+\.[0-9]+\.[0-9]+/"; 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) { @@ -584,7 +586,7 @@ class Application_Model_Preference return $link; } } - + public static function SetLatestLink($link){ $pattern = "#^(http|https|ftp)://" . "([a-zA-Z0-9]+\.)*[a-zA-Z0-9]+" . @@ -609,7 +611,7 @@ class Application_Model_Preference public static function GetSoundCloudDownloadbleOption() { return self::GetValue("soundcloud_downloadable"); } - + public static function SetWeekStartDay($day) { self::SetValue("week_start_day", $day); } @@ -622,7 +624,7 @@ class Application_Model_Preference return $val; } } - + /** * Stores the last timestamp of user updating stream setting */ @@ -630,7 +632,7 @@ class Application_Model_Preference $now = time(); self::SetValue("stream_update_timestamp", $now); } - + /** * Gets the last timestamp of user updating stream setting */ @@ -641,22 +643,22 @@ class Application_Model_Preference } return $update_time; } - + public static function GetClientId() { return self::GetValue("client_id"); } - + public static function SetClientId($id) { if (is_numeric($id)) { self::SetValue("client_id", $id); } } - + /* User specific preferences start */ /** * Sets the time scale preference (agendaDay/agendaWeek/month) in Calendar. - * + * * @param $timeScale new time scale */ public static function SetCalendarTimeScale($timeScale) { @@ -674,16 +676,16 @@ class Application_Model_Preference } return $val; } - + /** * Sets the number of entries to show preference in library under Playlist Builder. - * + * * @param $numEntries new number of entries to show */ 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 @@ -695,10 +697,10 @@ class Application_Model_Preference } return $val; } - + /** * Sets the time interval preference in Calendar. - * + * * @param $timeInterval new time interval */ public static function SetCalendarTimeInterval($timeInterval) { @@ -716,11 +718,11 @@ class Application_Model_Preference } return $val; } - + public static function SetDiskQuota($value){ self::SetValue("disk_quota", $value, false); } - + public static function GetDiskQuota(){ $val = self::GetValue("disk_quota"); if(strlen($val) == 0) { @@ -728,27 +730,27 @@ class Application_Model_Preference } return $val; } - + public static function SetLiveSteamMasterUsername($value){ self::SetValue("live_stream_master_username", $value, false); } - + public static function GetLiveSteamMasterUsername(){ return self::GetValue("live_stream_master_username"); } - + public static function SetLiveSteamMasterPassword($value){ self::SetValue("live_stream_master_password", $value, false); } - + public static function GetLiveSteamMasterPassword(){ return self::GetValue("live_stream_master_password"); } - + 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"){ @@ -757,11 +759,11 @@ class Application_Model_Preference return true; } } - + 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"){ @@ -770,19 +772,19 @@ class Application_Model_Preference return "on"; } } - + 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 GetLiveDJSourceConnectionURL(){ return self::GetValue("live_dj_source_connection_url"); } @@ -795,7 +797,7 @@ class Application_Model_Preference return self::GetValue("system_email"); } /* User specific preferences end */ - + public static function ShouldShowPopUp(){ $today = mktime(0, 0, 0, gmdate("m"), gmdate("d"), gmdate("Y")); $remindDate = Application_Model_Preference::GetRemindMeDate(); diff --git a/airtime_mvc/application/models/Schedule.php b/airtime_mvc/application/models/Schedule.php index ba65f4a22..b185ae93f 100644 --- a/airtime_mvc/application/models/Schedule.php +++ b/airtime_mvc/application/models/Schedule.php @@ -9,10 +9,11 @@ class Application_Model_Schedule { */ public function IsFileScheduledInTheFuture($p_fileId) { - global $CC_CONFIG, $CC_DBC; + global $CC_CONFIG; + $con = Propel::getConnection(); $sql = "SELECT COUNT(*) FROM ".$CC_CONFIG["scheduleTable"] ." WHERE file_id = {$p_fileId} AND starts > NOW()"; - $count = $CC_DBC->GetOne($sql); + $count = $con->query($sql)->fetchColumn(0); if (is_numeric($count) && ($count != '0')) { return TRUE; } else { @@ -37,13 +38,13 @@ class Application_Model_Schedule { $date = new Application_Common_DateHelper; $timeNow = $date->getTimestamp(); $utcTimeNow = $date->getUtcTimestamp(); - + $shows = Application_Model_Show::getPrevCurrentNext($utcTimeNow); $previousShowID = count($shows['previousShow'])>0?$shows['previousShow'][0]['instance_id']:null; $currentShowID = count($shows['currentShow'])>0?$shows['currentShow'][0]['instance_id']:null; $nextShowID = count($shows['nextShow'])>0?$shows['nextShow'][0]['instance_id']:null; $results = Application_Model_Schedule::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), @@ -53,10 +54,10 @@ class Application_Model_Schedule { "nextShow"=>$shows['nextShow'], "timezone"=> date("T"), "timezoneOffset"=> date("Z")); - + return $range; } - + /** * Queries the database for the set of schedules one hour before and after the given time. * If a show starts and ends within that time that is considered the current show. Then the @@ -69,19 +70,20 @@ class Application_Model_Schedule { { if ($p_previousShowID == null && $p_currentShowID == null && $p_nextShowID == null) return; - - global $CC_CONFIG, $CC_DBC; - $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 + + + 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 .= '('; @@ -102,17 +104,17 @@ class Application_Model_Schedule { $sql .= ')'; } else if($p_previousShowID != null && $p_currentShowID != null) $sql .= ')'; - + $sql .= ' AND st.playout_status > 0 ORDER BY st.starts'; - - $rows = $CC_DBC->GetAll($sql); - + + + $rows = $con->query($sql)->fetchAll(); $numberOfRows = count($rows); $results['previous'] = null; $results['current'] = null; $results['next'] = null; - + $timeNowAsMillis = strtotime($p_timeNow); for( $i = 0; $i < $numberOfRows; ++$i ){ // if the show is overbooked, then update the track end time to the end of the show time. @@ -130,7 +132,6 @@ class Application_Model_Schedule { "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); - if ( isset($rows[$i+1])){ $results['next'] = array("name"=>$rows[$i+1]["artist_name"]." - ".$rows[$i+1]["track_title"], "starts"=>$rows[$i+1]["starts"], @@ -157,10 +158,10 @@ class Application_Model_Schedule { } return $results; } - - public static function GetLastScheduleItem($p_timeNow){ - global $CC_CONFIG, $CC_DBC; + 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" @@ -175,14 +176,14 @@ class Application_Model_Schedule { ." ORDER BY st.ends DESC" ." LIMIT 1"; - $row = $CC_DBC->GetAll($sql); + $row = $con->query($sql)->fetchAll(); return $row; } public static function GetCurrentScheduleItem($p_timeNow, $p_instanceId){ - global $CC_CONFIG, $CC_DBC; - + 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,13 +201,13 @@ class Application_Model_Schedule { ." ORDER BY st.starts DESC" ." LIMIT 1"; - $row = $CC_DBC->GetAll($sql); + $row = $con->query($sql)->fetchAll(); return $row; } public static function GetNextScheduleItem($p_timeNow){ - global $CC_CONFIG, $CC_DBC; - + global $CC_CONFIG; + $con = Propel::getConnection(); $sql = "SELECT" ." ft.artist_name, ft.track_title," ." st.starts as starts, st.ends as ends" @@ -221,7 +222,7 @@ class Application_Model_Schedule { ." ORDER BY st.starts" ." LIMIT 1"; - $row = $CC_DBC->GetAll($sql); + $row = $con->query($sql)->fetchAll(); return $row; } @@ -236,8 +237,8 @@ class Application_Model_Schedule { */ public static function GetScheduleDetailItems($p_start, $p_end, $p_shows) { - global $CC_CONFIG, $CC_DBC; - + global $CC_CONFIG; + $con = Propel::getConnection(); $sql = "SELECT DISTINCT showt.name AS show_name, showt.color AS show_color, @@ -265,32 +266,35 @@ class Application_Model_Schedule { ((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}'))"; - - + + if (count($p_shows) > 0) { $sql .= " AND show_id IN (".implode(",", $p_shows).")"; } $sql .= " ORDER BY si.starts, sched.starts;"; - $rows = $CC_DBC->GetAll($sql); + $rows = $con->query($sql)->fetchAll(); return $rows; } public static function UpdateMediaPlayedStatus($p_id) { - global $CC_CONFIG, $CC_DBC; + global $CC_CONFIG; + $con = Propel::getConnection(); $sql = "UPDATE ".$CC_CONFIG['scheduleTable'] ." SET media_item_played=TRUE" ." WHERE id=$p_id"; - $retVal = $CC_DBC->query($sql); + $retVal = $con->exec($sql); return $retVal; } - public static function getSchduledPlaylistCount(){ - global $CC_CONFIG, $CC_DBC; + public static function getSchduledPlaylistCount() + { + global $CC_CONFIG; + $con = Propel::getConnection(); $sql = "SELECT count(*) as cnt FROM ".$CC_CONFIG['scheduleTable']; - return $CC_DBC->GetOne($sql); + return $con->query($sql)->fetchColumn(0); } @@ -398,7 +402,7 @@ class Application_Model_Schedule { * $p_startTime and $p_endTime specify the range. Schedule items returned * do not have to be entirely within this range. It is enough that the end * or beginning of the scheduled item is in the range. - * + * * * @param string $p_startTime * In the format YYYY-MM-DD HH:MM:SS.nnnnnn @@ -409,8 +413,9 @@ class Application_Model_Schedule { * arrays representing each row. */ public static function GetItems($p_startTime, $p_endTime) { - global $CC_CONFIG, $CC_DBC; - + global $CC_CONFIG; + $con = Propel::getConnection(); + $baseQuery = "SELECT st.file_id AS file_id," ." st.id as id," ." st.instance_id as instance_id," @@ -425,48 +430,42 @@ class Application_Model_Schedule { ." FROM $CC_CONFIG[scheduleTable] as st" ." LEFT JOIN $CC_CONFIG[showInstances] as si" ." ON st.instance_id = si.id"; - + $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 = $CC_DBC->GetAll($sql); - if (PEAR::isError($rows)) { - return null; - } - + $rows = $con->query($sql)->fetchAll(); + if (count($rows) < 3){ - Logging::debug("Get Schedule: Less than 3 results returned. Do another query in an attempt to get 3."); - + Logging::debug("Get Schedule: Less than 3 results returned. Doing another query since we need a minimum of 3 results."); + $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"; - + $sql = $baseQuery.$predicates; - $rows = $CC_DBC->GetAll($sql); - if (PEAR::isError($rows)) { - return null; - } + $rows = $con->query($sql)->fetchAll(); } - + return $rows; } public static function GetScheduledPlaylists($p_fromDateTime = null, $p_toDateTime = null){ - global $CC_CONFIG, $CC_DBC; + global $CC_CONFIG; /* if $p_fromDateTime and $p_toDateTime function parameters are null, then set range * from "now" to "now + 24 hours". */ @@ -478,16 +477,16 @@ class Application_Model_Schedule { } if (is_null($p_fromDateTime)) { $t2 = new DateTime("@".time()); - + $cache_ahead_hours = $CC_CONFIG["cache_ahead_hours"]; - + if (is_numeric($cache_ahead_hours)){ //make sure we are not dealing with a float $cache_ahead_hours = intval($cache_ahead_hours); } else { $cache_ahead_hours = 1; } - + $t2->add(new DateInterval("PT".$cache_ahead_hours."H")); $range_end = $t2->format("Y-m-d H:i:s"); } else { @@ -502,7 +501,7 @@ class Application_Model_Schedule { $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']; @@ -513,13 +512,13 @@ class Application_Model_Schedule { $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){ $data["media"][$switch_start]['start'] = Application_Model_Schedule::AirtimeTimeToPypoTime($switch_off_time); $data["media"][$switch_start]['end'] = Application_Model_Schedule::AirtimeTimeToPypoTime($switch_off_time); @@ -547,7 +546,7 @@ class Application_Model_Schedule { /* TODO: Not all tracks will have "show_end" */ 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"); } @@ -576,8 +575,9 @@ class Application_Model_Schedule { public static function deleteAll() { - global $CC_CONFIG, $CC_DBC; - $CC_DBC->query("TRUNCATE TABLE ".$CC_CONFIG["scheduleTable"]); + global $CC_CONFIG; + $con = Propel::getConnection(); + $con->exec("TRUNCATE TABLE ".$CC_CONFIG["scheduleTable"]); } public static function deleteWithFileId($fileId){ diff --git a/airtime_mvc/application/models/Show.php b/airtime_mvc/application/models/Show.php index a3cf0588a..8e8e558e4 100644 --- a/airtime_mvc/application/models/Show.php +++ b/airtime_mvc/application/models/Show.php @@ -113,36 +113,38 @@ class Application_Model_Show { public function getHosts() { - global $CC_DBC; + $con = Propel::getConnection(); $sql = "SELECT first_name, last_name FROM cc_show_hosts LEFT JOIN cc_subjs ON cc_show_hosts.subjs_id = cc_subjs.id WHERE show_id = {$this->_showId}"; - $hosts = $CC_DBC->GetAll($sql); + $hosts = $con->query($sql)->fetchAll(); $res = array(); - foreach($hosts as $host) { + foreach ($hosts as $host) { $res[] = $host['first_name']." ".$host['last_name']; } return $res; } - + public function getHostsIds() { - global $CC_DBC; + $con = Propel::getConnection(); $sql = "SELECT subjs_id FROM cc_show_hosts WHERE show_id = {$this->_showId}"; - $hosts = $CC_DBC->GetAll($sql); + $hosts = $con->query($sql)->fetchAll(); return $hosts; } - //remove everything about this show. + /** + * remove everything about this show. + */ public function delete() { //usually we hide the show-instance, but in this case we are deleting the show template @@ -155,7 +157,7 @@ class Application_Model_Show { public function resizeShow($deltaDay, $deltaMin) { - global $CC_DBC; + $con = Propel::getConnection(); if ($deltaDay > 0) { return "Shows can have a max length of 24 hours."; @@ -186,7 +188,7 @@ class Application_Model_Show { AND ((CAST(duration AS interval) + interval '{$deltaDay} days' + interval '{$hours}:{$mins}') <= interval '24:00')"; //do both the queries at once. - $CC_DBC->query($sql); + $con->exec($sql); $con = Propel::getConnection(CcSchedulePeer::DATABASE_NAME); $con->beginTransaction(); @@ -215,7 +217,7 @@ class Application_Model_Show { public function cancelShow($day_timestamp) { - global $CC_DBC; + $con = Propel::getConnection(); $timeinfo = explode(" ", $day_timestamp); @@ -227,7 +229,7 @@ class Application_Model_Show { SET modified_instance = TRUE WHERE starts >= '{$day_timestamp}' AND show_id = {$this->_showId}"; - $CC_DBC->query($sql); + $con->exec($sql); // check if we can safely delete the show $showInstancesRow = CcShowInstancesQuery::create() @@ -237,7 +239,7 @@ class Application_Model_Show { if(is_null($showInstancesRow)){ $sql = "DELETE FROM cc_show WHERE id = {$this->_showId}"; - $CC_DBC->query($sql); + $con->exec($sql); } Application_Model_RabbitMq::PushSchedule(); @@ -258,7 +260,7 @@ class Application_Model_Show { */ public function removeUncheckedDaysInstances($p_uncheckedDays) { - global $CC_DBC; + $con = Propel::getConnection(); //need to convert local doftw to UTC doftw (change made for 2.0 since shows are stored in UTC) $daysRemovedUTC = array(); @@ -303,7 +305,7 @@ class Application_Model_Show { //Logging::log($sql); - $CC_DBC->query($sql); + $con->exec($sql); } /** @@ -315,10 +317,10 @@ class Application_Model_Show { */ public function isRecorded(){ $showInstancesRow = CcShowInstancesQuery::create() - ->filterByDbShowId($this->getId()) - ->filterByDbRecord(1) - ->filterByDbModifiedInstance(false) - ->findOne(); + ->filterByDbShowId($this->getId()) + ->filterByDbRecord(1) + ->filterByDbModifiedInstance(false) + ->findOne(); return !is_null($showInstancesRow); } @@ -351,7 +353,7 @@ class Application_Model_Show { */ public function getRebroadcastsAbsolute() { - global $CC_DBC; + $con = Propel::getConnection(); $showId = $this->getId(); @@ -361,7 +363,7 @@ class Application_Model_Show { //Logging::log($sql); - $rebroadcasts = $CC_DBC->GetAll($sql); + $rebroadcasts = $con->query($sql)->fetchAll(); $rebroadcastsLocal = array(); //get each rebroadcast show in cc_show_instances, convert to current timezone to get start date/time. @@ -389,14 +391,14 @@ class Application_Model_Show { */ public function getRebroadcastsRelative() { - global $CC_DBC; + $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 $CC_DBC->GetAll($sql); + return $con->query($sql)->fetchAll(); } /** @@ -431,8 +433,8 @@ class Application_Model_Show { public function getRepeatType() { $showDaysRow = CcShowDaysQuery::create() - ->filterByDbShowId($this->_showId) - ->findOne(); + ->filterByDbShowId($this->_showId) + ->findOne(); if (!is_null($showDaysRow)){ return $showDaysRow->getDbRepeatType(); @@ -447,21 +449,17 @@ class Application_Model_Show { * Return the end date for the repeating show or the empty * string if there is no end. */ - public function getRepeatingEndDate(){ - global $CC_DBC; + public function getRepeatingEndDate() + { + $con = Propel::getConnection(); $showId = $this->getId(); $sql = "SELECT last_show FROM cc_show_days" ." WHERE show_id = $showId" ." ORDER BY last_show DESC"; - $endDate = $CC_DBC->GetOne($sql); - - if (is_null($endDate)){ - return ""; - } else { - return $endDate; - } + $query = $con->query($sql)->fetchColumn(0); + return $query ? $query : ""; } /** @@ -475,7 +473,7 @@ class Application_Model_Show { * be gone for good. */ public function deleteAllInstances(){ - global $CC_DBC; + $con = Propel::getConnection(); $timestamp = gmdate("Y-m-d H:i:s"); @@ -484,7 +482,7 @@ class Application_Model_Show { ." WHERE starts > TIMESTAMP '$timestamp'" ." AND show_id = $showId"; - $CC_DBC->query($sql); + $con->exec($sql); } /** @@ -492,7 +490,7 @@ class Application_Model_Show { * show object from the show_instances table. */ public function deleteAllRebroadcasts(){ - global $CC_DBC; + $con = Propel::getConnection(); $timestamp = gmdate("Y-m-d H:i:s"); @@ -502,7 +500,7 @@ class Application_Model_Show { ." AND show_id = $showId" ." AND rebroadcast = 1"; - $CC_DBC->query($sql); + $con->exec($sql); } /** @@ -515,7 +513,7 @@ class Application_Model_Show { * The date which to delete after, if null deletes from the current timestamp. */ public function removeAllInstancesFromDate($p_date=null){ - global $CC_DBC; + $con = Propel::getConnection(); $timestamp = gmdate("Y-m-d H:i:s"); @@ -530,7 +528,7 @@ class Application_Model_Show { ." AND starts > TIMESTAMP '$timestamp'" ." AND show_id = $showId"; - $CC_DBC->query($sql); + $con->exec($sql); } @@ -547,7 +545,7 @@ class Application_Model_Show { * The date which to delete before */ public function removeAllInstancesBeforeDate($p_date){ - global $CC_DBC; + $con = Propel::getConnection(); $timestamp = gmdate("Y-m-d H:i:s"); @@ -557,7 +555,7 @@ class Application_Model_Show { ." AND starts > TIMESTAMP '$timestamp'" ." AND show_id = $showId"; - $CC_DBC->query($sql); + $con->exec($sql); } /** @@ -567,7 +565,7 @@ class Application_Model_Show { * The start date in the format YYYY-MM-DD */ public function getStartDate(){ - global $CC_DBC; + $con = Propel::getConnection(); $showId = $this->getId(); $sql = "SELECT first_show, start_time, timezone FROM cc_show_days" @@ -575,11 +573,12 @@ class Application_Model_Show { ." ORDER BY first_show" ." LIMIT 1"; - $rows = $CC_DBC->GetAll($sql); + $query = $con->query($sql); - if (count($rows) == 0){ + if ($query->rowCount() == 0){ return ""; } else { + $rows = $query->fetchAll(); $row = $rows[0]; $dt = new DateTime($row["first_show"]." ".$row["start_time"], new DateTimeZone($row["timezone"])); @@ -596,7 +595,7 @@ class Application_Model_Show { */ public function getStartTime(){ - global $CC_DBC; + $con = Propel::getConnection(); $showId = $this->getId(); $sql = "SELECT first_show, start_time, timezone FROM cc_show_days" @@ -604,11 +603,12 @@ class Application_Model_Show { ." ORDER BY first_show" ." LIMIT 1"; - $rows = $CC_DBC->GetAll($sql); + $query = $con->query($sql); - if (count($rows) == 0){ + if ($query->rowCount() == 0){ 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")); @@ -676,7 +676,7 @@ class Application_Model_Show { * scheduled in the future. */ public function getAllFutureInstanceIds(){ - global $CC_DBC; + $con = Propel::getConnection(); $date = new Application_Common_DateHelper; $timestamp = $date->getTimestamp(); @@ -687,10 +687,10 @@ class Application_Model_Show { ." AND starts > TIMESTAMP '$timestamp'" ." AND modified_instance != TRUE"; - $rows = $CC_DBC->GetAll($sql); + $rows = $con->query($sql)->fetchAll(); $instance_ids = array(); - foreach ($rows as $row){ + foreach ($rows as $row) { $instance_ids[] = $row["id"]; } return $instance_ids; @@ -705,8 +705,7 @@ class Application_Model_Show { */ private function updateDurationTime($p_data){ //need to update cc_show_instances, cc_show_days - - global $CC_DBC; + $con = Propel::getConnection(); $date = new Application_Common_DateHelper; $timestamp = $date->getUtcTimestamp(); @@ -714,20 +713,20 @@ class Application_Model_Show { $sql = "UPDATE cc_show_days " ."SET duration = '$p_data[add_show_duration]' " ."WHERE show_id = $p_data[add_show_id]"; - $CC_DBC->query($sql); + $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'"; - $CC_DBC->query($sql); + $con->exec($sql); + } private function updateStartDateTime($p_data, $p_endDate){ //need to update cc_schedule, cc_show_instances, cc_show_days - - global $CC_DBC; + $con = Propel::getConnection(); $date = new Application_Common_DateHelper; $timestamp = $date->getTimestamp(); @@ -742,7 +741,7 @@ class Application_Model_Show { $sql .= "last_show = DATE '$p_endDate' "; } $sql .= "WHERE show_id = $p_data[add_show_id]"; - $CC_DBC->query($sql); + $con->exec($sql); $dtOld = new DateTime($this->getStartDate()." ".$this->getStartTime(), new DateTimeZone("UTC")); $dtNew = new DateTime($p_data['add_show_start_date']." ".$p_data['add_show_start_time'], new DateTimeZone(date_default_timezone_get())); @@ -753,7 +752,7 @@ class Application_Model_Show { ."ends = ends + INTERVAL '$diff sec' " ."WHERE show_id = $p_data[add_show_id] " ."AND starts > TIMESTAMP '$timestamp'"; - $CC_DBC->query($sql); + $con->exec($sql); $showInstanceIds = $this->getAllFutureInstanceIds(); if (count($showInstanceIds) > 0 && $diff != 0){ @@ -762,7 +761,7 @@ class Application_Model_Show { ."SET starts = starts + INTERVAL '$diff sec', " ."ends = ends + INTERVAL '$diff sec' " ."WHERE instance_id IN ($showIdsImploded)"; - $CC_DBC->query($sql); + $con->exec($sql); } } @@ -805,7 +804,7 @@ class Application_Model_Show { return $showInstance; } - + /** * returns info about live stream override info */ @@ -848,7 +847,8 @@ class Application_Model_Show { * @return CcShowInstancesQuery: An propel object representing a * row in the cc_show_instances table. */ public function getInstanceOnDate($p_dateTime){ - global $CC_DBC; + $con = Propel::getConnection(); + $timestamp = $p_dateTime->format("Y-m-d H:i:s"); $showId = $this->getId(); @@ -856,7 +856,8 @@ class Application_Model_Show { ." WHERE date(starts) = date(TIMESTAMP '$timestamp') " ." AND show_id = $showId"; - $row = $CC_DBC->GetOne($sql); + $query = $con->query(); + $row = $query ? $query->fetchColumn(0) : null; return CcShowInstancesQuery::create() ->findPk($row); } @@ -1164,8 +1165,15 @@ class Application_Model_Show { */ public static function populateShowUntil($p_showId) { +<<<<<<< HEAD global $CC_DBC; $date = Application_Model_Preference::GetShowsPopulatedUntil(); +======= + $con = Propel::getConnection(); + + if (is_null($p_dateTime)) { + $date = Application_Model_Preference::GetShowsPopulatedUntil(); +>>>>>>> CC-1927: Remove PEAR DB if (is_null($date)) { $p_populateUntilDateTime = new DateTime("now", new DateTimeZone('UTC')); @@ -1175,7 +1183,7 @@ class Application_Model_Show { } $sql = "SELECT * FROM cc_show_days WHERE show_id = $p_showId"; - $res = $CC_DBC->GetAll($sql); + $res = $con->query($sql)->fetchAll(); foreach ($res as $showRow) { Application_Model_Show::populateShow($showRow, $p_populateUntilDateTime); @@ -1220,8 +1228,13 @@ class Application_Model_Show { */ private static function populateNonRepeatingShow($p_showRow, $p_populateUntilDateTime) { +<<<<<<< HEAD global $CC_DBC; +======= + $con = Propel::getConnection(); + +>>>>>>> CC-1927: Remove PEAR DB $show_id = $p_showRow["show_id"]; $first_show = $p_showRow["first_show"]; //non-UTC $start_time = $p_showRow["start_time"]; //non-UTC @@ -1261,11 +1274,17 @@ class Application_Model_Show { } $sql = "SELECT * FROM cc_show_rebroadcast WHERE show_id={$show_id}"; - $rebroadcasts = $CC_DBC->GetAll($sql); + $rebroadcasts = $con->query($sql)->fetchAll(); //Logging::log('$start time of non repeating record '.$start); +<<<<<<< HEAD self::createRebroadcastInstances($rebroadcasts, $currentUtcTimestamp, $show_id, $show_instance_id, $start, $duration, $timezone); +======= + if ($newInstance) { + self::createRebroadcastInstances($rebroadcasts, $currentUtcTimestamp, $show_id, $show_instance_id, $start, $duration, $timezone); + } +>>>>>>> CC-1927: Remove PEAR DB } } @@ -1283,7 +1302,7 @@ class Application_Model_Show { */ private static function populateRepeatingShow($p_showRow, $p_populateUntilDateTime, $p_interval) { - global $CC_DBC; + $con = Propel::getConnection(); $show_id = $p_showRow["show_id"]; $next_pop_date = $p_showRow["next_pop_date"]; @@ -1308,11 +1327,15 @@ class Application_Model_Show { $utcLastShowDateTime = $last_show ? Application_Common_DateHelper::ConvertToUtcDateTime($last_show, $timezone) : null; $sql = "SELECT * FROM cc_show_rebroadcast WHERE show_id={$show_id}"; - $rebroadcasts = $CC_DBC->GetAll($sql); + $rebroadcasts = $con->query($sql)->fetchAll(); $show = new Application_Model_Show($show_id); +<<<<<<< HEAD while($utcStartDateTime->getTimestamp() <= $p_populateUntilDateTime->getTimestamp() +======= + while ($utcStartDateTime->getTimestamp() <= $p_dateTime->getTimestamp() +>>>>>>> CC-1927: Remove PEAR DB && (is_null($utcLastShowDateTime) || $utcStartDateTime->getTimestamp() < $utcLastShowDateTime->getTimestamp())){ list($utcStartDateTime, $utcEndDateTime) = Application_Model_Show::createUTCStartEndDateTime($start, $duration, $timezone); @@ -1481,7 +1504,7 @@ class Application_Model_Show { */ public static function getShows($start_timestamp, $end_timestamp, $excludeInstance=NULL, $onlyRecord=FALSE) { - global $CC_DBC; + $con = Propel::getConnection(); //UTC DateTime object $showsPopUntil = Application_Model_Preference::GetShowsPopulatedUntil(); @@ -1527,8 +1550,8 @@ class Application_Model_Show { //Logging::log("getShows"); //Logging::log($sql); - - return $CC_DBC->GetAll($sql); + $result = $con->query($sql)->fetchAll(); + return $result; } private static function setNextPop($next_date, $show_id, $day) @@ -1554,7 +1577,7 @@ class Application_Model_Show { */ public static function populateAllShowsInRange($p_startTimestamp, $p_endTimestamp) { - global $CC_DBC; + $con = Propel::getConnection(); $endTimeString = $p_endTimestamp->format("Y-m-d H:i:s"); if (!is_null($p_startTimestamp)) { @@ -1570,8 +1593,7 @@ class Application_Model_Show { OR first_show < '{$endTimeString}' AND last_show > '{$startTimeString}'"; //Logging::log($sql); - - $res = $CC_DBC->GetAll($sql); + $res = $con->query($sql)->fetchAll(); foreach ($res as $row) { Application_Model_Show::populateShow($row, $p_endTimestamp); @@ -1588,22 +1610,18 @@ class Application_Model_Show { */ public static function getFullCalendarEvents($p_start, $p_end, $p_editable=false) { - $events = array(); - $interval = $p_start->diff($p_end); $days = $interval->format('%a'); - $shows = Application_Model_Show::getShows($p_start, $p_end); - $today_timestamp = gmdate("Y-m-d H:i:s"); foreach ($shows as $show) { $options = array(); //only bother calculating percent for week or day view. - - if(intval($days) <= 7) { + + if (intval($days) <= 7) { $options["percent"] = Application_Model_Show::getPercentScheduled($show["starts"], $show["ends"], $show["time_filled"]); } @@ -1612,19 +1630,19 @@ class Application_Model_Show { } $events[] = Application_Model_Show::makeFullCalendarEvent($show, $options); } - + return $events; } - + /** * Calculates the percentage of a show scheduled given the start and end times in date/time format * and the time_filled as the total time the schow is scheduled for in time format. **/ private static function getPercentScheduled($p_starts, $p_ends, $p_time_filled){ - $durationSeconds = (strtotime($p_ends) - strtotime($p_starts)); - $time_filled = Application_Model_Schedule::WallTimeToMillisecs($p_time_filled) / 1000; + $durationSeconds = (strtotime($p_ends) - strtotime($p_starts)); + $time_filled = Application_Model_Schedule::WallTimeToMillisecs($p_time_filled) / 1000; $percent = ceil(( $time_filled / $durationSeconds) * 100); - + return $percent; } @@ -1722,10 +1740,16 @@ class Application_Model_Show { */ public static function GetCurrentShow($timeNow=null) { - global $CC_CONFIG, $CC_DBC; + global $CC_CONFIG; + $con = Propel::getConnection(); if($timeNow == null){ +<<<<<<< HEAD $date = new Application_Common_DateHelper; $timeNow = $date->getUtcTimestamp(); +======= + $date = new Application_Model_DateHelper; + $timeNow = $date->getUtcTimestamp(); +>>>>>>> CC-1927: Remove PEAR DB } //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" @@ -1736,8 +1760,7 @@ class Application_Model_Show { ." AND modified_instance != TRUE"; // Convert back to local timezone - $rows = $CC_DBC->GetAll($sql); - + $rows = $con->query($sql)->fetchAll(); return $rows; } @@ -1746,7 +1769,8 @@ class Application_Model_Show { */ public static function getPrevCurrentNext($p_timeNow) { - global $CC_CONFIG, $CC_DBC; + 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" @@ -1757,15 +1781,15 @@ class Application_Model_Show { ." ORDER BY si.starts"; // Convert back to local timezone - $rows = $CC_DBC->GetAll($sql); + $rows = $con->query($sql)->fetchAll(); $numberOfRows = count($rows); - + $results['previousShow'] = array(); $results['currentShow'] = array(); $results['nextShow'] = array(); - + $timeNowAsMillis = strtotime($p_timeNow); - + for( $i = 0; $i < $numberOfRows; ++$i ){ //Find the show that is within the current time. if ((strtotime($rows[$i]['starts']) <= $timeNowAsMillis) && (strtotime($rows[$i]['ends']) >= $timeNowAsMillis)){ @@ -1779,9 +1803,9 @@ class Application_Model_Show { "starts"=>$rows[$i-1]['starts'], "ends"=>$rows[$i-1]['ends']); } - + $results['currentShow'][0] = $rows[$i]; - + if ( isset($rows[$i+1])){ $results['nextShow'][0] = array( "id"=>$rows[$i+1]['id'], @@ -1791,7 +1815,7 @@ class Application_Model_Show { "end_timestamp"=>$rows[$i+1]['end_timestamp'], "starts"=>$rows[$i+1]['starts'], "ends"=>$rows[$i+1]['ends']); - + } break; } @@ -1826,6 +1850,7 @@ class Application_Model_Show { } return $results; } + /** * Given a start time $timeStart and end time $timeEnd, returns the next $limit * number of shows within the time interval; @@ -1840,11 +1865,12 @@ class Application_Model_Show { */ public static function GetNextShows($timeStart, $limit = "0", $timeEnd = "") { - global $CC_CONFIG, $CC_DBC; + global $CC_CONFIG; + $con = Propel::getConnection(); // defaults to retrieving shows from next 2 days if no end time has // been specified - if($timeEnd == "") { + if ($timeEnd == "") { $timeEnd = "'$timeStart' + INTERVAL '2 days'"; } else { $timeEnd = "'$timeEnd'"; @@ -1864,8 +1890,7 @@ class Application_Model_Show { $sql = $sql . " LIMIT $limit"; } - $rows = $CC_DBC->GetAll($sql); - + $rows = $con->query($sql)->fetchAll(); return $rows; } @@ -1890,14 +1915,16 @@ class Application_Model_Show { } public static function GetMaxLengths() { - global $CC_CONFIG, $CC_DBC; + global $CC_CONFIG; + $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 = $CC_DBC->GetAll($sql); + $result = $con->query($sql)->fetchAll(); // store result into assoc array $assocArray = array(); - foreach($result as $row) { + foreach ($result as $row) { $assocArray[$row['column_name']] = $row['character_maximum_length']; } diff --git a/airtime_mvc/application/models/ShowInstance.php b/airtime_mvc/application/models/ShowInstance.php index a6361dac0..e2af915f9 100644 --- a/airtime_mvc/application/models/ShowInstance.php +++ b/airtime_mvc/application/models/ShowInstance.php @@ -146,8 +146,9 @@ class Application_Model_ShowInstance { $this->_showInstance->getDbModifiedInstance(); } - public function correctScheduleStartTimes(){ - global $CC_DBC; + public function correctScheduleStartTimes() + { + $con = Propel::getConnection(); $instance_id = $this->getShowInstanceId(); $sql = "SELECT starts from cc_schedule" @@ -155,9 +156,9 @@ class Application_Model_ShowInstance { ." ORDER BY starts" ." LIMIT 1"; - $scheduleStarts = $CC_DBC->GetOne($sql); + $scheduleStarts = $con->query($sql)->fetchColumn(0); - if (!is_null($scheduleStarts)){ + if ($scheduleStarts) { $scheduleStartsEpoch = strtotime($scheduleStarts); $showStartsEpoch = strtotime($this->getShowInstanceStart()); @@ -169,7 +170,7 @@ class Application_Model_ShowInstance { ." ends = ends + INTERVAL '$diff' second" ." WHERE instance_id = $instance_id"; - $CC_DBC->query($sql); + $con->exec($sql); } } Application_Model_RabbitMq::PushSchedule(); @@ -300,7 +301,7 @@ class Application_Model_ShowInstance { */ public function resizeShow($deltaDay, $deltaMin) { - global $CC_DBC; + $con = Propel::getConnection(); $hours = $deltaMin/60; if($hours > 0) @@ -319,10 +320,10 @@ class Application_Model_ShowInstance { } $sql = "SELECT timestamp '{$ends}' + interval '{$deltaDay} days' + interval '{$hours}:{$mins}'"; - $new_ends = $CC_DBC->GetOne($sql); + $new_ends = $con->query($sql)->fetchColumn(0); //only need to check overlap if show increased in size. - if(strtotime($new_ends) > strtotime($ends)) { + if (strtotime($new_ends) > strtotime($ends)) { $utcStartDateTime = new DateTime($ends, new DateTimeZone("UTC")); $utcEndDateTime = new DateTime($new_ends, new DateTimeZone("UTC")); @@ -339,7 +340,7 @@ class Application_Model_ShowInstance { 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}"; - $CC_DBC->query($sql); + $con->exec($sql); } $this->setShowEnd($new_ends); @@ -481,8 +482,6 @@ class Application_Model_ShowInstance { public function delete() { - global $CC_DBC; - // see if it was recording show $recording = $this->isRecorded(); // get show id @@ -631,7 +630,7 @@ class Application_Model_ShowInstance { public function getShowListContent() { - global $CC_DBC; + $con = Propel::getConnection(); $sql = "SELECT * FROM (cc_schedule AS s LEFT JOIN cc_files AS f ON f.id = s.file_id) @@ -640,7 +639,7 @@ class Application_Model_ShowInstance { //Logging::log($sql); - $results = $CC_DBC->GetAll($sql); + $results = $con->query($sql)->fetchAll(); foreach ($results as &$row) { @@ -655,16 +654,18 @@ class Application_Model_ShowInstance { return $results; } - - public function getLastAudioItemEnd(){ - global $CC_DBC; + + public function getLastAudioItemEnd() + { + $con = Propel::getConnection(); $sql = "SELECT ends FROM cc_schedule " ."WHERE instance_id = {$this->_instanceId} " ."ORDER BY ends DESC " ."LIMIT 1"; - return $CC_DBC->GetOne($sql); + $query = $con->query($sql)->fetchColumn(0); + return $query ? $query : NULL; } public function getShowEndGapTime(){ @@ -682,25 +683,28 @@ class Application_Model_ShowInstance { } public static function GetLastShowInstance($p_timeNow){ - global $CC_CONFIG, $CC_DBC; + 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"; + ." FROM $CC_CONFIG[showInstances] si" + ." WHERE si.ends < TIMESTAMP '$p_timeNow'" + ." AND si.modified_instance = 'f'" + ." ORDER BY si.ends DESC" + ." LIMIT 1"; - $id = $CC_DBC->GetOne($sql); - if (is_null($id)){ - return null; - } else { + $id = $con->query($sql)->fetchColumn(0); + if ($id) { return new Application_Model_ShowInstance($id); + } else { + return null; } } - public static function GetCurrentShowInstance($p_timeNow){ - global $CC_CONFIG, $CC_DBC; + 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 @@ -709,57 +713,63 @@ class Application_Model_ShowInstance { */ $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"; + ." 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"; - $id = $CC_DBC->GetOne($sql); - if (is_null($id)){ - return null; - } else { + $id = $con->query($sql)->fetchColumn(0); + if ($id) { return new Application_Model_ShowInstance($id); + } else { + return null; } } - public static function GetNextShowInstance($p_timeNow){ - global $CC_CONFIG, $CC_DBC; + 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"; + ." FROM $CC_CONFIG[showInstances] si" + ." WHERE si.starts > TIMESTAMP '$p_timeNow'" + ." AND si.modified_instance = 'f'" + ." ORDER BY si.starts" + ." LIMIT 1"; - $id = $CC_DBC->GetOne($sql); - if (is_null($id)){ - return null; - } else { + $id = $con->query($sql)->fetchColumn(0); + if ($id) { return new Application_Model_ShowInstance($id); + } else { + return null; } } // returns number of show instances that ends later than $day - public static function GetShowInstanceCount($day){ - global $CC_CONFIG, $CC_DBC; + public static function GetShowInstanceCount($day) + { + global $CC_CONFIG; + $con = Propel::getConnection(); $sql = "SELECT count(*) as cnt FROM $CC_CONFIG[showInstances] WHERE ends < '$day'"; - return $CC_DBC->GetOne($sql); + return $con->query($sql)->fetchColumn(0); } - + // 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, $CC_DBC; - + 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 $CC_DBC->GetAll($sql); + + return $con->query($sql)->fetchAll(); } function isRepeating(){ diff --git a/airtime_mvc/application/models/StoredFile.php b/airtime_mvc/application/models/StoredFile.php index 770fecaf8..7347e3f0c 100644 --- a/airtime_mvc/application/models/StoredFile.php +++ b/airtime_mvc/application/models/StoredFile.php @@ -242,16 +242,14 @@ class Application_Model_StoredFile { */ public function setState($p_state, $p_editedby=NULL) { - global $CC_CONFIG, $CC_DBC; + 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 = $CC_DBC->query($sql); - if (PEAR::isError($res)) { - return $res; - } + ." SET state='$escapedState'$eb, mtime=now()" + ." WHERE gunid='{$this->gunid}'"; + $res = $con->exec($sql); $this->state = $p_state; $this->editedby = $p_editedby; return TRUE; @@ -262,11 +260,12 @@ class Application_Model_StoredFile { * @return array */ public function getPlaylists() { - global $CC_CONFIG, $CC_DBC; + global $CC_CONFIG; + $con = Propel::getConnection(); $sql = "SELECT playlist_id " - ." FROM ".$CC_CONFIG['playistTable'] - ." WHERE file_id='{$this->id}'"; - $ids = $CC_DBC->getAll($sql); + ." 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) { @@ -583,7 +582,7 @@ Logging::log("getting media! - 2"); } public static function searchLibraryFiles($datatables) { - + $con = Propel::getConnection(CcFilesPeer::DATABASE_NAME); $displayColumns = array("id", "track_title", "artist_name", "album_title", "genre", "length", @@ -656,7 +655,7 @@ Logging::log("getting media! - 2"); default: $fromTable = $unionTable; } - + $results = Application_Model_Datatables::findEntries($con, $displayColumns, $fromTable, $datatables); //Used by the audio preview functionality in the library. @@ -803,7 +802,7 @@ Logging::log("getting media! - 2"); //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); @@ -820,6 +819,7 @@ Logging::log("getting media! - 2"); $md5 = md5_file($audio_file); $duplicate = Application_Model_StoredFile::RecallByMd5($md5, true); + $result = null; if ($duplicate) { if (PEAR::isError($duplicate)) { @@ -865,9 +865,11 @@ Logging::log("getting media! - 2"); public static function getFileCount() { - global $CC_CONFIG, $CC_DBC; + global $CC_CONFIG; + $con = Propel::getConnection(); + $sql = "SELECT count(*) as cnt FROM ".$CC_CONFIG["filesTable"]." WHERE file_exists"; - return $CC_DBC->GetOne($sql); + return $con->query($sql)->fetchColumn(0); } /** @@ -876,26 +878,27 @@ Logging::log("getting media! - 2"); * @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 */ - public static function listAllFiles($dir_id=null, $propelObj=false){ - global $CC_DBC; + public static function listAllFiles($dir_id=null, $propelObj=false) + { + $con = Propel::getConnection(); - if($propelObj){ + 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{ + } else { $sql = "SELECT filepath as fp" ." FROM CC_FILES" ." WHERE directory = $dir_id and file_exists = 'TRUE'"; } - $rows = $CC_DBC->getAll($sql); + $rows = $con->query($sql)->fetchAll(); $results = array(); - foreach ($rows as $row){ - if($propelObj){ + foreach ($rows as $row) { + if ($propelObj) { $results[] = Application_Model_StoredFile::RecallByFilepath($row["fp"]); - }else{ + } else { $results[] = $row["fp"]; } } diff --git a/airtime_mvc/application/models/StreamSetting.php b/airtime_mvc/application/models/StreamSetting.php index ab05fadb9..7c3d9715f 100644 --- a/airtime_mvc/application/models/StreamSetting.php +++ b/airtime_mvc/application/models/StreamSetting.php @@ -1,19 +1,21 @@ GetOne($sql); + ." WHERE keyname = '$key'"; - if($result == 1) { + $result = $con->query($sql)->fetchColumn(0); + + if ($result == 1) { $sql = "UPDATE cc_stream_setting" ." SET value = '$value', type='$type'" ." WHERE keyname = '$key'"; @@ -21,139 +23,146 @@ class Application_Model_StreamSetting { $sql = "INSERT INTO cc_stream_setting (keyname, value, type)" ." VALUES ('$key', '$value', '$type')"; } - - return $CC_DBC->query($sql); + + return $con->exec($sql); } - - public static function GetValue($key){ - global $CC_CONFIG, $CC_DBC; - + + public static function GetValue($key) + { + global $CC_CONFIG; + $con = Propel::getConnection(); + //Check if key already exists $sql = "SELECT COUNT(*) FROM cc_stream_setting" ." WHERE keyname = '$key'"; - $result = $CC_DBC->GetOne($sql); + $result = $con->query($sql)->fetchColumn(0); if ($result == 0) return ""; else { $sql = "SELECT value FROM cc_stream_setting" - ." WHERE keyname = '$key'"; - - $result = $CC_DBC->GetOne($sql); - return $result; + ." WHERE keyname = '$key'"; + + $result = $con->query($sql)->fetchColumn(0); + return $result ? $result : NULL; } } /* Returns the id's of all streams that are enabled in an array. An * example of the array returned in JSON notation is ["s1", "s2", "s3"] */ - public static function getEnabledStreamIds(){ - global $CC_DBC; + public static function getEnabledStreamIds() + { + $con = Propel::getConnection(); $sql = "SELECT * " ."FROM cc_stream_setting " ."WHERE keyname LIKE '%_enable' " ."AND value='true'"; - $rows = $CC_DBC->getAll($sql); + $rows = $con->query($sql)->fetchAll(); $ids = array(); - foreach ($rows as $row){ + foreach ($rows as $row) { $ids[] = substr($row["keyname"], 0, strpos($row["keyname"], "_")); } //Logging::log(print_r($ids, true)); - return $ids; } - - /* Retruns only global data as array*/ - public static function getGlobalData(){ - global $CC_DBC; - $sql = "SELECT * " - ."FROM cc_stream_setting " - ."WHERE keyname IN ('output_sound_device', 'icecast_vorbis_metadata')"; - - $rows = $CC_DBC->getAll($sql); - $data = array(); - - foreach($rows as $row){ - $data[$row["keyname"]] = $row["value"]; - } - - return $data; - } - /* Returns all information related to a specific stream. An example - * of a stream id is 's1' or 's2'. */ - public static function getStreamData($p_streamId){ - global $CC_DBC; - $sql = "SELECT * " - ."FROM cc_stream_setting " - ."WHERE keyname LIKE '${p_streamId}_%'"; - $rows = $CC_DBC->getAll($sql); + /* Returns only global data as array*/ + public static function getGlobalData() + { + $con = Propel::getConnection(); + $sql = "SELECT * " + ."FROM cc_stream_setting " + ."WHERE keyname IN ('output_sound_device', 'icecast_vorbis_metadata')"; + + $rows = $con->query($sql)->fetchAll(); $data = array(); - foreach($rows as $row){ + foreach ($rows as $row) { $data[$row["keyname"]] = $row["value"]; } return $data; } - - public static function getStreamSetting(){ - global $CC_DBC; + + /* Returns all information related to a specific stream. An example + * of a stream id is 's1' or 's2'. */ + public static function getStreamData($p_streamId) + { + $con = Propel::getConnection(); + $sql = "SELECT * " + ."FROM cc_stream_setting " + ."WHERE keyname LIKE '${p_streamId}_%'"; + + $rows = $con->query($sql)->fetchAll(); + $data = array(); + + foreach ($rows as $row) { + $data[$row["keyname"]] = $row["value"]; + } + + return $data; + } + + public static function getStreamSetting() + { + $con = Propel::getConnection(); $sql = "SELECT *" ." FROM cc_stream_setting" ." WHERE keyname not like '%_error'"; - $rows = $CC_DBC->getAll($sql); - + $rows = $con->query($sql)->fetchAll(); + $exists = array(); - - foreach($rows as $r){ - if($r['keyname'] == 'master_live_stream_port'){ + + 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"])){ + + if (!isset($exists["master_live_stream_port"])) { $rows[] = (array("keyname" =>"master_live_stream_port", "value"=>self::GetMasterLiveSteamPort(), "type"=>"integer")); } - if(!isset($exists["master_live_stream_mp"])){ + if (!isset($exists["master_live_stream_mp"])) { $rows[] = (array("keyname" =>"master_live_stream_mp", "value"=>self::GetMasterLiveSteamMountPoint(), "type"=>"string")); } - if(!isset($exists["dj_live_stream_port"])){ + if (!isset($exists["dj_live_stream_port"])) { $rows[] = (array("keyname" =>"dj_live_stream_port", "value"=>self::GetDJLiveSteamPort(), "type"=>"integer")); } - if(!isset($exists["dj_live_stream_mp"])){ + if (!isset($exists["dj_live_stream_mp"])) { $rows[] = (array("keyname" =>"dj_live_stream_mp", "value"=>self::GetDJLiveSteamMountPoint(), "type"=>"string")); } return $rows; } - + /* * function that take all the information of stream and sets them. * This is used by stream setting via UI. - * + * * @param $data - array that contains all the data. $data is [][] which * contains multiple stream information */ - public static function setStreamSetting($data){ - global $CC_DBC; - + public static function setStreamSetting($data) + { + $con = Propel::getConnection(); + 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'"; - $CC_DBC->query($sql); + $con->exec($sql); } else if ($key == "output_sound_device_type") { $sql = "UPDATE cc_stream_setting SET value='$d' WHERE keyname='$key'"; - $CC_DBC->query($sql); + $con->exec($sql); } else if (is_array($d)) { $temp = explode('_', $key); $prefix = $temp[0]; @@ -164,71 +173,75 @@ class Application_Model_StreamSetting { } $v = trim($v); $sql = "UPDATE cc_stream_setting SET value='$v' WHERE keyname='$keyname'"; - $CC_DBC->query($sql); + $con->exec($sql); } } else { Logging::log("Warning unexpected value: ".$key); } } } - + /* * Sets indivisual stream setting. - * + * * $data - data array. $data is []. */ - public static function setIndivisualStreamSetting($data){ - global $CC_DBC; - - foreach($data as $keyname => $v){ + public static function setIndivisualStreamSetting($data) + { + $con = Propel::getConnection(); + + foreach ($data as $keyname => $v) { $sql = "UPDATE cc_stream_setting SET value='$v' WHERE keyname='$keyname'"; - $CC_DBC->query($sql); + $con->exec($sql); } } - + /* * 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){ - global $CC_DBC; - + public static function setLiquidsoapError($stream_id, $msg, $boot_time=null) + { + $con = Propel::getConnection(); + $update_time = Application_Model_Preference::GetStreamUpdateTimestemp(); - if($boot_time == null || $boot_time > $update_time ){ + 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 = $CC_DBC->GetOne($sql); - if ($result == 1){ + $result = $con->query($sql)->fetchColumn(0); + if ($result == 1) { $sql = "UPDATE cc_stream_setting" ." SET value = '$msg'" ." WHERE keyname = '$keyname'"; - }else{ + } else { $sql = "INSERT INTO cc_stream_setting (keyname, value, type)" ." VALUES ('$keyname', '$msg', 'string')"; } - $res = $CC_DBC->query($sql); + $res = $con->exec($sql); } } - - public static function getLiquidsoapError($stream_id){ - global $CC_DBC; - + + public static function getLiquidsoapError($stream_id) + { + $con = Propel::getConnection(); + $keyname = "s".$stream_id."_liquidsoap_error"; $sql = "SELECT value FROM cc_stream_setting" ." WHERE keyname = '$keyname'"; - $result = $CC_DBC->GetOne($sql); - - return $result; + $result = $con->query($sql)->fetchColumn(0); + + return $result ? $result : NULL; } - - public static function getStreamEnabled($stream_id){ - global $CC_DBC; - + + public static function getStreamEnabled($stream_id) + { + $con = Propel::getConnection(); + $keyname = "s" . $stream_id . "_enable"; $sql = "SELECT value FROM cc_stream_setting" ." WHERE keyname = '$keyname'"; - $result = $CC_DBC->GetOne($sql); + $result = $con->query($sql)->fetchColumn(0); if ($result == 'false') { $result = false; } else { @@ -236,62 +249,63 @@ class Application_Model_StreamSetting { } return $result; } - + /* * Only returns info that is needed for data collection * returns array('s1'=>array(keyname=>value)) */ - public static function getStreamInfoForDataCollection(){ - global $CC_DBC; - + public static function getStreamInfoForDataCollection() + { + $con = Propel::getConnection(); + $out = array(); $enabled_stream = self::getEnabledStreamIds(); - - foreach($enabled_stream as $stream){ + + foreach ($enabled_stream as $stream) { $keys = "'".$stream."_output', "."'".$stream."_type', "."'".$stream."_bitrate', "."'".$stream."_host'"; - + $sql = "SELECT keyname, value FROM cc_stream_setting" - ." WHERE keyname IN ($keys)"; - - $rows = $CC_DBC->getAll($sql); + ." WHERE keyname IN ($keys)"; + + $rows = $con->query($sql)->fetchAll(); $info = array(); - foreach($rows as $r){ + foreach ($rows as $r) { $temp = explode("_", $r['keyname']); $info[$temp[1]] = $r['value']; - $out[$stream] = $info; + $out[$stream] = $info; } } return $out; } - + public static function SetMasterLiveSteamPort($value){ self::SetValue("master_live_stream_port", $value, "integer"); } - + public static function GetMasterLiveSteamPort(){ return self::GetValue("master_live_stream_port"); } - + public static function SetMasterLiveSteamMountPoint($value){ self::SetValue("master_live_stream_mp", $value, "string"); } - + public static function GetMasterLiveSteamMountPoint(){ return self::GetValue("master_live_stream_mp"); } - + public static function SetDJLiveSteamPort($value){ self::SetValue("dj_live_stream_port", $value, "integer"); } - + public static function GetDJLiveSteamPort(){ return self::GetValue("dj_live_stream_port"); } - + public static function SetDJLiveSteamMountPoint($value){ self::SetValue("dj_live_stream_mp", $value, "string"); } - + public static function GetDJLiveSteamMountPoint(){ return self::GetValue("dj_live_stream_mp"); } diff --git a/airtime_mvc/application/models/Subjects.php b/airtime_mvc/application/models/Subjects.php index 59eeefff1..45c672b61 100644 --- a/airtime_mvc/application/models/Subjects.php +++ b/airtime_mvc/application/models/Subjects.php @@ -28,16 +28,15 @@ class Application_Model_Subjects { */ public static function Authenticate($login, $pass='') { - global $CC_CONFIG, $CC_DBC; + 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'"; - $id = $CC_DBC->getOne($sql); - if (PEAR::isError($id)) { - return $id; - } - return (is_null($id) ? FALSE : $id); - } // fn authenticate + ." WHERE login='$login' AND pass='$cpass' AND type='U'" + ." LIMIT 1"; + $query = $con->query($sql)->fetchColumn(0); + return $query; + } /** @@ -54,7 +53,8 @@ class Application_Model_Subjects { */ public static function Passwd($login, $oldpass=null, $pass='', $passenc=FALSE) { - global $CC_CONFIG, $CC_DBC; + global $CC_CONFIG; + $con = Propel::getConnection(); if (!$passenc) { $cpass = md5($pass); } else { @@ -68,12 +68,9 @@ class Application_Model_Subjects { } $sql = "UPDATE ".$CC_CONFIG['subjTable']." SET pass='$cpass'" ." WHERE login='$login' $oldpCond AND type='U'"; - $r = $CC_DBC->query($sql); - if (PEAR::isError($r)) { - return $r; - } + $con->exec($sql); return TRUE; - } // fn passwd + } /* --------------------------------------------------------------- groups */ @@ -84,20 +81,21 @@ class Application_Model_Subjects { * Get subject id from login * * @param string $login - * @return int|PEAR_Error + * @return int|false */ public static function GetSubjId($login) { global $CC_CONFIG; - global $CC_DBC; + $con = Propel::getConnection(); $sql = "SELECT id FROM ".$CC_CONFIG['subjTable'] ." WHERE login='$login'"; - return $CC_DBC->getOne($sql); - } // fn getSubjId + $query = $con->query($sql)->fetchColumn(0); + return $query ? $query : NULL; + } /** - * Return true if uid is [id]direct member of gid + * Return true if uid is direct member of gid * * @param int $uid * local user id @@ -107,47 +105,42 @@ class Application_Model_Subjects { */ public static function IsMemberOf($uid, $gid) { - global $CC_CONFIG, $CC_DBC; - $sql = "SELECT count(*)as cnt" + global $CC_CONFIG; + $con = Propel::getConnection(); + $sql = "SELECT count(*) as cnt" ." FROM ".$CC_CONFIG['smembTable'] ." WHERE uid='$uid' AND gid='$gid'"; - $res = $CC_DBC->getOne($sql); - if (PEAR::isError($res)) { - return $res; - } + $res = $con->query($sql)->fetchColumn(0); return (intval($res) > 0); - } // fn isMemberOf + } - public static function increaseLoginAttempts($login){ - global $CC_CONFIG, $CC_DBC; + public static function increaseLoginAttempts($login) + { + global $CC_CONFIG; + $con = Propel::getConnection(); $sql = "UPDATE ".$CC_CONFIG['subjTable']." SET login_attempts = login_attempts+1" ." WHERE login='$login'"; - $res = $CC_DBC->query($sql); - if (PEAR::isError($res)) { - return $res; - } + $res = $con->exec($sql); return (intval($res) > 0); } - - public static function resetLoginAttempts($login){ - global $CC_CONFIG, $CC_DBC; + + public static function resetLoginAttempts($login) + { + global $CC_CONFIG; + $con = Propel::getConnection(); $sql = "UPDATE ".$CC_CONFIG['subjTable']." SET login_attempts = '0'" ." WHERE login='$login'"; - $res = $CC_DBC->query($sql); - if (PEAR::isError($res)) { - return $res; - } - return (intval($res) > 0); + $res = $con->exec($sql); + return TRUE; } - - public static function getLoginAttempts($login){ - global $CC_CONFIG, $CC_DBC; + + public static function getLoginAttempts($login) + { + global $CC_CONFIG; + $con = Propel::getConnection(); $sql = "SELECT login_attempts FROM ".$CC_CONFIG['subjTable']." WHERE login='$login'"; - $res = $CC_DBC->getOne($sql); - if (PEAR::isError($res)) { - return $res; - } - return $res; + $res = $con->query($sql)->fetchColumn(0); + return $res ? $res : 0; } } // class Subjects diff --git a/airtime_mvc/application/models/User.php b/airtime_mvc/application/models/User.php index 5c0d701df..f09af3371 100644 --- a/airtime_mvc/application/models/User.php +++ b/airtime_mvc/application/models/User.php @@ -26,7 +26,7 @@ class Application_Model_User { public function getId() { return $this->_userInstance->getDbId(); } - + public function isGuest() { return $this->getType() == UTYPE_GUEST; } @@ -34,7 +34,7 @@ class Application_Model_User { public function isHost($showId) { return $this->isUserType(UTYPE_HOST, $showId); } - + public function isPM() { return $this->isUserType(UTYPE_PROGRAM_MANAGER); } @@ -185,15 +185,14 @@ class Application_Model_User { return $user; } - public static function getUsers($type, $search=NULL) { - global $CC_DBC; - - $sql; + public static function getUsers($type, $search=NULL) + { + $con = Propel::getConnection(); $sql_gen = "SELECT login AS value, login AS label, id as index FROM cc_subjs "; $sql = $sql_gen; - if(is_array($type)) { + if (is_array($type)) { for($i=0; $iGetAll($sql); + return $con->query($sql)->fetchAll();; } public static function getUserCount($type=NULL){ - global $CC_DBC; - - $sql; - + $con = Propel::getConnection(); + $sql = ''; $sql_gen = "SELECT count(*) AS cnt FROM cc_subjs "; - if(!isset($type)){ + if (!isset($type)) { $sql = $sql_gen; } else{ - if(is_array($type)) { - for($i=0; $iGetOne($sql); + $query = $con->query($sql)->fetchColumn(0); + return $query ? $query : NULL; } public static function getHosts($search=NULL) { @@ -248,7 +246,7 @@ class Application_Model_User { } public static function getUsersDataTablesInfo($datatables) { - + $con = Propel::getConnection(CcSubjsPeer::DATABASE_NAME); $displayColumns = array("id", "login", "first_name", "last_name", "type"); @@ -263,7 +261,7 @@ 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){ @@ -277,13 +275,13 @@ class Application_Model_User { } public static function getUserData($id){ - global $CC_DBC; + $con = Propel::getConnection(); $sql = "SELECT login, first_name, last_name, type, id, email, skype_contact, jabber_contact" ." FROM cc_subjs" ." WHERE id = $id"; - return $CC_DBC->GetRow($sql); + return $con->query($sql)->fetch(); } public static function GetUserID($login){ From 95d69a3bbe634ec5dddc2594b383f57d69b849d6 Mon Sep 17 00:00:00 2001 From: "paul.baranowski" Date: Sun, 1 Apr 2012 23:39:15 -0400 Subject: [PATCH 09/15] CC-1927: Remove PEAR DB Fixed all install/upgrade scripts. --- airtime_mvc/application/Bootstrap.php | 14 +- .../configs/airtime-conf-production.php | 8 +- install_minimal/include/AirtimeInstall.php | 174 +++--- .../include/airtime-db-install.php | 19 +- install_minimal/include/airtime-install.php | 6 +- install_minimal/include/airtime-uninstall.php | 19 +- install_minimal/include/airtime-upgrade.php | 45 +- .../airtime-1.8.0/airtime-upgrade.php | 5 +- .../airtime-1.9.0/airtime-upgrade.php | 84 ++- .../upgrades/airtime-2.0.0/UpgradeCommon.php | 53 +- .../airtime-2.0.0/airtime-upgrade-old.php | 586 ------------------ .../airtime-2.0.0/airtime-upgrade.php | 127 ++-- .../upgrades/airtime-2.0.1/UpgradeCommon.php | 58 +- .../airtime-2.0.1/airtime-upgrade-old.php | 586 ------------------ .../upgrades/airtime-2.0.2/UpgradeCommon.php | 58 +- .../airtime-2.0.2/airtime-upgrade-old.php | 586 ------------------ .../upgrade-template/UpgradeCommon.php | 63 +- 17 files changed, 351 insertions(+), 2140 deletions(-) delete mode 100644 install_minimal/upgrades/airtime-2.0.0/airtime-upgrade-old.php delete mode 100644 install_minimal/upgrades/airtime-2.0.1/airtime-upgrade-old.php delete mode 100644 install_minimal/upgrades/airtime-2.0.2/airtime-upgrade-old.php diff --git a/airtime_mvc/application/Bootstrap.php b/airtime_mvc/application/Bootstrap.php index e7f4ac90e..99ed6c71b 100644 --- a/airtime_mvc/application/Bootstrap.php +++ b/airtime_mvc/application/Bootstrap.php @@ -17,7 +17,7 @@ require_once "DateHelper.php"; require_once "OsPath.php"; require_once __DIR__.'/controllers/plugins/RabbitMqPlugin.php'; -global $CC_CONFIG, $CC_DBC; +global $CC_CONFIG; //, $CC_DBC; $dsn = $CC_CONFIG['dsn']; // ****************************************************************** @@ -27,6 +27,7 @@ $dsn = $CC_CONFIG['dsn']; // PDO returns false // ****************************************************************** + // $CC_DBC = DB::connect($dsn, FALSE); // if (PEAR::isError($CC_DBC)) { // echo "ERROR: ".$CC_DBC->getMessage()." ".$CC_DBC->getUserInfo()."\n"; @@ -41,9 +42,14 @@ $dsn = $CC_CONFIG['dsn']; // $result = $CC_DBC->GetOne($sql); // var_dump($result); -// $con = Propel::getConnection(); -// $q = $con->query($sql); -// //var_dump($q); +// $sql = "SELECT 1"; +// try { +// $con = Propel::getConnection(); +// //$q = $con->query($sql); +// } catch (Exception $e) { +// var_dump($e); +// } +// var_dump($q); // //var_dump($q->fetchAll()); // var_dump($q->fetchColumn(0)); diff --git a/airtime_mvc/application/configs/airtime-conf-production.php b/airtime_mvc/application/configs/airtime-conf-production.php index 5ae3a44cb..78e26d9d3 100644 --- a/airtime_mvc/application/configs/airtime-conf-production.php +++ b/airtime_mvc/application/configs/airtime-conf-production.php @@ -7,7 +7,7 @@ * our custom changes requires the database parameters to be loaded from /etc/airtime/airtime.conf so * that the user can customize these. */ - + global $CC_CONFIG; @@ -17,12 +17,12 @@ $dbuser = $CC_CONFIG['dsn']['username']; $dbpass = $CC_CONFIG['dsn']['password']; $conf = array ( - 'datasources' => + 'datasources' => array ( - 'airtime' => + 'airtime' => array ( 'adapter' => 'pgsql', - 'connection' => + 'connection' => array ( 'dsn' => "pgsql:host=$dbhost;port=5432;dbname=$dbname;user=$dbuser;password=$dbpass", ), diff --git a/install_minimal/include/AirtimeInstall.php b/install_minimal/include/AirtimeInstall.php index aa9ebc545..4b8819178 100644 --- a/install_minimal/include/AirtimeInstall.php +++ b/install_minimal/include/AirtimeInstall.php @@ -5,7 +5,6 @@ if (file_exists('/usr/share/php/libzend-framework-php')){ set_include_path('/usr/share/php/libzend-framework-php' . PATH_SEPARATOR . get_include_path()); } require_once('Zend/Loader/Autoloader.php'); -require_once('DB.php'); class AirtimeInstall { @@ -41,61 +40,46 @@ class AirtimeInstall public static function GetVersionInstalled() { - global $CC_DBC, $CC_CONFIG; + global $CC_CONFIG; + $con = Propel::getConnection(); - if(file_exists('/etc/airtime/airtime.conf')) { + if (file_exists('/etc/airtime/airtime.conf')) { $values = parse_ini_file('/etc/airtime/airtime.conf', true); } else { - //echo "New Airtime Install.".PHP_EOL; return null; } - // Database config - $CC_CONFIG['dsn']['username'] = $values['database']['dbuser']; - $CC_CONFIG['dsn']['password'] = $values['database']['dbpass']; - $CC_CONFIG['dsn']['hostspec'] = $values['database']['host']; - $CC_CONFIG['dsn']['phptype'] = 'pgsql'; - $CC_CONFIG['dsn']['database'] = $values['database']['dbname']; + $sql = "SELECT valstr FROM cc_pref WHERE keystr = 'system_version' LIMIT 1"; + $version = $con->query($sql)->fetchColumn(0); - $CC_DBC = DB::connect($CC_CONFIG['dsn'], FALSE); - if (PEAR::isError($CC_DBC)) { - //echo "New Airtime Install.".PHP_EOL; + if (!$version) { + // no pref table something is wrong. return null; } - else { - $CC_DBC->setFetchMode(DB_FETCHMODE_ASSOC); - $sql = "SELECT valstr FROM cc_pref WHERE keystr = 'system_version'"; - $version = $CC_DBC->GetOne($sql); - - if (PEAR::isError($version)) { - // no pref table something is wrong. - return null; + if ($version == '') { + $sql = "SELECT * FROM cc_show_rebroadcast LIMIT 1"; + $result = $con->query($sql)->fetchColumn(0); + if (!PEAR::isError($result)) { + $version = "1.7.0"; + //echo "Airtime Version: ".$version." ".PHP_EOL; } - - if ($version == '') { - $sql = "SELECT * FROM cc_show_rebroadcast LIMIT 1"; - $result = $CC_DBC->GetOne($sql); - if (!PEAR::isError($result)) { - $version = "1.7.0"; - //echo "Airtime Version: ".$version." ".PHP_EOL; - } - else { - $version = false; - } + else { + $version = false; } - - return $version; } + + return $version; } public static function DbTableExists($p_name) { - global $CC_DBC; - $sql = "SELECT * FROM ".$p_name; - $result = $CC_DBC->GetOne($sql); - if (PEAR::isError($result)) { + $con = Propel::getConnection(); + try { + $sql = "SELECT * FROM ".$p_name." LIMIT 1"; + $con->query($sql); + } catch (PDOException $e){ return false; } return true; @@ -103,35 +87,46 @@ class AirtimeInstall public static function InstallQuery($sql, $verbose = true) { - global $CC_DBC; - $result = $CC_DBC->query($sql); - if (PEAR::isError($result)) { - echo "Error! ".$result->getMessage()."\n"; - echo " SQL statement was:\n"; - echo " ".$sql."\n\n"; - } else { + $con = Propel::getConnection(); + try { + $con->exec($sql); if ($verbose) { echo "done.\n"; } + } catch (Exception $e) { + echo "Error!\n".$e->getMessage()."\n"; + echo " SQL statement was:\n"; + echo " ".$sql."\n\n"; } } + public static function DropSequence($p_sequenceName) + { + AirtimeInstall::InstallQuery("DROP SEQUENCE IF EXISTS $p_sequenceName"); + } + + /** + * Try to connect to the database. Return true on success, false on failure. + * @param boolean $p_exitOnError + * Exit the program on failure. + * @return boolean + */ public static function DbConnect($p_exitOnError = true) { - global $CC_DBC, $CC_CONFIG; - $CC_DBC = DB::connect($CC_CONFIG['dsn'], FALSE); - if (PEAR::isError($CC_DBC)) { - echo $CC_DBC->getMessage().PHP_EOL; - echo $CC_DBC->getUserInfo().PHP_EOL; - echo "Database connection problem.".PHP_EOL; - echo "Check if database '{$CC_CONFIG['dsn']['database']}' exists". - " with corresponding permissions.".PHP_EOL; - if ($p_exitOnError) { - exit(1); + global $CC_CONFIG; + try { + $con = Propel::getConnection(); + } catch (Exception $e) { + echo $e->getMessage().PHP_EOL; + echo "Database connection problem.".PHP_EOL; + echo "Check if database '{$CC_CONFIG['dsn']['database']}' exists". + " with corresponding permissions.".PHP_EOL; + if ($p_exitOnError) { + exit(1); } - } else { - $CC_DBC->setFetchMode(DB_FETCHMODE_ASSOC); + return false; } + return true; } @@ -139,7 +134,7 @@ class AirtimeInstall * install script. */ public static function InstallStorageDirectory() { - global $CC_CONFIG, $CC_DBC; + global $CC_CONFIG; echo "* Storage directory setup".PHP_EOL; $ini = parse_ini_file(__DIR__."/airtime-install.ini"); @@ -231,10 +226,11 @@ class AirtimeInstall public static function InstallPostgresScriptingLanguage() { - global $CC_DBC; + $con = Propel::getConnection(); // Install postgres scripting language - $langIsInstalled = $CC_DBC->GetOne('SELECT COUNT(*) FROM pg_language WHERE lanname = \'plpgsql\''); + $sql = 'SELECT COUNT(*) FROM pg_language WHERE lanname = \'plpgsql\''; + $langIsInstalled = $con->query($sql)->fetchColumn(0); if ($langIsInstalled == '0') { echo " * Installing Postgres scripting language".PHP_EOL; $sql = "CREATE LANGUAGE 'plpgsql'"; @@ -250,15 +246,15 @@ class AirtimeInstall // Put Propel sql files in Database //$command = AirtimeInstall::CONF_DIR_WWW."/library/propel/generator/bin/propel-gen ".AirtimeInstall::CONF_DIR_WWW."/build/ insert-sql 2>/dev/null"; - + $dir = AirtimeInstall::CONF_DIR_WWW."/build/sql/"; $files = array("schema.sql", "sequences.sql", "views.sql", "triggers.sql", "defaultdata.sql"); - + foreach ($files as $f){ $command = "export PGPASSWORD=$p_dbpasswd && psql --username $p_dbuser --dbname $p_dbname --host $p_dbhost --file $dir$f 2>/dev/null"; @exec($command, $output, $results); } - + AirtimeInstall::$databaseTablesCreated = true; } @@ -284,13 +280,13 @@ class AirtimeInstall public static function SetAirtimeVersion($p_version) { - global $CC_DBC; + $con = Propel::getConnection(); $sql = "DELETE FROM cc_pref WHERE keystr = 'system_version'"; - $CC_DBC->query($sql); + $con->exec($sql); $sql = "INSERT INTO cc_pref (keystr, valstr) VALUES ('system_version', '$p_version')"; - $result = $CC_DBC->query($sql); - if (PEAR::isError($result)) { + $result = $con->exec($sql); + if ($result < 1) { return false; } return true; @@ -298,54 +294,46 @@ class AirtimeInstall public static function SetUniqueId() { - global $CC_DBC; - + $con = Propel::getConnection(); $uniqueId = md5(uniqid("", true)); $sql = "INSERT INTO cc_pref (keystr, valstr) VALUES ('uniqueId', '$uniqueId')"; - $result = $CC_DBC->query($sql); - if (PEAR::isError($result)) { + $result = $con->exec($sql); + if ($result < 1) { return false; } return true; } - + public static function SetDefaultTimezone() { - global $CC_DBC; - + $con = Propel::getConnection(); $defaultTimezone = exec("cat /etc/timezone"); - $sql = "INSERT INTO cc_pref (keystr, valstr) VALUES ('timezone', '$defaultTimezone')"; - $result = $CC_DBC->query($sql); - if (PEAR::isError($result)) { + $result = $con->exec($sql); + if ($result < 1) { return false; } return true; } - + public static function SetImportTimestamp() { - global $CC_DBC; - + $con = Propel::getConnection(); $sql = "INSERT INTO cc_pref (keystr, valstr) VALUES ('import_timestamp', '0')"; - $result = $CC_DBC->query($sql); - if (PEAR::isError($result)) { + $result = $con->exec($sql); + if ($result < 1) { return false; } return true; } - + public static function GetAirtimeVersion() { - global $CC_DBC; - $sql = "SELECT valstr FROM cc_pref WHERE keystr = 'system_version'"; - $version = $CC_DBC->GetOne($sql); - - if (PEAR::isError($version)) { - return false; - } + $con = Propel::getConnection(); + $sql = "SELECT valstr FROM cc_pref WHERE keystr = 'system_version' LIMIT 1"; + $version = $con->query($sql)->fetchColumn(0); return $version; } @@ -473,21 +461,21 @@ class AirtimeInstall fwrite($fp, "$minute $hour * * * root /usr/lib/airtime/utils/phone_home_stat\n"); fclose($fp); } - + public static function removeVirtualEnvDistributeFile(){ echo "* Removing distribute-0.6.10.tar.gz".PHP_EOL; if(file_exists('/usr/share/python-virtualenv/distribute-0.6.10.tar.gz')){ exec("rm -f /usr/share/python-virtualenv/distribute-0.6.10.tar.gz"); } } - + public static function printUsage($opts) { $msg = $opts->getUsageMessage(); echo PHP_EOL."Usage: airtime-install [options]"; echo substr($msg, strpos($msg, "\n")).PHP_EOL; } - + public static function getOpts() { try { diff --git a/install_minimal/include/airtime-db-install.php b/install_minimal/include/airtime-db-install.php index b582b5f9b..8fc21f6b6 100644 --- a/install_minimal/include/airtime-db-install.php +++ b/install_minimal/include/airtime-db-install.php @@ -5,13 +5,15 @@ * cannot be created. So this script is run after all DEB packages have been installed. */ -set_include_path(__DIR__.'/../airtime_mvc/library' . PATH_SEPARATOR . get_include_path()); +//set_include_path(__DIR__.'/../airtime_mvc/library' . PATH_SEPARATOR . get_include_path()); -require_once(dirname(__FILE__).'/AirtimeIni.php'); -require_once(dirname(__FILE__).'/AirtimeInstall.php'); +require_once(__DIR__.'/AirtimeIni.php'); +require_once(__DIR__.'/AirtimeInstall.php'); require_once(__DIR__.'/airtime-constants.php'); require_once(AirtimeInstall::GetAirtimeSrcDir().'/application/configs/conf.php'); +require_once 'propel/runtime/lib/Propel.php'; +Propel::init(AirtimeInstall::GetAirtimeSrcDir()."/application/configs/airtime-conf-production.php"); echo PHP_EOL."* Database Installation".PHP_EOL; @@ -19,7 +21,7 @@ AirtimeInstall::CreateDatabaseUser(); $databaseExisted = AirtimeInstall::CreateDatabase(); -AirtimeInstall::DbConnect(true); +//AirtimeInstall::DbConnect(true); AirtimeInstall::InstallPostgresScriptingLanguage(); @@ -65,12 +67,13 @@ if (AirtimeInstall::$databaseTablesCreated) { $stor_dir = realpath($ini["storage_dir"])."/"; echo " * Inserting stor directory location $stor_dir into music_dirs table".PHP_EOL; - + $con = Propel::getConnection(); $sql = "INSERT INTO cc_music_dirs (directory, type) VALUES ('$stor_dir', 'stor')"; - $result = $CC_DBC->query($sql); - if (PEAR::isError($result)) { + try { + $con->exec($sql); + } catch (Exception $e) { echo " * Failed inserting {$stor_dir} in cc_music_dirs".PHP_EOL; - echo " * Message {$result->getMessage()}".PHP_EOL; + echo " * Message {$e->getMessage()}".PHP_EOL; exit(1); } } diff --git a/install_minimal/include/airtime-install.php b/install_minimal/include/airtime-install.php index dc6790cb4..281c346f8 100644 --- a/install_minimal/include/airtime-install.php +++ b/install_minimal/include/airtime-install.php @@ -7,8 +7,8 @@ * Checks if a previous version of Airtime is currently installed and upgrades Airtime if so. * Performs a new install (new configs, database install) otherwise. */ -require_once(dirname(__FILE__).'/AirtimeIni.php'); -require_once(dirname(__FILE__).'/AirtimeInstall.php'); +require_once(__DIR__.'/AirtimeIni.php'); +require_once(__DIR__.'/AirtimeInstall.php'); require_once(__DIR__.'/airtime-constants.php'); $version = AirtimeInstall::GetVersionInstalled(); @@ -18,7 +18,7 @@ $version = AirtimeInstall::GetVersionInstalled(); // ------------------------------------------------------------------------- $newInstall = false; -if(is_null($version)) { +if (is_null($version)) { $newInstall = true; } diff --git a/install_minimal/include/airtime-uninstall.php b/install_minimal/include/airtime-uninstall.php index 44a7d4126..0bfc38b63 100644 --- a/install_minimal/include/airtime-uninstall.php +++ b/install_minimal/include/airtime-uninstall.php @@ -25,8 +25,8 @@ echo "* Uninstalling Airtime ".AIRTIME_VERSION.PHP_EOL; //------------------------------------------------------------------------ // Delete the database // Note: Do not put a call to AirtimeInstall::DbConnect() -// before this function, even if you called $CC_DBC->disconnect(), there will -// still be a connection to the database and you wont be able to delete it. +// before this function, it will create a connection to the database +// and you wont be able to delete it. //------------------------------------------------------------------------ //close connection for any process id using airtime database since we are about to drop the database. @@ -47,12 +47,14 @@ $command = "su postgres -c \"dropdb ".$CC_CONFIG["dsn"]["database"]."\""; //------------------------------------------------------------------------ if ($dbDeleteFailed) { echo " * Couldn't delete the database, so deleting all the DB tables...".PHP_EOL; - AirtimeInstall::DbConnect(false); + $connected = AirtimeInstall::DbConnect(false); - if (!PEAR::isError($CC_DBC)) { + if ($connected) { + $con = Propel::getConnection(); $sql = "select * from pg_tables where tableowner = 'airtime'"; - $rows = $CC_DBC->GetAll($sql); - if (PEAR::isError($rows)) { + try { + $rows = $con->query($sql)->fetchAll(); + } catch (Exception $e) { $rows = array(); } @@ -60,11 +62,10 @@ if ($dbDeleteFailed) { $tablename = $row["tablename"]; echo " * Removing database table $tablename..."; - if (AirtimeInstall::DbTableExists($tablename)){ + if (AirtimeInstall::DbTableExists($tablename)) { $sql = "DROP TABLE $tablename CASCADE"; AirtimeInstall::InstallQuery($sql, false); - - $CC_DBC->dropSequence($tablename."_id"); + AirtimeInstall::DropSequence($tablename."_id"); } echo "done.".PHP_EOL; } diff --git a/install_minimal/include/airtime-upgrade.php b/install_minimal/include/airtime-upgrade.php index 7b1ce115f..26adcacc4 100644 --- a/install_minimal/include/airtime-upgrade.php +++ b/install_minimal/include/airtime-upgrade.php @@ -11,12 +11,20 @@ require_once(__DIR__.'/airtime-constants.php'); require_once(dirname(__FILE__).'/AirtimeIni.php'); require_once(dirname(__FILE__).'/AirtimeInstall.php'); -if(posix_geteuid() != 0){ +if(posix_geteuid() != 0) { echo "Must be root user.\n"; exit(1); } -function pause(){ +require_once(__DIR__.'/airtime-constants.php'); +require_once(__DIR__.'/AirtimeIni.php'); +require_once(__DIR__.'/AirtimeInstall.php'); +require_once 'propel/runtime/lib/Propel.php'; +Propel::init(AirtimeInstall::GetAirtimeSrcDir()."/application/configs/airtime-conf-production.php"); + + +function pause() +{ /* Type "sudo -s" to change to root user then type "export AIRTIME_INSTALL_DEBUG=1" and then * start airtime-install to enable this feature. Is used to pause between upgrade scripts * to examine the state of the system and see if everything is as expected. */ @@ -26,33 +34,8 @@ function pause(){ } } -const CONF_FILE_AIRTIME = "/etc/airtime/airtime.conf"; - - -global $CC_DBC, $CC_CONFIG; - -$values = parse_ini_file('/etc/airtime/airtime.conf', true); - -// Database config -$CC_CONFIG['dsn']['username'] = $values['database']['dbuser']; -$CC_CONFIG['dsn']['password'] = $values['database']['dbpass']; -$CC_CONFIG['dsn']['hostspec'] = $values['database']['host']; -$CC_CONFIG['dsn']['phptype'] = 'pgsql'; -$CC_CONFIG['dsn']['database'] = $values['database']['dbname']; - -$CC_DBC = DB::connect($CC_CONFIG['dsn'], FALSE); - -if (PEAR::isError($CC_DBC)) { - echo $CC_DBC->getMessage().PHP_EOL; - echo $CC_DBC->getUserInfo().PHP_EOL; - echo "Database connection problem.".PHP_EOL; - echo "Check if database '{$CC_CONFIG['dsn']['database']}' exists". - " with corresponding permissions.".PHP_EOL; - exit(1); -} else { - echo "* Connected to database".PHP_EOL; - $CC_DBC->setFetchMode(DB_FETCHMODE_ASSOC); -} +AirtimeInstall::DbConnect(true); +$con = Propel::getConnection(); $version = AirtimeInstall::GetVersionInstalled(); @@ -121,13 +104,13 @@ if (strcmp($version, "2.1.0") < 0){ //set the new version in the database. $sql = "DELETE FROM cc_pref WHERE keystr = 'system_version'"; -$CC_DBC->query($sql); +$con->exec($sql); $values = parse_ini_file(CONF_FILE_AIRTIME, true); $phpDir = $values['general']['airtime_dir']; $newVersion = AIRTIME_VERSION; $sql = "INSERT INTO cc_pref (keystr, valstr) VALUES ('system_version', '$newVersion')"; -$CC_DBC->query($sql); +$con->exec($sql); echo "******************************* Upgrade Complete *******************************".PHP_EOL; diff --git a/install_minimal/upgrades/airtime-1.8.0/airtime-upgrade.php b/install_minimal/upgrades/airtime-1.8.0/airtime-upgrade.php index a6d6b8c25..bb0994f14 100644 --- a/install_minimal/upgrades/airtime-1.8.0/airtime-upgrade.php +++ b/install_minimal/upgrades/airtime-1.8.0/airtime-upgrade.php @@ -55,6 +55,7 @@ $CC_CONFIG = array( ); AirtimeInstall::DbConnect(true); +$con = Propel::getConnection(); echo PHP_EOL."*** Updating Database Tables ***".PHP_EOL; @@ -68,11 +69,11 @@ AirtimeInstall::MigrateTablesToVersion(__DIR__, '20110406182005'); //setting data for new aggregate show length column. $sql = "SELECT id FROM cc_show_instances"; -$show_instances = $CC_DBC->GetAll($sql); +$show_instances = $con->query($sql)->fetchAll(); foreach ($show_instances as $show_instance) { $sql = "UPDATE cc_show_instances SET time_filled = (SELECT SUM(clip_length) FROM cc_schedule WHERE instance_id = {$show_instance["id"]}) WHERE id = {$show_instance["id"]}"; - $CC_DBC->query($sql); + $con->exec($sql); } //end setting data for new aggregate show length column. diff --git a/install_minimal/upgrades/airtime-1.9.0/airtime-upgrade.php b/install_minimal/upgrades/airtime-1.9.0/airtime-upgrade.php index ce4beb954..bda3fb5fd 100644 --- a/install_minimal/upgrades/airtime-1.9.0/airtime-upgrade.php +++ b/install_minimal/upgrades/airtime-1.9.0/airtime-upgrade.php @@ -1,17 +1,7 @@ GetOne($sql); - if (PEAR::isError($result)) { + $con = Propel::getConnection(); + try { + $sql = "SELECT * FROM ".$p_name." LIMIT 1"; + $con->query($sql); + } catch (PDOException $e){ return false; } return true; @@ -99,7 +90,7 @@ class AirtimeInstall{ public static function MigrateTablesToVersion($dir, $version) { echo "Upgrading database, may take several minutes, please wait".PHP_EOL; - + $appDir = AirtimeInstall::GetAirtimeSrcDir(); $SCRIPTPATH = __DIR__; $command = "php --php-ini $SCRIPTPATH/../../airtime-php.ini ". @@ -368,28 +359,26 @@ class AirtimeInstall{ echo "* Inserting data into country table".PHP_EOL; Airtime190Upgrade::execSqlQuery($sql); } - + public static function SetUniqueId() { - global $CC_DBC; - + $con = Propel::getConnection(); $uniqueId = md5(uniqid("", true)); $sql = "INSERT INTO cc_pref (keystr, valstr) VALUES ('uniqueId', '$uniqueId')"; - $result = $CC_DBC->query($sql); - if (PEAR::isError($result)) { + $result = $con->exec($sql); + if ($result < 1) { return false; } return true; } - + public static function SetImportTimestamp() { - global $CC_DBC; - + $con = Propel::getConnection(); $sql = "INSERT INTO cc_pref (keystr, valstr) VALUES ('import_timestamp', '0')"; - $result = $CC_DBC->query($sql); - if (PEAR::isError($result)) { + $result = $con->exec($sql); + if ($result < 1) { return false; } return true; @@ -586,31 +575,30 @@ class Airtime190Upgrade{ } - public static function execSqlQuery($sql){ - global $CC_DBC; - - $result = $CC_DBC->query($sql); - if (PEAR::isError($result)) { - echo "* Failed sql query: $sql".PHP_EOL; - echo "* Message {$result->getMessage()}".PHP_EOL; + public static function execSqlQuery($sql) + { + $result = 0; + try { + $con = Propel::getConnection(); + $result = $con->exec($sql); + } catch (Exception $e) { + echo "* Failed sql query: $sql".PHP_EOL; + echo "* Message {$e->getMessage()}".PHP_EOL; } - return $result; } - public static function connectToDatabase(){ - global $CC_DBC, $CC_CONFIG; - - $values = parse_ini_file('/etc/airtime/airtime.conf', true); - - // Database config - $CC_CONFIG['dsn']['username'] = $values['database']['dbuser']; - $CC_CONFIG['dsn']['password'] = $values['database']['dbpass']; - $CC_CONFIG['dsn']['hostspec'] = $values['database']['host']; - $CC_CONFIG['dsn']['phptype'] = 'pgsql'; - $CC_CONFIG['dsn']['database'] = $values['database']['dbname']; - - $CC_DBC = DB::connect($CC_CONFIG['dsn'], FALSE); + public static function connectToDatabase() + { + try { + $con = Propel::getConnection(); + } catch (Exception $e) { + echo $e->getMessage().PHP_EOL; + echo "Database connection problem.".PHP_EOL; + echo "Check if database exists with corresponding permissions.".PHP_EOL; + return false; + } + return true; } public static function backupFileInfoInStorToFile($values) { @@ -626,7 +614,7 @@ class Airtime190Upgrade{ if ($baseDir[strlen($baseDir)-1] != '/'){ $baseDir.='/'; } - + $stor_dir = $baseDir.'stor'; @@ -696,7 +684,7 @@ class Airtime190Upgrade{ $pi = pathinfo($values['general']['base_files_dir']); $stor_dir = $pi["dirname"].DIRECTORY_SEPARATOR.$pi["basename"].DIRECTORY_SEPARATOR."stor".DIRECTORY_SEPARATOR; - + echo "* Inserting stor directory location $stor_dir into music_dirs table".PHP_EOL; $propel_stor_dir->setDirectory($stor_dir); $propel_stor_dir->save(); diff --git a/install_minimal/upgrades/airtime-2.0.0/UpgradeCommon.php b/install_minimal/upgrades/airtime-2.0.0/UpgradeCommon.php index ce14cc675..89161ed89 100644 --- a/install_minimal/upgrades/airtime-2.0.0/UpgradeCommon.php +++ b/install_minimal/upgrades/airtime-2.0.0/UpgradeCommon.php @@ -1,7 +1,5 @@ getMessage().PHP_EOL; - echo $CC_DBC->getUserInfo().PHP_EOL; + try { + $con = Propel::getConnection(); + } catch (Exception $e) { + echo $e->getMessage().PHP_EOL; echo "Database connection problem.".PHP_EOL; - echo "Check if database '{$CC_CONFIG['dsn']['database']}' exists". - " with corresponding permissions.".PHP_EOL; + echo "Check if database exists with corresponding permissions.".PHP_EOL; if ($p_exitOnError) { exit(1); } - } else { - $CC_DBC->setFetchMode(DB_FETCHMODE_ASSOC); + return false; } + return true; } - + public static function DbTableExists($p_name) { - global $CC_DBC; - $sql = "SELECT * FROM ".$p_name; - $result = $CC_DBC->GetOne($sql); - if (PEAR::isError($result)) { + $con = Propel::getConnection(); + try { + $sql = "SELECT * FROM ".$p_name." LIMIT 1"; + $con->query($sql); + } catch (PDOException $e){ return false; } return true; @@ -56,7 +53,7 @@ class UpgradeCommon{ public static function MigrateTablesToVersion($dir, $version) { echo "Upgrading database, may take several minutes, please wait".PHP_EOL; - + $appDir = self::GetAirtimeSrcDir(); $command = "php --php-ini $dir/../../airtime-php.ini ". "$appDir/library/doctrine/migrations/doctrine-migrations.phar ". @@ -182,9 +179,9 @@ class UpgradeCommon{ private static function ReadPythonConfig($p_filename) { $values = array(); - + $fh = fopen($p_filename, 'r'); - + while(!feof($fh)){ $line = fgets($fh); if(substr(trim($line), 0, 1) == '#' || trim($line) == ""){ @@ -233,16 +230,18 @@ class UpgradeCommon{ } fclose($fp); } - - public static function queryDb($p_sql){ - global $CC_DBC; - $result = $CC_DBC->query($p_sql); - if (PEAR::isError($result)) { - echo "Error executing $sql. Exiting."; + public static function queryDb($p_sql) + { + $con = Propel::getConnection(); + + try { + $result = $con->exec($p_sql); + } catch (Exception $e) { + echo "Error executing $p_sql. Exiting."; exit(1); } - + return $result; } } diff --git a/install_minimal/upgrades/airtime-2.0.0/airtime-upgrade-old.php b/install_minimal/upgrades/airtime-2.0.0/airtime-upgrade-old.php deleted file mode 100644 index b540021dc..000000000 --- a/install_minimal/upgrades/airtime-2.0.0/airtime-upgrade-old.php +++ /dev/null @@ -1,586 +0,0 @@ -query($sql); - if (PEAR::isError($result)) { - return false; - } - return true; - } - - public static function GetUtilsSrcDir() - { - return __DIR__."/../../../utils"; - } - - public static function InstallBinaries() - { - echo "* Installing binaries to ".AirtimeInstall::CONF_DIR_BINARIES.PHP_EOL; - exec("mkdir -p ".AirtimeInstall::CONF_DIR_BINARIES); - exec("cp -R ".AirtimeInstall::GetUtilsSrcDir()." ".AirtimeInstall::CONF_DIR_BINARIES); - } - - public static function CreateSymlinksToUtils() - { - echo "* Installing airtime-log".PHP_EOL; - $dir = AirtimeInstall::CONF_DIR_BINARIES."/utils/airtime-log"; - copy(AirtimeInstall::GetUtilsSrcDir()."/airtime-log.php", AirtimeInstall::CONF_DIR_BINARIES."/utils/airtime-log.php"); - - exec("ln -s $dir /usr/bin/airtime-log"); - } - - public static function SetDefaultStreamSetting() - { - global $CC_DBC; - - echo "* Setting up default stream setting".PHP_EOL; - $sql = "INSERT INTO cc_pref(keystr, valstr) VALUES('stream_type', 'ogg, mp3'); - INSERT INTO cc_pref(keystr, valstr) VALUES('stream_bitrate', '24, 32, 48, 64, 96, 128, 160, 192, 224, 256, 320'); - INSERT INTO cc_pref(keystr, valstr) VALUES('num_of_streams', '3'); - INSERT INTO cc_pref(keystr, valstr) VALUES('max_bitrate', '128'); - INSERT INTO cc_pref(keystr, valstr) VALUES('plan_level', 'disabled'); - - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('output_sound_device', 'false', 'boolean'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('icecast_vorbis_metadata', 'false', 'boolean'); - - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s1_output', 'icecast', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s1_type', 'ogg', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s1_bitrate', '128', 'integer'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s1_host', '127.0.0.1', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s1_port', '8000', 'integer'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s1_user', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s1_pass', 'hackme', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s1_mount', 'airtime_128', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s1_url', 'http://airtime.sourcefabric.org', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s1_description', 'Airtime Radio! Stream #1', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s1_genre', 'genre', 'string'); - - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s2_output', 'disabled', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s2_type', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s2_bitrate', '', 'integer'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s2_host', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s2_port', '', 'integer'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s2_user', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s2_pass', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s2_mount', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s2_url', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s2_description', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s2_genre', '', 'string'); - - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s3_output', 'disabled', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s3_type', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s3_bitrate', '', 'integer'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s3_host', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s3_port', '', 'integer'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s3_user', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s3_pass', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s3_mount', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s3_url', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s3_description', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s3_genre', '', 'string');"; - $result = $CC_DBC->query($sql); - if (PEAR::isError($result)) { - return false; - } - return true; - } - - public static function BypassMigrations($dir, $version) - { - $appDir = AirtimeInstall::GetAirtimeSrcDir(); - $command = "php $appDir/library/doctrine/migrations/doctrine-migrations.phar ". - "--configuration=$dir/../../DoctrineMigrations/migrations.xml ". - "--db-configuration=$appDir/library/doctrine/migrations/migrations-db.php ". - "--no-interaction --add migrations:version $version"; - system($command); - } - - public static function MigrateTablesToVersion($dir, $version) - { - $appDir = AirtimeInstall::GetAirtimeSrcDir(); - $command = "php $appDir/library/doctrine/migrations/doctrine-migrations.phar ". - "--configuration=$dir/../../DoctrineMigrations/migrations.xml ". - "--db-configuration=$appDir/library/doctrine/migrations/migrations-db.php ". - "--no-interaction migrations:migrate $version"; - system($command); - } - - public static function GetAirtimeSrcDir() - { - return __DIR__."/../../../airtime_mvc"; - } - - public static function DbTableExists($p_name) - { - global $CC_DBC; - $sql = "SELECT * FROM ".$p_name; - $result = $CC_DBC->GetOne($sql); - if (PEAR::isError($result)) { - return false; - } - return true; - } - public static function GetOldLiquidsoapCfgAndUpdate(){ - global $CC_DBC; - echo "* Retrieving old liquidsoap configuration".PHP_EOL; - $map = array(); - $fh = fopen("/etc/airtime/liquidsoap.cfg", 'r'); - $newConfigMap = array(); - - while(!feof($fh)){ - $line = fgets($fh); - if(substr(trim($line), 0, 1) == '#' || trim($line) == ""){ - continue; - }else{ - $info = explode('=', $line, 2); - $map[trim($info[0])] = trim($info[1]); - } - } - $newConfigMap['output_sound_device'] = $map['output_sound_device']; - $newConfigMap['icecast_vorbis_metadata'] = $map['output_icecast_vorbis_metadata']; - $newConfigMap['log_file'] = $map['log_file']; - - $count = 1; - if( $map['output_icecast_vorbis'] == 'true'){ - $newConfigMap['s'.$count.'_output'] = 'icecast'; - $newConfigMap['s'.$count.'_host'] = $map['icecast_host']; - $newConfigMap['s'.$count.'_port'] = $map['icecast_port']; - $newConfigMap['s'.$count.'_pass'] = $map['icecast_pass']; - $newConfigMap['s'.$count.'_mount'] = $map['mount_point_vorbis']; - $newConfigMap['s'.$count.'_url'] = $map['icecast_url']; - $newConfigMap['s'.$count.'_description'] = $map['icecast_description']; - $newConfigMap['s'.$count.'_genre'] = $map['icecast_genre']; - $newConfigMap['s'.$count.'_type'] = "ogg"; - $newConfigMap['s'.$count.'_bitrate'] = "128"; - $count++; - } - if($map['output_icecast_mp3'] == 'true'){ - $newConfigMap['s'.$count.'_output'] = 'icecast'; - $newConfigMap['s'.$count.'_host'] = $map['icecast_host']; - $newConfigMap['s'.$count.'_port'] = $map['icecast_port']; - $newConfigMap['s'.$count.'_pass'] = $map['icecast_pass']; - $newConfigMap['s'.$count.'_mount'] = $map['mount_point_mp3']; - $newConfigMap['s'.$count.'_url'] = $map['icecast_url']; - $newConfigMap['s'.$count.'_description'] = $map['icecast_description']; - $newConfigMap['s'.$count.'_genre'] = $map['icecast_genre']; - $newConfigMap['s'.$count.'_type'] = "mp3"; - $newConfigMap['s'.$count.'_bitrate'] = "128"; - $count++; - } - if($map['output_shoutcast'] == 'true'){ - $newConfigMap['s'.$count.'_output'] = 'shoutcast'; - $newConfigMap['s'.$count.'_host'] = $map['shoutcast_host']; - $newConfigMap['s'.$count.'_port'] = $map['shoutcast_port']; - $newConfigMap['s'.$count.'_pass'] = $map['shoutcast_pass']; - $newConfigMap['s'.$count.'_url'] = $map['shoutcast_url']; - $newConfigMap['s'.$count.'_genre'] = $map['shoutcast_genre']; - $newConfigMap['s'.$count.'_type'] = "mp3"; - $newConfigMap['s'.$count.'_bitrate'] = "128"; - $count++; - } - - $sql = ""; - foreach( $newConfigMap as $key=>$val){ - if(substr($val, 0, 1) == '"' && substr($val, strlen($val)-1,1)){ - $val = ltrim($val, '"'); - $val = rtrim($val, '"'); - } - $sql .= "UPDATE cc_stream_setting SET value='$val' WHERE keyname='$key';"; - } - $result = $CC_DBC->query($sql); - if (PEAR::isError($result)) { - return false; - } - return true; - } -} - -class Airtime200Upgrade{ - - public static function connectToDatabase(){ - global $CC_DBC, $CC_CONFIG; - - $values = parse_ini_file('/etc/airtime/airtime.conf', true); - - // Database config - $CC_CONFIG['dsn']['username'] = $values['database']['dbuser']; - $CC_CONFIG['dsn']['password'] = $values['database']['dbpass']; - $CC_CONFIG['dsn']['hostspec'] = $values['database']['host']; - $CC_CONFIG['dsn']['phptype'] = 'pgsql'; - $CC_CONFIG['dsn']['database'] = $values['database']['dbname']; - - $CC_DBC = DB::connect($CC_CONFIG['dsn'], FALSE); - } - - public static function InstallAirtimePhpServerCode($phpDir) - { - - $AIRTIME_SRC = realpath(__DIR__.'/../../../airtime_mvc'); - - // delete old files - exec("rm -rf ".$phpDir); - echo "* Installing PHP code to ".$phpDir.PHP_EOL; - exec("mkdir -p ".$phpDir); - exec("cp -R ".$AIRTIME_SRC."/* ".$phpDir); - } - - public static function RemoveOldMonitFile(){ - unlink("/etc/monit/conf.d/airtime-monit.cfg"); - } -} - -class ConvertToUtc{ - - public static function setPhpDefaultTimeZoneToSystemTimezone(){ - //we can get the default system timezone on debian/ubuntu by reading "/etc/timezone" - $filename = "/etc/timezone"; - $handle = fopen($filename, "r"); - $contents = trim(fread($handle, filesize($filename))); - echo "System timezone detected as: $contents".PHP_EOL; - fclose($handle); - - date_default_timezone_set($contents); - } - - public static function convert_cc_playlist(){ - /* cc_playlist has a field that keeps track of when the playlist was last modified. */ - $playlists = CcPlaylistQuery::create()->find(); - - foreach ($playlists as $pl){ - $dt = new DateTime($pl->getDbMtime(), new DateTimeZone(date_default_timezone_get())); - $dt->setTimezone(new DateTimeZone("UTC")); - $pl->setDbMtime($dt); - - $pl->save(); - } - } - - public static function convert_cc_schedule(){ - /* cc_schedule has start and end fields that need to be changed to UTC. */ - $schedules = CcScheduleQuery::create()->find(); - - foreach ($schedules as $s){ - $dt = new DateTime($s->getDbStarts(), new DateTimeZone(date_default_timezone_get())); - $dt->setTimezone(new DateTimeZone("UTC")); - $s->setDbStarts($dt); - - $dt = new DateTime($s->getDbEnds(), new DateTimeZone(date_default_timezone_get())); - $dt->setTimezone(new DateTimeZone("UTC")); - $s->setDbEnds($dt); - - $s->save(); - } - } - - public static function convert_cc_show_days(){ - /* cc_show_days has first_show, last_show and start_time fields that need to be changed to UTC. */ - $showDays = CcShowDaysQuery::create()->find(); - - foreach ($showDays as $sd){ - $dt = new DateTime($sd->getDbFirstShow()." ".$sd->getDbStartTime(), new DateTimeZone(date_default_timezone_get())); - $dt->setTimezone(new DateTimeZone("UTC")); - $sd->setDbFirstShow($dt->format("Y-m-d")); - $sd->setDbStartTime($dt->format("H:i:s")); - - $dt = new DateTime($sd->getDbLastShow()." ".$sd->getDbStartTime(), new DateTimeZone(date_default_timezone_get())); - $dt->setTimezone(new DateTimeZone("UTC")); - $sd->setDbLastShow($dt->format("Y-m-d")); - - $sd->save(); - } - } - - public static function convert_cc_show_instances(){ - /* convert_cc_show_instances has starts and ends fields that need to be changed to UTC. */ - $showInstances = CcShowInstancesQuery::create()->find(); - - foreach ($showInstances as $si){ - $dt = new DateTime($si->getDbStarts(), new DateTimeZone(date_default_timezone_get())); - $dt->setTimezone(new DateTimeZone("UTC")); - $si->setDbStarts($dt); - - $dt = new DateTime($si->getDbEnds(), new DateTimeZone(date_default_timezone_get())); - $dt->setTimezone(new DateTimeZone("UTC")); - $si->setDbEnds($dt); - - $si->save(); - } - } -} - -class AirtimeIni200{ - - const CONF_FILE_AIRTIME = "/etc/airtime/airtime.conf"; - const CONF_FILE_PYPO = "/etc/airtime/pypo.cfg"; - const CONF_FILE_RECORDER = "/etc/airtime/recorder.cfg"; - const CONF_FILE_LIQUIDSOAP = "/etc/airtime/liquidsoap.cfg"; - const CONF_FILE_MEDIAMONITOR = "/etc/airtime/media-monitor.cfg"; - const CONF_FILE_API_CLIENT = "/etc/airtime/api_client.cfg"; - - const CONF_PYPO_GRP = "pypo"; - const CONF_WWW_DATA_GRP = "www-data"; - - /** - * This function updates an INI style config file. - * - * A property and the value the property should be changed to are - * supplied. If the property is not found, then no changes are made. - * - * @param string $p_filename - * The path the to the file. - * @param string $p_property - * The property to look for in order to change its value. - * @param string $p_value - * The value the property should be changed to. - * - */ - public static function UpdateIniValue($p_filename, $p_property, $p_value) - { - $lines = file($p_filename); - $n=count($lines); - foreach ($lines as &$line) { - if ($line[0] != "#"){ - $key_value = explode("=", $line); - $key = trim($key_value[0]); - - if ($key == $p_property){ - $line = "$p_property = $p_value".PHP_EOL; - } - } - } - - $fp=fopen($p_filename, 'w'); - for($i=0; $i<$n; $i++){ - fwrite($fp, $lines[$i]); - } - fclose($fp); - } - - public static function ReadPythonConfig($p_filename) - { - $values = array(); - - $fh = fopen($p_filename, 'r'); - - while(!feof($fh)){ - $line = fgets($fh); - if(substr(trim($line), 0, 1) == '#' || trim($line) == ""){ - continue; - }else{ - $info = explode('=', $line, 2); - $values[trim($info[0])] = trim($info[1]); - } - } - - return $values; - } - - public static function MergeConfigFiles($configFiles, $suffix) { - foreach ($configFiles as $conf) { - // we want to use new liquidsoap.cfg so don't merge - // also for monit - if( $conf == AirtimeIni200::CONF_FILE_LIQUIDSOAP){ - continue; - } - if (file_exists("$conf$suffix.bak")) { - - if($conf === AirtimeIni200::CONF_FILE_AIRTIME) { - // Parse with sections - $newSettings = parse_ini_file($conf, true); - $oldSettings = parse_ini_file("$conf$suffix.bak", true); - } - else { - $newSettings = AirtimeIni200::ReadPythonConfig($conf); - $oldSettings = AirtimeIni200::ReadPythonConfig("$conf$suffix.bak"); - } - - $settings = array_keys($newSettings); - - foreach($settings as $section) { - if(isset($oldSettings[$section])) { - if(is_array($oldSettings[$section])) { - $sectionKeys = array_keys($newSettings[$section]); - foreach($sectionKeys as $sectionKey) { - // skip airtim_dir as we want to use new value - if($sectionKey != "airtime_dir"){ - if(isset($oldSettings[$section][$sectionKey])) { - AirtimeIni200::UpdateIniValue($conf, $sectionKey, $oldSettings[$section][$sectionKey]); - } - } - } - } - else { - AirtimeIni200::UpdateIniValue($conf, $section, $oldSettings[$section]); - } - } - } - } - } - } - - /* Re: http://dev.sourcefabric.org/browse/CC-2797 - * We don't want config files to be world-readable so we - * set the strictest permissions possible. */ - public static function changeConfigFilePermissions(){ - if (!self::ChangeFileOwnerGroupMod(AirtimeIni200::CONF_FILE_AIRTIME, self::CONF_WWW_DATA_GRP)){ - echo "Could not set ownership of api_client.cfg to 'pypo'. Exiting."; - exit(1); - } - if (!self::ChangeFileOwnerGroupMod(AirtimeIni200::CONF_FILE_API_CLIENT, self::CONF_PYPO_GRP)){ - echo "Could not set ownership of api_client.cfg to 'pypo'. Exiting."; - exit(1); - } - if (!self::ChangeFileOwnerGroupMod(AirtimeIni200::CONF_FILE_PYPO, self::CONF_PYPO_GRP)){ - echo "Could not set ownership of pypo.cfg to 'pypo'. Exiting."; - exit(1); - } - if (!self::ChangeFileOwnerGroupMod(AirtimeIni200::CONF_FILE_RECORDER, self::CONF_PYPO_GRP)){ - echo "Could not set ownership of recorder.cfg to 'pypo'. Exiting."; - exit(1); - } - if (!self::ChangeFileOwnerGroupMod(AirtimeIni200::CONF_FILE_LIQUIDSOAP, self::CONF_PYPO_GRP)){ - echo "Could not set ownership of liquidsoap.cfg to 'pypo'. Exiting."; - exit(1); - } - if (!self::ChangeFileOwnerGroupMod(AirtimeIni200::CONF_FILE_MEDIAMONITOR, self::CONF_PYPO_GRP)){ - echo "Could not set ownership of media-monitor.cfg to 'pypo'. Exiting."; - exit(1); - } - } - - public static function ChangeFileOwnerGroupMod($filename, $user){ - return (chown($filename, $user) && - chgrp($filename, $user) && - chmod($filename, 0640)); - } - - public static function upgradeConfigFiles(){ - - $configFiles = array(AirtimeIni200::CONF_FILE_AIRTIME, - AirtimeIni200::CONF_FILE_PYPO, - AirtimeIni200::CONF_FILE_RECORDER, - AirtimeIni200::CONF_FILE_LIQUIDSOAP, - AirtimeIni200::CONF_FILE_MEDIAMONITOR, - AirtimeIni200::CONF_FILE_API_CLIENT); - - // Backup the config files - $suffix = date("Ymdhis")."-2.0.0"; - foreach ($configFiles as $conf) { - // do not back up monit cfg - if (file_exists($conf)) { - echo "Backing up $conf to $conf$suffix.bak".PHP_EOL; - //copy($conf, $conf.$suffix.".bak"); - exec("cp -p $conf $conf$suffix.bak"); //use cli version to preserve file attributes - } - } - - $default_suffix = "200"; - AirtimeIni200::CreateIniFiles($default_suffix); - AirtimeIni200::MergeConfigFiles($configFiles, $suffix); - } - - /** - * This function creates the /etc/airtime configuration folder - * and copies the default config files to it. - */ - public static function CreateIniFiles($suffix) - { - if (!file_exists("/etc/airtime/")){ - if (!mkdir("/etc/airtime/", 0755, true)){ - echo "Could not create /etc/airtime/ directory. Exiting."; - exit(1); - } - } - - if (!copy(__DIR__."/airtime.conf.$suffix", AirtimeIni200::CONF_FILE_AIRTIME)){ - echo "Could not copy airtime.conf to /etc/airtime/. Exiting."; - exit(1); - } - if (!copy(__DIR__."/pypo.cfg.$suffix", AirtimeIni200::CONF_FILE_PYPO)){ - echo "Could not copy pypo.cfg to /etc/airtime/. Exiting."; - exit(1); - } - if (!copy(__DIR__."/recorder.cfg.$suffix", AirtimeIni200::CONF_FILE_RECORDER)){ - echo "Could not copy recorder.cfg to /etc/airtime/. Exiting."; - exit(1); - } - /*if (!copy(__DIR__."/liquidsoap.cfg.$suffix", AirtimeIni200::CONF_FILE_LIQUIDSOAP)){ - echo "Could not copy liquidsoap.cfg to /etc/airtime/. Exiting."; - exit(1); - }*/ - if (!copy(__DIR__."/api_client.cfg.$suffix", AirtimeIni200::CONF_FILE_API_CLIENT)){ - echo "Could not copy airtime-monit.cfg to /etc/monit/conf.d/. Exiting."; - exit(1); - } - } -} - -Airtime200Upgrade::connectToDatabase(); -AirtimeInstall::SetDefaultTimezone(); - -AirtimeInstall::InstallBinaries(); -AirtimeInstall::CreateSymlinksToUtils(); - -/* Airtime 2.0.0 starts interpreting all database times in UTC format. Prior to this, all the times - * were stored using the local time zone. Let's convert to UTC time. */ -ConvertToUtc::setPhpDefaultTimeZoneToSystemTimezone(); -ConvertToUtc::convert_cc_playlist(); -ConvertToUtc::convert_cc_schedule(); -ConvertToUtc::convert_cc_show_days(); -ConvertToUtc::convert_cc_show_instances(); - -// merging/updating config files -echo "* Updating configFiles\n"; -AirtimeIni200::changeConfigFilePermissions(); -AirtimeIni200::upgradeConfigFiles(); - -$values = parse_ini_file(AirtimeIni200::CONF_FILE_AIRTIME, true); -$phpDir = $values['general']['airtime_dir']; -Airtime200Upgrade::InstallAirtimePhpServerCode($phpDir); - -if(AirtimeInstall::DbTableExists('doctrine_migration_versions') === false) { - $migrations = array('20110312121200', '20110331111708', '20110402164819', '20110406182005', '20110629143017', '20110711161043', '20110713161043'); - foreach($migrations as $migration) { - AirtimeInstall::BypassMigrations(__DIR__, $migration); - } -} - -AirtimeInstall::MigrateTablesToVersion(__DIR__, '20110925171256'); - -AirtimeInstall::SetDefaultStreamSetting(); - -AirtimeInstall::GetOldLiquidsoapCfgAndUpdate(); - -AirtimeUpgrade::RemoveOldMonitFile(); - -// restart monit -exec("service monit restart"); - - - - diff --git a/install_minimal/upgrades/airtime-2.0.0/airtime-upgrade.php b/install_minimal/upgrades/airtime-2.0.0/airtime-upgrade.php index c89cdde2a..54cf95177 100644 --- a/install_minimal/upgrades/airtime-2.0.0/airtime-upgrade.php +++ b/install_minimal/upgrades/airtime-2.0.0/airtime-upgrade.php @@ -1,11 +1,4 @@ query($sql); - if (PEAR::isError($result)) { + try { + $result = $con->exec($sql); + } catch (Exception $e) { return false; } return true; @@ -72,45 +67,45 @@ class AirtimeDatabaseUpgrade{ private static function convert_cc_playlist(){ echo " * Converting playlists to UTC".PHP_EOL; - + $sql = "SELECT * FROM cc_playlist"; $result = UpgradeCommon::queryDb($sql); while ($result->fetchInto($row, DB_FETCHMODE_ASSOC)){ $dt = new DateTime($row['mtime'], new DateTimeZone(date_default_timezone_get())); $dt->setTimezone(new DateTimeZone("UTC")); - + $id = $row['id']; $mtime = $dt->format("Y-m-d H:i:s"); - + $sql = "UPDATE cc_playlist SET mtime = '$mtime' WHERE id = $id"; UpgradeCommon::queryDb($sql); //echo "."; //flush(); //usleep(100000); } - - + + /* echo " * Converting playlists to UTC".PHP_EOL; // cc_playlist has a field that keeps track of when the playlist was last modified. $playlists = CcPlaylistQuery::create()->find(); - + foreach ($playlists as $pl){ $dt = new DateTime($pl->getDbMtime(), new DateTimeZone(date_default_timezone_get())); $dt->setTimezone(new DateTimeZone("UTC")); $pl->setDbMtime($dt); - + $pl->save(); - + } */ } private static function convert_cc_schedule(){ - + echo " * Converting schedule to UTC".PHP_EOL; - + $sql = "SELECT * FROM cc_schedule"; $result = UpgradeCommon::queryDb($sql); @@ -120,11 +115,11 @@ class AirtimeDatabaseUpgrade{ $dtEnds = new DateTime($row['ends'], new DateTimeZone(date_default_timezone_get())); $dtEnds->setTimezone(new DateTimeZone("UTC")); - + $id = $row['id']; $starts = $dtStarts->format("Y-m-d H:i:s"); $ends = $dtEnds->format("Y-m-d H:i:s"); - + $sql = "UPDATE cc_schedule SET starts = '$starts', ends = '$ends' WHERE id = $id"; UpgradeCommon::queryDb($sql); //echo "."; @@ -132,62 +127,62 @@ class AirtimeDatabaseUpgrade{ //usleep(100000); } /* - + echo " * Converting schedule to UTC".PHP_EOL; //cc_schedule has start and end fields that need to be changed to UTC. $schedules = CcScheduleQuery::create()->find(); - + foreach ($schedules as $s){ $dt = new DateTime($s->getDbStarts(), new DateTimeZone(date_default_timezone_get())); $dt->setTimezone(new DateTimeZone("UTC")); $s->setDbStarts($dt); - + $dt = new DateTime($s->getDbEnds(), new DateTimeZone(date_default_timezone_get())); $dt->setTimezone(new DateTimeZone("UTC")); $s->setDbEnds($dt); - + $s->save(); echo "."; } * */ } - + private static function convert_cc_show_days(){ echo " * Converting show days to UTC".PHP_EOL; - + $sql = "SELECT * FROM cc_show_days"; $result = UpgradeCommon::queryDb($sql); while ($result->fetchInto($row, DB_FETCHMODE_ASSOC)){ - + $id = $row['id']; $timezone = date_default_timezone_get(); - + $sql = "UPDATE cc_show_days SET timezone = '$timezone' WHERE id = $id"; UpgradeCommon::queryDb($sql); //echo "."; //flush(); //usleep(100000); } - + /* // cc_show_days has first_show, last_show and start_time fields that need to be changed to UTC. $showDays = CcShowDaysQuery::create()->find(); - - foreach ($showDays as $sd){ + + foreach ($showDays as $sd){ $sd->setDbTimezone(date_default_timezone_get())->save(); - + echo "."; } */ } - + private static function convert_cc_show_instances(){ echo " * Converting show instances to UTC".PHP_EOL; - + // convert_cc_show_instances has starts and ends fields that need to be changed to UTC. - + $sql = "SELECT * FROM cc_show_instances"; $result = UpgradeCommon::queryDb($sql); @@ -197,32 +192,32 @@ class AirtimeDatabaseUpgrade{ $dtEnds = new DateTime($row['ends'], new DateTimeZone(date_default_timezone_get())); $dtEnds->setTimezone(new DateTimeZone("UTC")); - + $id = $row['id']; $starts = $dtStarts->format("Y-m-d H:i:s"); $ends = $dtEnds->format("Y-m-d H:i:s"); - + $sql = "UPDATE cc_show_instances SET starts = '$starts', ends = '$ends' WHERE id = $id"; UpgradeCommon::queryDb($sql); //echo "."; //flush(); //usleep(100000); - } - + } + /* $showInstances = CcShowInstancesQuery::create()->find(); - + foreach ($showInstances as $si){ $dt = new DateTime($si->getDbStarts(), new DateTimeZone(date_default_timezone_get())); $dt->setTimezone(new DateTimeZone("UTC")); $si->setDbStarts($dt); - + $dt = new DateTime($si->getDbEnds(), new DateTimeZone(date_default_timezone_get())); $dt->setTimezone(new DateTimeZone("UTC")); $si->setDbEnds($dt); - + $si->save(); - + echo "."; } * */ @@ -241,19 +236,19 @@ class AirtimeDatabaseUpgrade{ private static function SetDefaultStreamSetting() { - global $CC_DBC; - + $con = Propel::getConnection(); + echo "* Setting up default stream setting".PHP_EOL; $sql = "INSERT INTO cc_pref(keystr, valstr) VALUES('stream_type', 'ogg, mp3'); INSERT INTO cc_pref(keystr, valstr) VALUES('stream_bitrate', '24, 32, 48, 64, 96, 128, 160, 192, 224, 256, 320'); INSERT INTO cc_pref(keystr, valstr) VALUES('num_of_streams', '3'); INSERT INTO cc_pref(keystr, valstr) VALUES('max_bitrate', '320'); INSERT INTO cc_pref(keystr, valstr) VALUES('plan_level', 'disabled'); - + INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('output_sound_device', 'false', 'boolean'); INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('output_sound_device_type', 'ALSA', 'string'); INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('icecast_vorbis_metadata', 'false', 'boolean'); - + INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s1_enable', 'true', 'boolean'); INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s1_output', 'icecast', 'string'); INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s1_type', 'ogg', 'string'); @@ -266,7 +261,7 @@ class AirtimeDatabaseUpgrade{ INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s1_url', 'http://airtime.sourcefabric.org', 'string'); INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s1_description', 'Airtime Radio! Stream #1', 'string'); INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s1_genre', 'genre', 'string'); - + INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s2_enable', 'false', 'boolean'); INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s2_output', 'icecast', 'string'); INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s2_type', '', 'string'); @@ -279,7 +274,7 @@ class AirtimeDatabaseUpgrade{ INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s2_url', '', 'string'); INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s2_description', '', 'string'); INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s2_genre', '', 'string'); - + INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s3_enable', 'false', 'boolean'); INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s3_output', 'icecast', 'string'); INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s3_type', '', 'string'); @@ -292,21 +287,24 @@ class AirtimeDatabaseUpgrade{ INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s3_url', '', 'string'); INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s3_description', '', 'string'); INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s3_genre', '', 'string');"; - $result = $CC_DBC->query($sql); - if (PEAR::isError($result)) { + try { + $con->exec($sql); + } catch (Exception $e) { return false; } return true; } - private static function GetOldLiquidsoapCfgAndUpdate(){ - global $CC_DBC; + private static function GetOldLiquidsoapCfgAndUpdate() + { + $con = Propel::getConnection(); + echo "* Retrieving old liquidsoap configuration".PHP_EOL; $map = array(); $fh = fopen("/etc/airtime/liquidsoap.cfg", 'r'); $newConfigMap = array(); - - while(!feof($fh)){ + + while (!feof($fh)) { $line = fgets($fh); if(substr(trim($line), 0, 1) == '#' || trim($line) == ""){ continue; @@ -318,7 +316,7 @@ class AirtimeDatabaseUpgrade{ $newConfigMap['output_sound_device'] = $map['output_sound_device']; $newConfigMap['icecast_vorbis_metadata'] = $map['output_icecast_vorbis_metadata']; $newConfigMap['log_file'] = $map['log_file']; - + $count = 1; if( $map['output_icecast_vorbis'] == 'true'){ $newConfigMap['s'.$count.'_output'] = 'icecast'; @@ -366,8 +364,9 @@ class AirtimeDatabaseUpgrade{ } $sql .= "UPDATE cc_stream_setting SET value='$val' WHERE keyname='$key';"; } - $result = $CC_DBC->query($sql); - if (PEAR::isError($result)) { + try { + $con->exec($sql); + } catch (Exception $e) { return false; } return true; diff --git a/install_minimal/upgrades/airtime-2.0.1/UpgradeCommon.php b/install_minimal/upgrades/airtime-2.0.1/UpgradeCommon.php index 63f797938..8d45db5b8 100644 --- a/install_minimal/upgrades/airtime-2.0.1/UpgradeCommon.php +++ b/install_minimal/upgrades/airtime-2.0.1/UpgradeCommon.php @@ -1,7 +1,5 @@ getMessage().PHP_EOL; - echo $CC_DBC->getUserInfo().PHP_EOL; + try { + $con = Propel::getConnection(); + } catch (Exception $e) { + echo $e->getMessage().PHP_EOL; echo "Database connection problem.".PHP_EOL; - echo "Check if database '{$CC_CONFIG['dsn']['database']}' exists". - " with corresponding permissions.".PHP_EOL; + echo "Check if database exists with corresponding permissions.".PHP_EOL; if ($p_exitOnError) { exit(1); } - } else { - $CC_DBC->setFetchMode(DB_FETCHMODE_ASSOC); + return false; } + return true; } - + public static function DbTableExists($p_name) { - global $CC_DBC; - $sql = "SELECT * FROM ".$p_name; - $result = $CC_DBC->GetOne($sql); - if (PEAR::isError($result)) { + $con = Propel::getConnection(); + try { + $sql = "SELECT * FROM ".$p_name." LIMIT 1"; + $con->query($sql); + } catch (PDOException $e){ return false; } return true; @@ -66,7 +63,7 @@ class UpgradeCommon{ public static function MigrateTablesToVersion($dir, $version) { echo "Upgrading database, may take several minutes, please wait".PHP_EOL; - + $appDir = self::GetAirtimeSrcDir(); $command = "php --php-ini $dir/../../airtime-php.ini ". "$appDir/library/doctrine/migrations/doctrine-migrations.phar ". @@ -192,9 +189,9 @@ class UpgradeCommon{ private static function ReadPythonConfig($p_filename) { $values = array(); - + $fh = fopen($p_filename, 'r'); - + while(!feof($fh)){ $line = fgets($fh); if(substr(trim($line), 0, 1) == '#' || trim($line) == ""){ @@ -243,16 +240,17 @@ class UpgradeCommon{ } fclose($fp); } - - public static function queryDb($p_sql){ - global $CC_DBC; - $result = $CC_DBC->getRow($p_sql, $fetchmode=DB_FETCHMODE_ASSOC); - if (PEAR::isError($result)) { - echo "Error executing $sql. Exiting."; + public static function queryDb($p_sql){ + $con = Propel::getConnection(); + + try { + $result = $con->exec($p_sql); + } catch (Exception $e) { + echo "Error executing $p_sql. Exiting."; exit(1); } - + return $result; } } diff --git a/install_minimal/upgrades/airtime-2.0.1/airtime-upgrade-old.php b/install_minimal/upgrades/airtime-2.0.1/airtime-upgrade-old.php deleted file mode 100644 index b540021dc..000000000 --- a/install_minimal/upgrades/airtime-2.0.1/airtime-upgrade-old.php +++ /dev/null @@ -1,586 +0,0 @@ -query($sql); - if (PEAR::isError($result)) { - return false; - } - return true; - } - - public static function GetUtilsSrcDir() - { - return __DIR__."/../../../utils"; - } - - public static function InstallBinaries() - { - echo "* Installing binaries to ".AirtimeInstall::CONF_DIR_BINARIES.PHP_EOL; - exec("mkdir -p ".AirtimeInstall::CONF_DIR_BINARIES); - exec("cp -R ".AirtimeInstall::GetUtilsSrcDir()." ".AirtimeInstall::CONF_DIR_BINARIES); - } - - public static function CreateSymlinksToUtils() - { - echo "* Installing airtime-log".PHP_EOL; - $dir = AirtimeInstall::CONF_DIR_BINARIES."/utils/airtime-log"; - copy(AirtimeInstall::GetUtilsSrcDir()."/airtime-log.php", AirtimeInstall::CONF_DIR_BINARIES."/utils/airtime-log.php"); - - exec("ln -s $dir /usr/bin/airtime-log"); - } - - public static function SetDefaultStreamSetting() - { - global $CC_DBC; - - echo "* Setting up default stream setting".PHP_EOL; - $sql = "INSERT INTO cc_pref(keystr, valstr) VALUES('stream_type', 'ogg, mp3'); - INSERT INTO cc_pref(keystr, valstr) VALUES('stream_bitrate', '24, 32, 48, 64, 96, 128, 160, 192, 224, 256, 320'); - INSERT INTO cc_pref(keystr, valstr) VALUES('num_of_streams', '3'); - INSERT INTO cc_pref(keystr, valstr) VALUES('max_bitrate', '128'); - INSERT INTO cc_pref(keystr, valstr) VALUES('plan_level', 'disabled'); - - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('output_sound_device', 'false', 'boolean'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('icecast_vorbis_metadata', 'false', 'boolean'); - - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s1_output', 'icecast', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s1_type', 'ogg', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s1_bitrate', '128', 'integer'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s1_host', '127.0.0.1', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s1_port', '8000', 'integer'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s1_user', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s1_pass', 'hackme', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s1_mount', 'airtime_128', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s1_url', 'http://airtime.sourcefabric.org', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s1_description', 'Airtime Radio! Stream #1', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s1_genre', 'genre', 'string'); - - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s2_output', 'disabled', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s2_type', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s2_bitrate', '', 'integer'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s2_host', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s2_port', '', 'integer'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s2_user', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s2_pass', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s2_mount', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s2_url', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s2_description', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s2_genre', '', 'string'); - - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s3_output', 'disabled', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s3_type', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s3_bitrate', '', 'integer'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s3_host', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s3_port', '', 'integer'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s3_user', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s3_pass', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s3_mount', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s3_url', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s3_description', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s3_genre', '', 'string');"; - $result = $CC_DBC->query($sql); - if (PEAR::isError($result)) { - return false; - } - return true; - } - - public static function BypassMigrations($dir, $version) - { - $appDir = AirtimeInstall::GetAirtimeSrcDir(); - $command = "php $appDir/library/doctrine/migrations/doctrine-migrations.phar ". - "--configuration=$dir/../../DoctrineMigrations/migrations.xml ". - "--db-configuration=$appDir/library/doctrine/migrations/migrations-db.php ". - "--no-interaction --add migrations:version $version"; - system($command); - } - - public static function MigrateTablesToVersion($dir, $version) - { - $appDir = AirtimeInstall::GetAirtimeSrcDir(); - $command = "php $appDir/library/doctrine/migrations/doctrine-migrations.phar ". - "--configuration=$dir/../../DoctrineMigrations/migrations.xml ". - "--db-configuration=$appDir/library/doctrine/migrations/migrations-db.php ". - "--no-interaction migrations:migrate $version"; - system($command); - } - - public static function GetAirtimeSrcDir() - { - return __DIR__."/../../../airtime_mvc"; - } - - public static function DbTableExists($p_name) - { - global $CC_DBC; - $sql = "SELECT * FROM ".$p_name; - $result = $CC_DBC->GetOne($sql); - if (PEAR::isError($result)) { - return false; - } - return true; - } - public static function GetOldLiquidsoapCfgAndUpdate(){ - global $CC_DBC; - echo "* Retrieving old liquidsoap configuration".PHP_EOL; - $map = array(); - $fh = fopen("/etc/airtime/liquidsoap.cfg", 'r'); - $newConfigMap = array(); - - while(!feof($fh)){ - $line = fgets($fh); - if(substr(trim($line), 0, 1) == '#' || trim($line) == ""){ - continue; - }else{ - $info = explode('=', $line, 2); - $map[trim($info[0])] = trim($info[1]); - } - } - $newConfigMap['output_sound_device'] = $map['output_sound_device']; - $newConfigMap['icecast_vorbis_metadata'] = $map['output_icecast_vorbis_metadata']; - $newConfigMap['log_file'] = $map['log_file']; - - $count = 1; - if( $map['output_icecast_vorbis'] == 'true'){ - $newConfigMap['s'.$count.'_output'] = 'icecast'; - $newConfigMap['s'.$count.'_host'] = $map['icecast_host']; - $newConfigMap['s'.$count.'_port'] = $map['icecast_port']; - $newConfigMap['s'.$count.'_pass'] = $map['icecast_pass']; - $newConfigMap['s'.$count.'_mount'] = $map['mount_point_vorbis']; - $newConfigMap['s'.$count.'_url'] = $map['icecast_url']; - $newConfigMap['s'.$count.'_description'] = $map['icecast_description']; - $newConfigMap['s'.$count.'_genre'] = $map['icecast_genre']; - $newConfigMap['s'.$count.'_type'] = "ogg"; - $newConfigMap['s'.$count.'_bitrate'] = "128"; - $count++; - } - if($map['output_icecast_mp3'] == 'true'){ - $newConfigMap['s'.$count.'_output'] = 'icecast'; - $newConfigMap['s'.$count.'_host'] = $map['icecast_host']; - $newConfigMap['s'.$count.'_port'] = $map['icecast_port']; - $newConfigMap['s'.$count.'_pass'] = $map['icecast_pass']; - $newConfigMap['s'.$count.'_mount'] = $map['mount_point_mp3']; - $newConfigMap['s'.$count.'_url'] = $map['icecast_url']; - $newConfigMap['s'.$count.'_description'] = $map['icecast_description']; - $newConfigMap['s'.$count.'_genre'] = $map['icecast_genre']; - $newConfigMap['s'.$count.'_type'] = "mp3"; - $newConfigMap['s'.$count.'_bitrate'] = "128"; - $count++; - } - if($map['output_shoutcast'] == 'true'){ - $newConfigMap['s'.$count.'_output'] = 'shoutcast'; - $newConfigMap['s'.$count.'_host'] = $map['shoutcast_host']; - $newConfigMap['s'.$count.'_port'] = $map['shoutcast_port']; - $newConfigMap['s'.$count.'_pass'] = $map['shoutcast_pass']; - $newConfigMap['s'.$count.'_url'] = $map['shoutcast_url']; - $newConfigMap['s'.$count.'_genre'] = $map['shoutcast_genre']; - $newConfigMap['s'.$count.'_type'] = "mp3"; - $newConfigMap['s'.$count.'_bitrate'] = "128"; - $count++; - } - - $sql = ""; - foreach( $newConfigMap as $key=>$val){ - if(substr($val, 0, 1) == '"' && substr($val, strlen($val)-1,1)){ - $val = ltrim($val, '"'); - $val = rtrim($val, '"'); - } - $sql .= "UPDATE cc_stream_setting SET value='$val' WHERE keyname='$key';"; - } - $result = $CC_DBC->query($sql); - if (PEAR::isError($result)) { - return false; - } - return true; - } -} - -class Airtime200Upgrade{ - - public static function connectToDatabase(){ - global $CC_DBC, $CC_CONFIG; - - $values = parse_ini_file('/etc/airtime/airtime.conf', true); - - // Database config - $CC_CONFIG['dsn']['username'] = $values['database']['dbuser']; - $CC_CONFIG['dsn']['password'] = $values['database']['dbpass']; - $CC_CONFIG['dsn']['hostspec'] = $values['database']['host']; - $CC_CONFIG['dsn']['phptype'] = 'pgsql'; - $CC_CONFIG['dsn']['database'] = $values['database']['dbname']; - - $CC_DBC = DB::connect($CC_CONFIG['dsn'], FALSE); - } - - public static function InstallAirtimePhpServerCode($phpDir) - { - - $AIRTIME_SRC = realpath(__DIR__.'/../../../airtime_mvc'); - - // delete old files - exec("rm -rf ".$phpDir); - echo "* Installing PHP code to ".$phpDir.PHP_EOL; - exec("mkdir -p ".$phpDir); - exec("cp -R ".$AIRTIME_SRC."/* ".$phpDir); - } - - public static function RemoveOldMonitFile(){ - unlink("/etc/monit/conf.d/airtime-monit.cfg"); - } -} - -class ConvertToUtc{ - - public static function setPhpDefaultTimeZoneToSystemTimezone(){ - //we can get the default system timezone on debian/ubuntu by reading "/etc/timezone" - $filename = "/etc/timezone"; - $handle = fopen($filename, "r"); - $contents = trim(fread($handle, filesize($filename))); - echo "System timezone detected as: $contents".PHP_EOL; - fclose($handle); - - date_default_timezone_set($contents); - } - - public static function convert_cc_playlist(){ - /* cc_playlist has a field that keeps track of when the playlist was last modified. */ - $playlists = CcPlaylistQuery::create()->find(); - - foreach ($playlists as $pl){ - $dt = new DateTime($pl->getDbMtime(), new DateTimeZone(date_default_timezone_get())); - $dt->setTimezone(new DateTimeZone("UTC")); - $pl->setDbMtime($dt); - - $pl->save(); - } - } - - public static function convert_cc_schedule(){ - /* cc_schedule has start and end fields that need to be changed to UTC. */ - $schedules = CcScheduleQuery::create()->find(); - - foreach ($schedules as $s){ - $dt = new DateTime($s->getDbStarts(), new DateTimeZone(date_default_timezone_get())); - $dt->setTimezone(new DateTimeZone("UTC")); - $s->setDbStarts($dt); - - $dt = new DateTime($s->getDbEnds(), new DateTimeZone(date_default_timezone_get())); - $dt->setTimezone(new DateTimeZone("UTC")); - $s->setDbEnds($dt); - - $s->save(); - } - } - - public static function convert_cc_show_days(){ - /* cc_show_days has first_show, last_show and start_time fields that need to be changed to UTC. */ - $showDays = CcShowDaysQuery::create()->find(); - - foreach ($showDays as $sd){ - $dt = new DateTime($sd->getDbFirstShow()." ".$sd->getDbStartTime(), new DateTimeZone(date_default_timezone_get())); - $dt->setTimezone(new DateTimeZone("UTC")); - $sd->setDbFirstShow($dt->format("Y-m-d")); - $sd->setDbStartTime($dt->format("H:i:s")); - - $dt = new DateTime($sd->getDbLastShow()." ".$sd->getDbStartTime(), new DateTimeZone(date_default_timezone_get())); - $dt->setTimezone(new DateTimeZone("UTC")); - $sd->setDbLastShow($dt->format("Y-m-d")); - - $sd->save(); - } - } - - public static function convert_cc_show_instances(){ - /* convert_cc_show_instances has starts and ends fields that need to be changed to UTC. */ - $showInstances = CcShowInstancesQuery::create()->find(); - - foreach ($showInstances as $si){ - $dt = new DateTime($si->getDbStarts(), new DateTimeZone(date_default_timezone_get())); - $dt->setTimezone(new DateTimeZone("UTC")); - $si->setDbStarts($dt); - - $dt = new DateTime($si->getDbEnds(), new DateTimeZone(date_default_timezone_get())); - $dt->setTimezone(new DateTimeZone("UTC")); - $si->setDbEnds($dt); - - $si->save(); - } - } -} - -class AirtimeIni200{ - - const CONF_FILE_AIRTIME = "/etc/airtime/airtime.conf"; - const CONF_FILE_PYPO = "/etc/airtime/pypo.cfg"; - const CONF_FILE_RECORDER = "/etc/airtime/recorder.cfg"; - const CONF_FILE_LIQUIDSOAP = "/etc/airtime/liquidsoap.cfg"; - const CONF_FILE_MEDIAMONITOR = "/etc/airtime/media-monitor.cfg"; - const CONF_FILE_API_CLIENT = "/etc/airtime/api_client.cfg"; - - const CONF_PYPO_GRP = "pypo"; - const CONF_WWW_DATA_GRP = "www-data"; - - /** - * This function updates an INI style config file. - * - * A property and the value the property should be changed to are - * supplied. If the property is not found, then no changes are made. - * - * @param string $p_filename - * The path the to the file. - * @param string $p_property - * The property to look for in order to change its value. - * @param string $p_value - * The value the property should be changed to. - * - */ - public static function UpdateIniValue($p_filename, $p_property, $p_value) - { - $lines = file($p_filename); - $n=count($lines); - foreach ($lines as &$line) { - if ($line[0] != "#"){ - $key_value = explode("=", $line); - $key = trim($key_value[0]); - - if ($key == $p_property){ - $line = "$p_property = $p_value".PHP_EOL; - } - } - } - - $fp=fopen($p_filename, 'w'); - for($i=0; $i<$n; $i++){ - fwrite($fp, $lines[$i]); - } - fclose($fp); - } - - public static function ReadPythonConfig($p_filename) - { - $values = array(); - - $fh = fopen($p_filename, 'r'); - - while(!feof($fh)){ - $line = fgets($fh); - if(substr(trim($line), 0, 1) == '#' || trim($line) == ""){ - continue; - }else{ - $info = explode('=', $line, 2); - $values[trim($info[0])] = trim($info[1]); - } - } - - return $values; - } - - public static function MergeConfigFiles($configFiles, $suffix) { - foreach ($configFiles as $conf) { - // we want to use new liquidsoap.cfg so don't merge - // also for monit - if( $conf == AirtimeIni200::CONF_FILE_LIQUIDSOAP){ - continue; - } - if (file_exists("$conf$suffix.bak")) { - - if($conf === AirtimeIni200::CONF_FILE_AIRTIME) { - // Parse with sections - $newSettings = parse_ini_file($conf, true); - $oldSettings = parse_ini_file("$conf$suffix.bak", true); - } - else { - $newSettings = AirtimeIni200::ReadPythonConfig($conf); - $oldSettings = AirtimeIni200::ReadPythonConfig("$conf$suffix.bak"); - } - - $settings = array_keys($newSettings); - - foreach($settings as $section) { - if(isset($oldSettings[$section])) { - if(is_array($oldSettings[$section])) { - $sectionKeys = array_keys($newSettings[$section]); - foreach($sectionKeys as $sectionKey) { - // skip airtim_dir as we want to use new value - if($sectionKey != "airtime_dir"){ - if(isset($oldSettings[$section][$sectionKey])) { - AirtimeIni200::UpdateIniValue($conf, $sectionKey, $oldSettings[$section][$sectionKey]); - } - } - } - } - else { - AirtimeIni200::UpdateIniValue($conf, $section, $oldSettings[$section]); - } - } - } - } - } - } - - /* Re: http://dev.sourcefabric.org/browse/CC-2797 - * We don't want config files to be world-readable so we - * set the strictest permissions possible. */ - public static function changeConfigFilePermissions(){ - if (!self::ChangeFileOwnerGroupMod(AirtimeIni200::CONF_FILE_AIRTIME, self::CONF_WWW_DATA_GRP)){ - echo "Could not set ownership of api_client.cfg to 'pypo'. Exiting."; - exit(1); - } - if (!self::ChangeFileOwnerGroupMod(AirtimeIni200::CONF_FILE_API_CLIENT, self::CONF_PYPO_GRP)){ - echo "Could not set ownership of api_client.cfg to 'pypo'. Exiting."; - exit(1); - } - if (!self::ChangeFileOwnerGroupMod(AirtimeIni200::CONF_FILE_PYPO, self::CONF_PYPO_GRP)){ - echo "Could not set ownership of pypo.cfg to 'pypo'. Exiting."; - exit(1); - } - if (!self::ChangeFileOwnerGroupMod(AirtimeIni200::CONF_FILE_RECORDER, self::CONF_PYPO_GRP)){ - echo "Could not set ownership of recorder.cfg to 'pypo'. Exiting."; - exit(1); - } - if (!self::ChangeFileOwnerGroupMod(AirtimeIni200::CONF_FILE_LIQUIDSOAP, self::CONF_PYPO_GRP)){ - echo "Could not set ownership of liquidsoap.cfg to 'pypo'. Exiting."; - exit(1); - } - if (!self::ChangeFileOwnerGroupMod(AirtimeIni200::CONF_FILE_MEDIAMONITOR, self::CONF_PYPO_GRP)){ - echo "Could not set ownership of media-monitor.cfg to 'pypo'. Exiting."; - exit(1); - } - } - - public static function ChangeFileOwnerGroupMod($filename, $user){ - return (chown($filename, $user) && - chgrp($filename, $user) && - chmod($filename, 0640)); - } - - public static function upgradeConfigFiles(){ - - $configFiles = array(AirtimeIni200::CONF_FILE_AIRTIME, - AirtimeIni200::CONF_FILE_PYPO, - AirtimeIni200::CONF_FILE_RECORDER, - AirtimeIni200::CONF_FILE_LIQUIDSOAP, - AirtimeIni200::CONF_FILE_MEDIAMONITOR, - AirtimeIni200::CONF_FILE_API_CLIENT); - - // Backup the config files - $suffix = date("Ymdhis")."-2.0.0"; - foreach ($configFiles as $conf) { - // do not back up monit cfg - if (file_exists($conf)) { - echo "Backing up $conf to $conf$suffix.bak".PHP_EOL; - //copy($conf, $conf.$suffix.".bak"); - exec("cp -p $conf $conf$suffix.bak"); //use cli version to preserve file attributes - } - } - - $default_suffix = "200"; - AirtimeIni200::CreateIniFiles($default_suffix); - AirtimeIni200::MergeConfigFiles($configFiles, $suffix); - } - - /** - * This function creates the /etc/airtime configuration folder - * and copies the default config files to it. - */ - public static function CreateIniFiles($suffix) - { - if (!file_exists("/etc/airtime/")){ - if (!mkdir("/etc/airtime/", 0755, true)){ - echo "Could not create /etc/airtime/ directory. Exiting."; - exit(1); - } - } - - if (!copy(__DIR__."/airtime.conf.$suffix", AirtimeIni200::CONF_FILE_AIRTIME)){ - echo "Could not copy airtime.conf to /etc/airtime/. Exiting."; - exit(1); - } - if (!copy(__DIR__."/pypo.cfg.$suffix", AirtimeIni200::CONF_FILE_PYPO)){ - echo "Could not copy pypo.cfg to /etc/airtime/. Exiting."; - exit(1); - } - if (!copy(__DIR__."/recorder.cfg.$suffix", AirtimeIni200::CONF_FILE_RECORDER)){ - echo "Could not copy recorder.cfg to /etc/airtime/. Exiting."; - exit(1); - } - /*if (!copy(__DIR__."/liquidsoap.cfg.$suffix", AirtimeIni200::CONF_FILE_LIQUIDSOAP)){ - echo "Could not copy liquidsoap.cfg to /etc/airtime/. Exiting."; - exit(1); - }*/ - if (!copy(__DIR__."/api_client.cfg.$suffix", AirtimeIni200::CONF_FILE_API_CLIENT)){ - echo "Could not copy airtime-monit.cfg to /etc/monit/conf.d/. Exiting."; - exit(1); - } - } -} - -Airtime200Upgrade::connectToDatabase(); -AirtimeInstall::SetDefaultTimezone(); - -AirtimeInstall::InstallBinaries(); -AirtimeInstall::CreateSymlinksToUtils(); - -/* Airtime 2.0.0 starts interpreting all database times in UTC format. Prior to this, all the times - * were stored using the local time zone. Let's convert to UTC time. */ -ConvertToUtc::setPhpDefaultTimeZoneToSystemTimezone(); -ConvertToUtc::convert_cc_playlist(); -ConvertToUtc::convert_cc_schedule(); -ConvertToUtc::convert_cc_show_days(); -ConvertToUtc::convert_cc_show_instances(); - -// merging/updating config files -echo "* Updating configFiles\n"; -AirtimeIni200::changeConfigFilePermissions(); -AirtimeIni200::upgradeConfigFiles(); - -$values = parse_ini_file(AirtimeIni200::CONF_FILE_AIRTIME, true); -$phpDir = $values['general']['airtime_dir']; -Airtime200Upgrade::InstallAirtimePhpServerCode($phpDir); - -if(AirtimeInstall::DbTableExists('doctrine_migration_versions') === false) { - $migrations = array('20110312121200', '20110331111708', '20110402164819', '20110406182005', '20110629143017', '20110711161043', '20110713161043'); - foreach($migrations as $migration) { - AirtimeInstall::BypassMigrations(__DIR__, $migration); - } -} - -AirtimeInstall::MigrateTablesToVersion(__DIR__, '20110925171256'); - -AirtimeInstall::SetDefaultStreamSetting(); - -AirtimeInstall::GetOldLiquidsoapCfgAndUpdate(); - -AirtimeUpgrade::RemoveOldMonitFile(); - -// restart monit -exec("service monit restart"); - - - - diff --git a/install_minimal/upgrades/airtime-2.0.2/UpgradeCommon.php b/install_minimal/upgrades/airtime-2.0.2/UpgradeCommon.php index 75fe5012c..40922a442 100644 --- a/install_minimal/upgrades/airtime-2.0.2/UpgradeCommon.php +++ b/install_minimal/upgrades/airtime-2.0.2/UpgradeCommon.php @@ -1,7 +1,5 @@ getMessage().PHP_EOL; - echo $CC_DBC->getUserInfo().PHP_EOL; + try { + $con = Propel::getConnection(); + } catch (Exception $e) { + echo $e->getMessage().PHP_EOL; echo "Database connection problem.".PHP_EOL; - echo "Check if database '{$CC_CONFIG['dsn']['database']}' exists". - " with corresponding permissions.".PHP_EOL; + echo "Check if database exists with corresponding permissions.".PHP_EOL; if ($p_exitOnError) { exit(1); } - } else { - $CC_DBC->setFetchMode(DB_FETCHMODE_ASSOC); + return false; } + return true; } - + public static function DbTableExists($p_name) { - global $CC_DBC; - $sql = "SELECT * FROM ".$p_name; - $result = $CC_DBC->GetOne($sql); - if (PEAR::isError($result)) { + $con = Propel::getConnection(); + try { + $sql = "SELECT * FROM ".$p_name." LIMIT 1"; + $con->query($sql); + } catch (PDOException $e){ return false; } return true; @@ -65,7 +62,7 @@ class UpgradeCommon{ public static function MigrateTablesToVersion($dir, $version) { echo "Upgrading database, may take several minutes, please wait".PHP_EOL; - + $appDir = self::GetAirtimeSrcDir(); $command = "php --php-ini $dir/../../airtime-php.ini ". "$appDir/library/doctrine/migrations/doctrine-migrations.phar ". @@ -186,9 +183,9 @@ class UpgradeCommon{ private static function ReadPythonConfig($p_filename) { $values = array(); - + $fh = fopen($p_filename, 'r'); - + while(!feof($fh)){ $line = fgets($fh); if(substr(trim($line), 0, 1) == '#' || trim($line) == ""){ @@ -237,16 +234,17 @@ class UpgradeCommon{ } fclose($fp); } - - public static function queryDb($p_sql){ - global $CC_DBC; - $result = $CC_DBC->getRow($p_sql, $fetchmode=DB_FETCHMODE_ASSOC); - if (PEAR::isError($result)) { - echo "Error executing $sql. Exiting."; + public static function queryDb($p_sql){ + $con = Propel::getConnection(); + + try { + $result = $con->exec($p_sql); + } catch (Exception $e) { + echo "Error executing $p_sql. Exiting."; exit(1); } - + return $result; } } diff --git a/install_minimal/upgrades/airtime-2.0.2/airtime-upgrade-old.php b/install_minimal/upgrades/airtime-2.0.2/airtime-upgrade-old.php deleted file mode 100644 index b540021dc..000000000 --- a/install_minimal/upgrades/airtime-2.0.2/airtime-upgrade-old.php +++ /dev/null @@ -1,586 +0,0 @@ -query($sql); - if (PEAR::isError($result)) { - return false; - } - return true; - } - - public static function GetUtilsSrcDir() - { - return __DIR__."/../../../utils"; - } - - public static function InstallBinaries() - { - echo "* Installing binaries to ".AirtimeInstall::CONF_DIR_BINARIES.PHP_EOL; - exec("mkdir -p ".AirtimeInstall::CONF_DIR_BINARIES); - exec("cp -R ".AirtimeInstall::GetUtilsSrcDir()." ".AirtimeInstall::CONF_DIR_BINARIES); - } - - public static function CreateSymlinksToUtils() - { - echo "* Installing airtime-log".PHP_EOL; - $dir = AirtimeInstall::CONF_DIR_BINARIES."/utils/airtime-log"; - copy(AirtimeInstall::GetUtilsSrcDir()."/airtime-log.php", AirtimeInstall::CONF_DIR_BINARIES."/utils/airtime-log.php"); - - exec("ln -s $dir /usr/bin/airtime-log"); - } - - public static function SetDefaultStreamSetting() - { - global $CC_DBC; - - echo "* Setting up default stream setting".PHP_EOL; - $sql = "INSERT INTO cc_pref(keystr, valstr) VALUES('stream_type', 'ogg, mp3'); - INSERT INTO cc_pref(keystr, valstr) VALUES('stream_bitrate', '24, 32, 48, 64, 96, 128, 160, 192, 224, 256, 320'); - INSERT INTO cc_pref(keystr, valstr) VALUES('num_of_streams', '3'); - INSERT INTO cc_pref(keystr, valstr) VALUES('max_bitrate', '128'); - INSERT INTO cc_pref(keystr, valstr) VALUES('plan_level', 'disabled'); - - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('output_sound_device', 'false', 'boolean'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('icecast_vorbis_metadata', 'false', 'boolean'); - - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s1_output', 'icecast', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s1_type', 'ogg', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s1_bitrate', '128', 'integer'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s1_host', '127.0.0.1', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s1_port', '8000', 'integer'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s1_user', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s1_pass', 'hackme', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s1_mount', 'airtime_128', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s1_url', 'http://airtime.sourcefabric.org', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s1_description', 'Airtime Radio! Stream #1', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s1_genre', 'genre', 'string'); - - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s2_output', 'disabled', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s2_type', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s2_bitrate', '', 'integer'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s2_host', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s2_port', '', 'integer'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s2_user', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s2_pass', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s2_mount', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s2_url', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s2_description', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s2_genre', '', 'string'); - - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s3_output', 'disabled', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s3_type', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s3_bitrate', '', 'integer'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s3_host', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s3_port', '', 'integer'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s3_user', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s3_pass', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s3_mount', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s3_url', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s3_description', '', 'string'); - INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s3_genre', '', 'string');"; - $result = $CC_DBC->query($sql); - if (PEAR::isError($result)) { - return false; - } - return true; - } - - public static function BypassMigrations($dir, $version) - { - $appDir = AirtimeInstall::GetAirtimeSrcDir(); - $command = "php $appDir/library/doctrine/migrations/doctrine-migrations.phar ". - "--configuration=$dir/../../DoctrineMigrations/migrations.xml ". - "--db-configuration=$appDir/library/doctrine/migrations/migrations-db.php ". - "--no-interaction --add migrations:version $version"; - system($command); - } - - public static function MigrateTablesToVersion($dir, $version) - { - $appDir = AirtimeInstall::GetAirtimeSrcDir(); - $command = "php $appDir/library/doctrine/migrations/doctrine-migrations.phar ". - "--configuration=$dir/../../DoctrineMigrations/migrations.xml ". - "--db-configuration=$appDir/library/doctrine/migrations/migrations-db.php ". - "--no-interaction migrations:migrate $version"; - system($command); - } - - public static function GetAirtimeSrcDir() - { - return __DIR__."/../../../airtime_mvc"; - } - - public static function DbTableExists($p_name) - { - global $CC_DBC; - $sql = "SELECT * FROM ".$p_name; - $result = $CC_DBC->GetOne($sql); - if (PEAR::isError($result)) { - return false; - } - return true; - } - public static function GetOldLiquidsoapCfgAndUpdate(){ - global $CC_DBC; - echo "* Retrieving old liquidsoap configuration".PHP_EOL; - $map = array(); - $fh = fopen("/etc/airtime/liquidsoap.cfg", 'r'); - $newConfigMap = array(); - - while(!feof($fh)){ - $line = fgets($fh); - if(substr(trim($line), 0, 1) == '#' || trim($line) == ""){ - continue; - }else{ - $info = explode('=', $line, 2); - $map[trim($info[0])] = trim($info[1]); - } - } - $newConfigMap['output_sound_device'] = $map['output_sound_device']; - $newConfigMap['icecast_vorbis_metadata'] = $map['output_icecast_vorbis_metadata']; - $newConfigMap['log_file'] = $map['log_file']; - - $count = 1; - if( $map['output_icecast_vorbis'] == 'true'){ - $newConfigMap['s'.$count.'_output'] = 'icecast'; - $newConfigMap['s'.$count.'_host'] = $map['icecast_host']; - $newConfigMap['s'.$count.'_port'] = $map['icecast_port']; - $newConfigMap['s'.$count.'_pass'] = $map['icecast_pass']; - $newConfigMap['s'.$count.'_mount'] = $map['mount_point_vorbis']; - $newConfigMap['s'.$count.'_url'] = $map['icecast_url']; - $newConfigMap['s'.$count.'_description'] = $map['icecast_description']; - $newConfigMap['s'.$count.'_genre'] = $map['icecast_genre']; - $newConfigMap['s'.$count.'_type'] = "ogg"; - $newConfigMap['s'.$count.'_bitrate'] = "128"; - $count++; - } - if($map['output_icecast_mp3'] == 'true'){ - $newConfigMap['s'.$count.'_output'] = 'icecast'; - $newConfigMap['s'.$count.'_host'] = $map['icecast_host']; - $newConfigMap['s'.$count.'_port'] = $map['icecast_port']; - $newConfigMap['s'.$count.'_pass'] = $map['icecast_pass']; - $newConfigMap['s'.$count.'_mount'] = $map['mount_point_mp3']; - $newConfigMap['s'.$count.'_url'] = $map['icecast_url']; - $newConfigMap['s'.$count.'_description'] = $map['icecast_description']; - $newConfigMap['s'.$count.'_genre'] = $map['icecast_genre']; - $newConfigMap['s'.$count.'_type'] = "mp3"; - $newConfigMap['s'.$count.'_bitrate'] = "128"; - $count++; - } - if($map['output_shoutcast'] == 'true'){ - $newConfigMap['s'.$count.'_output'] = 'shoutcast'; - $newConfigMap['s'.$count.'_host'] = $map['shoutcast_host']; - $newConfigMap['s'.$count.'_port'] = $map['shoutcast_port']; - $newConfigMap['s'.$count.'_pass'] = $map['shoutcast_pass']; - $newConfigMap['s'.$count.'_url'] = $map['shoutcast_url']; - $newConfigMap['s'.$count.'_genre'] = $map['shoutcast_genre']; - $newConfigMap['s'.$count.'_type'] = "mp3"; - $newConfigMap['s'.$count.'_bitrate'] = "128"; - $count++; - } - - $sql = ""; - foreach( $newConfigMap as $key=>$val){ - if(substr($val, 0, 1) == '"' && substr($val, strlen($val)-1,1)){ - $val = ltrim($val, '"'); - $val = rtrim($val, '"'); - } - $sql .= "UPDATE cc_stream_setting SET value='$val' WHERE keyname='$key';"; - } - $result = $CC_DBC->query($sql); - if (PEAR::isError($result)) { - return false; - } - return true; - } -} - -class Airtime200Upgrade{ - - public static function connectToDatabase(){ - global $CC_DBC, $CC_CONFIG; - - $values = parse_ini_file('/etc/airtime/airtime.conf', true); - - // Database config - $CC_CONFIG['dsn']['username'] = $values['database']['dbuser']; - $CC_CONFIG['dsn']['password'] = $values['database']['dbpass']; - $CC_CONFIG['dsn']['hostspec'] = $values['database']['host']; - $CC_CONFIG['dsn']['phptype'] = 'pgsql'; - $CC_CONFIG['dsn']['database'] = $values['database']['dbname']; - - $CC_DBC = DB::connect($CC_CONFIG['dsn'], FALSE); - } - - public static function InstallAirtimePhpServerCode($phpDir) - { - - $AIRTIME_SRC = realpath(__DIR__.'/../../../airtime_mvc'); - - // delete old files - exec("rm -rf ".$phpDir); - echo "* Installing PHP code to ".$phpDir.PHP_EOL; - exec("mkdir -p ".$phpDir); - exec("cp -R ".$AIRTIME_SRC."/* ".$phpDir); - } - - public static function RemoveOldMonitFile(){ - unlink("/etc/monit/conf.d/airtime-monit.cfg"); - } -} - -class ConvertToUtc{ - - public static function setPhpDefaultTimeZoneToSystemTimezone(){ - //we can get the default system timezone on debian/ubuntu by reading "/etc/timezone" - $filename = "/etc/timezone"; - $handle = fopen($filename, "r"); - $contents = trim(fread($handle, filesize($filename))); - echo "System timezone detected as: $contents".PHP_EOL; - fclose($handle); - - date_default_timezone_set($contents); - } - - public static function convert_cc_playlist(){ - /* cc_playlist has a field that keeps track of when the playlist was last modified. */ - $playlists = CcPlaylistQuery::create()->find(); - - foreach ($playlists as $pl){ - $dt = new DateTime($pl->getDbMtime(), new DateTimeZone(date_default_timezone_get())); - $dt->setTimezone(new DateTimeZone("UTC")); - $pl->setDbMtime($dt); - - $pl->save(); - } - } - - public static function convert_cc_schedule(){ - /* cc_schedule has start and end fields that need to be changed to UTC. */ - $schedules = CcScheduleQuery::create()->find(); - - foreach ($schedules as $s){ - $dt = new DateTime($s->getDbStarts(), new DateTimeZone(date_default_timezone_get())); - $dt->setTimezone(new DateTimeZone("UTC")); - $s->setDbStarts($dt); - - $dt = new DateTime($s->getDbEnds(), new DateTimeZone(date_default_timezone_get())); - $dt->setTimezone(new DateTimeZone("UTC")); - $s->setDbEnds($dt); - - $s->save(); - } - } - - public static function convert_cc_show_days(){ - /* cc_show_days has first_show, last_show and start_time fields that need to be changed to UTC. */ - $showDays = CcShowDaysQuery::create()->find(); - - foreach ($showDays as $sd){ - $dt = new DateTime($sd->getDbFirstShow()." ".$sd->getDbStartTime(), new DateTimeZone(date_default_timezone_get())); - $dt->setTimezone(new DateTimeZone("UTC")); - $sd->setDbFirstShow($dt->format("Y-m-d")); - $sd->setDbStartTime($dt->format("H:i:s")); - - $dt = new DateTime($sd->getDbLastShow()." ".$sd->getDbStartTime(), new DateTimeZone(date_default_timezone_get())); - $dt->setTimezone(new DateTimeZone("UTC")); - $sd->setDbLastShow($dt->format("Y-m-d")); - - $sd->save(); - } - } - - public static function convert_cc_show_instances(){ - /* convert_cc_show_instances has starts and ends fields that need to be changed to UTC. */ - $showInstances = CcShowInstancesQuery::create()->find(); - - foreach ($showInstances as $si){ - $dt = new DateTime($si->getDbStarts(), new DateTimeZone(date_default_timezone_get())); - $dt->setTimezone(new DateTimeZone("UTC")); - $si->setDbStarts($dt); - - $dt = new DateTime($si->getDbEnds(), new DateTimeZone(date_default_timezone_get())); - $dt->setTimezone(new DateTimeZone("UTC")); - $si->setDbEnds($dt); - - $si->save(); - } - } -} - -class AirtimeIni200{ - - const CONF_FILE_AIRTIME = "/etc/airtime/airtime.conf"; - const CONF_FILE_PYPO = "/etc/airtime/pypo.cfg"; - const CONF_FILE_RECORDER = "/etc/airtime/recorder.cfg"; - const CONF_FILE_LIQUIDSOAP = "/etc/airtime/liquidsoap.cfg"; - const CONF_FILE_MEDIAMONITOR = "/etc/airtime/media-monitor.cfg"; - const CONF_FILE_API_CLIENT = "/etc/airtime/api_client.cfg"; - - const CONF_PYPO_GRP = "pypo"; - const CONF_WWW_DATA_GRP = "www-data"; - - /** - * This function updates an INI style config file. - * - * A property and the value the property should be changed to are - * supplied. If the property is not found, then no changes are made. - * - * @param string $p_filename - * The path the to the file. - * @param string $p_property - * The property to look for in order to change its value. - * @param string $p_value - * The value the property should be changed to. - * - */ - public static function UpdateIniValue($p_filename, $p_property, $p_value) - { - $lines = file($p_filename); - $n=count($lines); - foreach ($lines as &$line) { - if ($line[0] != "#"){ - $key_value = explode("=", $line); - $key = trim($key_value[0]); - - if ($key == $p_property){ - $line = "$p_property = $p_value".PHP_EOL; - } - } - } - - $fp=fopen($p_filename, 'w'); - for($i=0; $i<$n; $i++){ - fwrite($fp, $lines[$i]); - } - fclose($fp); - } - - public static function ReadPythonConfig($p_filename) - { - $values = array(); - - $fh = fopen($p_filename, 'r'); - - while(!feof($fh)){ - $line = fgets($fh); - if(substr(trim($line), 0, 1) == '#' || trim($line) == ""){ - continue; - }else{ - $info = explode('=', $line, 2); - $values[trim($info[0])] = trim($info[1]); - } - } - - return $values; - } - - public static function MergeConfigFiles($configFiles, $suffix) { - foreach ($configFiles as $conf) { - // we want to use new liquidsoap.cfg so don't merge - // also for monit - if( $conf == AirtimeIni200::CONF_FILE_LIQUIDSOAP){ - continue; - } - if (file_exists("$conf$suffix.bak")) { - - if($conf === AirtimeIni200::CONF_FILE_AIRTIME) { - // Parse with sections - $newSettings = parse_ini_file($conf, true); - $oldSettings = parse_ini_file("$conf$suffix.bak", true); - } - else { - $newSettings = AirtimeIni200::ReadPythonConfig($conf); - $oldSettings = AirtimeIni200::ReadPythonConfig("$conf$suffix.bak"); - } - - $settings = array_keys($newSettings); - - foreach($settings as $section) { - if(isset($oldSettings[$section])) { - if(is_array($oldSettings[$section])) { - $sectionKeys = array_keys($newSettings[$section]); - foreach($sectionKeys as $sectionKey) { - // skip airtim_dir as we want to use new value - if($sectionKey != "airtime_dir"){ - if(isset($oldSettings[$section][$sectionKey])) { - AirtimeIni200::UpdateIniValue($conf, $sectionKey, $oldSettings[$section][$sectionKey]); - } - } - } - } - else { - AirtimeIni200::UpdateIniValue($conf, $section, $oldSettings[$section]); - } - } - } - } - } - } - - /* Re: http://dev.sourcefabric.org/browse/CC-2797 - * We don't want config files to be world-readable so we - * set the strictest permissions possible. */ - public static function changeConfigFilePermissions(){ - if (!self::ChangeFileOwnerGroupMod(AirtimeIni200::CONF_FILE_AIRTIME, self::CONF_WWW_DATA_GRP)){ - echo "Could not set ownership of api_client.cfg to 'pypo'. Exiting."; - exit(1); - } - if (!self::ChangeFileOwnerGroupMod(AirtimeIni200::CONF_FILE_API_CLIENT, self::CONF_PYPO_GRP)){ - echo "Could not set ownership of api_client.cfg to 'pypo'. Exiting."; - exit(1); - } - if (!self::ChangeFileOwnerGroupMod(AirtimeIni200::CONF_FILE_PYPO, self::CONF_PYPO_GRP)){ - echo "Could not set ownership of pypo.cfg to 'pypo'. Exiting."; - exit(1); - } - if (!self::ChangeFileOwnerGroupMod(AirtimeIni200::CONF_FILE_RECORDER, self::CONF_PYPO_GRP)){ - echo "Could not set ownership of recorder.cfg to 'pypo'. Exiting."; - exit(1); - } - if (!self::ChangeFileOwnerGroupMod(AirtimeIni200::CONF_FILE_LIQUIDSOAP, self::CONF_PYPO_GRP)){ - echo "Could not set ownership of liquidsoap.cfg to 'pypo'. Exiting."; - exit(1); - } - if (!self::ChangeFileOwnerGroupMod(AirtimeIni200::CONF_FILE_MEDIAMONITOR, self::CONF_PYPO_GRP)){ - echo "Could not set ownership of media-monitor.cfg to 'pypo'. Exiting."; - exit(1); - } - } - - public static function ChangeFileOwnerGroupMod($filename, $user){ - return (chown($filename, $user) && - chgrp($filename, $user) && - chmod($filename, 0640)); - } - - public static function upgradeConfigFiles(){ - - $configFiles = array(AirtimeIni200::CONF_FILE_AIRTIME, - AirtimeIni200::CONF_FILE_PYPO, - AirtimeIni200::CONF_FILE_RECORDER, - AirtimeIni200::CONF_FILE_LIQUIDSOAP, - AirtimeIni200::CONF_FILE_MEDIAMONITOR, - AirtimeIni200::CONF_FILE_API_CLIENT); - - // Backup the config files - $suffix = date("Ymdhis")."-2.0.0"; - foreach ($configFiles as $conf) { - // do not back up monit cfg - if (file_exists($conf)) { - echo "Backing up $conf to $conf$suffix.bak".PHP_EOL; - //copy($conf, $conf.$suffix.".bak"); - exec("cp -p $conf $conf$suffix.bak"); //use cli version to preserve file attributes - } - } - - $default_suffix = "200"; - AirtimeIni200::CreateIniFiles($default_suffix); - AirtimeIni200::MergeConfigFiles($configFiles, $suffix); - } - - /** - * This function creates the /etc/airtime configuration folder - * and copies the default config files to it. - */ - public static function CreateIniFiles($suffix) - { - if (!file_exists("/etc/airtime/")){ - if (!mkdir("/etc/airtime/", 0755, true)){ - echo "Could not create /etc/airtime/ directory. Exiting."; - exit(1); - } - } - - if (!copy(__DIR__."/airtime.conf.$suffix", AirtimeIni200::CONF_FILE_AIRTIME)){ - echo "Could not copy airtime.conf to /etc/airtime/. Exiting."; - exit(1); - } - if (!copy(__DIR__."/pypo.cfg.$suffix", AirtimeIni200::CONF_FILE_PYPO)){ - echo "Could not copy pypo.cfg to /etc/airtime/. Exiting."; - exit(1); - } - if (!copy(__DIR__."/recorder.cfg.$suffix", AirtimeIni200::CONF_FILE_RECORDER)){ - echo "Could not copy recorder.cfg to /etc/airtime/. Exiting."; - exit(1); - } - /*if (!copy(__DIR__."/liquidsoap.cfg.$suffix", AirtimeIni200::CONF_FILE_LIQUIDSOAP)){ - echo "Could not copy liquidsoap.cfg to /etc/airtime/. Exiting."; - exit(1); - }*/ - if (!copy(__DIR__."/api_client.cfg.$suffix", AirtimeIni200::CONF_FILE_API_CLIENT)){ - echo "Could not copy airtime-monit.cfg to /etc/monit/conf.d/. Exiting."; - exit(1); - } - } -} - -Airtime200Upgrade::connectToDatabase(); -AirtimeInstall::SetDefaultTimezone(); - -AirtimeInstall::InstallBinaries(); -AirtimeInstall::CreateSymlinksToUtils(); - -/* Airtime 2.0.0 starts interpreting all database times in UTC format. Prior to this, all the times - * were stored using the local time zone. Let's convert to UTC time. */ -ConvertToUtc::setPhpDefaultTimeZoneToSystemTimezone(); -ConvertToUtc::convert_cc_playlist(); -ConvertToUtc::convert_cc_schedule(); -ConvertToUtc::convert_cc_show_days(); -ConvertToUtc::convert_cc_show_instances(); - -// merging/updating config files -echo "* Updating configFiles\n"; -AirtimeIni200::changeConfigFilePermissions(); -AirtimeIni200::upgradeConfigFiles(); - -$values = parse_ini_file(AirtimeIni200::CONF_FILE_AIRTIME, true); -$phpDir = $values['general']['airtime_dir']; -Airtime200Upgrade::InstallAirtimePhpServerCode($phpDir); - -if(AirtimeInstall::DbTableExists('doctrine_migration_versions') === false) { - $migrations = array('20110312121200', '20110331111708', '20110402164819', '20110406182005', '20110629143017', '20110711161043', '20110713161043'); - foreach($migrations as $migration) { - AirtimeInstall::BypassMigrations(__DIR__, $migration); - } -} - -AirtimeInstall::MigrateTablesToVersion(__DIR__, '20110925171256'); - -AirtimeInstall::SetDefaultStreamSetting(); - -AirtimeInstall::GetOldLiquidsoapCfgAndUpdate(); - -AirtimeUpgrade::RemoveOldMonitFile(); - -// restart monit -exec("service monit restart"); - - - - diff --git a/install_minimal/upgrades/upgrade-template/UpgradeCommon.php b/install_minimal/upgrades/upgrade-template/UpgradeCommon.php index ead2ba311..218ecfa3c 100644 --- a/install_minimal/upgrades/upgrade-template/UpgradeCommon.php +++ b/install_minimal/upgrades/upgrade-template/UpgradeCommon.php @@ -1,11 +1,10 @@ getMessage().PHP_EOL; - echo $CC_DBC->getUserInfo().PHP_EOL; - echo "Database connection problem.".PHP_EOL; - echo "Check if database '{$CC_CONFIG['dsn']['database']}' exists". - " with corresponding permissions.".PHP_EOL; - if ($p_exitOnError) { - exit(1); - } - } else { - $CC_DBC->setFetchMode(DB_FETCHMODE_ASSOC); - } + try { + $con = Propel::getConnection(); + } catch (Exception $e) { + echo $e->getMessage().PHP_EOL; + echo "Database connection problem.".PHP_EOL; + echo "Check if database exists with corresponding permissions.".PHP_EOL; + if ($p_exitOnError) { + exit(1); + } + return false; + } + return true; } - + public static function DbTableExists($p_name) { - global $CC_DBC; - $sql = "SELECT * FROM ".$p_name; - $result = $CC_DBC->GetOne($sql); - if (PEAR::isError($result)) { - return false; - } - return true; + $con = Propel::getConnection(); + try { + $sql = "SELECT * FROM ".$p_name." LIMIT 1"; + $con->query($sql); + } catch (PDOException $e){ + return false; + } + return true; } private static function GetAirtimeSrcDir() @@ -176,9 +181,9 @@ class UpgradeCommon{ private static function ReadPythonConfig($p_filename) { $values = array(); - + $fh = fopen($p_filename, 'r'); - + while(!feof($fh)){ $line = fgets($fh); if(substr(trim($line), 0, 1) == '#' || trim($line) == ""){ From c0da27b445917e98f8795004765593809d93b8e9 Mon Sep 17 00:00:00 2001 From: "paul.baranowski" Date: Mon, 2 Apr 2012 00:31:26 -0400 Subject: [PATCH 10/15] CC-1927: Remove Pear DB Final touches on install/upgrade scripts, now they are working. Still need to remove last traces of PEAR throughout the code. --- airtime_mvc/application/Bootstrap.php | 44 +------------------ .../include/airtime-db-install.php | 4 +- install_minimal/include/airtime-install.php | 3 ++ .../include/airtime-installed-check.php | 15 ++++--- 4 files changed, 13 insertions(+), 53 deletions(-) diff --git a/airtime_mvc/application/Bootstrap.php b/airtime_mvc/application/Bootstrap.php index 99ed6c71b..7b4813e19 100644 --- a/airtime_mvc/application/Bootstrap.php +++ b/airtime_mvc/application/Bootstrap.php @@ -2,59 +2,17 @@ require_once __DIR__."/logging/Logging.php"; Logging::setLogPath('/var/log/airtime/zendphp.log'); - require_once __DIR__."/configs/conf.php"; - require_once __DIR__."/configs/ACL.php"; require_once 'propel/runtime/lib/Propel.php'; Propel::init(__DIR__."/configs/airtime-conf-production.php"); - require_once __DIR__."/configs/constants.php"; -// require_once 'DB.php'; - require_once 'Preference.php'; require_once "DateHelper.php"; require_once "OsPath.php"; require_once __DIR__.'/controllers/plugins/RabbitMqPlugin.php'; -global $CC_CONFIG; //, $CC_DBC; -$dsn = $CC_CONFIG['dsn']; - -// ****************************************************************** -// Differences between PEAR DB & Propel/PDO: -// When selecting a single value from a null return set, -// PEAR returns NULL -// PDO returns false -// ****************************************************************** - - -// $CC_DBC = DB::connect($dsn, FALSE); -// if (PEAR::isError($CC_DBC)) { -// echo "ERROR: ".$CC_DBC->getMessage()." ".$CC_DBC->getUserInfo()."\n"; -// exit(1); -// } -// $CC_DBC->setFetchMode(DB_FETCHMODE_ASSOC); - -// $sql = "SELECT column_name, character_maximum_length FROM information_schema.columns" -// ." WHERE table_name = 'cc_show' AND character_maximum_length > 0 and table_name=''"; -// // $sql = "SELECT * FROM cc_files WHERE id=1"; -// // $result = $CC_DBC->GetAll($sql); -// $result = $CC_DBC->GetOne($sql); -// var_dump($result); - -// $sql = "SELECT 1"; -// try { -// $con = Propel::getConnection(); -// //$q = $con->query($sql); -// } catch (Exception $e) { -// var_dump($e); -// } -// var_dump($q); -// //var_dump($q->fetchAll()); -// var_dump($q->fetchColumn(0)); - -// exit; - +global $CC_CONFIG; $CC_CONFIG['airtime_version'] = Application_Model_Preference::GetAirtimeVersion(); require_once __DIR__."/configs/navigation.php"; diff --git a/install_minimal/include/airtime-db-install.php b/install_minimal/include/airtime-db-install.php index 8fc21f6b6..862ce3756 100644 --- a/install_minimal/include/airtime-db-install.php +++ b/install_minimal/include/airtime-db-install.php @@ -5,8 +5,6 @@ * cannot be created. So this script is run after all DEB packages have been installed. */ -//set_include_path(__DIR__.'/../airtime_mvc/library' . PATH_SEPARATOR . get_include_path()); - require_once(__DIR__.'/AirtimeIni.php'); require_once(__DIR__.'/AirtimeInstall.php'); require_once(__DIR__.'/airtime-constants.php'); @@ -21,7 +19,7 @@ AirtimeInstall::CreateDatabaseUser(); $databaseExisted = AirtimeInstall::CreateDatabase(); -//AirtimeInstall::DbConnect(true); +AirtimeInstall::DbConnect(true); AirtimeInstall::InstallPostgresScriptingLanguage(); diff --git a/install_minimal/include/airtime-install.php b/install_minimal/include/airtime-install.php index 281c346f8..6ff0aa492 100644 --- a/install_minimal/include/airtime-install.php +++ b/install_minimal/include/airtime-install.php @@ -10,6 +10,9 @@ require_once(__DIR__.'/AirtimeIni.php'); require_once(__DIR__.'/AirtimeInstall.php'); require_once(__DIR__.'/airtime-constants.php'); +require_once(AirtimeInstall::GetAirtimeSrcDir().'/application/configs/conf.php'); +require_once 'propel/runtime/lib/Propel.php'; +Propel::init(AirtimeInstall::GetAirtimeSrcDir()."/application/configs/airtime-conf-production.php"); $version = AirtimeInstall::GetVersionInstalled(); diff --git a/install_minimal/include/airtime-installed-check.php b/install_minimal/include/airtime-installed-check.php index 5cbd65b10..29afd50f6 100644 --- a/install_minimal/include/airtime-installed-check.php +++ b/install_minimal/include/airtime-installed-check.php @@ -1,30 +1,31 @@ Date: Thu, 5 Apr 2012 02:22:21 -0400 Subject: [PATCH 11/15] CC-1927 Remove PEAR DB * Removed all traces of PEAR functions. * Fixed AirtimeInstall::GetVersionInstalled() to return the correct answer even when it cant connect to the database. Also fixed return value to be consistent on failure. * Fixed phone_home_stat.php and soundcloud-uploader.php --- .../application/controllers/ApiController.php | 61 ++++++++----------- airtime_mvc/application/models/StoredFile.php | 3 - .../application/models/tests/AllTests.php | 1 - .../models/tests/SchedulerTests.php | 10 --- .../models/tests/StoredFileTests.php | 16 ----- install_minimal/include/AirtimeInstall.php | 14 ++++- .../include/airtime-installed-check.php | 2 +- .../pypo/test/airtime-schedule-insert.php | 16 ----- utils/phone_home_stat.php | 39 ++++++------ utils/soundcloud-uploader.php | 23 +++---- 10 files changed, 65 insertions(+), 120 deletions(-) diff --git a/airtime_mvc/application/controllers/ApiController.php b/airtime_mvc/application/controllers/ApiController.php index 232577ae5..9243ee0a6 100644 --- a/airtime_mvc/application/controllers/ApiController.php +++ b/airtime_mvc/application/controllers/ApiController.php @@ -123,7 +123,7 @@ class ApiController extends Zend_Controller_Action if (ctype_alnum($file_id) && strlen($file_id) == 32) { $media = Application_Model_StoredFile::RecallByGunid($file_id); - if ( $media != null && !PEAR::isError($media)) + if ( $media != null ) { $filepath = $media->getFilePath(); if(is_file($filepath)){ @@ -164,13 +164,13 @@ class ApiController extends Zend_Controller_Action /** * Reads the requested portion of a file and sends its contents to the client with the appropriate headers. - * + * * This HTTP_RANGE compatible read file function is necessary for allowing streaming media to be skipped around in. - * + * * @param string $location * @param string $mimeType * @return void - * + * * @link https://groups.google.com/d/msg/jplayer/nSM2UmnSKKA/Hu76jDZS4xcJ * @link http://php.net/manual/en/function.readfile.php#86244 */ @@ -178,17 +178,17 @@ class ApiController extends Zend_Controller_Action { $size= filesize($location); $time= date('r', filemtime($location)); - + $fm = @fopen($location, 'rb'); if (!$fm) { header ("HTTP/1.1 505 Internal server error"); return; } - + $begin= 0; $end= $size - 1; - + if (isset($_SERVER['HTTP_RANGE'])) { if (preg_match('/bytes=\h*(\d+)-(\d*)[\D.*]?/i', $_SERVER['HTTP_RANGE'], $matches)) @@ -200,7 +200,7 @@ class ApiController extends Zend_Controller_Action } } } - + if (isset($_SERVER['HTTP_RANGE'])) { header('HTTP/1.1 206 Partial Content'); @@ -209,9 +209,9 @@ class ApiController extends Zend_Controller_Action { header('HTTP/1.1 200 OK'); } - header("Content-Type: $mimeType"); + header("Content-Type: $mimeType"); header('Cache-Control: public, must-revalidate, max-age=0'); - header('Pragma: no-cache'); + header('Pragma: no-cache'); header('Accept-Ranges: bytes'); header('Content-Length:' . (($end - $begin) + 1)); if (isset($_SERVER['HTTP_RANGE'])) @@ -225,7 +225,7 @@ class ApiController extends Zend_Controller_Action //keep looping until all have been disabled!!! //http://www.php.net/manual/en/function.ob-end-flush.php while (@ob_end_flush()); - + $cur = $begin; fseek($fm, $begin, 0); @@ -235,7 +235,7 @@ class ApiController extends Zend_Controller_Action $cur += 1024 * 16; } } - + /** * Retrieve the currently playing show as well as upcoming shows. * Number of shows returned and the time interval in which to @@ -342,8 +342,6 @@ class ApiController extends Zend_Controller_Action exit; } - //PEAR::setErrorHandling(PEAR_ERROR_RETURN); - $data = Application_Model_Schedule::GetScheduledPlaylists(); echo json_encode($data, JSON_FORCE_OBJECT); } @@ -368,12 +366,7 @@ class ApiController extends Zend_Controller_Action $schedule_group_id = $this->_getParam("schedule_id"); $media_id = $this->_getParam("media_id"); $result = Application_Model_Schedule::UpdateMediaPlayedStatus($media_id); - - if (!PEAR::isError($result)) { - echo json_encode(array("status"=>1, "message"=>"")); - } else { - echo json_encode(array("status"=>0, "message"=>"DB Error:".$result->getMessage())); - } + echo json_encode(array("status"=>1, "message"=>"")); } public function recordedShowsAction() @@ -429,7 +422,7 @@ 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].'"}}'); } @@ -780,7 +773,7 @@ class ApiController extends Zend_Controller_Action print 'You are not allowed to access this resource.'; exit; } - + $info = Application_Model_StreamSetting::getStreamSetting(); $this->view->msg = $info; } @@ -836,7 +829,7 @@ class ApiController extends Zend_Controller_Action Application_Model_StreamSetting::setLiquidsoapError($stream_id, $msg, $boot_time); } - + public function updateSourceStatusAction(){ $request = $this->getRequest(); @@ -945,13 +938,13 @@ class ApiController extends Zend_Controller_Action $dir = base64_decode($request->getParam('dir')); Application_Model_MusicDir::removeWatchedDir($dir, 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 rabbitmqDoPushAction(){ global $CC_CONFIG; - + $request = $this->getRequest(); $api_key = $request->getParam('api_key'); if (!in_array($api_key, $CC_CONFIG["apiKey"]) && @@ -962,10 +955,10 @@ class ApiController extends Zend_Controller_Action exit; } Logging::log("Notifying RabbitMQ to send message to pypo"); - + Application_Model_RabbitMq::PushSchedule(); } - + public function getBootstrapInfoAction(){ $live_dj = Application_Model_Preference::GetSourceSwitchStatus('live_dj'); $master_dj = Application_Model_Preference::GetSourceSwitchStatus('master_dj'); @@ -977,14 +970,14 @@ class ApiController extends Zend_Controller_Action $this->view->stream_label = Application_Model_Preference::GetStreamLabelFormat(); $this->view->transition_fade = Application_Model_Preference::GetDefaultTransitionFade(); } - + /* This is used but Liquidsoap to check authentication of live streams*/ public function checkLiveStreamAuthAction(){ global $CC_CONFIG; - + $request = $this->getRequest(); $api_key = $request->getParam('api_key'); - + $username = $request->getParam('username'); $password = $request->getParam('password'); $djtype = $request->getParam('djtype'); @@ -996,7 +989,7 @@ class ApiController extends Zend_Controller_Action print 'You are not allowed to access this resource.'; exit; } - + if($djtype == 'master'){ //check against master if($username == Application_Model_Preference::GetLiveSteamMasterUsername() && $password == Application_Model_Preference::GetLiveSteamMasterPassword()){ @@ -1011,15 +1004,15 @@ class ApiController extends Zend_Controller_Action if(isset($showInfo[0]['id'])){ $current_show_id = $showInfo[0]['id']; $CcShow = CcShowQuery::create()->findPK($current_show_id); - + // get custom pass info from the show $custom_user = $CcShow->getDbLiveStreamUser(); $custom_pass = $CcShow->getDbLiveStreamPass(); - + // get hosts ids $show = new Application_Model_Show($current_show_id); $hosts_ids = $show->getHostsIds(); - + // check against hosts auth if($CcShow->getDbLiveStreamUsingAirtimeAuth()){ foreach( $hosts_ids as $host){ diff --git a/airtime_mvc/application/models/StoredFile.php b/airtime_mvc/application/models/StoredFile.php index 7347e3f0c..ee9eea356 100644 --- a/airtime_mvc/application/models/StoredFile.php +++ b/airtime_mvc/application/models/StoredFile.php @@ -822,9 +822,6 @@ Logging::log("getting media! - 2"); $result = null; if ($duplicate) { - if (PEAR::isError($duplicate)) { - $result = array("code" => 105, "message" => $duplicate->getMessage()); - } 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."); diff --git a/airtime_mvc/application/models/tests/AllTests.php b/airtime_mvc/application/models/tests/AllTests.php index 2d5620935..fbd803c07 100644 --- a/airtime_mvc/application/models/tests/AllTests.php +++ b/airtime_mvc/application/models/tests/AllTests.php @@ -3,7 +3,6 @@ set_include_path(get_include_path() . PATH_SEPARATOR . $path); $WHITE_SCREEN_OF_DEATH = false; require_once(dirname(__FILE__).'/../../configs/conf.php'); -require_once('DB.php'); require_once('PHPUnit.php'); require_once 'StoredFileTests.php'; require_once 'SchedulerTests.php'; diff --git a/airtime_mvc/application/models/tests/SchedulerTests.php b/airtime_mvc/application/models/tests/SchedulerTests.php index e4094c313..a51fa6fef 100644 --- a/airtime_mvc/application/models/tests/SchedulerTests.php +++ b/airtime_mvc/application/models/tests/SchedulerTests.php @@ -46,9 +46,6 @@ class SchedulerTests extends PHPUnit_TestCase { function testAddAndRemoveAudioFile() { $i = new Application_Model_ScheduleGroup(); $this->groupIdCreated = $i->add('2010-10-10 01:30:23', $this->storedFile->getId()); - if (PEAR::isError($this->groupIdCreated)) { - $this->fail("Failed to create scheduled item: ". $this->groupIdCreated->getMessage()); - } $i = new Application_Model_ScheduleGroup($this->groupIdCreated); $result = $i->remove(); @@ -67,9 +64,6 @@ class SchedulerTests extends PHPUnit_TestCase { $i = new Application_Model_ScheduleGroup(); $this->groupIdCreated = $i->add('2010-11-11 01:30:23', null, $playlist->getId()); - if (PEAR::isError($this->groupIdCreated)) { - $this->fail("Failed to create scheduled item: ". $this->groupIdCreated->getMessage()); - } $group = new Application_Model_ScheduleGroup($this->groupIdCreated); if ($group->count() != 3) { $this->fail("Wrong number of items added."); @@ -90,10 +84,6 @@ class SchedulerTests extends PHPUnit_TestCase { function testIsScheduleEmptyInRange() { $i = new Application_Model_ScheduleGroup(); $this->groupIdCreated = $i->add('2011-10-10 01:30:23', $this->storedFile->getId()); - if (PEAR::isError($this->groupIdCreated)) { - $this->fail($this->groupIdCreated->getMessage()); - return; - } if (Application_Model_Schedule::isScheduleEmptyInRange('2011-10-10 01:30:23', '00:00:12.555')) { $this->fail("Reporting empty schedule when it isnt."); return; diff --git a/airtime_mvc/application/models/tests/StoredFileTests.php b/airtime_mvc/application/models/tests/StoredFileTests.php index cb2ee4eb5..851c62741 100644 --- a/airtime_mvc/application/models/tests/StoredFileTests.php +++ b/airtime_mvc/application/models/tests/StoredFileTests.php @@ -1,14 +1,6 @@ getMessage()." ".$CC_DBC->getUserInfo()."\n"; - exit(1); -} -$CC_DBC->setFetchMode(DB_FETCHMODE_ASSOC); - class StoredFileTest extends PHPUnit_TestCase { function __construct($name) { @@ -21,10 +13,6 @@ class StoredFileTest extends PHPUnit_TestCase { function testGetAudioMetadata() { $filePath = dirname(__FILE__)."/ex1.mp3"; $metadata = Metadata::LoadFromFile($filePath); - if (PEAR::isError($metadata)) { - $this->fail($metadata->getMessage()); - return; - } if (($metadata["dc:description"] != "Tmu sem tam videla ...") || ($metadata["audio"]["dataformat"] != "mp3") || ($metadata["dc:type"] != "Speech")) { @@ -52,10 +40,6 @@ class StoredFileTest extends PHPUnit_TestCase { $values = array("filepath" => $filePath, "dc:description" => "Unit test ".time()); $storedFile = Application_Model_StoredFile::Insert($values, false); - if (PEAR::isError($storedFile)) { - $this->fail("Failed to create StoredFile: ".$storedFile->getMessage()); - return; - } //var_dump($storedFile); $id = $storedFile->getId(); if (!is_numeric($id)) { diff --git a/install_minimal/include/AirtimeInstall.php b/install_minimal/include/AirtimeInstall.php index 4b8819178..5af33878c 100644 --- a/install_minimal/include/AirtimeInstall.php +++ b/install_minimal/include/AirtimeInstall.php @@ -38,10 +38,20 @@ class AirtimeInstall } } + /** + * Return the version of Airtime currently installed. + * If not installed, return null. + * + * @return NULL|string + */ public static function GetVersionInstalled() { global $CC_CONFIG; - $con = Propel::getConnection(); + try { + $con = Propel::getConnection(); + } catch (PropelException $e) { + return null; + } if (file_exists('/etc/airtime/airtime.conf')) { $values = parse_ini_file('/etc/airtime/airtime.conf', true); @@ -66,7 +76,7 @@ class AirtimeInstall //echo "Airtime Version: ".$version." ".PHP_EOL; } else { - $version = false; + $version = null; } } diff --git a/install_minimal/include/airtime-installed-check.php b/install_minimal/include/airtime-installed-check.php index 29afd50f6..f398105b2 100644 --- a/install_minimal/include/airtime-installed-check.php +++ b/install_minimal/include/airtime-installed-check.php @@ -23,7 +23,7 @@ $version = AirtimeInstall::GetVersionInstalled(); // The current version is already installed. echo "* Checking for existing Airtime installation...".PHP_EOL; if (isset($version)){ - if ($version === false){ + if (is_null($version)){ //version of Airtime older than 1.7.0 detected exit(3); } else { diff --git a/python_apps/pypo/test/airtime-schedule-insert.php b/python_apps/pypo/test/airtime-schedule-insert.php index defb843b4..70c1f38c7 100644 --- a/python_apps/pypo/test/airtime-schedule-insert.php +++ b/python_apps/pypo/test/airtime-schedule-insert.php @@ -15,7 +15,6 @@ set_include_path(APPLICATION_PATH . get_include_path() . PATH_SEPARATOR . '/cont require_once APPLICATION_PATH.'/configs/conf.php'; -require_once 'DB.php'; require_once(APPLICATION_PATH.'/../library/propel/runtime/lib/Propel.php'); require_once 'Soundcloud.php'; @@ -31,17 +30,6 @@ require_once 'Preference.php'; // Initialize Propel with the runtime configuration Propel::init(__DIR__."/../../../application/configs/airtime-conf.php"); - -$dsn = $CC_CONFIG['dsn']; - -$CC_DBC = DB::connect($dsn, FALSE); -if (PEAR::isError($CC_DBC)) { - echo "ERROR: ".$CC_DBC->getMessage()." ".$CC_DBC->getUserInfo()."\n"; - exit(1); -} -$CC_DBC->setFetchMode(DB_FETCHMODE_ASSOC); - - $playlistName = "pypo_playlist_test"; $secondsFromNow = 30; @@ -70,10 +58,6 @@ if (is_null($mediaFile)) { echo "Adding test audio clip to the database.\n"; $v = array("filepath" => __DIR__."/../../../audio_samples/vorbis.com/Hydrate-Kenny_Beltrey.ogg"); $mediaFile = Application_Model_StoredFile::Insert($v); - if (PEAR::isError($mediaFile)) { - var_dump($mediaFile); - exit(); - } } $pl->addAudioClip($mediaFile->getId()); echo "done.\n"; diff --git a/utils/phone_home_stat.php b/utils/phone_home_stat.php index 3a0e6526a..a55d3da6c 100644 --- a/utils/phone_home_stat.php +++ b/utils/phone_home_stat.php @@ -29,6 +29,12 @@ require_once($CC_CONFIG['phpDir'].'/application/configs/conf.php'); $CC_CONFIG['phpDir'] = $values['general']['airtime_dir']; +// Ensure library/ is on include_path +set_include_path(implode(PATH_SEPARATOR, array( + get_include_path(), + realpath($CC_CONFIG['phpDir'] . '/library') +))); + require_once($CC_CONFIG['phpDir'].'/application/models/User.php'); require_once($CC_CONFIG['phpDir'].'/application/models/StoredFile.php'); require_once($CC_CONFIG['phpDir'].'/application/models/Playlist.php'); @@ -38,50 +44,39 @@ require_once($CC_CONFIG['phpDir'].'/application/models/ShowInstance.php'); require_once($CC_CONFIG['phpDir'].'/application/models/Preference.php'); require_once($CC_CONFIG['phpDir'].'/application/models/StreamSetting.php'); -require_once('DB.php'); -$CC_DBC = DB::connect($CC_CONFIG['dsn'], FALSE); -if (PEAR::isError($CC_DBC)) { - /*echo $CC_DBC->getMessage().PHP_EOL; - echo $CC_DBC->getUserInfo().PHP_EOL; - echo "Database connection problem.".PHP_EOL; - echo "Check if database '{$CC_CONFIG['dsn']['database']}' exists". - " with corresponding permissions.".PHP_EOL;*/ - exit(1); -} else { - //echo "* Connected to database".PHP_EOL; - $CC_DBC->setFetchMode(DB_FETCHMODE_ASSOC); -} +require_once 'propel/runtime/lib/Propel.php'; +Propel::init($CC_CONFIG['phpDir']."/application/configs/airtime-conf-production.php"); if(Application_Model_Preference::GetSupportFeedback() == '1'){ $infoArray = Application_Model_Preference::GetSystemInfo(true); - + $url = 'http://stat.sourcefabric.org/index.php?p=airtime'; //$url = 'http://stat-dev.sourcefabric.org/index.php?p=airtime'; - + $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_URL, $url); - + $data = json_encode($infoArray); - + $dataArray = array("data" => $data ); - + curl_setopt($ch, CURLOPT_POSTFIELDS, $dataArray); $result = curl_exec($ch); - + curl_close($ch); } // Get latest version from stat server and store to db if(Application_Model_Preference::GetPlanLevel() == 'disabled'){ $url = 'http://stat.sourcefabric.org/airtime-stats/airtime_latest_version'; - + $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_URL, $url); $result = curl_exec($ch); - + if(curl_errno($ch)) { echo "curl error: " . curl_error($ch) . "\n"; } else { @@ -89,7 +84,7 @@ if(Application_Model_Preference::GetPlanLevel() == 'disabled'){ Application_Model_Preference::SetLatestVersion($resultArray[0]); Application_Model_Preference::SetLatestLink($resultArray[1]); } - + curl_close($ch); } diff --git a/utils/soundcloud-uploader.php b/utils/soundcloud-uploader.php index 43b8e150a..e7b116785 100644 --- a/utils/soundcloud-uploader.php +++ b/utils/soundcloud-uploader.php @@ -24,6 +24,12 @@ require_once($CC_CONFIG['phpDir'].'/application/configs/conf.php'); $CC_CONFIG['phpDir'] = $values['general']['airtime_dir']; +// Ensure library/ is on include_path +set_include_path(implode(PATH_SEPARATOR, array( + get_include_path(), + realpath($CC_CONFIG['phpDir'] . '/library') +))); + require_once($CC_CONFIG['phpDir'].'/application/models/StoredFile.php'); require_once($CC_CONFIG['phpDir'].'/application/models/Preference.php'); require_once($CC_CONFIG['phpDir'].'/application/models/MusicDir.php'); @@ -35,21 +41,8 @@ set_include_path($CC_CONFIG['phpDir']."/application/models" . PATH_SEPARATOR . g require_once($CC_CONFIG['phpDir']."/library/propel/runtime/lib/Propel.php"); Propel::init($CC_CONFIG['phpDir']."/application/configs/airtime-conf.php"); -require_once('DB.php'); -$CC_DBC = DB::connect($CC_CONFIG['dsn'], FALSE); -if (PEAR::isError($CC_DBC)) { - /*echo $CC_DBC->getMessage().PHP_EOL; - echo $CC_DBC->getUserInfo().PHP_EOL; - echo "Database connection problem.".PHP_EOL; - echo "Check if database '{$CC_CONFIG['dsn']['database']}' exists". - " with corresponding permissions.".PHP_EOL;*/ - if ($p_exitOnError) { - exit(1); - } -} else { - //echo "* Connected to database".PHP_EOL; - $CC_DBC->setFetchMode(DB_FETCHMODE_ASSOC); -} +require_once 'propel/runtime/lib/Propel.php'; +Propel::init($CC_CONFIG['phpDir']."/application/configs/airtime-conf-production.php"); if(count($argv) != 2){ exit; From 9ec584e90cc3a3a721134f0fee97023b46d8cbce Mon Sep 17 00:00:00 2001 From: "paul.baranowski" Date: Thu, 5 Apr 2012 02:27:52 -0400 Subject: [PATCH 12/15] CC-1927 Remove PEAR DB Removed remaining references to $CC_DBC --- airtime_mvc/application/Bootstrap.php | 2 -- .../application/models/tests/SchedulerExportTests.php | 7 ++++--- .../application/models/tests/SchedulerTests.php | 4 +--- airtime_mvc/application/models/tests/populator.php | 11 ++++++----- 4 files changed, 11 insertions(+), 13 deletions(-) diff --git a/airtime_mvc/application/Bootstrap.php b/airtime_mvc/application/Bootstrap.php index 7b4813e19..bc41379a0 100644 --- a/airtime_mvc/application/Bootstrap.php +++ b/airtime_mvc/application/Bootstrap.php @@ -102,8 +102,6 @@ class Bootstrap extends Zend_Application_Bootstrap_Bootstrap protected function _initZFDebug() { if (APPLICATION_ENV == "development"){ - global $CC_DBC; - $autoloader = Zend_Loader_Autoloader::getInstance(); $autoloader->registerNamespace('ZFDebug'); diff --git a/airtime_mvc/application/models/tests/SchedulerExportTests.php b/airtime_mvc/application/models/tests/SchedulerExportTests.php index 24a6813ba..79fbad1b7 100644 --- a/airtime_mvc/application/models/tests/SchedulerExportTests.php +++ b/airtime_mvc/application/models/tests/SchedulerExportTests.php @@ -4,11 +4,12 @@ require_once(dirname(__FILE__)."/../Schedule.php"); class SchedulerExportTests extends PHPUnit_TestCase { function setup() { - global $CC_CONFIG, $CC_DBC; + global $CC_CONFIG; + $con = Propel::getConnection(); // Clear the files table $sql = "DELETE FROM ".$CC_CONFIG["filesTable"]; - $CC_DBC->query($sql); + $con->exec($sql); // Add a file $values = array("filepath" => dirname(__FILE__)."/test10001.mp3"); @@ -20,7 +21,7 @@ class SchedulerExportTests extends PHPUnit_TestCase { // Clear the schedule table $sql = "DELETE FROM ".$CC_CONFIG["scheduleTable"]; - $CC_DBC->query($sql); + $con->exec($sql); // Create a playlist $playlist = new Application_Model_Playlist(); diff --git a/airtime_mvc/application/models/tests/SchedulerTests.php b/airtime_mvc/application/models/tests/SchedulerTests.php index a51fa6fef..40235e786 100644 --- a/airtime_mvc/application/models/tests/SchedulerTests.php +++ b/airtime_mvc/application/models/tests/SchedulerTests.php @@ -8,11 +8,10 @@ class SchedulerTests extends PHPUnit_TestCase { private $storedFile2; function setup() { - global $CC_CONFIG, $CC_DBC; + global $CC_CONFIG; // Clear the files table //$sql = "DELETE FROM ".$CC_CONFIG["filesTable"]; - //$CC_DBC->query($sql); // Add a file $values = array("filepath" => dirname(__FILE__)."/test10001.mp3"); @@ -24,7 +23,6 @@ class SchedulerTests extends PHPUnit_TestCase { // Clear the schedule table //$sql = "DELETE FROM ".$CC_CONFIG["scheduleTable"]; - //$CC_DBC->query($sql); } function testDateToId() { diff --git a/airtime_mvc/application/models/tests/populator.php b/airtime_mvc/application/models/tests/populator.php index bf3f5b27b..1ad1b2806 100644 --- a/airtime_mvc/application/models/tests/populator.php +++ b/airtime_mvc/application/models/tests/populator.php @@ -15,12 +15,13 @@ require_once __DIR__.'/../../../library/propel/runtime/lib/Propel.php'; Propel::init(__DIR__.'/../../configs/airtime-conf.php'); AirtimeInstall::DbConnect(true); +$con = Propel::getConnection(); $sql = "DELETE FROM cc_show"; -$CC_DBC->query($sql); +$con->exec($sql); $sql = "DELETE FROM cc_show_days"; -$CC_DBC->query($sql); +$con->exec($sql); $sql = "DELETE FROM cc_show_instances"; -$CC_DBC->query($sql); +$con->exec($sql); /* // Create a playlist @@ -88,10 +89,10 @@ echo "End date: ".$endDate->format("Y-m-d H:i")."\n"; while ($showTime < $endDate) { echo $showTime->format("Y-m-d H:i")." < " .$endDate->format("Y-m-d H:i")."\n"; if ($resolution == "minute") { - createTestShow($showNumber, $showTime, "0:01"); + createTestShow($showNumber, $showTime, "0:01"); $showTime->add(new DateInterval("PT1M")); } elseif ($resolution == "hour") { - createTestShow($showNumber, $showTime); + createTestShow($showNumber, $showTime); $showTime->add(new DateInterval("PT1H")); } $showNumber = $showNumber + 1; From 235997c616f83dfbac47771d70d1c1f33d2b3c07 Mon Sep 17 00:00:00 2001 From: "paul.baranowski" Date: Thu, 5 Apr 2012 02:41:51 -0400 Subject: [PATCH 13/15] CC-1927 Remove PEAR DB * Removed the DEB package "php-db" from the full install script as it is no longer needed. * Missed one call to PEAR::isError() --- airtime_mvc/application/models/StoredFile.php | 2 +- install_full/ubuntu/airtime-full-install | 2 +- install_full/ubuntu/airtime-full-install-nginx | 2 +- install_minimal/include/AirtimeInstall.php | 11 +++++------ 4 files changed, 8 insertions(+), 9 deletions(-) diff --git a/airtime_mvc/application/models/StoredFile.php b/airtime_mvc/application/models/StoredFile.php index ee9eea356..06e788095 100644 --- a/airtime_mvc/application/models/StoredFile.php +++ b/airtime_mvc/application/models/StoredFile.php @@ -238,7 +238,7 @@ class Application_Model_StoredFile { * 'empty'|'incomplete'|'ready'|'edited' * @param int $p_editedby * user id | 'NULL' for clear editedBy field - * @return TRUE|PEAR_Error + * @return TRUE */ public function setState($p_state, $p_editedby=NULL) { diff --git a/install_full/ubuntu/airtime-full-install b/install_full/ubuntu/airtime-full-install index e063cdd63..18881796b 100755 --- a/install_full/ubuntu/airtime-full-install +++ b/install_full/ubuntu/airtime-full-install @@ -39,7 +39,7 @@ php-pear php5-gd postgresql odbc-postgresql python2.6 libsoundtouch-ocaml \ libtaglib-ocaml libao-ocaml libmad-ocaml ecasound \ libesd0 libportaudio2 libsamplerate0 rabbitmq-server patch \ php5-curl mpg123 monit python-virtualenv multitail libcamomile-ocaml-data \ -libpulse0 vorbis-tools lsb-release php-db +libpulse0 vorbis-tools lsb-release #install packages with --force-yes option (this is useful in the case #of Debian, where these packages are unauthorized) diff --git a/install_full/ubuntu/airtime-full-install-nginx b/install_full/ubuntu/airtime-full-install-nginx index d05e5e978..2466ff33e 100755 --- a/install_full/ubuntu/airtime-full-install-nginx +++ b/install_full/ubuntu/airtime-full-install-nginx @@ -42,7 +42,7 @@ php-pear php5-gd postgresql odbc-postgresql python2.6 libsoundtouch-ocaml \ libtaglib-ocaml libao-ocaml libmad-ocaml ecasound \ libesd0 libportaudio2 libsamplerate0 rabbitmq-server patch \ php5-curl mpg123 monit python-virtualenv multitail libcamomile-ocaml-data \ -libpulse0 vorbis-tools lsb-release php-db +libpulse0 vorbis-tools lsb-release #install packages with --force-yes option (this is useful in the case #of Debian, where these packages are unauthorized) diff --git a/install_minimal/include/AirtimeInstall.php b/install_minimal/include/AirtimeInstall.php index 5af33878c..107a002da 100644 --- a/install_minimal/include/AirtimeInstall.php +++ b/install_minimal/include/AirtimeInstall.php @@ -69,13 +69,12 @@ class AirtimeInstall } if ($version == '') { - $sql = "SELECT * FROM cc_show_rebroadcast LIMIT 1"; - $result = $con->query($sql)->fetchColumn(0); - if (!PEAR::isError($result)) { + try { + // If this table exists, then it's 1.7.0 + $sql = "SELECT * FROM cc_show_rebroadcast LIMIT 1"; + $result = $con->query($sql)->fetchColumn(0); $version = "1.7.0"; - //echo "Airtime Version: ".$version." ".PHP_EOL; - } - else { + } catch (Exception $e) { $version = null; } } From cba253439a0faa01588c0d5dd3b8162d101acc7a Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Thu, 19 Apr 2012 16:54:38 -0400 Subject: [PATCH 14/15] CC-1927: Remove PEAR DB -various fixes --- airtime_mvc/application/models/Preference.php | 2 +- airtime_mvc/application/models/Show.php | 2 +- airtime_mvc/application/models/ShowInstance.php | 2 +- airtime_mvc/application/models/StreamSetting.php | 4 ++-- airtime_mvc/application/models/Subjects.php | 4 ++-- airtime_mvc/application/models/User.php | 2 +- 6 files changed, 8 insertions(+), 8 deletions(-) diff --git a/airtime_mvc/application/models/Preference.php b/airtime_mvc/application/models/Preference.php index 5601a6158..0e728d56c 100644 --- a/airtime_mvc/application/models/Preference.php +++ b/airtime_mvc/application/models/Preference.php @@ -87,7 +87,7 @@ class Application_Model_Preference } $result = $con->query($sql)->fetchColumn(0); - return $result ? $result : ""; + return ($result !== false) ? $result : ""; } } diff --git a/airtime_mvc/application/models/Show.php b/airtime_mvc/application/models/Show.php index 8e8e558e4..29dc890ae 100644 --- a/airtime_mvc/application/models/Show.php +++ b/airtime_mvc/application/models/Show.php @@ -459,7 +459,7 @@ class Application_Model_Show { ." ORDER BY last_show DESC"; $query = $con->query($sql)->fetchColumn(0); - return $query ? $query : ""; + return ($query !== false) ? $query : ""; } /** diff --git a/airtime_mvc/application/models/ShowInstance.php b/airtime_mvc/application/models/ShowInstance.php index e2af915f9..8d4b4d95f 100644 --- a/airtime_mvc/application/models/ShowInstance.php +++ b/airtime_mvc/application/models/ShowInstance.php @@ -665,7 +665,7 @@ class Application_Model_ShowInstance { ."LIMIT 1"; $query = $con->query($sql)->fetchColumn(0); - return $query ? $query : NULL; + return ($query !== false) ? $query : NULL; } public function getShowEndGapTime(){ diff --git a/airtime_mvc/application/models/StreamSetting.php b/airtime_mvc/application/models/StreamSetting.php index 7c3d9715f..4cc60127c 100644 --- a/airtime_mvc/application/models/StreamSetting.php +++ b/airtime_mvc/application/models/StreamSetting.php @@ -44,7 +44,7 @@ class Application_Model_StreamSetting { ." WHERE keyname = '$key'"; $result = $con->query($sql)->fetchColumn(0); - return $result ? $result : NULL; + return ($result !== false) ? $result : NULL; } } @@ -231,7 +231,7 @@ class Application_Model_StreamSetting { ." WHERE keyname = '$keyname'"; $result = $con->query($sql)->fetchColumn(0); - return $result ? $result : NULL; + return ($result !== false) ? $result : NULL; } public static function getStreamEnabled($stream_id) diff --git a/airtime_mvc/application/models/Subjects.php b/airtime_mvc/application/models/Subjects.php index 45c672b61..e66bbaa8a 100644 --- a/airtime_mvc/application/models/Subjects.php +++ b/airtime_mvc/application/models/Subjects.php @@ -90,7 +90,7 @@ class Application_Model_Subjects { $sql = "SELECT id FROM ".$CC_CONFIG['subjTable'] ." WHERE login='$login'"; $query = $con->query($sql)->fetchColumn(0); - return $query ? $query : NULL; + return ($query !== false) ? $query : NULL; } @@ -140,7 +140,7 @@ 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 ? $res : 0; + return ($res !== false) ? $res : 0; } } // class Subjects diff --git a/airtime_mvc/application/models/User.php b/airtime_mvc/application/models/User.php index f09af3371..081110b50 100644 --- a/airtime_mvc/application/models/User.php +++ b/airtime_mvc/application/models/User.php @@ -238,7 +238,7 @@ class Application_Model_User { } $query = $con->query($sql)->fetchColumn(0); - return $query ? $query : NULL; + return ($query !== false) ? $query : NULL; } public static function getHosts($search=NULL) { From 16f3a331bbfa52e7c6216902a165934cc8783b3d Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Thu, 19 Apr 2012 17:03:13 -0400 Subject: [PATCH 15/15] CC-1927: Remove PEAR DB -missed some conflicts :/ --- airtime_mvc/application/models/Show.php | 31 ++----------------------- 1 file changed, 2 insertions(+), 29 deletions(-) diff --git a/airtime_mvc/application/models/Show.php b/airtime_mvc/application/models/Show.php index 29dc890ae..85107dfad 100644 --- a/airtime_mvc/application/models/Show.php +++ b/airtime_mvc/application/models/Show.php @@ -1165,15 +1165,8 @@ class Application_Model_Show { */ public static function populateShowUntil($p_showId) { -<<<<<<< HEAD - global $CC_DBC; - $date = Application_Model_Preference::GetShowsPopulatedUntil(); -======= $con = Propel::getConnection(); - - if (is_null($p_dateTime)) { - $date = Application_Model_Preference::GetShowsPopulatedUntil(); ->>>>>>> CC-1927: Remove PEAR DB + $date = Application_Model_Preference::GetShowsPopulatedUntil(); if (is_null($date)) { $p_populateUntilDateTime = new DateTime("now", new DateTimeZone('UTC')); @@ -1228,13 +1221,8 @@ class Application_Model_Show { */ private static function populateNonRepeatingShow($p_showRow, $p_populateUntilDateTime) { -<<<<<<< HEAD - global $CC_DBC; - -======= $con = Propel::getConnection(); ->>>>>>> CC-1927: Remove PEAR DB $show_id = $p_showRow["show_id"]; $first_show = $p_showRow["first_show"]; //non-UTC $start_time = $p_showRow["start_time"]; //non-UTC @@ -1278,13 +1266,7 @@ class Application_Model_Show { //Logging::log('$start time of non repeating record '.$start); -<<<<<<< HEAD self::createRebroadcastInstances($rebroadcasts, $currentUtcTimestamp, $show_id, $show_instance_id, $start, $duration, $timezone); -======= - if ($newInstance) { - self::createRebroadcastInstances($rebroadcasts, $currentUtcTimestamp, $show_id, $show_instance_id, $start, $duration, $timezone); - } ->>>>>>> CC-1927: Remove PEAR DB } } @@ -1331,11 +1313,7 @@ class Application_Model_Show { $show = new Application_Model_Show($show_id); -<<<<<<< HEAD - while($utcStartDateTime->getTimestamp() <= $p_populateUntilDateTime->getTimestamp() -======= - while ($utcStartDateTime->getTimestamp() <= $p_dateTime->getTimestamp() ->>>>>>> CC-1927: Remove PEAR DB + while ($utcStartDateTime->getTimestamp() <= $p_populateUntilDateTime->getTimestamp() && (is_null($utcLastShowDateTime) || $utcStartDateTime->getTimestamp() < $utcLastShowDateTime->getTimestamp())){ list($utcStartDateTime, $utcEndDateTime) = Application_Model_Show::createUTCStartEndDateTime($start, $duration, $timezone); @@ -1743,13 +1721,8 @@ class Application_Model_Show { global $CC_CONFIG; $con = Propel::getConnection(); if($timeNow == null){ -<<<<<<< HEAD $date = new Application_Common_DateHelper; $timeNow = $date->getUtcTimestamp(); -======= - $date = new Application_Model_DateHelper; - $timeNow = $date->getUtcTimestamp(); ->>>>>>> CC-1927: Remove PEAR DB } //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"