Merge branch '2.4.x' into 2.4.x-saas

Conflicts:
	python_apps/pypo/liquidsoap_scripts/ls_script.liq
	utils/phone_home_stat.php
This commit is contained in:
Naomi Aro 2013-06-26 01:25:26 -04:00
commit f2d5fa96da
114 changed files with 9850 additions and 9170 deletions

View file

@ -523,6 +523,15 @@ class ApiController extends Zend_Controller_Action
}
//Updating a metadata change.
else {
//CC-5207 - restart media-monitor causes it to reevaluate all
//files in watched directories, and reset their cue-in/cue-out
//values. Since media-monitor has nothing to do with cue points
//let's unset it here. Note that on mode == "create", we still
//want media-monitor sending info about cue_out which by default
//will be equal to length of track until silan can take over.
unset($md['MDATA_KEY_CUE_IN']);
unset($md['MDATA_KEY_CUE_OUT']);
$file->setMetadata($md);
}
} elseif ($mode == "moved") {

View file

@ -24,7 +24,7 @@ class ErrorController extends Zend_Controller_Action
}
// Log exception, if logger available
if ($log = $this->getLog()) {
if (($log = $this->getLog())) {
$log->crit($this->view->message, $errors->exception);
}

View file

@ -393,7 +393,8 @@ class LibraryController extends Zend_Controller_Action
}
$c[0] = $c['item_id'];
}
$newPl->addAudioClips($contents, null, 'begining');
$newPl->addAudioClips($contents, null, 'before');
$newPl->setCreator(Application_Model_User::getCurrentUser()->getId());
$newPl->setDescription($originalPl->getDescription());
@ -425,6 +426,9 @@ class LibraryController extends Zend_Controller_Action
$request = $this->getRequest();
$file_id = $this->_getParam('id', null);
$file = Application_Model_StoredFile::RecallById($file_id);
@ -437,7 +441,15 @@ class LibraryController extends Zend_Controller_Action
$form->populate($file->getDbColMetadata());
if ($request->isPost()) {
if ($form->isValid($request->getPost())) {
$js = $this->_getParam('data');
$serialized = array();
//need to convert from serialized jQuery array.
foreach ($js as $j) {
$serialized[$j["name"]] = $j["value"];
}
if ($form->isValid($serialized)) {
$formValues = $this->_getParam('data', null);
$formdata = array();

View file

@ -9,36 +9,36 @@ class ListenerstatController extends Zend_Controller_Action
->addActionContext('get-data', 'json')
->initContext();
}
public function indexAction()
{
$CC_CONFIG = Config::getConfig();
$request = $this->getRequest();
$baseUrl = Application_Common_OsPath::getBaseDir();
$this->view->headScript()->appendFile($baseUrl.'js/flot/jquery.flot.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'js/flot/jquery.flot.crosshair.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'js/airtime/listenerstat/listenerstat.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$offset = date("Z") * -1;
$this->view->headScript()->appendScript("var serverTimezoneOffset = {$offset}; //in seconds");
$this->view->headScript()->appendFile($baseUrl.'js/timepicker/jquery.ui.timepicker.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'js/airtime/buttons/buttons.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'js/airtime/utilities/utilities.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headLink()->appendStylesheet($baseUrl.'css/jquery.ui.timepicker.css?'.$CC_CONFIG['airtime_version']);
//default time is the last 24 hours.
$now = time();
$from = $request->getParam("from", $now - (24*60*60));
$to = $request->getParam("to", $now);
$start = DateTime::createFromFormat("U", $from, new DateTimeZone("UTC"));
$start->setTimezone(new DateTimeZone(date_default_timezone_get()));
$end = DateTime::createFromFormat("U", $to, new DateTimeZone("UTC"));
$end->setTimezone(new DateTimeZone(date_default_timezone_get()));
$form = new Application_Form_DateRange();
$form->populate(array(
'his_date_start' => $start->format("Y-m-d"),
@ -46,7 +46,7 @@ class ListenerstatController extends Zend_Controller_Action
'his_date_end' => $end->format("Y-m-d"),
'his_time_end' => $end->format("H:i")
));
$errorStatus = Application_Model_StreamSetting::GetAllListenerStatErrors();
Logging::info($errorStatus);
$out = array();
@ -57,25 +57,24 @@ class ListenerstatController extends Zend_Controller_Action
}
$out[$key[0]] = $v['value'];
}
$this->view->errorStatus = $out;
$this->view->date_form = $form;
}
public function getDataAction(){
$request = $this->getRequest();
$current_time = time();
$params = $request->getParams();
$starts_epoch = $request->getParam("startTimestamp", $current_time - (60*60*24));
$ends_epoch = $request->getParam("endTimestamp", $current_time);
$mountName = $request->getParam("mountName", null);
$startsDT = DateTime::createFromFormat("U", $starts_epoch, new DateTimeZone("UTC"));
$endsDT = DateTime::createFromFormat("U", $ends_epoch, new DateTimeZone("UTC"));
$data = Application_Model_ListenerStat::getDataPointsWithinRange($startsDT->format("Y-m-d H:i:s"), $endsDT->format("Y-m-d H:i:s"), $mountName);
$this->_helper->json->sendJson($data);
$data = Application_Model_ListenerStat::getDataPointsWithinRange($startsDT->format("Y-m-d H:i:s"), $endsDT->format("Y-m-d H:i:s"));
$this->_helper->json->sendJson($data);
}
}

View file

@ -167,7 +167,7 @@ class LocaleController extends Zend_Controller_Action
"Are you sure you want to remove the watched folder?" => _("Are you sure you want to remove the watched folder?"),
"This path is currently not accessible." => _("This path is currently not accessible."),
//preferences/streamsetting.js
"Some steam types require extra configuration. Details about enabling %sAAC+ Support%s or %sOpus Support%s are provided." => _("Some steam types require extra configuration. Details about enabling %sAAC+ Support%s or %sOpus Support%s are provided."),
"Some stream types require extra configuration. Details about enabling %sAAC+ Support%s or %sOpus Support%s are provided." => _("Some stream types require extra configuration. Details about enabling %sAAC+ Support%s or %sOpus Support%s are provided."),
"Connected to the streaming server" => _("Connected to the streaming server"),
"The stream is disabled" => _("The stream is disabled"),
"Getting information from the server..." => _("Getting information from the server..."),
@ -193,6 +193,7 @@ class LocaleController extends Zend_Controller_Action
"If your live streaming client does not ask for a username, this field should be 'source'." => _("If your live streaming client does not ask for a username, this field should be 'source'."),
"The show instance doesn't exist anymore!" => _("The show instance doesn't exist anymore!"),
"Warning: Shows cannot be re-linked" => _("Warning: Shows cannot be re-linked"),
"By linking your repeating shows any media items scheduled in any repeat show will also get scheduled in the other repeat shows" => _("By linking your repeating shows any media items scheduled in any repeat show will also get scheduled in the other repeat shows"),
//schedule/full-calendar-functions
//already in schedule/add-show.js
//"The show instance doesn't exist anymore!" => _("The show instance doesn't exist anymore!"),

View file

@ -30,6 +30,7 @@ class PreferenceController extends Zend_Controller_Action
$this->view->statusMsg = "";
$form = new Application_Form_Preferences();
$values = array();
if ($request->isPost()) {
$params = $request->getPost();
@ -137,11 +138,12 @@ class PreferenceController extends Zend_Controller_Action
$setting[$t['keyname']] = $t['value'];
}
$name_map = array('ogg' => 'Ogg Vorbis',
'aacplus' => 'AAC+',
$name_map = array(
'ogg' => 'Ogg Vorbis',
'fdkaac' => 'AAC+',
'aac' => 'AAC',
'opus' => 'Opus',
'mp3' => 'MP3'
'mp3' => 'MP3',
);
// get predefined type and bitrate from pref table
@ -162,7 +164,7 @@ class PreferenceController extends Zend_Controller_Action
$stream_bitrates = array();
foreach ($temp_bitrate as $type) {
if (intval($type) <= $max_bitrate) {
$stream_bitrates[trim($type)] = strtoupper(trim($type))." Kbit/s";
$stream_bitrates[trim($type)] = strtoupper(trim($type))." kbit/s";
}
}
@ -193,6 +195,7 @@ class PreferenceController extends Zend_Controller_Action
$s1_data = array();
$s2_data = array();
$s3_data = array();
$values = array();
foreach($postData as $k=>$v) {
$v = explode('=', urldecode($v));
if (strpos($v[0], "s1_data") !== false) {

View file

@ -600,6 +600,7 @@ class ScheduleController extends Zend_Controller_Action
$baseUrl = $this->getRequest()->getBaseUrl();
$url = $file->getRelativeFileUrl($baseUrl).'download/true';
$menu = array();
$menu[] = array('action' => array('type' => 'gourl', 'url' => $url),
'title' => _('Download'));

View file

@ -41,6 +41,7 @@ class UserController extends Zend_Controller_Action
if ($request->isPost()) {
$params = $request->getPost();
$postData = explode('&', $params['data']);
$formData = array();
foreach($postData as $k=>$v) {
$v = explode('=', $v);
$formData[$v[0]] = urldecode($v[1]);

View file

@ -39,7 +39,7 @@ class Application_Form_EditAudioMD extends Zend_Form
$this->addElement('text', 'track_number', array(
'label' => _('Track:'),
'class' => 'input_text',
'filters' => array('StringTrim')
'filters' => array('StringTrim'),
));
// Add genre field
@ -50,16 +50,17 @@ class Application_Form_EditAudioMD extends Zend_Form
));
// Add year field
$this->addElement('text', 'year', array(
'label' => _('Year:'),
'class' => 'input_text',
'filters' => array('StringTrim'),
'validators' => array(
$year = new Zend_Form_Element_Text('year');
$year->class = 'input_text';
$year->setLabel(_('Year:'))
->setFilters(array('StringTrim'))
->setValidators(array(
new Zend_Validate_StringLength(array('max' => 10)),
Application_Form_Helper_ValidationTypes::overrrideDateValidator("YYYY-MM-DD"),
Application_Form_Helper_ValidationTypes::overrrideDateValidator("YYYY-MM"),
Application_Form_Helper_ValidationTypes::overrrideDateValidator("YYYY")
)
));
));
$this->addElement($year);
// Add label field
$this->addElement('text', 'label', array(

View file

@ -5,7 +5,7 @@ class Application_Form_SmartBlockCriteria extends Zend_Form_SubForm
private $stringCriteriaOptions;
private $numericCriteriaOptions;
private $limitOptions;
/* We need to know if the criteria value will be a string
* or numeric value in order to populate the modifier
* select list
@ -40,7 +40,7 @@ class Application_Form_SmartBlockCriteria extends Zend_Form_SubForm
"info_url" => "s",
"year" => "n"
);
private function getCriteriaOptions($option = null)
{
if (!isset($this->criteriaOptions)) {
@ -75,7 +75,7 @@ class Application_Form_SmartBlockCriteria extends Zend_Form_SubForm
"year" => _("Year")
);
}
if (is_null($option)) return $this->criteriaOptions;
else return $this->criteriaOptions[$option];
}
@ -122,7 +122,7 @@ class Application_Form_SmartBlockCriteria extends Zend_Form_SubForm
}
return $this->limitOptions;
}
public function init()
{
@ -259,7 +259,7 @@ class Application_Form_SmartBlockCriteria extends Zend_Form_SubForm
$repeatTracks->setChecked($storedCrit["repeat_tracks"]["value"] == 1?true:false);
}
$this->addElement($repeatTracks);
$limit = new Zend_Form_Element_Select('sp_limit_options');
$limit->setAttrib('class', 'sp_input_select')
->setDecorators(array('viewHelper'))
@ -268,7 +268,7 @@ class Application_Form_SmartBlockCriteria extends Zend_Form_SubForm
$limit->setValue($storedCrit["limit"]["modifier"]);
}
$this->addElement($limit);
$limitValue = new Zend_Form_Element_Text('sp_limit_value');
$limitValue->setAttrib('class', 'sp_input_text_limit')
->setLabel(_('Limit to'))
@ -541,7 +541,7 @@ class Application_Form_SmartBlockCriteria extends Zend_Form_SubForm
$isValid = false;
}
// length check
if (intval($d['sp_criteria_value']) >= pow(2,31)) {
if ($d['sp_criteria_value'] >= pow(2,31)) {
$element->addError(_("The value should be less then 2147483648"));
$isValid = false;
}

View file

@ -36,6 +36,7 @@
<script id="tmpl-pl-cues" type="text/template">
<div class="waveform-cues">
<div class="playlist-time-scale"></div>
<div class="playlist-tracks"></div>
<div class="playlist-controls">
<a class="btn btn-small btn_play"><i class="icon-play icon-white"></i><?php echo _("Play"); ?></a>
@ -61,10 +62,12 @@
<script id="tmpl-pl-fades" type="text/template">
<div class="waveform-fades">
<div class="playlist-time-scale"></div>
<div class="playlist-tracks"></div>
<div class="playlist-controls left-floated">
<a class="btn btn-small btn_play"><i class="icon-play icon-white"></i><?php echo _("Play"); ?></a>
<a class="btn btn-small btn_stop"><i class="icon-stop icon-white"></i><?php echo _("Stop"); ?></a>
<label class="audio audio_pos">00:00:00.0</label>
</div>
<div class="set-fade left-floated">
<a type="button" class="btn btn-small btn_cursor" data-state="cursor"><?php echo _("Cursor"); ?></a>

View file

@ -330,7 +330,7 @@ SQL;
{
list($value, $modifier) = $this->getLimitValueAndModifier();
if ($modifier == "items") {
$length = $value." ".$modifier;
$length = $value." "._("items");
} else {
$hour = "00";
$mins = "00";
@ -686,6 +686,10 @@ SQL;
public function createCrossfade($id1, $fadeOut, $id2, $fadeIn, $offset)
{
$this->con->beginTransaction();
if (!isset($offset)) {
$offset = Application_Model_Preference::GetDefaultCrossfadeDuration();
}
try {
if (isset($id1)) {
@ -1350,6 +1354,21 @@ SQL;
"year" => _("Year")
);
$modifierOptions = array(
"0" => _("Select modifier"),
"contains" => _("contains"),
"does not contain" => _("does not contain"),
"is" => _("is"),
"is not" => _("is not"),
"starts with" => _("starts with"),
"ends with" => _("ends with"),
"is" => _("is"),
"is not" => _("is not"),
"is greater than" => _("is greater than"),
"is less than" => _("is less than"),
"is in the range" => _("is in the range")
);
// Load criteria from db
$out = CcBlockcriteriaQuery::create()->orderByDbCriteria()->findByDbBlockId($this->id);
$storedCrit = array();
@ -1361,11 +1380,20 @@ SQL;
$extra = $crit->getDbExtra();
if ($criteria == "limit") {
$storedCrit["limit"] = array("value"=>$value, "modifier"=>$modifier);
$storedCrit["limit"] = array(
"value"=>$value,
"modifier"=>$modifier,
"display_modifier"=>_($modifier));
} else if($criteria == "repeat_tracks") {
$storedCrit["repeat_tracks"] = array("value"=>$value);
} else {
$storedCrit["crit"][$criteria][] = array("criteria"=>$criteria, "value"=>$value, "modifier"=>$modifier, "extra"=>$extra, "display_name"=>$criteriaOptions[$criteria]);
$storedCrit["crit"][$criteria][] = array(
"criteria"=>$criteria,
"value"=>$value,
"modifier"=>$modifier,
"extra"=>$extra,
"display_name"=>$criteriaOptions[$criteria],
"display_modifier"=>$modifierOptions[$modifier]);
}
}

View file

@ -4,6 +4,7 @@ class Application_Model_Datatables
{
private static function buildWhereClauseForAdvancedSearch($dbname2searchTerm)
{
$where = array();
$where['clause'] = array();
$where['params'] = array();
foreach ($dbname2searchTerm as $dbname=>$term) {

View file

@ -4,7 +4,7 @@ class Application_Model_ListenerStat
public function __construct()
{
}
public static function getDataPointsWithinRange($p_start, $p_end) {
$sql = <<<SQL
SELECT mount_name, count(*)
@ -16,13 +16,13 @@ group by mount_name
SQL;
$data = Application_Common_Database::prepareAndExecute($sql,
array('p1'=>$p_start, 'p2'=>$p_end));
$out = array();
foreach ($data as $d) {
$jump = intval($d['count']/1000);
$jump = max(1, $jump);
$remainder = $jump == 1?0:1;
$sql = <<<SQL
SELECT *
FROM
@ -41,29 +41,36 @@ SQL;
$t->setTimezone(new DateTimeZone(date_default_timezone_get()));
// tricking javascript so it thinks the server timezone is in UTC
$dt = new DateTime($t->format("Y-m-d H:i:s"), new DateTimeZone("UTC"));
$r['timestamp'] = $dt->format("U");
$out[$r['mount_name']][] = $r;
}
}
$enabledStreamIds = Application_Model_StreamSetting::getEnabledStreamIds();
$enabledOut = array();
foreach ($enabledStreamIds as $sId) {
$sql = "SELECT value FROM cc_stream_setting"
." WHERE keyname = :key";
$result = Application_Common_Database::prepareAndExecute($sql, array('key' => $sId."_mount"), "single");
$enabledMountPoint = $result["value"];
if (isset($out[$enabledMountPoint])) {
$enabledOut[$enabledMountPoint] = $out[$enabledMountPoint];
}
else {
//TODO fix this hack (here for CC-5254)
//all shoutcast streams are automatically put under "shoutcast" mount point.
if (isset($out["shoutcast"])) {
$enabledOut["shoutcast"] = $out["shoutcast"];
}
}
}
return $enabledOut;
}

View file

@ -154,8 +154,6 @@ class Application_Model_Playlist implements Application_Model_LibraryEditable
*/
public function getContents($filterFiles=false)
{
Logging::info("Getting contents for playlist {$this->id}");
$sql = <<<SQL
SELECT *
FROM (
@ -411,26 +409,44 @@ SQL;
|| $obj instanceof CcWebstream ||
$obj instanceof CcBlock) {
$entry = $this->plItem;
$entry["id"] = $obj->getDbId();
$entry["pos"] = $pos;
$entry = $this->plItem;
$entry["id"] = $obj->getDbId();
$entry["pos"] = $pos;
$entry["cliplength"] = $obj->getDbLength();
if ($obj instanceof CcFiles && $obj) {
$entry["cuein"] = $obj->getDbCuein();
$entry["cueout"] = $obj->getDbCueout();
$entry["cuein"] = isset($p_item['cuein']) ?
$p_item['cuein'] : $obj->getDbCuein();
$entry["cueout"] = isset($p_item['cueout']) ?
$p_item['cueout'] : $obj->getDbCueout();
$cue_out = Application_Common_DateHelper::calculateLengthInSeconds($entry['cueout']);
$cue_in = Application_Common_DateHelper::calculateLengthInSeconds($entry['cuein']);
$entry["cliplength"] = Application_Common_DateHelper::secondsToPlaylistTime($cue_out-$cue_in);
} elseif ($obj instanceof CcWebstream && $obj) {
$cue_in = isset($p_item['cueInSec']) ?
$p_item['cueInSec'] : Application_Common_DateHelper::calculateLengthInSeconds($entry['cuein']);
$cue_out = isset($p_item['cueOutSec']) ?
$p_item['cueOutSec'] : Application_Common_DateHelper::calculateLengthInSeconds($entry['cueout']);
$entry["cliplength"] = isset($p_item['length']) ?
$p_item['length'] : Application_Common_DateHelper::secondsToPlaylistTime($cue_out-$cue_in);
}
elseif ($obj instanceof CcWebstream && $obj) {
$entry["cuein"] = "00:00:00";
$entry["cueout"] = $entry["cliplength"];
}
$entry["ftype"] = $objType;
$entry["ftype"] = $objType;
$entry["fadein"] = isset($p_item['fadein']) ?
$p_item['fadein'] : $entry["fadein"];
$entry["fadeout"] = isset($p_item['fadeout']) ?
$p_item['fadeout'] : $entry["fadeout"];
}
return $entry;
} else {
}
else {
throw new Exception("trying to add a object that does not exist.");
}
}
@ -451,11 +467,10 @@ SQL;
try {
if (is_numeric($p_afterItem)) {
Logging::info("Finding playlist content item {$p_afterItem}");
$afterItem = CcPlaylistcontentsQuery::create()->findPK($p_afterItem);
$index = $afterItem->getDbPosition();
Logging::info("index is {$index}");
$pos = ($addType == 'after') ? $index + 1 : $index;
$contentsToUpdate = CcPlaylistcontentsQuery::create()
@ -488,9 +503,6 @@ SQL;
}
Logging::info("Adding to playlist");
Logging::info("at position {$pos}");
foreach ($p_items as $ac) {
$res = $this->insertPlaylistElement($this->buildEntry($ac, $pos));
@ -500,8 +512,6 @@ SQL;
$db_file->setDbIsPlaylist(true)->save($this->con);
$pos = $pos + 1;
Logging::info("Adding $ac[1] $ac[0]");
}
//reset the positions of the remaining items.
@ -673,6 +683,10 @@ SQL;
{
$this->con->beginTransaction();
if (!isset($offset)) {
$offset = Application_Model_Preference::GetDefaultCrossfadeDuration();
}
try {
if (isset($id1)) {
$this->changeFadeInfo($id1, null, $fadeOut);
@ -729,7 +743,6 @@ SQL;
if (!is_null($offset)) {
$row->setDbTrackOffset($offset);
Logging::info("Setting offset {$offset} on item {$id}");
$row->save($this->con);
}
}
@ -1071,8 +1084,7 @@ SQL;
$sql .= "END WHERE position IN ($currentPos) and playlist_id=:p1";
Application_Common_Database::prepareAndExecute($sql, array("p1"=>$this->id));
$result['result'] = 0;
return $result;
return array('result' => 0);
}
public static function getAllPlaylistFiles()

View file

@ -38,9 +38,11 @@ class Application_Model_Preference
$paramMap[':id'] = $userId;
}
Application_Common_Database::prepareAndExecute("LOCK TABLE cc_pref");
$result = Application_Common_Database::prepareAndExecute($sql,
$paramMap,
'column',
Application_Common_Database::COLUMN,
PDO::FETCH_ASSOC,
$con);

View file

@ -30,7 +30,7 @@ AND file_id is not null
SQL;
$files = Application_Common_Database::prepareAndExecute( $sql, array());
$real_files = array();
foreach ($files as $f) {
$real_files[] = $f['file_id'];
@ -48,7 +48,7 @@ WHERE ends > now() AT TIME ZONE 'UTC'
AND stream_id is not null
SQL;
$streams = Application_Common_Database::prepareAndExecute( $sql, array());
$real_streams = array();
foreach ($streams as $s) {
$real_streams[] = $s['stream_id'];
@ -322,7 +322,8 @@ SQL;
ft.album_title AS file_album_title,
ft.length AS file_length,
ft.file_exists AS file_exists,
ft.mime AS file_mime
ft.mime AS file_mime,
ft.soundcloud_id AS soundcloud_id
SQL;
$filesJoin = <<<SQL
cc_schedule AS sched
@ -357,7 +358,8 @@ SQL;
ws.description AS file_album_title,
ws.length AS file_length,
't'::BOOL AS file_exists,
ws.mime as file_mime
ws.mime AS file_mime,
(SELECT NULL::integer AS soundcloud_id)
SQL;
$streamJoin = <<<SQL
cc_schedule AS sched
@ -391,17 +393,17 @@ SQL;
$showPredicate = "";
if (count($p_shows) > 0) {
$params = array();
$map = array();
for ($i = 0, $len = count($p_shows); $i < $len; $i++) {
$holder = "show_".$i;
$holder = ":show_".$i;
$params[] = $holder;
$map[$holder] = $p_shows[$i];
}
$showPredicate = " AND show_id IN (".implode(",", $params).")";
$paramMap = $paramMap + $map;
} else if (count($p_show_instances) > 0) {
@ -448,13 +450,13 @@ SQL;
":ts_6" => $p_end_str,
);
$paramMap = $paramMap + $map;
$rows = Application_Common_Database::prepareAndExecute(
$sql,
$paramMap,
Application_Common_Database::ALL
);
return $rows;
}
@ -475,7 +477,7 @@ SQL;
$sql .= " WHERE id=:pid";
$map = array(":pid" => $p_id);
Application_Common_Database::prepareAndExecute($sql, $map,
Application_Common_Database::prepareAndExecute($sql, $map,
Application_Common_Database::EXECUTE);
}
@ -501,9 +503,9 @@ SQL;
{
$sql = "SELECT count(*) as cnt FROM cc_schedule";
$res = Application_Common_Database::prepareAndExecute($sql, array(),
$res = Application_Common_Database::prepareAndExecute($sql, array(),
Application_Common_Database::COLUMN);
return $res;
}
@ -706,7 +708,7 @@ SQL;
$key = "{$time}_{$i}";
$i++;
}
$data["media"][$key] = $item;
}
@ -755,7 +757,7 @@ SQL;
$replay_gain = is_null($item["replay_gain"]) ? "0": $item["replay_gain"];
$replay_gain += Application_Model_Preference::getReplayGainModifier();
if ( !Application_Model_Preference::GetEnableReplayGain() ) {
$replay_gain = 0;
}
@ -775,7 +777,7 @@ SQL;
'replay_gain' => $replay_gain,
'independent_event' => $independent_event,
);
if ($schedule_item['cue_in'] > $schedule_item['cue_out']) {
$schedule_item['cue_in'] = $schedule_item['cue_out'];
}
@ -915,10 +917,10 @@ SQL;
} else {
throw new Exception("Unknown schedule type: ".print_r($item, true));
}
}
}
/* Check if two events are less than or equal to 1 second apart
*/
public static function areEventsLinked($event1, $event2) {
@ -996,7 +998,7 @@ SQL;
public static function deleteAll()
{
$sql = "TRUNCATE TABLE cc_schedule";
Application_Common_Database::prepareAndExecute($sql, array(),
Application_Common_Database::prepareAndExecute($sql, array(),
Application_Common_Database::EXECUTE);
}
@ -1199,14 +1201,14 @@ SQL;
$update=false, $instanceId=null, $showId=null)
{
$overlapping = false;
$params = array(
':show_end1' => $show_end->format('Y-m-d H:i:s'),
':show_end2' => $show_end->format('Y-m-d H:i:s'),
':show_end3' => $show_end->format('Y-m-d H:i:s')
);
/* If a show is being edited, exclude it from the query
* In both cases (new and edit) we only grab shows that
* are scheduled 2 days prior
@ -1277,18 +1279,18 @@ SQL;
return 'file';
}
}
public static function GetFileId($p_scheduleId)
{
$scheduledItem = CcScheduleQuery::create()->findPK($p_scheduleId);
return $scheduledItem->getDbFileId();
}
public static function GetStreamId($p_scheduleId)
{
$scheduledItem = CcScheduleQuery::create()->findPK($p_scheduleId);
return $scheduledItem->getDbStreamId();
}
}

View file

@ -17,7 +17,7 @@ class Application_Model_Scheduler
private $epochNow;
private $nowDT;
private $user;
private $crossfadeDuration;
private $checkUserPermissions = true;
@ -40,7 +40,7 @@ class Application_Model_Scheduler
}
$this->user = Application_Model_User::getCurrentUser();
$this->crossfadeDuration = Application_Model_Preference::GetDefaultCrossfadeDuration();
}
@ -85,6 +85,9 @@ class Application_Model_Scheduler
$nowEpoch = floatval($this->nowDT->format("U.u"));
$schedInfo = array();
$instanceInfo = array();
for ($i = 0; $i < count($items); $i++) {
$id = $items[$i]["id"];
@ -103,7 +106,7 @@ class Application_Model_Scheduler
}
$schedIds = array();
if (isset($schedInfo)) {
if (count($schedInfo) > 0) {
$schedIds = array_keys($schedInfo);
}
$schedItems = CcScheduleQuery::create()->findPKs($schedIds, $this->con);
@ -191,16 +194,18 @@ class Application_Model_Scheduler
if ($type === "audioclip") {
$file = CcFilesQuery::create()->findPK($id, $this->con);
$storedFile = new Application_Model_StoredFile($file, $this->con);
if (is_null($file) || !$file->visible()) {
throw new Exception(_("A selected File does not exist!"));
} else {
$data = $this->fileInfo;
$data["id"] = $id;
$data["cliplength"] = $storedFile->getRealClipLength(
$file->getDbCuein(),
$file->getDbCueout());
$cuein = Application_Common_DateHelper::playlistTimeToSeconds($file->getDbCuein());
$cueout = Application_Common_DateHelper::playlistTimeToSeconds($file->getDbCueout());
$row_length = Application_Common_DateHelper::secondsToPlaylistTime($cueout - $cuein);
$data["cliplength"] = $row_length;
$data["cuein"] = $file->getDbCuein();
$data["cueout"] = $file->getDbCueout();
@ -263,11 +268,11 @@ class Application_Model_Scheduler
$cuein = Application_Common_DateHelper::calculateLengthInSeconds($data["cuein"]);
$cueout = Application_Common_DateHelper::calculateLengthInSeconds($data["cueout"]);
$data["cliplength"] = Application_Common_DateHelper::secondsToPlaylistTime($cueout - $cuein);
//fade is in format SS.uuuuuu
$data["fadein"] = $defaultFadeIn;
$data["fadeout"] = $defaultFadeOut;
$data["type"] = 0;
$files[] = $data;
}
@ -322,11 +327,11 @@ class Application_Model_Scheduler
$cuein = Application_Common_DateHelper::calculateLengthInSeconds($data["cuein"]);
$cueout = Application_Common_DateHelper::calculateLengthInSeconds($data["cueout"]);
$data["cliplength"] = Application_Common_DateHelper::secondsToPlaylistTime($cueout - $cuein);
//fade is in format SS.uuuuuu
$data["fadein"] = $defaultFadeIn;
$data["fadeout"] = $defaultFadeOut;
$data["type"] = 0;
$files[] = $data;
}
@ -336,7 +341,7 @@ class Application_Model_Scheduler
return $files;
}
/*
* @param DateTime startDT in UTC
* @param string duration
@ -347,18 +352,18 @@ class Application_Model_Scheduler
private function findTimeDifference($p_startDT, $p_seconds)
{
$startEpoch = $p_startDT->format("U.u");
//add two float numbers to 6 subsecond precision
//DateTime::createFromFormat("U.u") will have a problem if there is no decimal in the resulting number.
$newEpoch = bcsub($startEpoch , (string) $p_seconds, 6);
$dt = DateTime::createFromFormat("U.u", $newEpoch, new DateTimeZone("UTC"));
if ($dt === false) {
//PHP 5.3.2 problem
$dt = DateTime::createFromFormat("U", intval($newEpoch), new DateTimeZone("UTC"));
}
return $dt;
}
@ -388,7 +393,7 @@ class Application_Model_Scheduler
return $dt;
}
private function findNextStartTime($DT, $instance)
private function findNextStartTime($DT, $instanceId)
{
$sEpoch = $DT->format("U.u");
$nEpoch = $this->epochNow;
@ -410,7 +415,7 @@ class Application_Model_Scheduler
->setDbCueIn('00:00:00')
->setDbCueOut('00:00:00')
->setDbPlayoutStatus(-1)
->setDbInstanceId($instance->getDbId())
->setDbInstanceId($instanceId)
->save($this->con);
} else {
$nextDT = $DT;
@ -418,39 +423,45 @@ class Application_Model_Scheduler
return $nextDT;
}
/*
* @param int $showInstance
* This function recalculates the start/end times of items in a gapless show to
* account for crossfade durations.
*/
private function calculateCrossfades($showInstance)
private function calculateCrossfades($instanceId)
{
Logging::info("adjusting start, end times of scheduled items to account for crossfades show instance #".$showInstance);
$instance = CcShowInstancesQuery::create()->findPK($showInstance, $this->con);
if (is_null($instance)) {
throw new OutDatedScheduleException(_("The schedule you're viewing is out of date!"));
}
$itemStartDT = $instance->getDbStarts(null);
$itemEndDT = null;
$schedule = CcScheduleQuery::create()
->filterByDbInstanceId($showInstance)
->orderByDbStarts()
->find($this->con);
foreach ($schedule as $item) {
$itemEndDT = $this->findEndTime($itemStartDT, $item->getDbClipLength());
Logging::info("adjusting start, end times of scheduled items to account for crossfades show instance #".$instanceId);
$item->setDbStarts($itemStartDT)
->setDbEnds($itemEndDT);
$sql = "SELECT * FROM cc_show_instances ".
"WHERE id = {$instanceId}";
$instance = Application_Common_Database::prepareAndExecute(
$sql, array(), Application_Common_Database::SINGLE);
$itemStartDT = $this->findTimeDifference($itemEndDT, $this->crossfadeDuration);
}
$schedule->save($this->con);
if (is_null($instance)) {
throw new OutDatedScheduleException(_("The schedule you're viewing is out of date!"));
}
$itemStartDT = new DateTime($instance["starts"], new DateTimeZone("UTC"));
$itemEndDT = null;
$schedule_sql = "SELECT * FROM cc_schedule ".
"WHERE instance_id = {$instanceId} ".
"ORDER BY starts";
$schedule = Application_Common_Database::prepareAndExecute($schedule_sql);
foreach ($schedule as $item) {
$itemEndDT = $this->findEndTime($itemStartDT, $item["clip_length"]);
$update_sql = "UPDATE cc_schedule SET ".
"starts = '{$itemStartDT->format("Y-m-d H:i:s")}', ".
"ends = '{$itemEndDT->format("Y-m-d H:i:s")}' ".
"WHERE id = {$item["id"]}";
Application_Common_Database::prepareAndExecute(
$update_sql, array(), Application_Common_Database::EXECUTE);
$itemStartDT = $this->findTimeDifference($itemEndDT, $this->crossfadeDuration);
}
}
/*
@ -491,7 +502,7 @@ class Application_Model_Scheduler
}
/**
*
*
* Enter description here ...
* @param $scheduleItems
* cc_schedule items, where the items get inserted after
@ -531,12 +542,18 @@ class Application_Model_Scheduler
* of inserted items
*/
if ($id != 0) {
$ccSchedule = CcScheduleQuery::create()->findPk($id);
$ccShowInstance = CcShowInstancesQuery::create()->findPk($ccSchedule->getDbInstanceId());
$ccShow = $ccShowInstance->getCcShow();
$linked = $ccShow->isLinked();
$schedule_sql = "SELECT * FROM cc_schedule WHERE id = ".$id;
$ccSchedule = Application_Common_Database::prepareAndExecute(
$schedule_sql, array(), Application_Common_Database::SINGLE);
$show_sql = "SELECT * FROM cc_show WHERE id IN (".
"SELECT show_id FROM cc_show_instances WHERE id = ".$ccSchedule["instance_id"].")";
$ccShow = Application_Common_Database::prepareAndExecute(
$show_sql, array(), Application_Common_Database::SINGLE);
$linked = $ccShow["linked"];
if ($linked) {
$unique = $ccShow->getDbId() . $ccSchedule->getDbPosition();
$unique = $ccShow["id"] . $ccSchedule["position"];
if (!in_array($unique, $temp)) {
$temp[] = $unique;
} else {
@ -544,11 +561,14 @@ class Application_Model_Scheduler
}
}
} else {
$ccShowInstance = CcShowInstancesQuery::create()->findPk($schedule["instance"]);
$ccShow = $ccShowInstance->getccShow();
$linked = $ccShow->isLinked();
$show_sql = "SELECT * FROM cc_show WHERE id IN (".
"SELECT show_id FROM cc_show_instances WHERE id = ".$schedule["instance"].")";
$ccShow = Application_Common_Database::prepareAndExecute(
$show_sql, array(), Application_Common_Database::SINGLE);
$linked = $ccShow["linked"];
if ($linked) {
$unique = $ccShow->getDbId() . "a";
$unique = $ccShow["id"] . "a";
if (!in_array($unique, $temp)) {
$temp[] = $unique;
} else {
@ -562,38 +582,59 @@ class Application_Model_Scheduler
* to that show
*/
if ($linked) {
$instances = $ccShow->getCcShowInstancess();
$instance_sql = "SELECT * FROM cc_show_instances ".
"WHERE show_id = ".$ccShow["id"];
$instances = Application_Common_Database::prepareAndExecute(
$instance_sql);
} else {
$instances = array($ccShowInstance);
$instance_sql = "SELECT * FROM cc_show_instances ".
"WHERE id = ".$schedule["instance"];
$instances = Application_Common_Database::prepareAndExecute(
$instance_sql);
}
$excludePositions = array();
foreach($instances as &$instance) {
$instanceId = $instance->getDbId();
$instanceId = $instance["id"];
if ($id !== 0) {
/* We use the selected cursor's position to find the same
* positions in every other linked instance
*/
$pos = $ccSchedule->getDbPosition();
$pos = $ccSchedule["position"];
$linkCcSchedule = CcScheduleQuery::create()
->filterByDbInstanceId($instanceId)
->filterByDbPosition($pos)
->findOne();
$linkedItem_sql = "SELECT ends FROM cc_schedule ".
"WHERE instance_id = {$instanceId} ".
"AND position = {$pos} ".
"AND playout_status != -1";
$linkedItemEnds = Application_Common_Database::prepareAndExecute(
$linkedItem_sql, array(), Application_Common_Database::COLUMN);
$schedItemEndDT = $linkCcSchedule->getDbEnds(null);
$nextStartDT = $this->findNextStartTime($schedItemEndDT, $instance);
$nextStartDT = $this->findNextStartTime(
new DateTime($linkedItemEnds, new DateTimeZone("UTC")),
$instanceId);
$pos++;
/* Show is not empty so we need to apply crossfades
* for the first inserted item
*/
$applyCrossfades = true;
}
//selected empty row to add after
else {
$showStartDT = $instance->getDbStarts(null);
$nextStartDT = $this->findNextStartTime($showStartDT, $instance);
$showStartDT = new DateTime($instance["starts"], new DateTimeZone("UTC"));
$nextStartDT = $this->findNextStartTime($showStartDT, $instanceId);
//show is empty so start position counter at 0
//first item in show so start position counter at 0
$pos = 0;
/* Show is empty so we don't need to calculate crossfades
* for the first inserted item
*/
$applyCrossfades = false;
}
if (!in_array($instance->getDbId(), $affectedShowInstances)) {
if (!in_array($instanceId, $affectedShowInstances)) {
$affectedShowInstances[] = $instanceId;
}
@ -605,7 +646,12 @@ class Application_Model_Scheduler
$pstart = microtime(true);
$initalStartDT = clone $nextStartDT;
if ($applyCrossfades) {
$initalStartDT = clone $this->findTimeDifference(
$nextStartDT, $this->crossfadeDuration);
} else {
$initalStartDT = clone $nextStartDT;
}
$pend = microtime(true);
Logging::debug("finding all following items.");
@ -620,83 +666,129 @@ class Application_Model_Scheduler
}
}
$doInsert = false;
$doUpdate = false;
$values = array();
foreach ($filesToInsert as &$file) {
//item existed previously and is being moved.
//need to keep same id for resources if we want REST.
if (isset($file['sched_id'])) {
$sched = CcScheduleQuery::create()->findPk($file["sched_id"]);
$adjustFromDT = clone $nextStartDT;
$doUpdate = true;
$movedItem_sql = "SELECT * FROM cc_schedule ".
"WHERE id = ".$file["sched_id"];
$sched = Application_Common_Database::prepareAndExecute(
$movedItem_sql, array(), Application_Common_Database::SINGLE);
/* We need to keep a record of the original positon a track
* is being moved from so we can use it to retrieve the correct
* items in linked instances
*/
if (!isset($originalPosition)) {
$originalPosition = $sched->getDbPosition();
$originalPosition = $sched["position"];
}
/* If we are moving an item in a linked show we need to get
* the relative item to move in each instance. We know what the
* relative item is by its position
*/
if ($linked && $moveAction) {
$sched = CcScheduleQuery::create()
->filterByDbInstanceId($instanceId)
->filterByDbPosition($originalPosition)
->findOne();
}
$excludeIds[] = intval($sched->getDbId());
if ($linked) {
$movedItem_sql = "SELECT * FROM cc_schedule ".
"WHERE position = {$originalPosition} ".
"AND instance_id = {$instanceId}";
$file["cliplength"] = $sched->getDbClipLength();
$file["cuein"] = $sched->getDbCueIn();
$file["cueout"] = $sched->getDbCueOut();
$file["fadein"] = $sched->getDbFadeIn();
$file["fadeout"] = $sched->getDbFadeOut();
$sched = Application_Common_Database::prepareAndExecute(
$movedItem_sql, array(), Application_Common_Database::SINGLE);
}
$excludeIds[] = intval($sched["id"]);
$file["cliplength"] = $sched["clip_length"];
$file["cuein"] = $sched["cue_in"];
$file["cueout"] = $sched["cue_out"];
$file["fadein"] = $sched["fade_in"];
$file["fadeout"] = $sched["fade_out"];
} else {
$sched = new CcSchedule();
$doInsert = true;
}
$endTimeDT = $this->findEndTime($nextStartDT, $file['cliplength']);
// default fades are in seconds
// we need to convert to '00:00:00' format
$file['fadein'] = Application_Common_DateHelper::secondsToPlaylistTime($file['fadein']);
$file['fadeout'] = Application_Common_DateHelper::secondsToPlaylistTime($file['fadeout']);
$sched->setDbStarts($nextStartDT)
->setDbEnds($endTimeDT)
->setDbCueIn($file['cuein'])
->setDbCueOut($file['cueout'])
->setDbFadeIn($file['fadein'])
->setDbFadeOut($file['fadeout'])
->setDbClipLength($file['cliplength'])
->setDbPosition($pos);
if (!$moveAction) {
$sched->setDbInstanceId($instanceId);
}
switch ($file["type"]) {
case 0:
$sched->setDbFileId($file['id']);
$fileId = $file["id"];
$streamId = "null";
break;
case 1:
$sched->setDbStreamId($file['id']);
$streamId = $file["id"];
$fileId = "null";
break;
default: break;
}
$sched->save($this->con);
if ($applyCrossfades) {
$nextStartDT = $this->findTimeDifference($nextStartDT,
$this->crossfadeDuration);
$endTimeDT = $this->findEndTime($nextStartDT, $file['cliplength']);
$endTimeDT = $this->findTimeDifference($endTimeDT, $this->crossfadeDuration);
/* Set it to false because the rest of the crossfades
* will be applied after we insert each item
*/
$applyCrossfades = false;
}
$nextStartDT = $endTimeDT;
$endTimeDT = $this->findEndTime($nextStartDT, $file['cliplength']);
if ($doInsert) {
$values[] = "(".
"'{$nextStartDT->format("Y-m-d H:i:s")}', ".
"'{$endTimeDT->format("Y-m-d H:i:s")}', ".
"'{$file["cuein"]}', ".
"'{$file["cueout"]}', ".
"'{$file["fadein"]}', ".
"'{$file["fadeout"]}', ".
"'{$file["cliplength"]}', ".
"{$pos}, ".
"{$instanceId}, ".
"{$fileId}, ".
"{$streamId})";
} elseif ($doUpdate) {
$update_sql = "UPDATE cc_schedule SET ".
"starts = '{$nextStartDT->format("Y-m-d H:i:s")}', ".
"ends = '{$endTimeDT->format("Y-m-d H:i:s")}', ".
"cue_in = '{$file["cuein"]}', ".
"cue_out = '{$file["cueout"]}', ".
"fade_in = '{$file["fadein"]}', ".
"fade_out = '{$file["fadeout"]}', ".
"clip_length = '{$file["cliplength"]}', ".
"position = {$pos} ".
"WHERE id = {$sched["id"]}";
Application_Common_Database::prepareAndExecute(
$update_sql, array(), Application_Common_Database::EXECUTE);
}
$nextStartDT = $this->findTimeDifference($endTimeDT, $this->crossfadeDuration);
$pos++;
/* If we are adjusting start and end times for items
* after the insert location, we need to exclude the
* schedule item we just inserted because it has correct
* start and end times*/
$excludeIds[] = $sched->getDbId();
}//all files have been inserted/moved
if ($doInsert) {
$insert_sql = "INSERT INTO cc_schedule ".
"(starts, ends, cue_in, cue_out, fade_in, fade_out, ".
"clip_length, position, instance_id, file_id, stream_id) VALUES ".
implode($values, ",")." RETURNING id";
$stmt = $this->con->prepare($insert_sql);
if ($stmt->execute()) {
foreach ($stmt->fetchAll() as $row) {
$excludeIds[] = $row["id"];
}
};
}
// update is_scheduled flag for each cc_file
$fileIds = array();
foreach ($filesToInsert as &$file) {
@ -717,34 +809,43 @@ class Application_Model_Scheduler
}
if ($adjustSched === true) {
$followingSchedItems = CcScheduleQuery::create()
->filterByDBStarts($initalStartDT->format("Y-m-d H:i:s.u"), Criteria::GREATER_EQUAL)
->filterByDbInstanceId($instance->getDbId())
->filterByDbId($excludeIds, Criteria::NOT_IN)
->orderByDbStarts()
->find($this->con);
$followingItems_sql = "SELECT * FROM cc_schedule ".
"WHERE starts >= '{$initalStartDT->format("Y-m-d H:i:s.u")}' ".
"AND instance_id = {$instanceId} ";
if (count($excludeIds) > 0) {
$followingItems_sql .= "AND id NOT IN (". implode($excludeIds, ",").") ";
}
$followingItems_sql .= "ORDER BY starts";
$followingSchedItems = Application_Common_Database::prepareAndExecute(
$followingItems_sql);
$pstart = microtime(true);
//recalculate the start/end times after the inserted items.
foreach ($followingSchedItems as $item) {
$endTimeDT = $this->findEndTime($nextStartDT, $item->getDbClipLength());
$item->setDbStarts($nextStartDT);
$item->setDbEnds($endTimeDT);
$item->setDbPosition($pos);
$item->save($this->con);
$nextStartDT = $endTimeDT;
$endTimeDT = $this->findEndTime($nextStartDT, $item["clip_length"]);
$endTimeDT = $this->findTimeDifference($endTimeDT, $this->crossfadeDuration);
$update_sql = "UPDATE cc_schedule SET ".
"starts = '{$nextStartDT->format("Y-m-d H:i:s")}', ".
"ends = '{$endTimeDT->format("Y-m-d H:i:s")}', ".
"position = {$pos} ".
"WHERE id = {$item["id"]}";
Application_Common_Database::prepareAndExecute(
$update_sql, array(), Application_Common_Database::EXECUTE);
$nextStartDT = $this->findTimeDifference($endTimeDT, $this->crossfadeDuration);
$pos++;
}
$pend = microtime(true);
Logging::debug("adjusting all following items.");
Logging::debug(floatval($pend) - floatval($pstart));
$this->calculateCrossfades($instance->getDbId());
}
if ($moveAction) {
$this->calculateCrossfades($instanceId);
}
}//for each instance
}//for each schedule location
$endProfile = microtime(true);
@ -782,6 +883,11 @@ class Application_Model_Scheduler
}
}
private function updateMovedItem()
{
}
private function getInstances($instanceId)
{
$ccShowInstance = CcShowInstancesQuery::create()->findPk($instanceId);
@ -999,7 +1105,7 @@ class Application_Model_Scheduler
} else {
$removedItem->delete($this->con);
}
// update is_scheduled in cc_files but only if
// the file is not scheduled somewhere else
$fileId = $removedItem->getDbFileId();

View file

@ -388,6 +388,7 @@ class Application_Model_ShowBuilder
$outdated = false;
$shows = Application_Model_Show::getShows($this->startDT, $this->endDT);
$include = array();
if ($this->opts["showFilter"] !== 0) {
$include[] = $this->opts["showFilter"];
} elseif ($this->opts["myShows"] === 1) {

View file

@ -352,10 +352,10 @@ SQL;
);
//only need to check overlap if show increased in size.
if (strtotime($new_ends) > strtotime($ends)) {
if (strtotime($now_ends) > strtotime($ends)) {
$utcStartDateTime = new DateTime($ends, new DateTimeZone("UTC"));
$utcEndDateTime = new DateTime($new_ends, new DateTimeZone("UTC"));
$utcEndDateTime = new DateTime($now_ends, new DateTimeZone("UTC"));
$overlap = Application_Model_Show::getShows($utcStartDateTime, $utcEndDateTime);
@ -381,7 +381,7 @@ SQL;
}
$this->setShowEnd($new_ends);
$this->setShowEnd($now_ends);
Application_Model_RabbitMq::PushSchedule();
}

View file

@ -150,7 +150,7 @@ class Application_Model_StoredFile
}
}
$dbMd[constant($mdConst)] = $mdValue;
}
}
$this->setDbColMetadata($dbMd);
@ -214,7 +214,7 @@ class Application_Model_StoredFile
if (isset($this->_dbMD[$dbColumn])) {
$propelColumn = $this->_dbMD[$dbColumn];
$method = "set$propelColumn";
/* We need to set track_number to null if it is an empty string
* because propel defaults empty strings to zeros */
if ($dbColumn == "track_number" && empty($mdValue)) $mdValue = null;
@ -330,7 +330,7 @@ SQL;
$stmt = $con->prepare($sql);
$stmt->bindParam(':file_id', $this->id, PDO::PARAM_INT);
if ($stmt->execute()) {
$ids = $stmt->fetchAll();
} else {
@ -386,7 +386,7 @@ SQL;
// set hidden flag to true
$this->_file->setDbHidden(true);
$this->_file->save();
// need to explicitly update any playlist's and block's length
// that contains the file getting deleted
$fileId = $this->_file->getDbId();
@ -396,7 +396,7 @@ SQL;
$pl->setDbLength($pl->computeDbLength(Propel::getConnection(CcPlaylistPeer::DATABASE_NAME)));
$pl->save();
}
$blRows = CcBlockcontentsQuery::create()->filterByDbFileId($fileId)->find();
foreach ($blRows as $row) {
$bl = CcBlockQuery::create()->filterByDbId($row->getDbBlockId())->findOne();
@ -506,19 +506,19 @@ SQL;
public function getFileUrl()
{
$CC_CONFIG = Config::getConfig();
$protocol = empty($_SERVER['HTTPS']) ? "http" : "https";
$serverName = $_SERVER['SERVER_NAME'];
$serverPort = $_SERVER['SERVER_PORT'];
$subDir = $CC_CONFIG['baseDir'];
if ($subDir[0] === "/") {
$subDir = substr($subDir, 1, strlen($subDir) - 1);
}
$baseUrl = "{$protocol}://{$serverName}:{$serverPort}/{$subDir}";
return $this->getRelativeFileUrl($baseUrl);
}
@ -528,8 +528,6 @@ SQL;
*/
public function getRelativeFileUrl($baseUrl)
{
Logging::debug("Zend base url: $baseUrl");
return $baseUrl."api/get-media/file/".$this->getId().".".$this->getFileExtension();
}
@ -643,7 +641,7 @@ SQL;
public static function searchLibraryFiles($datatables)
{
$baseUrl = Application_Common_OsPath::getBaseDir();
$con = Propel::getConnection(CcFilesPeer::DATABASE_NAME);
$displayColumns = self::getLibraryColumns();
@ -780,16 +778,18 @@ SQL;
foreach ($results['aaData'] as &$row) {
$row['id'] = intval($row['id']);
$len_formatter = new LengthFormatter($row['length']);
$row['length'] = $len_formatter->format();
$cuein_formatter = new LengthFormatter($row["cuein"]);
$row["cuein"] = $cuein_formatter->format();
$cueout_formatter = new LengthFormatter($row["cueout"]);
$row["cueout"] = $cueout_formatter->format();
if ($row['ftype'] === "audioclip") {
$cuein_formatter = new LengthFormatter($row["cuein"]);
$row["cuein"] = $cuein_formatter->format();
$cueout_formatter = new LengthFormatter($row["cueout"]);
$row["cueout"] = $cueout_formatter->format();
$cuein = Application_Common_DateHelper::playlistTimeToSeconds($row["cuein"]);
$cueout = Application_Common_DateHelper::playlistTimeToSeconds($row["cueout"]);
$row_length = Application_Common_DateHelper::secondsToPlaylistTime($cueout - $cuein);
$formatter = new SamplerateFormatter($row['sample_rate']);
$row['sample_rate'] = $formatter->format();
@ -798,13 +798,20 @@ SQL;
//soundcloud status
$file = Application_Model_StoredFile::RecallById($row['id']);
$row['soundcloud_status'] = $file->getSoundCloudId();
$row['soundcloud_id'] = $file->getSoundCloudId();
// for audio preview
$row['audioFile'] = $row['id'].".".pathinfo($row['filepath'], PATHINFO_EXTENSION);
} else {
$row['audioFile'] = $row['id'];
}
else {
$row['audioFile'] = $row['id'];
$row_length = $row['length'];
}
$len_formatter = new LengthFormatter($row_length);
$row['length'] = $len_formatter->format();
//convert mtime and utime to localtime
$row['mtime'] = new DateTime($row['mtime'], new DateTimeZone('UTC'));
@ -895,7 +902,7 @@ SQL;
$in = fopen($_FILES['file']['tmp_name'], "rb");
if ($in) {
while ($buff = fread($in, 4096))
while (($buff = fread($in, 4096)))
fwrite($out, $buff);
} else
die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": _("Failed to open input stream.")}, "id" : "id"}');
@ -914,7 +921,7 @@ SQL;
$in = fopen("php://input", "rb");
if ($in) {
while ($buff = fread($in, 4096))
while (($buff = fread($in, 4096)))
fwrite($out, $buff);
} else
die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": _("Failed to open input stream.")}, "id" : "id"}');
@ -963,6 +970,7 @@ SQL;
// Check if we have enough space before copying
if (!self::isEnoughDiskSpaceToCopy($stor, $audio_file)) {
$freeSpace = disk_free_space($stor);
$fileSize = filesize($audio_file);
return array("code" => 107,
"message" => sprintf(_("The file was not uploaded, there is "
@ -1030,7 +1038,7 @@ SQL;
$LIQUIDSOAP_ERRORS = array('TagLib: MPEG::Properties::read() -- Could not find a valid last MPEG frame in the stream.');
// Ask Liquidsoap if file is playable
$ls_command = sprintf('/usr/bin/airtime-liquidsoap -v -c "output.dummy(audio_to_stereo(single(%s)))" 2>&1',
$ls_command = sprintf('/usr/bin/airtime-liquidsoap -v -c "output.dummy(audio_to_stereo(single(%s)))" 2>&1',
escapeshellarg($audio_file));
$command = "export PATH=/usr/local/bin:/usr/bin:/bin/usr/bin/ && $ls_command";
@ -1070,14 +1078,14 @@ SQL;
$stmt = $con->prepare($sql);
$stmt->bindParam(':dir_id', $dir_id);
if ($stmt->execute()) {
$rows = $stmt->fetchAll();
} else {
$msg = implode(',', $stmt->errorInfo());
throw new Exception("Error: $msg");
}
$results = array();
foreach ($rows as $row) {
$results[] = $row["fp"];
@ -1113,10 +1121,10 @@ SQL;
return $rows;
}
public static function getAllFilesWithoutSilan() {
$con = Propel::getConnection();
$sql = <<<SQL
SELECT f.id,
m.directory || f.filepath AS fp
@ -1126,14 +1134,14 @@ WHERE file_exists = 'TRUE'
AND silan_check IS FALSE Limit 100
SQL;
$stmt = $con->prepare($sql);
if ($stmt->execute()) {
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
} else {
$msg = implode(',', $stmt->errorInfo());
throw new Exception("Error: $msg");
}
return $rows;
}
@ -1229,7 +1237,7 @@ SQL;
->save();
}
// This method seems to be unsued everywhere so I've commented it out
// If it's absence does not have any effect then it will be completely
// removed soon
@ -1257,7 +1265,7 @@ SQL;
$description = $file->getDbTrackTitle();
$tag = array();
$genre = $file->getDbGenre();
$release = $file->getDbYear();
$release = $file->getDbUtime();
try {
$soundcloud = new Application_Model_Soundcloud();
$soundcloud_res = $soundcloud->uploadTrack(
@ -1286,7 +1294,7 @@ SQL;
}
}
}
public static function setIsPlaylist($p_playlistItems, $p_type, $p_status) {
foreach ($p_playlistItems as $item) {
$file = self::RecallById($item->getDbFileId());
@ -1304,7 +1312,7 @@ SQL;
}
}
}
public static function setIsScheduled($p_scheduleItem, $p_status,
$p_fileId=null) {
@ -1347,14 +1355,6 @@ SQL;
Application_Common_Database::prepareAndExecute($sql, array(),
Application_Common_Database::EXECUTE);
}
public function getRealClipLength($p_cuein, $p_cueout) {
$sql = "SELECT :cueout::INTERVAL - :cuein::INTERVAL";
return Application_Common_Database::prepareAndExecute($sql, array(
':cueout' => $p_cueout,
':cuein' => $p_cuein), 'column');
}
}
class DeleteScheduledFileException extends Exception {}

View file

@ -125,6 +125,7 @@ class Application_Model_Systemstatus
public static function GetPlatformInfo()
{
$keys = array("release", "machine", "memory", "swap");
$data = array();
foreach ($keys as $key) {
$data[$key] = "UNKNOWN";
}
@ -212,7 +213,7 @@ class Application_Model_Systemstatus
public static function GetDiskInfo()
{
$partions = array();
$partitions = array();
//connect to DB and find how much total space user has allocated.
$totalSpace = Application_Model_Preference::GetDiskQuota();

View file

@ -226,7 +226,7 @@ class Application_Model_User
public function deleteAllFiles()
{
$my_files = $this->getOwnedFiles();
foreach ($files as $file) {
foreach ($my_files as $file) {
$file->delete();
}
}

View file

@ -57,6 +57,14 @@ class CcFiles extends BaseCcFiles {
return $this;
}
public function setDbTrackNumber($v)
{
$max = pow(2, 31)-1;
$v = ($v > $max) ? $max : $v;
return parent::setDbTrackNumber($v);
}
// returns true if the file exists and is not hidden
public function visible() {
return $this->getDbFileExists() && !$this->getDbHidden();

View file

@ -77,9 +77,9 @@ class Application_Service_CalendarService
//Show content can be modified from the calendar if:
// the show has not started,
// the user is admin or hosting the show,
// the show is not recorded or rebroadcasted
// the show is not recorded
if ($now < $start && ($isAdminOrPM || $isHostOfShow) &&
!$this->ccShowInstance->isRecorded() && !$this->ccShowInstance->isRebroadcast()) {
!$this->ccShowInstance->isRecorded() ) {
$menu["schedule"] = array(
"name"=> _("Add / Remove Content"),
@ -117,7 +117,7 @@ class Application_Service_CalendarService
}
$isRepeating = $this->ccShow->getFirstCcShowDay()->isRepeating();
if (!$this->ccShowInstance->isRebroadcast()) {
if (!$this->ccShowInstance->isRebroadcast() && $isAdminOrPM) {
if ($isRepeating) {
$menu["edit"] = array(
"name" => _("Edit"),
@ -328,4 +328,4 @@ class Application_Service_CalendarService
}
}
}
}

View file

@ -148,6 +148,24 @@ class Application_Service_SchedulerService
return $dt;
}
private static function findTimeDifference($p_startDT, $p_seconds)
{
$startEpoch = $p_startDT->format("U.u");
//add two float numbers to 6 subsecond precision
//DateTime::createFromFormat("U.u") will have a problem if there is no decimal in the resulting number.
$newEpoch = bcsub($startEpoch , (string) $p_seconds, 6);
$dt = DateTime::createFromFormat("U.u", $newEpoch, new DateTimeZone("UTC"));
if ($dt === false) {
//PHP 5.3.2 problem
$dt = DateTime::createFromFormat("U", intval($newEpoch), new DateTimeZone("UTC"));
}
return $dt;
}
public static function fillNewLinkedInstances($ccShow)
{
/* First check if any linked instances have content
@ -155,64 +173,98 @@ class Application_Service_SchedulerService
* any other instances with content
*/
$instanceIds = $ccShow->getInstanceIds();
$ccSchedules = CcScheduleQuery::create()
->filterByDbInstanceId($instanceIds, Criteria::IN)
->find();
if (!$ccSchedules->isEmpty()) {
$schedule_sql = "SELECT * FROM cc_schedule ".
"WHERE instance_id IN (".implode($instanceIds, ",").")";
$ccSchedules = Application_Common_Database::prepareAndExecute(
$schedule_sql);
if (count($ccSchedules) > 0) {
/* Find the show contents of just one of the instances. It doesn't
* matter which instance we use since all the content is the same
*/
$ccSchedule = $ccSchedules->getFirst();
$showStamp = CcScheduleQuery::create()
->filterByDbInstanceId($ccSchedule->getDbInstanceId())
->orderByDbStarts()
->find();
$ccSchedule = $ccSchedules[0];
$showStamp_sql = "SELECT * FROM cc_schedule ".
"WHERE instance_id = {$ccSchedule["instance_id"]} ".
"ORDER BY starts";
$showStamp = Application_Common_Database::prepareAndExecute(
$showStamp_sql);
//get time_filled so we can update cc_show_instances
$timeFilled = $ccSchedule->getCcShowInstances()->getDbTimeFilled();
$timeFilled_sql = "SELECT time_filled FROM cc_show_instances ".
"WHERE id = {$ccSchedule["instance_id"]}";
$timeFilled = Application_Common_Database::prepareAndExecute(
$timeFilled_sql, array(), Application_Common_Database::COLUMN);
//need to find out which linked instances are empty
foreach ($ccShow->getCcShowInstancess() as $ccShowInstance) {
$ccSchedules = CcScheduleQuery::create()
->filterByDbInstanceId($ccShowInstance->getDbId())
->find();
$values = array();
foreach ($instanceIds as $id) {
$instanceSched_sql = "SELECT * FROM cc_schedule ".
"WHERE instance_id = {$id} ".
"ORDER by starts";
$ccSchedules = Application_Common_Database::prepareAndExecute(
$instanceSched_sql);
/* If the show instance is empty OR it has different content than
* the first instance, we cant to fill/replace with the show stamp
* the first instance, we need to fill/replace with the show stamp
* (The show stamp is taken from the first show instance's content)
*/
if ($ccSchedules->isEmpty() ||
self::replaceInstanceContentCheck($ccShowInstance, $showStamp)) {
if (count($ccSchedules) < 1 ||
self::replaceInstanceContentCheck($ccSchedules, $showStamp)) {
$nextStartDT = $ccShowInstance->getDbStarts(null);
$instanceStart_sql = "SELECT starts FROM cc_show_instances ".
"WHERE id = {$id} ".
"ORDER BY starts";
$nextStartDT = new DateTime(
Application_Common_Database::prepareAndExecute(
$instanceStart_sql, array(), Application_Common_Database::COLUMN),
new DateTimeZone("UTC"));
foreach ($showStamp as $item) {
$endTimeDT = self::findEndTime($nextStartDT, $item->getDbClipLength());
$endTimeDT = self::findEndTime($nextStartDT, $item["clip_length"]);
$ccSchedule = new CcSchedule();
$ccSchedule
->setDbStarts($nextStartDT)
->setDbEnds($endTimeDT)
->setDbFileId($item->getDbFileId())
->setDbStreamId($item->getDbStreamId())
->setDbClipLength($item->getDbClipLength())
->setDbFadeIn($item->getDbFadeIn())
->setDbFadeOut($item->getDbFadeOut())
->setDbCuein($item->getDbCueIn())
->setDbCueOut($item->getDbCueOut())
->setDbInstanceId($ccShowInstance->getDbId())
->setDbPosition($item->getDbPosition())
->save();
if (is_null($item["file_id"])) {
$item["file_id"] = "null";
}
if (is_null($item["stream_id"])) {
$item["stream_id"] = "null";
}
$nextStartDT = $endTimeDT;
$values[] = "(".
"'{$nextStartDT->format("Y-m-d H:i:s")}', ".
"'{$endTimeDT->format("Y-m-d H:i:s")}', ".
"'{$item["clip_length"]}', ".
"'{$item["fade_in"]}', ".
"'{$item["fade_out"]}', ".
"'{$item["cue_in"]}', ".
"'{$item["cue_out"]}', ".
"{$item["file_id"]}, ".
"{$item["stream_id"]}, ".
"{$id}, ".
"{$item["position"]})";
$nextStartDT = self::findTimeDifference($endTimeDT,
Application_Model_Preference::GetDefaultCrossfadeDuration());
} //foreach show item
//update time_filled in cc_show_instances
$ccShowInstance
->setDbTimeFilled($timeFilled)
->setDbLastScheduled(gmdate("Y-m-d H:i:s"))
->save();
}
} //foreach linked instance
$insert_sql = "INSERT INTO cc_schedule (starts, ends, ".
"clip_length, fade_in, fade_out, cue_in, cue_out, ".
"file_id, stream_id, instance_id, position) VALUES ".
implode($values, ",");
Application_Common_Database::prepareAndExecute(
$insert_sql, array(), Application_Common_Database::EXECUTE);
//update time_filled in cc_show_instances
$now = gmdate("Y-m-d H:i:s");
$update_sql = "UPDATE cc_show_instances SET ".
"time_filled = '{$timeFilled}', ".
"last_scheduled = '{$now}' ".
"WHERE show_id = {$ccShow->getDbId()}";
Application_Common_Database::prepareAndExecute(
$update_sql, array(), Application_Common_Database::EXECUTE);
} //if at least one linked instance has content
}
@ -248,7 +300,8 @@ class Application_Service_SchedulerService
->setDbPosition($item->getDbPosition())
->save();
$nextStartDT = $endTimeDT;
$nextStartDT = self::findTimeDifference($endTimeDT,
Application_Model_Preference::GetDefaultCrossfadeDuration());
} //foreach show item
$ccShowInstance
@ -259,20 +312,24 @@ class Application_Service_SchedulerService
}
}
private static function replaceInstanceContentCheck($ccShowInstance, $showStamp)
private static function replaceInstanceContentCheck($currentShowStamp, $showStamp)
{
$currentShowStamp = CcScheduleQuery::create()
/*$currentShowStamp = CcScheduleQuery::create()
->filterByDbInstanceId($ccShowInstance->getDbId())
->orderByDbStarts()
->find();
->find();*/
$counter = 0;
foreach ($showStamp as $item) {
if ($item->getDbFileId() != $currentShowStamp[$counter]->getDbFileId() ||
$item->getDbStreamId() != $currentShowStamp[$counter]->getDbStreamId()) {
CcScheduleQuery::create()
if ($item["file_id"] != $currentShowStamp[$counter]["file_id"] ||
$item["stream_id"] != $currentShowStamp[$counter]["stream_id"]) {
/*CcScheduleQuery::create()
->filterByDbInstanceId($ccShowInstance->getDbId())
->delete();
->delete();*/
$delete_sql = "DELETE FROM cc_schedule ".
"WHERE instance_id = {$currentShowStamp[$counter]["instance_id"]}";
Application_Common_Database::prepareAndExecute(
$delete_sql, array(), Application_Common_Database::EXECUTE);
return true;
}
}

View file

@ -99,8 +99,9 @@ class Application_Service_ShowFormService
public function delegateShowFormPopulation($forms)
{
$this->populateFormWhat($forms["what"]);
$this->populateFormWhen($forms["when"]);
$this->populateFormRepeats($forms["repeats"]);
//local show start DT
$showStart = $this->populateFormWhen($forms["when"]);
$this->populateFormRepeats($forms["repeats"], $showStart);
$this->populateFormWho($forms["who"]);
$this->populateFormStyle($forms["style"]);
$this->populateFormLive($forms["live"]);
@ -136,6 +137,9 @@ class Application_Service_ShowFormService
$form->disableStartDateAndTime();
} else {
list($showStart, $showEnd) = $this->getNextFutureRepeatShowTime();
if ($this->hasShowStarted($showStart)) {
$form->disableStartDateAndTime();
}
}
}
@ -147,6 +151,8 @@ class Application_Service_ShowFormService
'add_show_end_time' => $showEnd->format("H:i"),
'add_show_duration' => $ccShowDay->formatDuration(true),
'add_show_repeats' => $ccShowDay->isRepeating() ? 1 : 0));
return $showStart;
}
private function populateInstanceFormWhen($form)
@ -179,7 +185,13 @@ class Application_Service_ShowFormService
$form->getElement('add_show_repeats')->setOptions(array("disabled" => true));
}
private function populateFormRepeats($form)
/**
*
* Enter description here ...
* @param $form
* @param DateTime $nextFutureShowStart user's local timezone
*/
private function populateFormRepeats($form, $nextFutureShowStart)
{
$ccShowDays = $this->ccShow->getCcShowDays();
@ -219,6 +231,14 @@ class Application_Service_ShowFormService
if (!$this->ccShow->isLinkable() || $this->ccShow->isRecorded()) {
$form->getElement('add_show_linked')->setOptions(array('disabled' => true));
}
/* Because live editing of a linked show is disabled, we will disable
* the linking option if the current show is being edited. We don't
* want the user to suddenly not be able to edit the current show
*/
if ($this->hasShowStarted($nextFutureShowStart)) {
$form->getElement('add_show_linked')->setOptions(array('disabled' => true));
}
}
private function populateFormWho($form)
@ -295,6 +315,22 @@ class Application_Service_ShowFormService
$form->populate($formValues);
}
/**
*
* Enter description here ...
* @param DateTime $showStart user's local time
*/
private function hasShowStarted($p_showStart) {
$showStart = clone $p_showStart;
$showStart->setTimeZone(new DateTimeZone("UTC"));
if ($showStart->format("Y-m-d H:i:s") < gmdate("Y-m-d H:i:s")) {
return true;
} else {
return false;
}
}
/**
*
* Before we send the form data in for validation, there

View file

@ -179,9 +179,6 @@ class Application_Service_ShowService
if (is_null($this->ccShow)) {
$ccShowDays = $this->getShowDaysInRange($populateUntil, $end);
if (count($ccShowDays) > 0) {
$this->ccShow = $ccShowDays[0]->getCcShow();
}
} else {
$ccShowDays = $this->ccShow->getCcShowDays();
}
@ -190,32 +187,43 @@ class Application_Service_ShowService
$populateUntil = $end;
}
/* In case the user is moving forward in the calendar and there are
* linked shows in the schedule we need to keep track of each cc_show
* so we know which shows need to be filled with content
*/
$ccShows = array();
foreach ($ccShowDays as $day) {
$this->ccShow = $day->getCcShow();
if (!isset($ccShows[$day->getDbShowId()])) {
$ccShows[$day->getDbShowId()] = $day->getccShow();
}
switch ($day->getDbRepeatType()) {
case NO_REPEAT:
$this->createNonRepeatingInstance($day, $populateUntil);
break;
case REPEAT_WEEKLY:
$this->createRepeatingInstances($day, $populateUntil, REPEAT_WEEKLY,
$this->createWeeklyRepeatInstances($day, $populateUntil, REPEAT_WEEKLY,
new DateInterval("P7D"), $daysAdded);
break;
case REPEAT_BI_WEEKLY:
$this->createRepeatingInstances($day, $populateUntil, REPEAT_BI_WEEKLY,
$this->createWeeklyRepeatInstances($day, $populateUntil, REPEAT_BI_WEEKLY,
new DateInterval("P14D"), $daysAdded);
break;
case REPEAT_MONTHLY_MONTHLY:
$this->createMonthlyMonthlyRepeatInstances($day, $populateUntil);
$this->createMonthlyRepeatInstances($day, $populateUntil);
break;
case REPEAT_MONTHLY_WEEKLY:
$this->createRepeatingInstances($day, $populateUntil, REPEAT_MONTHLY_WEEKLY,
null, $daysAdded);
$this->createMonthlyRepeatInstances($day, $populateUntil);
break;
}
}
if (isset($this->ccShow) && ($this->isUpdate || $fillInstances) &&
$this->ccShow->isLinked()) {
Application_Service_SchedulerService::fillNewLinkedInstances($this->ccShow);
foreach ($ccShows as $ccShow) {
if (($this->isUpdate || $fillInstances) && $ccShow->isLinked()) {
Application_Service_SchedulerService::fillNewLinkedInstances($ccShow);
}
}
if (isset($this->linkedShowContent)) {
@ -322,7 +330,7 @@ SQL;
$this->deleteAllRepeatInstances($currentShowDay, $showId);
//if repeat option was checked we need to treat the current show day
//as a new show day so the repeat instances get created properly
//in createRepeatingInstances()
//in createWeeklyRepeatInstances()
if ($showData['add_show_repeats']) {
array_push($daysAdded, $currentShowDay->getDbDay());
}
@ -619,29 +627,44 @@ SQL;
->filterByDbShowId($showId)
->filterByDbModifiedInstance(false)
->filterByDbRebroadcast(0)
->orderByDbStarts()
->find();
if ($ccShowInstances->isEmpty()) {
return true;
}
//only 1 show instance left of the show, make it non repeating.
else if (count($ccShowInstances) === 1) {
$ccShowInstance = $ccShowInstances[0];
/* We need to update the last_show in cc_show_days so the instances
* don't get recreated as the user moves forward in the calendar
*/
else if (count($ccShowInstances) >= 1) {
$lastShowDays = array();
/* Creates an array where the key is the day of the week (monday,
* tuesday, etc.) and the value is the last show date for each
* day of the week. We will use this array to update the last_show
* for each cc_show_days entry of a cc_show
*/
foreach ($ccShowInstances as $instance) {
$instanceStartDT = new DateTime($instance->getDbStarts(),
new DateTimeZone("UTC"));
$lastShowDays[$instanceStartDT->format("w")] = $instanceStartDT;
}
$ccShowDay = CcShowDaysQuery::create()
->filterByDbShowId($showId)
->findOne();
$tz = $ccShowDay->getDbTimezone();
foreach ($lastShowDays as $dayOfWeek => $lastShowStartDT) {
$ccShowDay = CcShowDaysQuery::create()
->filterByDbShowId($showId)
->filterByDbDay($dayOfWeek)
->findOne();
$startDate = new DateTime($ccShowInstance->getDbStarts(), new DateTimeZone("UTC"));
$startDate->setTimeZone(new DateTimeZone($tz));
$endDate = Application_Service_CalendarService::addDeltas($startDate, 1, 0);
$lastShowStartDT->setTimeZone(new DateTimeZone(
$ccShowDay->getDbTimezone()));
$lastShowEndDT = Application_Service_CalendarService::addDeltas(
$lastShowStartDT, 1, 0);
$ccShowDay->setDbFirstShow($startDate->format("Y-m-d"));
$ccShowDay->setDbLastShow($endDate->format("Y-m-d"));
$ccShowDay->setDbStartTime($startDate->format("H:i:s"));
$ccShowDay->setDbRepeatType(-1);
$ccShowDay->save();
$ccShowDay
->setDbLastShow($lastShowEndDT->format("Y-m-d"))
->save();
}
//remove the old repeating deleted instances.
CcShowInstancesQuery::create()
@ -846,7 +869,7 @@ SQL;
* @param unknown_type $repeatInterval
* @param unknown_type $isRebroadcast
*/
private function createRepeatingInstances($showDay, $populateUntil,
private function createWeeklyRepeatInstances($showDay, $populateUntil,
$repeatType, $repeatInterval, $daysAdded=null)
{
$show_id = $showDay->getDbShowId();
@ -872,7 +895,9 @@ SQL;
Application_Common_DateHelper::ConvertToUtcDateTime($last_show, $timezone) : null;
$utcStartDateTime = new DateTime("now");
$previousDate = clone $start;
foreach ($datePeriod as $date) {
list($utcStartDateTime, $utcEndDateTime) = $this->createUTCStartEndDateTime(
$date, $duration);
/*
@ -926,6 +951,7 @@ SQL;
$this->createRebroadcastInstances($showDay, $date, $ccShowInstance->getDbId());
}
}
$previousDate = clone $date;
}
/* Set UTC to local time before setting the next repeat date. If we don't
@ -936,7 +962,7 @@ SQL;
$this->setNextRepeatingShowDate($nextDate->format("Y-m-d"), $day, $show_id);
}
private function createMonthlyMonthlyRepeatInstances($showDay, $populateUntil)
private function createMonthlyRepeatInstances($showDay, $populateUntil)
{
$show_id = $showDay->getDbShowId();
$first_show = $showDay->getDbFirstShow(); //non-UTC
@ -954,6 +980,13 @@ SQL;
$end = $populateUntil;
}
// We will only need this if the repeat type is MONTHLY_WEEKLY
list($weekNumberOfMonth, $dayOfWeek) =
$this->getMonthlyWeeklyRepeatInterval(
new DateTime($first_show, new DateTimeZone($timezone)));
$this->repeatType = $showDay->getDbRepeatType();
$utcLastShowDateTime = $last_show ?
Application_Common_DateHelper::ConvertToUtcDateTime($last_show, $timezone) : null;
@ -999,10 +1032,23 @@ SQL;
}
if ($this->isRebroadcast) {
$this->createRebroadcastInstances($showDay, $date, $ccShowInstance->getDbId());
$this->createRebroadcastInstances($showDay, $start, $ccShowInstance->getDbId());
}
}
$start = $this->getNextMonthlyMonthlyRepeatDate($start, $timezone, $showDay->getDbStartTime());
if ($this->repeatType == REPEAT_MONTHLY_WEEKLY) {
$monthlyWeeklyStart = new DateTime($utcStartDateTime->format("Y-m"),
new DateTimeZone("UTC"));
$monthlyWeeklyStart->add(new DateInterval("P1M"));
$start = $this->getNextMonthlyWeeklyRepeatDate(
$monthlyWeeklyStart,
$timezone,
$showDay->getDbStartTime(),
$weekNumberOfMonth,
$dayOfWeek);
} else {
$start = $this->getNextMonthlyMonthlyRepeatDate(
$start, $timezone, $showDay->getDbStartTime());
}
}
$this->setNextRepeatingShowDate($start->format("Y-m-d"), $day, $show_id);
}
@ -1018,7 +1064,6 @@ SQL;
private function getMonthlyWeeklyRepeatInterval($showStart)
{
$start = clone $showStart;
$dayOfMonth = $start->format("j");
$dayOfWeek = $start->format("l");
$yearAndMonth = $start->format("Y-m");
@ -1047,22 +1092,24 @@ SQL;
$weekNumberOfMonth = "fourth";
break;
case 5:
$weekNumberOfMonth = "last";
$weekNumberOfMonth = "fifth";
break;
}
return DateInterval::createFromDateString(
$weekNumberOfMonth." ".$dayOfWeek." of next month");
/* return DateInterval::createFromDateString(
$weekNumberOfMonth." ".$dayOfWeek." of next month"); */
return array($weekNumberOfMonth, $dayOfWeek);
}
/**
*
* Enter description here ...
* @param $start
* @param $start user's local time
*/
private function getNextMonthlyMonthlyRepeatDate($start, $timezone, $startTime)
{
$dt = new DateTime($start->format("Y-m"), new DateTimeZone($timezone));
do {
$dt->add(new DateInterval("P1M"));
} while (!checkdate($dt->format("m"), $start->format("d"), $dt->format("Y")));
@ -1077,6 +1124,41 @@ SQL;
return $dt;
}
private function getNextMonthlyWeeklyRepeatDate(
$start,
$timezone,
$startTime,
$weekNumberOfMonth,
$dayOfWeek)
{
$dt = new DateTime($start->format("Y-m"), new DateTimeZone($timezone));
$tempDT = clone $dt;
$fifthWeekExists = false;
do {
$nextDT = date_create($weekNumberOfMonth." ".$dayOfWeek.
" of ".$tempDT->format("F")." ".$tempDT->format("Y"));
/* We have to check if the next date is in the same month in case
* the repeat day is in the fifth week of the month.
* If it's not in the same month we know that a fifth week of
* the next month does not exist. So let's skip it.
*/
if ($tempDT->format("F") == $nextDT->format("F")) {
$fifthWeekExists = true;
}
$tempDT->add(new DateInterval("P1M"));
} while (!$fifthWeekExists);
$dt = $nextDT;
$startTime = explode(":", $startTime);
$hours = isset($startTime[0]) ? $startTime[0] : "00";
$minutes = isset($startTime[1]) ? $startTime[1] : "00";
$seconds = isset($startTime[2]) ? $startTime[2] : "00";
$dt->setTime($hours, $minutes, $seconds);
return $dt;
}
private function getNextRepeatingPopulateStartDateTime($showDay)
{
$nextPopDate = $showDay->getDbNextPopDate();
@ -1426,4 +1508,4 @@ SQL;
$repeatInfo->setDbNextPopDate($nextInfo[0])
->save();
}
}
}

View file

@ -18,18 +18,26 @@
<div class="jp-type-playlist">
<div class="jp-gui jp-interface">
<ul class="jp-controls">
<?php if ($this->type != "audioclip"): ?>
<li class="ui-state-default ui-corner-all jp-previous">
<span class="ui-icon ui-icon-seek-prev" tabindex="1"><? echo _("previous") ?></span>
</li>
<?php endif;?>
<li class="ui-state-default ui-corner-all jp-play">
<span class="ui-icon ui-icon-play" tabindex="1"><? echo _("play") ?></span>
</li>
<li class="ui-state-default ui-corner-all jp-pause">
<span class="ui-icon ui-icon-pause" tabindex="1"><? echo _("pause") ?></span>
</li>
<?php if ($this->type != "audioclip"): ?>
<li class="ui-state-default ui-corner-all jp-next">
<span class="ui-icon ui-icon-seek-next" tabindex="1"><? echo _("next") ?></span>
</li>
<?php endif;?>
<li class="ui-state-default ui-corner-all jp-stop">
<span class="ui-icon ui-icon-stop" tabindex="1"><? echo _("stop") ?></span>
</li>
@ -42,7 +50,9 @@
</div>
<div class="jp-time-holder">
<div class="jp-current-time"></div>
<?php if ($this->type == "audioclip"): ?><div class="jp-duration"></div><?php endif;?>
<?php if ($this->type == "audioclip"): ?>
<div class="jp-duration"></div>
<?php endif;?>
</div>
</div>
<div class="jp-volume-block">

View file

@ -74,7 +74,7 @@ $(document).ready(function(){
if ($type == "ogg")
$type = "oga";
$label = "(".$streamData["${id}_host"].") ".$streamData["${id}_description"]." - ".$streamData["${id}_bitrate"]." Kbit/s";
$label = "(".$streamData["${id}_host"].") ".$streamData["${id}_description"]." - ".$streamData["${id}_bitrate"]." kbit/s";
echo sprintf("<option class='stream' value='%s' data-url='%s' data-type='%s' server-type='%s'>%s</option>", $id, $url, $type, $serverType, $label);
}
?>