diff --git a/3rd_party/pypo/api_clients/api_client.py b/3rd_party/pypo/api_clients/api_client.py
index eb948a4ce..c4c179643 100644
--- a/3rd_party/pypo/api_clients/api_client.py
+++ b/3rd_party/pypo/api_clients/api_client.py
@@ -17,7 +17,7 @@ def api_client_factory(config):
print 'API Client "'+config["api_client"]+'" not supported. Please check your config file.'
print
sys.exit()
-
+
class ApiClientInterface:
# This is optional.
@@ -25,10 +25,16 @@ class ApiClientInterface:
# 3rd party software.
def check_version(self):
nil
-
+
+ # Required.
# This is the main method you need to implement when creating a new API client.
def get_schedule(self):
return 0, []
+
+ # Required.
+ # This downloads the media from the server.
+ def get_media(self, src, dst):
+ nil
# This is optional.
# You dont actually have to implement this function for the liquidsoap playout to work.
@@ -76,7 +82,7 @@ class CampcasterApiClient(ApiClientInterface):
try:
if e[1] == 404:
print '#####################################'
- print '# Unable to contact the OBP-API'
+ print '# Unable to contact the Campcaster-API'
print '# ' + url
print '#####################################'
sys.exit()
@@ -140,6 +146,18 @@ class CampcasterApiClient(ApiClientInterface):
return status, response
+
+ def get_media(self, src, dst):
+ logger = logging.getLogger("CampcasterApiClient.get_media")
+
+ try:
+ src = src + "&api_key=" + self.config["api_key"]
+ urllib.urlretrieve(src, dst, False)
+ logger.info("downloaded %s to %s", src, dst)
+ except Exception, e:
+ logger.error("%s", e)
+
+
def update_scheduled_item(self, item_id, value):
logger = logging.getLogger("CampcasterApiClient.update_scheduled_item")
@@ -160,20 +178,18 @@ class CampcasterApiClient(ApiClientInterface):
def update_start_playing(self, playlist_type, export_source, media_id, playlist_id, transmission_id):
- return
- logger = logging.getLogger("ApiClient.update_scheduled_item")
-
- url = self.api_url + 'schedule/update_start_playing.php' \
- + '?playlist_type=' + str(playlist_type) \
- + '&export_source=' + str(export_source) \
- + '&media_id=' + str(media_id) \
- + '&playlist_id=' + str(playlist_id) \
- + '&transmission_id=' + str(transmission_id)
-
+ logger = logging.getLogger("CampcasterApiClient.update_scheduled_item")
+
+ url = self.config["base_url"] + self.config["api_base"] + self.config["update_start_playing_url"]
+ url = url.replace("%%playlist_type%%", str(playlist_type))
+ url = url.replace("%%export_source%%", str(export_source))
+ url = url.replace("%%media_id%%", str(media_id))
+ url = url.replace("%%playlist_id%%", str(playlist_id))
+ url = url.replace("%%transmission_id%%", str(transmission_id))
print url
try:
- response = urllib.urlopen(url, self.api_auth)
+ response = urllib.urlopen(url)
response = json.read(response.read())
logger.info("API-Status %s", response['status'])
logger.info("API-Message %s", response['message'])
@@ -188,7 +204,7 @@ class CampcasterApiClient(ApiClientInterface):
def generate_range_dp(self):
- logger = logging.getLogger("ApiClient.generate_range_dp")
+ logger = logging.getLogger("CampcasterApiClient.generate_range_dp")
url = self.api_url + 'schedule/generate_range_dp.php'
@@ -208,6 +224,10 @@ class CampcasterApiClient(ApiClientInterface):
################################################################################
+# OpenBroadcast API Client
+################################################################################
+# Also check out the php counterpart that handles the api requests:
+# https://lab.digris.ch/svn/elgg/trunk/unstable/mod/medialibrary/application/controllers/api/pypo.php
OBP_MIN_VERSION = 2010100101 # required obp version
@@ -215,9 +235,8 @@ class ObpApiClient():
def __init__(self, config):
self.config = config
- #self.api_url = api_url
- #self.api_auth = api_auth
-
+ self.api_auth = urllib.urlencode({'api_key': self.config["api_key"]})
+
def check_version(self):
obp_version = self.get_obp_version()
@@ -240,11 +259,12 @@ class ObpApiClient():
print 'pypo is compatible with this version of OBP'
print
+
def get_obp_version(self):
- logger = logging.getLogger("ApiClient.get_obp_version")
- # lookup OBP version
-
- url = self.api_url + 'api/pypo/status/json'
+ logger = logging.getLogger("ObpApiClient.get_obp_version")
+
+ # lookup OBP version
+ url = self.config["base_url"] + self.config["api_base"]+ self.config["version_url"]
try:
logger.debug("Trying to contact %s", url)
@@ -258,7 +278,7 @@ class ObpApiClient():
if e[1] == 401:
print '#####################################'
print '# YOUR API KEY SEEMS TO BE INVALID'
- print '# ' + self.api_auth
+ print '# ' + self.config["api_auth"]
print '#####################################'
sys.exit()
@@ -279,15 +299,26 @@ class ObpApiClient():
obp_version = 0
logger.error("Unable to detect OBP Version - %s", e)
-
return obp_version
+
-
+ def get_media(self, src, dest):
+ try:
+ print '** urllib auth with: ',
+ print self.api_auth
+ urllib.urlretrieve(src, dst, False, self.api_auth)
+ logger.info("downloaded %s to %s", src, dst)
+ except Exception, e:
+ logger.error("%s", e)
+
+
def update_scheduled_item(self, item_id, value):
- logger = logging.getLogger("ApiClient.update_shedueled_item")
+ logger = logging.getLogger("ObpApiClient.update_scheduled_item")
# lookup OBP version
- url = self.api_url + 'api/pypo/update_scheduled_item/' + str(item_id) + '?played=' + str(value)
+ url = self.config["base_url"] + self.config["api_base"] + self.config["update_item_url"]
+ url = url.replace("%%item_id%%", str(item_id))
+ url = url.replace("%%played%%", str(value))
try:
response = urllib.urlopen(url, self.api_auth)
@@ -300,22 +331,18 @@ class ObpApiClient():
api_status = False
logger.critical("Unable to connect to the OBP API - %s", e)
-
return response
def update_start_playing(self, playlist_type, export_source, media_id, playlist_id, transmission_id):
-
- logger = logging.getLogger("ApiClient.update_shedueled_item")
-
- url = self.api_url + 'api/pypo/update_start_playing/' \
- + '?playlist_type=' + str(playlist_type) \
- + '&export_source=' + str(export_source) \
- + '&export_source=' + str(export_source) \
- + '&media_id=' + str(media_id) \
- + '&playlist_id=' + str(playlist_id) \
- + '&transmission_id=' + str(transmission_id)
+ logger = logging.getLogger("ApiClient.update_scheduled_item")
+ url = self.config["base_url"] + self.config["api_base"] + self.config["update_start_playing_url"]
+ url = url.replace("%%playlist_type%%", str(playlist_type))
+ url = url.replace("%%export_source%%", str(export_source))
+ url = url.replace("%%media_id%%", str(media_id))
+ url = url.replace("%%playlist_id%%", str(playlist_id))
+ url = url.replace("%%transmission_id%%", str(transmission_id))
print url
try:
@@ -330,14 +357,13 @@ class ObpApiClient():
api_status = False
logger.critical("Unable to connect to the OBP API - %s", e)
-
return response
def generate_range_dp(self):
- logger = logging.getLogger("ApiClient.generate_range_dp")
+ logger = logging.getLogger("ObpApiClient.generate_range_dp")
- url = self.api_url + 'api/pypo/generate_range_dp/'
+ url = self.config["base_url"] + self.config["api_base"] + self.config["generate_range_url"]
try:
response = urllib.urlopen(url, self.api_auth)
diff --git a/3rd_party/pypo/config.cfg b/3rd_party/pypo/config.cfg
index 61630fde2..c812d4acc 100644
--- a/3rd_party/pypo/config.cfg
+++ b/3rd_party/pypo/config.cfg
@@ -27,23 +27,40 @@ api_key = 'AAA'
# Hostname
base_url = 'http://localhost/'
+################################################################################
+# Generic Config - if you are creating a new API client, define these values #
+################################################################################
+# Path to the base of the API
+api_base = ''
+
+# URL to get the version number of the API
+version_url = ''
+
+# Schedule export path.
+# %%from%% - starting date/time in the form YYYY-MM-DD-hh-mm
+# %%to%% - starting date/time in the form YYYY-MM-DD-hh-mm
+export_url = ''
+
+# Update whether an item has been played.
+# %%item_id%%
+# %%played%%
+update_item_url = ''
+
+# Update whether an item is currently playing.
+update_start_playing_url = ''
+
+# ???
+generate_range_url = ''
+
+
#####################
# Campcaster Config #
#####################
-# Path to the base of the API
api_base = 'campcaster/'
-
-# URL to get the version number of the API
version_url = 'schedule/api_version.php?api_key=%%api_key%%'
-
-# Schedule export path.
-# YYYY-MM-DD-hh-mm will be substituted for the tokens %%from%% and %%to%%
export_url = 'schedule/schedule.php?from=%%from%%&to=%%to%%&api_key=%%api_key%%'
-
update_item_url = 'schedule/schedule.php?item_id=%%item_id%%&played=%%played%%'
-
update_start_playing_url = 'schedule/update_start_playing.php?playlist_type=%%playlist_type%%&export_source=%%export_source%%&media_id=%%media_id%%&playlist_id=%%playlist_id%%&transmission_id=%%transmission_id%%'
-
generate_range_url = 'schedule/generate_range_dp.php'
@@ -51,13 +68,11 @@ generate_range_url = 'schedule/generate_range_dp.php'
# OBP config #
##############
#base_url = 'http://localhost/'
-#api_base = BASE_URL
-#version_url = api_base + 'api/pypo/status/json'
-#update_item_url = api_base + 'api/pypo/update_shedueled_item/$$item_id%%?played=%%played%%'
-
-# prod config
-#base_url = ''
-#api_key = ''
+#api_base = ''
+#version_url = 'api/pypo/status/json'
+#update_item_url = 'api/pypo/update_shedueled_item/$$item_id%%?played=%%played%%'
+#update_start_playing_url = 'api/pypo/update_start_playing/?playlist_type=%%playlist_type%%&export_source=%%export_source%%&media_id=%%media_id%%&playlist_id=%%playlist_id%%&transmission_id=%%transmission_id%%'
+#generate_range_url = 'api/pypo/generate_range_dp/'
############################################
diff --git a/3rd_party/pypo/pypo_cli.py b/3rd_party/pypo/pypo_cli.py
index f5996e107..3839acd09 100755
--- a/3rd_party/pypo/pypo_cli.py
+++ b/3rd_party/pypo/pypo_cli.py
@@ -8,8 +8,14 @@ Python part of radio playout (pypo)
The main functions are "fetch" (./pypo_cli.py -f) and "push" (./pypo_cli.py -p)
-Also check out the php counterpart that handles the api requests:
-https://lab.digris.ch/svn/elgg/trunk/unstable/mod/medialibrary/application/controllers/api/pypo.php
+There are two layers: scheduler & daypart (fallback)
+
+The daypart is a fallback-layer generated by the playlists daypart-settings
+(eg a playlist creator can say that the list is good for Monday and Tues,
+between 14:00 and 16:00). So if there is nothing in the schedule, pypo will
+still play something (instead of silence..) This layer is optional.
+It is there so that you dont have a fallback player which plays the same 100
+tracks over and over again.
Attention & ToDos
- liquidsoap does not like mono files! So we have to make sure that only files with
@@ -290,7 +296,6 @@ class Playout:
# TODO: maybe a bit more modular..
silence_file = self.file_dir + 'basic/silence.mp3'
-
if int(playlist['played']) == 1:
logger.info("playlist %s already played / sent to liquidsoap, so will ignore it", pkey)
@@ -311,14 +316,14 @@ class Playout:
else:
print 'Could not find silence file!'
- print 'file is excpected to be at: ' + silence_file
- logger.critical('file is excpected to be at: %s', silence_file)
+ print 'File is expected to be at: ' + silence_file
+ logger.critical('File is expected to be at: %s', silence_file)
sys.exit()
elif int(playlist['subtype']) == 6:
"""
This is a live-cast session
- create a silence list. (could eg also be a falback list..)
+ Create a silence list. (could eg also be a fallback list..)
"""
logger.debug("found %s seconds of live-cast session at %s", pkey, playlist['duration'])
@@ -330,8 +335,8 @@ class Playout:
else:
print 'Could not find silence file!'
- print 'file is excpected to be at: ' + silence_file
- logger.critical('file is excpected to be at: %s', silence_file)
+ print 'File is expected to be at: ' + silence_file
+ logger.critical('File is expected to be at: %s', silence_file)
sys.exit()
@@ -361,18 +366,16 @@ class Playout:
else:
logger.debug("try to download %s", src)
- try:
- print '** urllib auth with: ',
- print self.api_auth
- urllib.urlretrieve (src, dst, False, self.api_auth)
- logger.info("downloaded %s to %s", src, dst)
- except Exception, e:
- logger.error("%s", e)
+ api_client.get_media(src, dst)
+ #try:
+ # print '** urllib auth with: ',
+ # print self.api_auth
+ # urllib.urlretrieve (src, dst, False, self.api_auth)
+ # logger.info("downloaded %s to %s", src, dst)
+ #except Exception, e:
+ # logger.error("%s", e)
elif src[0:4] == 'http' and do_cue == True:
-
-
-
if os.path.isfile(dst):
logger.debug("file already in cache: %s", dst)
print 'cached'
@@ -384,15 +387,15 @@ class Playout:
dst_tmp = self.tmp_dir + "".join([random.choice(string.letters) for i in xrange(10)]) + '.mp3'
print dst_tmp
print '***'
-
- try:
- print '** urllib auth with: ',
- print self.api_auth
- urllib.urlretrieve (src, dst_tmp, False, self.api_auth)
- logger.info("downloaded %s to %s", src, dst_tmp)
- except Exception, e:
- logger.error("%s", e)
-
+ api_client.get_media(src, dst_tmp)
+ #try:
+ # print '** urllib auth with: ',
+ # print self.api_auth
+ # urllib.urlretrieve (src, dst_tmp, False, self.api_auth)
+ # logger.info("downloaded %s to %s", src, dst_tmp)
+ #except Exception, e:
+ # logger.error("%s", e)
+ #
# cue
print "STARTIONG CUE"
@@ -447,9 +450,6 @@ class Playout:
except Exception, e:
logger.error("%s", e)
-
-
-
if do_cue == True:
if os.path.isfile(dst):
@@ -494,9 +494,6 @@ class Playout:
except Exception, e:
logger.error("%s", e)
-
-
-
if True == os.access(dst, os.R_OK):
# check filesize (avoid zero-byte files)
#print 'waiting: ' + dst
@@ -513,7 +510,6 @@ class Playout:
print pl_entry
-
"""
Tracks are only added to the playlist if they are accessible
on the file system and larger than 0 bytes.
@@ -523,7 +519,6 @@ class Playout:
ls_playlist += pl_entry + "\n"
logger.debug("everything ok, adding %s to playlist", pl_entry)
-
else:
print 'zero-file: ' + dst + ' from ' + src
logger.warning("zero-size file - skiping %s. will not add it to playlist", dst)
@@ -531,8 +526,6 @@ class Playout:
else:
logger.warning("something went wrong. file %s not available. will not add it to playlist", dst)
-
-
except Exception, e: logger.info("%s", e)
diff --git a/3rd_party/pypo/pypo_notify.py b/3rd_party/pypo/pypo_notify.py
index a50f622a9..402b55453 100755
--- a/3rd_party/pypo/pypo_notify.py
+++ b/3rd_party/pypo/pypo_notify.py
@@ -38,7 +38,7 @@ from configobj import ConfigObj
# custom imports
from util import *
-from obp import *
+from api_clients import *
from dls import *
PYPO_VERSION = '0.9'
diff --git a/api/get_media.php b/api/get_media.php
index 824d7b453..27011d026 100644
--- a/api/get_media.php
+++ b/api/get_media.php
@@ -1,6 +1,7 @@
setFetchMode(DB_FETCHMODE_ASSOC);
-$file_id = $_GET[""]
-if(!is_file($src))
-{
- header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
- //print 'Ressource in database, but not in storage. Sorry.';
- exit;
+$file_id = $_GET["file_id"];
+if (ctype_alnum($file_id) && strlen($file_id) == 32) {
+ $media = StoredFile::RecallByGunid($file_id);
+ if ($media != null && !PEAR::isError($media)) {
+ //var_dump($media);
+ $filepath = $media->getRealFileName();
+ if(!is_file($filepath))
+ {
+ header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
+ //print 'Ressource in database, but not in storage. Sorry.';
+ exit;
+ }
+
+ // !! binary mode !!
+ $fp = fopen($filepath, 'rb');
+
+ header("Content-Type: audio/mpeg");
+ header("Content-Length: " . filesize($filepath));
+
+ fpassthru($fp);
+ }
+ else {
+ header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
+ exit;
+ }
+} else {
+ header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
+ exit;
}
-
-// !! binary mode !!
-$fp = fopen($src, 'rb');
-
-header("Content-Type: audio/mpeg");
-header("Content-Length: " . filesize($src));
-
-fpassthru($fp);
exit;
+
?>
\ No newline at end of file
diff --git a/backend/Backup.php b/backend/Backup.php
index 189ee6cff..211faa362 100755
--- a/backend/Backup.php
+++ b/backend/Backup.php
@@ -288,42 +288,42 @@ class Backup
*/
private function setFilenames()
{
- if ($this->loglevel=='debug') {
- $this->addLogItem("-I- ".date("Ymd-H:i:s")." setFilenames\n");
- }
- if (is_array($this->ids)) {
- foreach ($this->ids as $i => $item) {
- $gunid = $item['gunid'];
- // get a stored file object of this gunid
- $sf = StoredFile::RecallByGunid($gunid);
- if (is_null($sf) || PEAR::isError($sf)) {
- return $sf;
- }
- $lid = BasicStor::IdFromGunid($gunid);
- if (($res = BasicStor::Authorize('read', $lid, $this->sessid)) !== TRUE) {
- $this->addLogItem("-E- ".date("Ymd-H:i:s")." setFilenames - authorize gunid:$gunid\n");
- return PEAR::raiseError('Backup::setFilenames : Authorize ... error.');
- }
- // if the file is a playlist then it has only a meta file
- if (strtolower($sf->md->format) != 'playlist') {
- $this->filenames[] = array(
- 'filename' => $sf->getRealFileName(),
- 'format' => $sf->md->format
- );
- }
- $this->filenames[] = array(
- 'filename' => $sf->getRealMetadataFileName(),
- 'format' => $sf->md->format
- );
- if ($this->loglevel=='debug') {
- $this->addLogItem("-I- ".date("Ymd-H:i:s")." setFilenames - add file: {$sf->md->format}|".$sf->getRealMetadataFileName()."\n");
- }
- }
- return $this->filenames;
- } else {
- $this->addLogItem("-E- ".date("Ymd-H:i:s")." setFilenames - The IDs variable isn't array.\n");
- return PEAR::raiseError('Backup::setFilenames : The IDs variable isn\'t array.');
- }
+// if ($this->loglevel=='debug') {
+// $this->addLogItem("-I- ".date("Ymd-H:i:s")." setFilenames\n");
+// }
+// if (is_array($this->ids)) {
+// foreach ($this->ids as $i => $item) {
+// $gunid = $item['gunid'];
+// // get a stored file object of this gunid
+// $sf = StoredFile::RecallByGunid($gunid);
+// if (is_null($sf) || PEAR::isError($sf)) {
+// return $sf;
+// }
+// $lid = BasicStor::IdFromGunid($gunid);
+// if (($res = BasicStor::Authorize('read', $lid, $this->sessid)) !== TRUE) {
+// $this->addLogItem("-E- ".date("Ymd-H:i:s")." setFilenames - authorize gunid:$gunid\n");
+// return PEAR::raiseError('Backup::setFilenames : Authorize ... error.');
+// }
+// // if the file is a playlist then it has only a meta file
+// if (strtolower($sf->md->format) != 'playlist') {
+// $this->filenames[] = array(
+// 'filename' => $sf->getRealFileName(),
+// 'format' => $sf->md->format
+// );
+// }
+// $this->filenames[] = array(
+// 'filename' => $sf->getRealMetadataFileName(),
+// 'format' => $sf->md->format
+// );
+// if ($this->loglevel=='debug') {
+// $this->addLogItem("-I- ".date("Ymd-H:i:s")." setFilenames - add file: {$sf->md->format}|".$sf->getRealMetadataFileName()."\n");
+// }
+// }
+// return $this->filenames;
+// } else {
+// $this->addLogItem("-E- ".date("Ymd-H:i:s")." setFilenames - The IDs variable isn't array.\n");
+// return PEAR::raiseError('Backup::setFilenames : The IDs variable isn\'t array.');
+// }
}
diff --git a/backend/BasicStor.php b/backend/BasicStor.php
index ef9ffd6c6..22cd01bbf 100644
--- a/backend/BasicStor.php
+++ b/backend/BasicStor.php
@@ -59,51 +59,51 @@ require_once(dirname(__FILE__)."/StoredFile.php");
require_once(dirname(__FILE__)."/Transport.php");
require_once(dirname(__FILE__)."/Playlist.php");
-$g_metadata_xml_to_db_mapping = array(
- "dc:format" => "format",
- "ls:bitrate" => "bit_rate",
- "ls:samplerate" => "sample_rate",
- "dcterms:extent" => "length",
- "dc:title" => "track_title",
- "dc:description" => "comments",
- "dc:type" => "genre",
- "dc:creator" => "artist_name",
- "dc:source" => "album_title",
- "ls:channels" => "channels",
- "ls:filename" => "name",
- "ls:year" => "year",
- "ls:url" => "url",
- "ls:track_num" => "track_number",
- "ls:mood" => "mood",
- "ls:bpm" => "bpm",
- "ls:disc_num" => "disc_number",
- "ls:rating" => "rating",
- "ls:encoded_by" => "encoded_by",
- "dc:publisher" => "label",
- "ls:composer" => "composer",
- "ls:encoder" => "encoder",
- "ls:crc" => "checksum",
- "ls:lyrics" => "lyrics",
- "ls:orchestra" => "orchestra",
- "ls:conductor" => "conductor",
- "ls:lyricist" => "lyricist",
- "ls:originallyricist" => "original_lyricist",
- "ls:radiostationname" => "radio_station_name",
- "ls:audiofileinfourl" => "info_url",
- "ls:artisturl" => "artist_url",
- "ls:audiosourceurl" => "audio_source_url",
- "ls:radiostationurl" => "radio_station_url",
- "ls:buycdurl" => "buy_this_url",
- "ls:isrcnumber" => "isrc_number",
- "ls:catalognumber" => "catalog_number",
- "ls:originalartist" => "original_artist",
- "dc:rights" => "copyright",
- "dcterms:temporal" => "report_datetime",
- "dcterms:spatial" => "report_location",
- "dcterms:entity" => "report_organization",
- "dc:subject" => "subject",
- "dc:contributor" => "contributor",
- "dc:language" => "language");
+//$g_metadata_xml_to_db_mapping = array(
+// "dc:format" => "format",
+// "ls:bitrate" => "bit_rate",
+// "ls:samplerate" => "sample_rate",
+// "dcterms:extent" => "length",
+// "dc:title" => "track_title",
+// "dc:description" => "comments",
+// "dc:type" => "genre",
+// "dc:creator" => "artist_name",
+// "dc:source" => "album_title",
+// "ls:channels" => "channels",
+// "ls:filename" => "name",
+// "ls:year" => "year",
+// "ls:url" => "url",
+// "ls:track_num" => "track_number",
+// "ls:mood" => "mood",
+// "ls:bpm" => "bpm",
+// "ls:disc_num" => "disc_number",
+// "ls:rating" => "rating",
+// "ls:encoded_by" => "encoded_by",
+// "dc:publisher" => "label",
+// "ls:composer" => "composer",
+// "ls:encoder" => "encoder",
+// "ls:crc" => "checksum",
+// "ls:lyrics" => "lyrics",
+// "ls:orchestra" => "orchestra",
+// "ls:conductor" => "conductor",
+// "ls:lyricist" => "lyricist",
+// "ls:originallyricist" => "original_lyricist",
+// "ls:radiostationname" => "radio_station_name",
+// "ls:audiofileinfourl" => "info_url",
+// "ls:artisturl" => "artist_url",
+// "ls:audiosourceurl" => "audio_source_url",
+// "ls:radiostationurl" => "radio_station_url",
+// "ls:buycdurl" => "buy_this_url",
+// "ls:isrcnumber" => "isrc_number",
+// "ls:catalognumber" => "catalog_number",
+// "ls:originalartist" => "original_artist",
+// "dc:rights" => "copyright",
+// "dcterms:temporal" => "report_datetime",
+// "dcterms:spatial" => "report_location",
+// "dcterms:entity" => "report_organization",
+// "dc:subject" => "subject",
+// "dc:contributor" => "contributor",
+// "dc:language" => "language");
/**
* Core of Campcaster file storage module
@@ -139,11 +139,11 @@ class BasicStor {
* @return StoredFile|PEAR_Error
* The StoredFile that was created.
*/
- public function bsPutFile($p_values, $p_copyMedia=TRUE)
- {
- $storedFile = StoredFile::Insert($p_values, $p_copyMedia);
- return $storedFile;
- } // fn bsPutFile
+// public function bsPutFile($p_values, $p_copyMedia=TRUE)
+// {
+// $storedFile = StoredFile::Insert($p_values, $p_copyMedia);
+// return $storedFile;
+// }
/**
@@ -154,28 +154,28 @@ class BasicStor {
* @param string $newName
* @return boolean|PEAR_Error
*/
- public function bsRenameFile($id, $newName)
- {
- switch (BasicStor::GetObjType($id)) {
- case "audioclip":
- case "playlist":
- case "webstream":
- $storedFile = StoredFile::Recall($id);
- if (is_null($storedFile) || PEAR::isError($storedFile)) {
- // catch nonerror exception:
- //if($storedFile->getCode() != GBERR_FOBJNEX)
- return $storedFile;
- }
- $res = $storedFile->setName($newName);
- if (PEAR::isError($res)) {
- return $res;
- }
- break;
- case "File":
- default:
- }
- return TRUE;
- }
+// public function bsRenameFile($id, $newName)
+// {
+// switch (BasicStor::GetObjType($id)) {
+// case "audioclip":
+// case "playlist":
+// case "webstream":
+// $storedFile = StoredFile::Recall($id);
+// if (is_null($storedFile) || PEAR::isError($storedFile)) {
+// // catch nonerror exception:
+// //if($storedFile->getCode() != GBERR_FOBJNEX)
+// return $storedFile;
+// }
+// $res = $storedFile->setName($newName);
+// if (PEAR::isError($res)) {
+// return $res;
+// }
+// break;
+// case "File":
+// default:
+// }
+// return TRUE;
+// }
/**
@@ -192,27 +192,27 @@ class BasicStor {
* @return true|PEAR_Error
* @exception PEAR::error
*/
- public function bsReplaceFile($id, $localFilePath, $metadataFilePath, $mdataLoc='file')
- {
- $storedFile = StoredFile::Recall($id);
- if (is_null($storedFile) || PEAR::isError($storedFile)) {
- return $storedFile;
- }
- if (!empty($metadataFilePath) &&
- ($mdataLoc!='file' || file_exists($metadataFilePath))) {
- $r = $storedFile->setMetadata($metadataFilePath, $mdataLoc);
- if (PEAR::isError($r)) {
- return $r;
- }
- }
- if (!empty($localFilePath) && file_exists($localFilePath)) {
- $r = $storedFile->setRawMediaData($localFilePath);
- if (PEAR::isError($r)) {
- return $r;
- }
- }
- return TRUE;
- }
+// public function bsReplaceFile($id, $localFilePath, $metadataFilePath, $mdataLoc='file')
+// {
+// $storedFile = StoredFile::Recall($id);
+// if (is_null($storedFile) || PEAR::isError($storedFile)) {
+// return $storedFile;
+// }
+// if (!empty($metadataFilePath) &&
+// ($mdataLoc!='file' || file_exists($metadataFilePath))) {
+// $r = $storedFile->setMetadata($metadataFilePath, $mdataLoc);
+// if (PEAR::isError($r)) {
+// return $r;
+// }
+// }
+// if (!empty($localFilePath) && file_exists($localFilePath)) {
+// $r = $storedFile->setRawMediaData($localFilePath);
+// if (PEAR::isError($r)) {
+// return $r;
+// }
+// }
+// return TRUE;
+// }
/**
@@ -224,64 +224,64 @@ class BasicStor {
* If true don't use trash
* @return true|PEAR_Error
*/
- public function bsDeleteFile($id, $forced=FALSE)
- {
- global $CC_CONFIG;
- // full delete:
- if (!$CC_CONFIG['useTrash'] || $forced) {
- $res = BasicStor::RemoveObj($id, $forced);
- return $res;
- }
-
- $storedFile = StoredFile::Recall($id);
-
- if (is_null($storedFile) || PEAR::isError($storedFile)) {
- return $storedFile;
- }
- if ($storedFile->isAccessed()) {
- return PEAR::raiseError(
- 'Cannot delete an object that is currently accessed.'
- );
- }
- // move to trash:
- switch (BasicStor::GetObjType($id)) {
-
- case "audioclip":
- $playLists = $storedFile->getPlaylists();
- $item_gunid = $storedFile->getGunid();
- if( $playLists != NULL) {
-
- foreach($playLists as $key=>$val) {
- $playList_id = BasicStor::IdFromGunidBigInt($val["gunid"]);
- $playList_titles[] = BasicStor::bsGetMetadataValue($playList_id, "dc:title");
- }
- return PEAR::raiseError(
- 'Please remove this song from all playlists: ' . join(",", $playList_titles)
- );
- }
- break;
-
- case "playlist":
- if($storedFile->isScheduled()) {
- return PEAR::raiseError(
- 'Cannot delete an object that is scheduled to play.'
- );
- }
- break;
-
- case "webstream":
-
- break;
- default:
- }
-
- $res = $storedFile->setState('deleted');
- if (PEAR::isError($res)) {
- return $res;
- }
-
- return TRUE;
- }
+// public function bsDeleteFile($id, $forced=FALSE)
+// {
+// global $CC_CONFIG;
+// // full delete:
+// if (!$CC_CONFIG['useTrash'] || $forced) {
+// $res = BasicStor::RemoveObj($id, $forced);
+// return $res;
+// }
+//
+// $storedFile = StoredFile::Recall($id);
+//
+// if (is_null($storedFile) || PEAR::isError($storedFile)) {
+// return $storedFile;
+// }
+// if ($storedFile->isAccessed()) {
+// return PEAR::raiseError(
+// 'Cannot delete an object that is currently accessed.'
+// );
+// }
+// // move to trash:
+// switch (BasicStor::GetObjType($id)) {
+//
+// case "audioclip":
+// $playLists = $storedFile->getPlaylists();
+// $item_gunid = $storedFile->getGunid();
+// if( $playLists != NULL) {
+//
+// foreach($playLists as $key=>$val) {
+// $playList_id = BasicStor::IdFromGunidBigInt($val["gunid"]);
+// $playList_titles[] = BasicStor::bsGetMetadataValue($playList_id, "dc:title");
+// }
+// return PEAR::raiseError(
+// 'Please remove this song from all playlists: ' . join(",", $playList_titles)
+// );
+// }
+// break;
+//
+// case "playlist":
+// if($storedFile->isScheduled()) {
+// return PEAR::raiseError(
+// 'Cannot delete an object that is scheduled to play.'
+// );
+// }
+// break;
+//
+// case "webstream":
+//
+// break;
+// default:
+// }
+//
+// $res = $storedFile->setState('deleted');
+// if (PEAR::isError($res)) {
+// return $res;
+// }
+//
+// return TRUE;
+// }
/* ----------------------------------------------------- put, access etc. */
@@ -472,42 +472,42 @@ class BasicStor {
* array with strings:
* downloadable URL, download token, chsum, size, filename
*/
- public function bsOpenDownload($id, $part='media')
- {
- $storedFile = StoredFile::Recall($id);
- if (is_null($storedFile) || PEAR::isError($storedFile)) {
- return $storedFile;
- }
- $gunid = $storedFile->gunid;
- switch ($part) {
- case "media":
- $realfile = $storedFile->getRealFileName();
- $ext = $storedFile->getFileExtension();
- $filename = $storedFile->getName();
- break;
- case "metadata":
- $realfile = $storedFile->getRealMetadataFileName();
- $ext = "xml";
- $filename = $storedFile->getName();
- break;
- default:
- return PEAR::raiseError(
- "BasicStor::bsOpenDownload: unknown part ($part)"
- );
- }
- $acc = BasicStor::bsAccess($realfile, $ext, $gunid, 'download');
- if (PEAR::isError($acc)) {
- return $acc;
- }
- $url = BasicStor::GetUrlPart()."access/".basename($acc['fname']);
- $chsum = md5_file($realfile);
- $size = filesize($realfile);
- return array(
- 'url'=>$url, 'token'=>$acc['token'],
- 'chsum'=>$chsum, 'size'=>$size,
- 'filename'=>$filename
- );
- }
+// public function bsOpenDownload($id, $part='media')
+// {
+// $storedFile = StoredFile::Recall($id);
+// if (is_null($storedFile) || PEAR::isError($storedFile)) {
+// return $storedFile;
+// }
+// $gunid = $storedFile->gunid;
+// switch ($part) {
+// case "media":
+// $realfile = $storedFile->getRealFileName();
+// $ext = $storedFile->getFileExtension();
+// $filename = $storedFile->getName();
+// break;
+// case "metadata":
+// $realfile = $storedFile->getRealMetadataFileName();
+// $ext = "xml";
+// $filename = $storedFile->getName();
+// break;
+// default:
+// return PEAR::raiseError(
+// "BasicStor::bsOpenDownload: unknown part ($part)"
+// );
+// }
+// $acc = BasicStor::bsAccess($realfile, $ext, $gunid, 'download');
+// if (PEAR::isError($acc)) {
+// return $acc;
+// }
+// $url = BasicStor::GetUrlPart()."access/".basename($acc['fname']);
+// $chsum = md5_file($realfile);
+// $size = filesize($realfile);
+// return array(
+// 'url'=>$url, 'token'=>$acc['token'],
+// 'chsum'=>$chsum, 'size'=>$size,
+// 'filename'=>$filename
+// );
+// }
/**
@@ -520,19 +520,19 @@ class BasicStor {
* @return string
* gunid
*/
- public function bsCloseDownload($token, $part='media')
- {
- if (!BasicStor::bsCheckToken($token, 'download')) {
- return PEAR::raiseError(
- "BasicStor::bsCloseDownload: invalid token ($token)"
- );
- }
- $r = BasicStor::bsRelease($token, 'download');
- if (PEAR::isError($r)){
- return $r;
- }
- return (is_null($r['gunid']) ? $r['realFname'] : $r['gunid']);
- }
+// public function bsCloseDownload($token, $part='media')
+// {
+// if (!BasicStor::bsCheckToken($token, 'download')) {
+// return PEAR::raiseError(
+// "BasicStor::bsCloseDownload: invalid token ($token)"
+// );
+// }
+// $r = BasicStor::bsRelease($token, 'download');
+// if (PEAR::isError($r)){
+// return $r;
+// }
+// return (is_null($r['gunid']) ? $r['realFname'] : $r['gunid']);
+// }
/**
@@ -551,35 +551,35 @@ class BasicStor {
* fname string: writable local filename
* token string: PUT token
*/
- public function bsOpenPut($chsum, $gunid, $owner=NULL)
- {
- global $CC_CONFIG, $CC_DBC;
- if (!is_null($gunid)) {
- $gunid = StoredFile::NormalizeGunid($gunid);
- }
- $escapedChsum = pg_escape_string($chsum);
- $token = StoredFile::CreateGunid();
- $res = $CC_DBC->query("DELETE FROM ".$CC_CONFIG['accessTable']
- ." WHERE token=x'$token'::bigint");
- if (PEAR::isError($res)) {
- return $res;
- }
- $gunidSql = (is_null($gunid) ? "NULL" : "x'{$gunid}'::bigint" );
- $ownerSql = (is_null($owner) ? "NULL" : "$owner" );
- $res = $CC_DBC->query("
- INSERT INTO ".$CC_CONFIG['accessTable']."
- (gunid, token, ext, chsum, type, owner, ts)
- VALUES
- ($gunidSql, x'$token'::bigint,
- '', '$escapedChsum', 'put', $ownerSql, now())");
- if (PEAR::isError($res)) {
- return $res;
- }
- $fname = $CC_CONFIG['accessDir']."/$token";
- touch($fname); // is it needed?
- $url = BasicStor::GetUrlPart()."xmlrpc/put.php?token=$token";
- return array('url'=>$url, 'fname'=>$fname, 'token'=>$token);
- }
+// public function bsOpenPut($chsum, $gunid, $owner=NULL)
+// {
+// global $CC_CONFIG, $CC_DBC;
+// if (!is_null($gunid)) {
+// $gunid = StoredFile::NormalizeGunid($gunid);
+// }
+// $escapedChsum = pg_escape_string($chsum);
+// $token = StoredFile::CreateGunid();
+// $res = $CC_DBC->query("DELETE FROM ".$CC_CONFIG['accessTable']
+// ." WHERE token=x'$token'::bigint");
+// if (PEAR::isError($res)) {
+// return $res;
+// }
+// $gunidSql = (is_null($gunid) ? "NULL" : "x'{$gunid}'::bigint" );
+// $ownerSql = (is_null($owner) ? "NULL" : "$owner" );
+// $res = $CC_DBC->query("
+// INSERT INTO ".$CC_CONFIG['accessTable']."
+// (gunid, token, ext, chsum, type, owner, ts)
+// VALUES
+// ($gunidSql, x'$token'::bigint,
+// '', '$escapedChsum', 'put', $ownerSql, now())");
+// if (PEAR::isError($res)) {
+// return $res;
+// }
+// $fname = $CC_CONFIG['accessDir']."/$token";
+// touch($fname); // is it needed?
+// $url = BasicStor::GetUrlPart()."xmlrpc/put.php?token=$token";
+// return array('url'=>$url, 'fname'=>$fname, 'token'=>$token);
+// }
/**
@@ -593,58 +593,58 @@ class BasicStor {
* fname string, local path of the file having been put
* owner int, local subject id - owner of token
*/
- public function bsClosePut($token)
- {
- global $CC_CONFIG, $CC_DBC;
- $token = StoredFile::NormalizeGunid($token);
-
- if (!BasicStor::bsCheckToken($token, 'put')) {
- return PEAR::raiseError(
- "BasicStor::bsClosePut: invalid token ($token)",
- GBERR_TOKEN);
- }
- $row = $CC_DBC->getRow(
- "SELECT chsum, owner FROM ".$CC_CONFIG['accessTable']
- ." WHERE token=x'{$token}'::bigint");
- if (PEAR::isError($row)) {
- return $row;
- }
- $fname = $CC_CONFIG['accessDir']."/$token";
- $md5sum = md5_file($fname);
-
- $chsum = $row['chsum'];
- $owner = $row['owner'];
- $error = null;
- if ( (trim($chsum) != '') && ($chsum != $md5sum) ) {
- // Delete the file if the checksums do not match.
- if (file_exists($fname)) {
- @unlink($fname);
- }
- $error = new PEAR_Error(
- "BasicStor::bsClosePut: md5sum does not match (token=$token)".
- " [$chsum/$md5sum]",
- GBERR_PUT);
- } else {
- // Remember the MD5 sum
- $storedFile = StoredFile::RecallByToken($token);
- if (!is_null($storedFile) && !PEAR::isError($storedFile)) {
- $storedFile->setMd5($md5sum);
- } else {
-# $error = $storedFile;
- }
- }
-
- // Delete entry from access table.
- $res = $CC_DBC->query("DELETE FROM ".$CC_CONFIG['accessTable']
- ." WHERE token=x'$token'::bigint");
- if (PEAR::isError($error)) {
- return $error;
- } elseif (PEAR::isError($res)) {
- return $res;
- }
-
- return array('fname'=>$fname, 'owner'=>$owner);
- }
+// public function bsClosePut($token)
+// {
+// global $CC_CONFIG, $CC_DBC;
+// $token = StoredFile::NormalizeGunid($token);
+//
+// if (!BasicStor::bsCheckToken($token, 'put')) {
+// return PEAR::raiseError(
+// "BasicStor::bsClosePut: invalid token ($token)",
+// GBERR_TOKEN);
+// }
+// $row = $CC_DBC->getRow(
+// "SELECT chsum, owner FROM ".$CC_CONFIG['accessTable']
+// ." WHERE token=x'{$token}'::bigint");
+// if (PEAR::isError($row)) {
+// return $row;
+// }
+// $fname = $CC_CONFIG['accessDir']."/$token";
+// $md5sum = md5_file($fname);
+//
+// $chsum = $row['chsum'];
+// $owner = $row['owner'];
+// $error = null;
+// if ( (trim($chsum) != '') && ($chsum != $md5sum) ) {
+// // Delete the file if the checksums do not match.
+// if (file_exists($fname)) {
+// @unlink($fname);
+// }
+// $error = new PEAR_Error(
+// "BasicStor::bsClosePut: md5sum does not match (token=$token)".
+// " [$chsum/$md5sum]",
+// GBERR_PUT);
+// } else {
+// // Remember the MD5 sum
+// $storedFile = StoredFile::RecallByToken($token);
+// if (!is_null($storedFile) && !PEAR::isError($storedFile)) {
+// $storedFile->setMd5($md5sum);
+// } else {
+//# $error = $storedFile;
+// }
+// }
+//
+// // Delete entry from access table.
+// $res = $CC_DBC->query("DELETE FROM ".$CC_CONFIG['accessTable']
+// ." WHERE token=x'$token'::bigint");
+// if (PEAR::isError($error)) {
+// return $error;
+// } elseif (PEAR::isError($res)) {
+// return $res;
+// }
+//
+// return array('fname'=>$fname, 'owner'=>$owner);
+// }
/**
@@ -660,31 +660,31 @@ class BasicStor {
* realsum: string - checksum of uploaded file
* )
*/
- public function bsCheckPut($token)
- {
- global $CC_CONFIG, $CC_DBC;
- if (!BasicStor::bsCheckToken($token, 'put')) {
- return PEAR::raiseError(
- "BasicStor::bsCheckPut: invalid token ($token)"
- );
- }
- $chsum = $CC_DBC->getOne("
- SELECT chsum FROM ".$CC_CONFIG['accessTable']."
- WHERE token=x'{$token}'::bigint
- ");
- if (PEAR::isError($chsum)) {
- return $chsum;
- }
- $fname = $CC_CONFIG['accessDir']."/$token";
- $md5sum = md5_file($fname);
- $size = filesize($fname);
- $status = ($chsum == $md5sum);
- return array(
- 'status'=>$status, 'size'=>$size,
- 'expectedsum'=>$chsum,
- 'realsum'=>$md5sum,
- );
- }
+// public function bsCheckPut($token)
+// {
+// global $CC_CONFIG, $CC_DBC;
+// if (!BasicStor::bsCheckToken($token, 'put')) {
+// return PEAR::raiseError(
+// "BasicStor::bsCheckPut: invalid token ($token)"
+// );
+// }
+// $chsum = $CC_DBC->getOne("
+// SELECT chsum FROM ".$CC_CONFIG['accessTable']."
+// WHERE token=x'{$token}'::bigint
+// ");
+// if (PEAR::isError($chsum)) {
+// return $chsum;
+// }
+// $fname = $CC_CONFIG['accessDir']."/$token";
+// $md5sum = md5_file($fname);
+// $size = filesize($fname);
+// $status = ($chsum == $md5sum);
+// return array(
+// 'status'=>$status, 'size'=>$size,
+// 'expectedsum'=>$chsum,
+// 'realsum'=>$md5sum,
+// );
+// }
/**
@@ -693,14 +693,14 @@ class BasicStor {
* @return string
* URL
*/
- public static function GetUrlPart()
- {
- global $CC_CONFIG;
- $host = $CC_CONFIG['storageUrlHost'];
- $port = $CC_CONFIG['storageUrlPort'];
- $path = $CC_CONFIG['storageUrlPath'];
- return "http://$host:$port$path/";
- }
+// public static function GetUrlPart()
+// {
+// global $CC_CONFIG;
+// $host = $CC_CONFIG['storageUrlHost'];
+// $port = $CC_CONFIG['storageUrlPort'];
+// $path = $CC_CONFIG['storageUrlPath'];
+// return "http://$host:$port$path/";
+// }
/**
@@ -711,17 +711,17 @@ class BasicStor {
* @return array
* array of tokens
*/
- public static function GetTokensByType($type)
- {
- global $CC_CONFIG, $CC_DBC;
- $res = $CC_DBC->query(
- "SELECT TO_HEX(token) AS token FROM ".$CC_CONFIG['accessTable']." WHERE type=?",
- array($type));
- while ($row = $res->fetchRow()) {
- $r[] = $row['token'];
- }
- return $r;
- }
+// public static function GetTokensByType($type)
+// {
+// global $CC_CONFIG, $CC_DBC;
+// $res = $CC_DBC->query(
+// "SELECT TO_HEX(token) AS token FROM ".$CC_CONFIG['accessTable']." WHERE type=?",
+// array($type));
+// while ($row = $res->fetchRow()) {
+// $r[] = $row['token'];
+// }
+// return $r;
+// }
/* ----------------------------------------------------- metadata methods */
@@ -737,14 +737,14 @@ class BasicStor {
* 'file'|'string'
* @return boolean|PEAR_Error
*/
- public function bsReplaceMetadata($id, $mdata, $mdataLoc='file')
- {
- $storedFile = StoredFile::Recall($id);
- if (is_null($storedFile) || PEAR::isError($storedFile)) {
- return $storedFile;
- }
- return $storedFile->setMetadata($mdata, $mdataLoc);
- }
+// public function bsReplaceMetadata($id, $mdata, $mdataLoc='file')
+// {
+// $storedFile = StoredFile::Recall($id);
+// if (is_null($storedFile) || PEAR::isError($storedFile)) {
+// return $storedFile;
+// }
+// return $storedFile->setMetadata($mdata, $mdataLoc);
+// }
/**
@@ -754,14 +754,14 @@ class BasicStor {
* Virtual file's local id
* @return string|PEAR_Error
*/
- public function bsGetMetadata($id)
- {
- $storedFile = StoredFile::Recall($id);
- if (is_null($storedFile) || PEAR::isError($storedFile)) {
- return $storedFile;
- }
- return $storedFile->getMetadata();
- }
+// public function bsGetMetadata($id)
+// {
+// $storedFile = StoredFile::Recall($id);
+// if (is_null($storedFile) || PEAR::isError($storedFile)) {
+// return $storedFile;
+// }
+// return $storedFile->getMetadata();
+// }
/**
@@ -774,20 +774,20 @@ class BasicStor {
* null, id is then ignored
* @return string|PEAR_Error
*/
- public function bsGetTitle($id, $gunid=NULL)
- {
- if (is_null($gunid)) {
- $storedFile = StoredFile::Recall($id);
- } else {
- $storedFile = StoredFile::RecallByGunid($gunid);
- }
- if (is_null($storedFile) || PEAR::isError($storedFile)) {
- return $storedFile;
- }
- $r = $storedFile->md["title"];
- $title = (empty($r) ? 'unknown' : $r);
- return $title;
- }
+// public function bsGetTitle($id, $gunid=NULL)
+// {
+// if (is_null($gunid)) {
+// $storedFile = StoredFile::Recall($id);
+// } else {
+// $storedFile = StoredFile::RecallByGunid($gunid);
+// }
+// if (is_null($storedFile) || PEAR::isError($storedFile)) {
+// return $storedFile;
+// }
+// $r = $storedFile->md["title"];
+// $title = (empty($r) ? 'unknown' : $r);
+// return $title;
+// }
/**
@@ -804,27 +804,27 @@ class BasicStor {
* if an array is passed, an array is returned.
* @see Metadata::getMetadataValue
*/
- public function bsGetMetadataValue($id, $category = null)
- {
- if (!is_numeric($id)) {
- return null;
- }
- $storedFile = StoredFile::Recall($id);
- if (is_null($storedFile) || PEAR::isError($storedFile)) {
- return $storedFile;
- }
- if (is_null($category)) {
- return $storedFile->md;
- } elseif (is_array($category)) {
- $values = array();
- foreach ($category as $tmpCat) {
- $values[$tmpCat] = $storedFile->md[$tmpCat];
- }
- return $values;
- } else {
- return $storedFile->md[$category];
- }
- }
+// public function bsGetMetadataValue($id, $category = null)
+// {
+// if (!is_numeric($id)) {
+// return null;
+// }
+// $storedFile = StoredFile::Recall($id);
+// if (is_null($storedFile) || PEAR::isError($storedFile)) {
+// return $storedFile;
+// }
+// if (is_null($category)) {
+// return $storedFile->md;
+// } elseif (is_array($category)) {
+// $values = array();
+// foreach ($category as $tmpCat) {
+// $values[$tmpCat] = $storedFile->md[$tmpCat];
+// }
+// return $values;
+// } else {
+// return $storedFile->md[$category];
+// }
+// }
/**
@@ -834,14 +834,14 @@ class BasicStor {
* @param string $p_category
* @return string|null
*/
- public static function xmlCategoryToDbColumn($p_category)
- {
- global $g_metadata_xml_to_db_mapping;
- if (array_key_exists($p_category, $g_metadata_xml_to_db_mapping)) {
- return $g_metadata_xml_to_db_mapping[$p_category];
- }
- return null;
- }
+// public static function xmlCategoryToDbColumn($p_category)
+// {
+// global $g_metadata_xml_to_db_mapping;
+// if (array_key_exists($p_category, $g_metadata_xml_to_db_mapping)) {
+// return $g_metadata_xml_to_db_mapping[$p_category];
+// }
+// return null;
+// }
/**
@@ -850,16 +850,16 @@ class BasicStor {
* @param string $p_dbColumn
* @return string|null
*/
- public static function dbColumnToXmlCatagory($p_dbColumn)
- {
- global $g_metadata_xml_to_db_mapping;
- $str = array_search($p_dbColumn, $g_metadata_xml_to_db_mapping);
- // make return value consistent with xmlCategoryToDbColumn()
- if ($str === FALSE) {
- $str = null;
- }
- return $str;
- }
+// public static function dbColumnToXmlCatagory($p_dbColumn)
+// {
+// global $g_metadata_xml_to_db_mapping;
+// $str = array_search($p_dbColumn, $g_metadata_xml_to_db_mapping);
+// // make return value consistent with xmlCategoryToDbColumn()
+// if ($str === FALSE) {
+// $str = null;
+// }
+// return $str;
+// }
/**
* Set metadata element value
@@ -872,33 +872,33 @@ class BasicStor {
* value to store, if NULL then delete record
* @return boolean
*/
- public static function bsSetMetadataValue($p_id, $p_category, $p_value)
- {
- global $CC_CONFIG, $CC_DBC;
- if (!is_string($p_category) || is_array($p_value)) {
- return FALSE;
- }
- if (is_a($p_id, "StoredFile")) {
- $p_id = $p_id->getId();
- }
- if ($p_category == 'dcterms:extent') {
- $p_value = BasicStor::NormalizeExtent($p_value);
- }
- $columnName = BasicStor::xmlCategoryToDbColumn($p_category); // Get column name
-
- if (!is_null($columnName)) {
- $escapedValue = pg_escape_string($p_value);
- $sql = "UPDATE ".$CC_CONFIG["filesTable"]
- ." SET $columnName='$escapedValue'"
- ." WHERE id=$p_id";
- //var_dump($sql);
- $res = $CC_DBC->query($sql);
- if (PEAR::isError($res)) {
- return $res;
- }
- }
- return TRUE;
- }
+// public static function bsSetMetadataValue($p_id, $p_category, $p_value)
+// {
+// global $CC_CONFIG, $CC_DBC;
+// if (!is_string($p_category) || is_array($p_value)) {
+// return FALSE;
+// }
+// if (is_a($p_id, "StoredFile")) {
+// $p_id = $p_id->getId();
+// }
+// if ($p_category == 'dcterms:extent') {
+// $p_value = BasicStor::NormalizeExtent($p_value);
+// }
+// $columnName = BasicStor::xmlCategoryToDbColumn($p_category); // Get column name
+//
+// if (!is_null($columnName)) {
+// $escapedValue = pg_escape_string($p_value);
+// $sql = "UPDATE ".$CC_CONFIG["filesTable"]
+// ." SET $columnName='$escapedValue'"
+// ." WHERE id=$p_id";
+// //var_dump($sql);
+// $res = $CC_DBC->query($sql);
+// if (PEAR::isError($res)) {
+// return $res;
+// }
+// }
+// return TRUE;
+// }
/**
@@ -908,15 +908,15 @@ class BasicStor {
* value to normalize
* @return string
*/
- private static function NormalizeExtent($v)
- {
- if (!preg_match("|^\d{2}:\d{2}:\d{2}.\d{6}$|", $v)) {
- $s = Playlist::playlistTimeToSeconds($v);
- $t = Playlist::secondsToPlaylistTime($s);
- return $t;
- }
- return $v;
- }
+// private static function NormalizeExtent($v)
+// {
+// if (!preg_match("|^\d{2}:\d{2}:\d{2}.\d{6}$|", $v)) {
+// $s = Playlist::playlistTimeToSeconds($v);
+// $t = Playlist::secondsToPlaylistTime($s);
+// return $t;
+// }
+// return $v;
+// }
/**
@@ -929,60 +929,60 @@ class BasicStor {
* (e.g. 'dc:title'=>'New title')
* @return boolean
*/
- public static function bsSetMetadataBatch($id, $values)
- {
- global $CC_CONFIG, $CC_DBC;
- if (!is_array($values)) {
- $values = array($values);
- }
- if (count($values) == 0) {
- return true;
- }
- if (is_a($id, "StoredFile")) {
- $storedFile =& $id;
- } else {
- $storedFile = StoredFile::Recall($id);
- if (is_null($storedFile) || PEAR::isError($storedFile)) {
- return $storedFile;
- }
- }
- foreach ($values as $category => $oneValue) {
- $columnName = BasicStor::xmlCategoryToDbColumn($category);
- if (!is_null($columnName)) {
- if ($category == 'dcterms:extent') {
- $oneValue = BasicStor::NormalizeExtent($oneValue);
- }
- // Since track_number is an integer, you cannot set
- // it to be the empty string, so we NULL it instead.
- if ($columnName == 'track_number' && empty($oneValue)) {
- $sqlPart = "$columnName = NULL";
- } elseif (($columnName == 'length') && (strlen($oneValue) > 8)) {
- // Postgres doesnt like it if you try to store really large hour
- // values. TODO: We need to fix the underlying problem of getting the
- // right values.
- $parts = explode(':', $oneValue);
- $hour = intval($parts[0]);
- if ($hour > 24) {
- continue;
- } else {
- $sqlPart = "$columnName = '$oneValue'";
- }
- } else {
- $escapedValue = pg_escape_string($oneValue);
- $sqlPart = "$columnName = '$escapedValue'";
- }
- $sqlValues[] = $sqlPart;
- }
- }
- if (count($sqlValues)==0) {
- return TRUE;
- }
- $sql = "UPDATE ".$CC_CONFIG["filesTable"]
- ." SET ".join(",", $sqlValues)
- ." WHERE id=$id";
- $CC_DBC->query($sql);
- return TRUE;
- }
+// public static function bsSetMetadataBatch($id, $values)
+// {
+// global $CC_CONFIG, $CC_DBC;
+// if (!is_array($values)) {
+// $values = array($values);
+// }
+// if (count($values) == 0) {
+// return true;
+// }
+// if (is_a($id, "StoredFile")) {
+// $storedFile =& $id;
+// } else {
+// $storedFile = StoredFile::Recall($id);
+// if (is_null($storedFile) || PEAR::isError($storedFile)) {
+// return $storedFile;
+// }
+// }
+// foreach ($values as $category => $oneValue) {
+// $columnName = BasicStor::xmlCategoryToDbColumn($category);
+// if (!is_null($columnName)) {
+// if ($category == 'dcterms:extent') {
+// $oneValue = BasicStor::NormalizeExtent($oneValue);
+// }
+// // Since track_number is an integer, you cannot set
+// // it to be the empty string, so we NULL it instead.
+// if ($columnName == 'track_number' && empty($oneValue)) {
+// $sqlPart = "$columnName = NULL";
+// } elseif (($columnName == 'length') && (strlen($oneValue) > 8)) {
+// // Postgres doesnt like it if you try to store really large hour
+// // values. TODO: We need to fix the underlying problem of getting the
+// // right values.
+// $parts = explode(':', $oneValue);
+// $hour = intval($parts[0]);
+// if ($hour > 24) {
+// continue;
+// } else {
+// $sqlPart = "$columnName = '$oneValue'";
+// }
+// } else {
+// $escapedValue = pg_escape_string($oneValue);
+// $sqlPart = "$columnName = '$escapedValue'";
+// }
+// $sqlValues[] = $sqlPart;
+// }
+// }
+// if (count($sqlValues)==0) {
+// return TRUE;
+// }
+// $sql = "UPDATE ".$CC_CONFIG["filesTable"]
+// ." SET ".join(",", $sqlValues)
+// ." WHERE id=$id";
+// $CC_DBC->query($sql);
+// return TRUE;
+// }
/**
* Method returning array with where-parts of sql queries
@@ -1002,7 +1002,7 @@ class BasicStor {
$whereArr = array();
if (is_array($conditions)) {
foreach ($conditions as $cond) {
- $columnName = BasicStor::xmlCategoryToDbColumn($cond['cat']);
+ $columnName = StoredFile::xmlCategoryToDbColumn($cond['cat']);
$op = strtolower($cond['op']);
$value = $cond['val'];
if (!empty($value)) {
@@ -1141,7 +1141,7 @@ class BasicStor {
// in the array is the qualified name with ":" replaced with "_".
// e.g. "dc:creator" becomes "dc_creator".
foreach ($orderbyQns as $xmlTag) {
- $columnName = BasicStor::xmlCategoryToDbColumn($xmlTag);
+ $columnName = StoredFile::xmlCategoryToDbColumn($xmlTag);
$orderBySql[] = $columnName;
}
@@ -1269,7 +1269,7 @@ class BasicStor {
);
$category = strtolower($category);
- $columnName = BasicStor::xmlCategoryToDbColumn($category);
+ $columnName = StoredFile::xmlCategoryToDbColumn($category);
if (is_null($columnName)) {
return new PEAR_Error(__FILE__.":".__LINE__." -- could not map XML category to DB column.");
}
@@ -1363,103 +1363,103 @@ class BasicStor {
* fname string: readable fname,
* token string: access token
*/
- public function bsExportPlaylistOpen($plids, $type='lspl', $withContent=TRUE)
- {
- global $CC_CONFIG;
- if (!is_array($plids)) {
- $plids = array($plids);
- }
- $gunids = array();
- foreach ($plids as $plid) {
- $pl = StoredFile::RecallByGunid($plid);
- if (is_null($pl) || PEAR::isError($pl)) {
- return $pl;
- }
- if ($withContent) {
- $gunidsX = $pl->export();
- if (PEAR::isError($gunidsX)) {
- return $gunidsX;
- }
- } else {
- $gunidsX = array(array('gunid'=>$plid, 'type'=>'playlist'));
- }
- $gunids = array_merge($gunids, $gunidsX);
- }
- $plExts = array('lspl'=>"lspl", 'smil'=>"smil", 'm3u'=>"m3u");
- $plExt = (isset($plExts[$type]) ? $plExts[$type] : "xml" );
- $res = array();
- $tmpn = tempnam($CC_CONFIG['bufferDir'], 'plExport_');
- $tmpf = "$tmpn.tar";
- $tmpd = "$tmpn.dir";
- mkdir($tmpd);
- $tmpdp = "$tmpn.dir/playlist";
- mkdir($tmpdp);
- if ($withContent) {
- $tmpdc = "$tmpn.dir/audioClip";
- mkdir($tmpdc);
- }
- foreach ($gunids as $i => $it) {
- $storedFile = StoredFile::RecallByGunid($it['gunid']);
- if (is_null($storedFile) || PEAR::isError($storedFile)) {
- return $storedFile;
- }
-// $MDfname = $storedFile->md->getFileName();
- $MDfname = $storedFile->md["name"];
- if (PEAR::isError($MDfname)) {
- return $MDfname;
- }
- if (file_exists($MDfname)) {
- switch ($it['type']) {
- case "playlist":
- $storedFile = $r = StoredFile::RecallByGunid($it['gunid']);
- switch ($type) {
- case "smil":
- $string = $r = $storedFile->outputToSmil();
- break;
- case "m3u":
- $string = $r = $storedFile->outputToM3u();
- break;
- default:
-// $string = $r = $storedFile->md->genXmlDoc();
- }
- if (PEAR::isError($r)) {
- return $r;
- }
- $r = BasicStor::WriteStringToFile($string, "$tmpdp/{$it['gunid']}.$plExt");
- if (PEAR::isError($r)) {
- return $r;
- }
- break;
- default:
- copy($MDfname, "$tmpdc/{$it['gunid']}.xml"); break;
- } // switch
- } // if file_exists()
- $RADfname = $storedFile->getRealFileName();
- if (PEAR::isError($RADfname)) {
- return $RADfname;
- }
- $RADext = $storedFile->getFileExtension();
- if (PEAR::isError($RADext)) {
- return $RADext;
- }
- if (file_exists($RADfname)) {
- copy($RADfname, "$tmpdc/{$it['gunid']}.$RADext");
- }
- }
- if (count($plids)==1) {
- copy("$tmpdp/$plid.$plExt", "$tmpd/exportedPlaylist.$plExt");
- }
- $res = `cd $tmpd; tar cf $tmpf * --remove-files`;
- @rmdir($tmpdc);
- @rmdir($tmpdp);
- @rmdir($tmpd);
- unlink($tmpn);
- $acc = BasicStor::bsAccess($tmpf, 'tar', NULL/*gunid*/, 'access');
- if (PEAR::isError($acc)) {
- return $acc;
- }
- return $acc;
- }
+// public function bsExportPlaylistOpen($plids, $type='lspl', $withContent=TRUE)
+// {
+// global $CC_CONFIG;
+// if (!is_array($plids)) {
+// $plids = array($plids);
+// }
+// $gunids = array();
+// foreach ($plids as $plid) {
+// $pl = StoredFile::RecallByGunid($plid);
+// if (is_null($pl) || PEAR::isError($pl)) {
+// return $pl;
+// }
+// if ($withContent) {
+// $gunidsX = $pl->export();
+// if (PEAR::isError($gunidsX)) {
+// return $gunidsX;
+// }
+// } else {
+// $gunidsX = array(array('gunid'=>$plid, 'type'=>'playlist'));
+// }
+// $gunids = array_merge($gunids, $gunidsX);
+// }
+// $plExts = array('lspl'=>"lspl", 'smil'=>"smil", 'm3u'=>"m3u");
+// $plExt = (isset($plExts[$type]) ? $plExts[$type] : "xml" );
+// $res = array();
+// $tmpn = tempnam($CC_CONFIG['bufferDir'], 'plExport_');
+// $tmpf = "$tmpn.tar";
+// $tmpd = "$tmpn.dir";
+// mkdir($tmpd);
+// $tmpdp = "$tmpn.dir/playlist";
+// mkdir($tmpdp);
+// if ($withContent) {
+// $tmpdc = "$tmpn.dir/audioClip";
+// mkdir($tmpdc);
+// }
+// foreach ($gunids as $i => $it) {
+// $storedFile = StoredFile::RecallByGunid($it['gunid']);
+// if (is_null($storedFile) || PEAR::isError($storedFile)) {
+// return $storedFile;
+// }
+//// $MDfname = $storedFile->md->getFileName();
+// $MDfname = $storedFile->md["name"];
+// if (PEAR::isError($MDfname)) {
+// return $MDfname;
+// }
+// if (file_exists($MDfname)) {
+// switch ($it['type']) {
+// case "playlist":
+// $storedFile = $r = StoredFile::RecallByGunid($it['gunid']);
+// switch ($type) {
+// case "smil":
+// $string = $r = $storedFile->outputToSmil();
+// break;
+// case "m3u":
+// $string = $r = $storedFile->outputToM3u();
+// break;
+// default:
+//// $string = $r = $storedFile->md->genXmlDoc();
+// }
+// if (PEAR::isError($r)) {
+// return $r;
+// }
+// $r = BasicStor::WriteStringToFile($string, "$tmpdp/{$it['gunid']}.$plExt");
+// if (PEAR::isError($r)) {
+// return $r;
+// }
+// break;
+// default:
+// copy($MDfname, "$tmpdc/{$it['gunid']}.xml"); break;
+// } // switch
+// } // if file_exists()
+// $RADfname = $storedFile->getRealFileName();
+// if (PEAR::isError($RADfname)) {
+// return $RADfname;
+// }
+// $RADext = $storedFile->getFileExtension();
+// if (PEAR::isError($RADext)) {
+// return $RADext;
+// }
+// if (file_exists($RADfname)) {
+// copy($RADfname, "$tmpdc/{$it['gunid']}.$RADext");
+// }
+// }
+// if (count($plids)==1) {
+// copy("$tmpdp/$plid.$plExt", "$tmpd/exportedPlaylist.$plExt");
+// }
+// $res = `cd $tmpd; tar cf $tmpf * --remove-files`;
+// @rmdir($tmpdc);
+// @rmdir($tmpdp);
+// @rmdir($tmpd);
+// unlink($tmpn);
+// $acc = BasicStor::bsAccess($tmpf, 'tar', NULL/*gunid*/, 'access');
+// if (PEAR::isError($acc)) {
+// return $acc;
+// }
+// return $acc;
+// }
/**
@@ -1470,22 +1470,22 @@ class BasicStor {
* Access token obtained from bsExportPlaylistOpen method call.
* @return true/PEAR_Error
*/
- public function bsExportPlaylistClose($token)
- {
- $r = BasicStor::bsRelease($token, 'access');
- if (PEAR::isError($r)) {
- return $r;
- }
- $file = $r['realFname'];
- if (file_exists($file)) {
- if(! @unlink($file)){
- return PEAR::raiseError(
- "BasicStor::bsExportPlaylistClose: unlink failed ($file)",
- GBERR_FILEIO);
- }
- }
- return TRUE;
- }
+// public function bsExportPlaylistClose($token)
+// {
+// $r = BasicStor::bsRelease($token, 'access');
+// if (PEAR::isError($r)) {
+// return $r;
+// }
+// $file = $r['realFname'];
+// if (file_exists($file)) {
+// if(! @unlink($file)){
+// return PEAR::raiseError(
+// "BasicStor::bsExportPlaylistClose: unlink failed ($file)",
+// GBERR_FILEIO);
+// }
+// }
+// return TRUE;
+// }
/**
@@ -1506,59 +1506,59 @@ class BasicStor {
* @return int
* Result file local id (or error object)
*/
- public function bsImportPlaylistRaw($plid, $aPath, $rPath, $ext, &$gunids, $subjid)
- {
- $id = BasicStor::IdFromGunid($plid);
- if (!is_null($id)) {
- return $id;
- }
- $path = realpath("$aPath/$rPath");
- if (FALSE === $path) {
- return PEAR::raiseError(
- "BasicStor::bsImportPlaylistRaw: file doesn't exist ($aPath/$rPath)"
- );
- }
- switch ($ext) {
- case "xml":
- case "lspl":
- $fname = $plid;
- $values = array(
- "filename" => $fname,
- "metadata" => $path,
- "gunid" => $plid,
- "filetype" => "playlist"
- );
- $storedFile = $this->bsPutFile($values);
- $res = $storedFile->getId();
- break;
- case "smil":
- require_once("SmilPlaylist.php");
- $res = SmilPlaylist::import($this, $aPath, $rPath, $gunids, $plid, $subjid);
- if (PEAR::isError($res)) {
- break;
- }
- $res = $res->getId();
- break;
- case "m3u":
- require_once("M3uPlaylist.php");
- $res = M3uPlaylist::import($this, $aPath, $rPath, $gunids, $plid, $subjid);
- if (PEAR::isError($res)) {
- break;
- }
- $res = $res->getId();
- break;
- default:
- $res = PEAR::raiseError(
- "BasicStor::importPlaylistRaw: unknown playlist format".
- " (gunid:$plid, format:$ext)"
- );
- break;
- }
- if (!PEAR::isError($res)) {
- $gunids[basename($rPath)] = $plid;
- }
- return $res;
- }
+// public function bsImportPlaylistRaw($plid, $aPath, $rPath, $ext, &$gunids, $subjid)
+// {
+// $id = BasicStor::IdFromGunid($plid);
+// if (!is_null($id)) {
+// return $id;
+// }
+// $path = realpath("$aPath/$rPath");
+// if (FALSE === $path) {
+// return PEAR::raiseError(
+// "BasicStor::bsImportPlaylistRaw: file doesn't exist ($aPath/$rPath)"
+// );
+// }
+// switch ($ext) {
+// case "xml":
+// case "lspl":
+// $fname = $plid;
+// $values = array(
+// "filename" => $fname,
+// "metadata" => $path,
+// "gunid" => $plid,
+// "filetype" => "playlist"
+// );
+// $storedFile = StoredFile::Insert($values);
+// $res = $storedFile->getId();
+// break;
+// case "smil":
+// require_once("SmilPlaylist.php");
+// $res = SmilPlaylist::import($this, $aPath, $rPath, $gunids, $plid, $subjid);
+// if (PEAR::isError($res)) {
+// break;
+// }
+// $res = $res->getId();
+// break;
+// case "m3u":
+// require_once("M3uPlaylist.php");
+// $res = M3uPlaylist::import($this, $aPath, $rPath, $gunids, $plid, $subjid);
+// if (PEAR::isError($res)) {
+// break;
+// }
+// $res = $res->getId();
+// break;
+// default:
+// $res = PEAR::raiseError(
+// "BasicStor::importPlaylistRaw: unknown playlist format".
+// " (gunid:$plid, format:$ext)"
+// );
+// break;
+// }
+// if (!PEAR::isError($res)) {
+// $gunids[basename($rPath)] = $plid;
+// }
+// return $res;
+// }
/**
@@ -1571,95 +1571,95 @@ class BasicStor {
* @return int
* Result file local id (or error object)
*/
- public function bsImportPlaylist($fpath, $subjid)
- {
- global $CC_CONFIG;
- // untar:
- $tmpn = tempnam($CC_CONFIG['bufferDir'], 'plImport_');
- $tmpd = "$tmpn.dir";
- $tmpdc = "$tmpd/audioClip";
- $tmpdp = "$tmpd/playlist";
- mkdir($tmpd);
- $res = `cd $tmpd; tar xf $fpath`;
- // clips:
- $d = @dir($tmpdc);
- $entries = array();
- $gunids = array();
- if ($d !== false) {
- while (false !== ($entry = $d->read())) {
- if (preg_match("|^([0-9a-fA-F]{16})\.(.*)$|", $entry, $va)) {
- list(,$gunid, $ext) = $va;
- switch ($ext) {
- case"xml":
- $entries[$gunid]['metadata'] = $entry;
- break;
- default:
- $entries[$gunid]['rawMedia'] = $entry;
- $entries[$gunid]['rawMediaExt'] = $ext;
- $gunids[$entry] = $gunid;
- break;
- }
- }
- }
- $d->close();
- }
- $res = TRUE;
- foreach ($entries as $gunid => $it) {
- $rawMedia = "$tmpdc/{$it['rawMedia']}";
- if (!file_exists($rawMedia)) {
- $rawMedia = NULL;
- }
- $metadata = "$tmpdc/{$it['metadata']}";
- if (!file_exists($metadata)) {
- $metadata = NULL;
- }
- $exists = $this->bsExistsFile($gunid, NULL, TRUE);
- if( $exists ) {
- $res = BasicStor::IdFromGunid($gunid);
- if (!PEAR::isError($res)) {
- $res = $this->bsDeleteFile($res, TRUE);
- }
- }
- if (!PEAR::isError($res) ) {
- $values = array(
- "filename" => $gunid,
- "filepath" => $rawMedia,
- "metadata" => $metadata,
- "gunid" => $gunid,
- "filetype" => "audioclip"
- );
- $storedFile = $this->bsPutFile($values);
- $res = $storedFile->getId();
- }
- @unlink("$tmpdc/{$it['rawMedia']}");
- @unlink("$tmpdc/{$it['metadata']}");
- if (PEAR::isError($res)) {
- break;
- }
- }
- // playlists:
- $d = @dir($tmpdp);
- if ($d !== false) {
- while ((!PEAR::isError($res)) && false !== ($entry = $d->read())) {
- if (preg_match("|^([0-9a-fA-F]{16})\.(.*)$|", $entry, $va)) {
- list(,$gunid, $ext) = $va;
- $res = $this->bsImportPlaylistRaw($gunid,
- $tmpdp, $entry, $ext, $gunids, $subjid);
- unlink("$tmpdp/$entry");
- if (PEAR::isError($res)) {
- break;
- }
- }
- }
- $d->close();
- }
- //@rmdir($tmpdc); @rmdir($tmpdp); @rmdir($tmpd);
- @system("rm -rf $tmpdc");
- @system("rm -rf $tmpdp");
- @system("rm -rf $tmpd");
- @unlink($tmpn);
- return $res;
- }
+// public function bsImportPlaylist($fpath, $subjid)
+// {
+// global $CC_CONFIG;
+// // untar:
+// $tmpn = tempnam($CC_CONFIG['bufferDir'], 'plImport_');
+// $tmpd = "$tmpn.dir";
+// $tmpdc = "$tmpd/audioClip";
+// $tmpdp = "$tmpd/playlist";
+// mkdir($tmpd);
+// $res = `cd $tmpd; tar xf $fpath`;
+// // clips:
+// $d = @dir($tmpdc);
+// $entries = array();
+// $gunids = array();
+// if ($d !== false) {
+// while (false !== ($entry = $d->read())) {
+// if (preg_match("|^([0-9a-fA-F]{16})\.(.*)$|", $entry, $va)) {
+// list(,$gunid, $ext) = $va;
+// switch ($ext) {
+// case"xml":
+// $entries[$gunid]['metadata'] = $entry;
+// break;
+// default:
+// $entries[$gunid]['rawMedia'] = $entry;
+// $entries[$gunid]['rawMediaExt'] = $ext;
+// $gunids[$entry] = $gunid;
+// break;
+// }
+// }
+// }
+// $d->close();
+// }
+// $res = TRUE;
+// foreach ($entries as $gunid => $it) {
+// $rawMedia = "$tmpdc/{$it['rawMedia']}";
+// if (!file_exists($rawMedia)) {
+// $rawMedia = NULL;
+// }
+// $metadata = "$tmpdc/{$it['metadata']}";
+// if (!file_exists($metadata)) {
+// $metadata = NULL;
+// }
+// $f = StoredFile::RecallByGunid($gunid);
+// if (!PEAR::isError($f)) {
+// $exists = $f->existsFile();
+// if ( $exists ) {
+// $res = $f->delete();
+// }
+// }
+// if (!PEAR::isError($res) ) {
+// $values = array(
+// "filename" => $gunid,
+// "filepath" => $rawMedia,
+// "metadata" => $metadata,
+// "gunid" => $gunid,
+// "filetype" => "audioclip"
+// );
+// $storedFile = StoredFile::Insert($values);
+// $res = $storedFile->getId();
+// }
+// @unlink("$tmpdc/{$it['rawMedia']}");
+// @unlink("$tmpdc/{$it['metadata']}");
+// if (PEAR::isError($res)) {
+// break;
+// }
+// }
+// // playlists:
+// $d = @dir($tmpdp);
+// if ($d !== false) {
+// while ((!PEAR::isError($res)) && false !== ($entry = $d->read())) {
+// if (preg_match("|^([0-9a-fA-F]{16})\.(.*)$|", $entry, $va)) {
+// list(,$gunid, $ext) = $va;
+// $res = $this->bsImportPlaylistRaw($gunid,
+// $tmpdp, $entry, $ext, $gunids, $subjid);
+// unlink("$tmpdp/$entry");
+// if (PEAR::isError($res)) {
+// break;
+// }
+// }
+// }
+// $d->close();
+// }
+// //@rmdir($tmpdc); @rmdir($tmpdp); @rmdir($tmpd);
+// @system("rm -rf $tmpdc");
+// @system("rm -rf $tmpdp");
+// @system("rm -rf $tmpd");
+// @unlink($tmpn);
+// return $res;
+// }
/* --------------------------------------------------------- info methods */
@@ -1671,15 +1671,15 @@ class BasicStor {
* Virtual file's local id
* @return array
*/
- public function bsAnalyzeFile($id)
- {
- $storedFile = StoredFile::Recall($id);
- if (is_null($storedFile) || PEAR::isError($storedFile)) {
- return $storedFile;
- }
- $ia = $storedFile->analyzeFile();
- return $ia;
- }
+// public function bsAnalyzeFile($id)
+// {
+// $storedFile = StoredFile::Recall($id);
+// if (is_null($storedFile) || PEAR::isError($storedFile)) {
+// return $storedFile;
+// }
+// $ia = $storedFile->analyzeFile();
+// return $ia;
+// }
/**
@@ -1693,37 +1693,37 @@ class BasicStor {
* select file by gunid (id is then ignored)
* @return boolean
*/
- public function bsExistsFile($id, $ftype=NULL, $byGunid=FALSE)
- {
- if ($byGunid) {
- $storedFile = StoredFile::RecallByGunid($id);
- } else {
- $storedFile = StoredFile::Recall($id);
- }
- if (is_null($storedFile)) {
- return $storedFile;
- }
- if (PEAR::isError($storedFile)) {
- // catch some exceptions
- switch ($storedFile->getCode()) {
- case GBERR_FILENEX:
- case GBERR_FOBJNEX:
- return FALSE;
- break;
- default:
- return $storedFile;
- }
- }
- $realFtype = BasicStor::GetType($storedFile->gunid);
- if (!is_null($ftype) && (
- (strtolower($realFtype) != strtolower($ftype))
- // webstreams are subset of audioclips
- && !($realFtype == 'webstream' && $ftype == 'audioclip')
- )) {
- return FALSE;
- }
- return TRUE;
- }
+// public function bsExistsFile($id, $ftype=NULL, $byGunid=FALSE)
+// {
+// if ($byGunid) {
+// $storedFile = StoredFile::RecallByGunid($id);
+// } else {
+// $storedFile = StoredFile::Recall($id);
+// }
+// if (is_null($storedFile)) {
+// return $storedFile;
+// }
+// if (PEAR::isError($storedFile)) {
+// // catch some exceptions
+// switch ($storedFile->getCode()) {
+// case GBERR_FILENEX:
+// case GBERR_FOBJNEX:
+// return FALSE;
+// break;
+// default:
+// return $storedFile;
+// }
+// }
+// $realFtype = BasicStor::GetType($storedFile->gunid);
+// if (!is_null($ftype) && (
+// (strtolower($realFtype) != strtolower($ftype))
+// // webstreams are subset of audioclips
+// && !($realFtype == 'webstream' && $ftype == 'audioclip')
+// )) {
+// return FALSE;
+// }
+// return TRUE;
+// }
/* ---------------------------------------------------- redefined methods */
@@ -1734,22 +1734,25 @@ class BasicStor {
* Local object id
* @return string|PEAR_Error
*/
- public static function GetObjType($oid)
- {
- $type = "unknown";
- $gunid = BasicStor::GunidFromId($oid);
- if (PEAR::isError($gunid)) {
- return $gunid;
- }
- $ftype = BasicStor::GetType($gunid);
- if (PEAR::isError($ftype)) {
- return $ftype;
- }
- if (!is_null($ftype)) {
- $type = $ftype;
- }
- return $type;
- }
+// public static function GetObjType($p_id)
+// {
+// $type = "unknown";
+// $f = StoredFile::Recall($p_id);
+// return $f->getType();
+
+// $gunid = BasicStor::GunidFromId($oid);
+// if (PEAR::isError($gunid)) {
+// return $gunid;
+// }
+// $ftype = BasicStor::GetType($gunid);
+// if (PEAR::isError($ftype)) {
+// return $ftype;
+// }
+// if (!is_null($ftype)) {
+// $type = $ftype;
+// }
+// return $type;
+// }
/**
@@ -1883,12 +1886,12 @@ class BasicStor {
* @return int
* Local id
*/
- public static function IdFromGunid($p_gunid)
- {
- global $CC_DBC;
- global $CC_CONFIG;
- return $CC_DBC->getOne("SELECT id FROM ".$CC_CONFIG['filesTable']." WHERE gunid=x'$p_gunid'::bigint");
- }
+// public static function IdFromGunid($p_gunid)
+// {
+// global $CC_DBC;
+// global $CC_CONFIG;
+// return $CC_DBC->getOne("SELECT id FROM ".$CC_CONFIG['filesTable']." WHERE gunid=x'$p_gunid'::bigint");
+// }
/**
* Get local id from global id (big int).
@@ -1898,12 +1901,12 @@ class BasicStor {
* @return int
* Local id
*/
- public static function IdFromGunidBigInt($p_gunid)
- {
- global $CC_DBC;
- global $CC_CONFIG;
- return $CC_DBC->getOne("SELECT id FROM ".$CC_CONFIG['filesTable']." WHERE gunid='$p_gunid'");
- }
+// public static function IdFromGunidBigInt($p_gunid)
+// {
+// global $CC_DBC;
+// global $CC_CONFIG;
+// return $CC_DBC->getOne("SELECT id FROM ".$CC_CONFIG['filesTable']." WHERE gunid='$p_gunid'");
+// }
/**
@@ -1914,25 +1917,25 @@ class BasicStor {
* @return string
* Global id
*/
- public static function GunidFromId($p_id)
- {
- global $CC_CONFIG;
- global $CC_DBC;
- if (!is_numeric($p_id)) {
- return NULL;
- }
- $gunid = $CC_DBC->getOne("
- SELECT to_hex(gunid)as gunid FROM ".$CC_CONFIG['filesTable']."
- WHERE id='$p_id'
- ");
- if (PEAR::isError($gunid)) {
- return $gunid;
- }
- if (is_null($gunid)) {
- return NULL;
- }
- return StoredFile::NormalizeGunid($gunid);
- }
+// public static function GunidFromId($p_id)
+// {
+// global $CC_CONFIG;
+// global $CC_DBC;
+// if (!is_numeric($p_id)) {
+// return NULL;
+// }
+// $gunid = $CC_DBC->getOne("
+// SELECT to_hex(gunid)as gunid FROM ".$CC_CONFIG['filesTable']."
+// WHERE id='$p_id'
+// ");
+// if (PEAR::isError($gunid)) {
+// return $gunid;
+// }
+// if (is_null($gunid)) {
+// return NULL;
+// }
+// return StoredFile::NormalizeGunid($gunid);
+// }
/**
@@ -1942,16 +1945,16 @@ class BasicStor {
* Global unique id of file
* @return string
*/
- public static function GetType($p_gunid)
- {
- global $CC_CONFIG;
- global $CC_DBC;
- $ftype = $CC_DBC->getOne("
- SELECT ftype FROM ".$CC_CONFIG['filesTable']."
- WHERE gunid=x'$p_gunid'::bigint
- ");
- return $ftype;
- }
+// public static function GetType($p_gunid)
+// {
+// global $CC_CONFIG;
+// global $CC_DBC;
+// $ftype = $CC_DBC->getOne("
+// SELECT ftype FROM ".$CC_CONFIG['filesTable']."
+// WHERE gunid=x'$p_gunid'::bigint
+// ");
+// return $ftype;
+// }
/**
@@ -1961,11 +1964,11 @@ class BasicStor {
* Global unique ID
* @return boolean
*/
- protected static function CheckGunid($p_gunid)
- {
- $res = preg_match("|^([0-9a-fA-F]{16})?$|", $p_gunid);
- return $res;
- }
+// protected static function CheckGunid($p_gunid)
+// {
+// $res = preg_match("|^([0-9a-fA-F]{16})?$|", $p_gunid);
+// return $res;
+// }
/**
* Set playlist edit flag
@@ -2035,24 +2038,24 @@ class BasicStor {
* @return int
* New object local id
*/
- protected static function CopyObj($id, $newParid, $after=NULL)
- {
- switch (BasicStor::GetObjType($id)) {
- case "audioclip":
- case "playlist":
- case "webstream":
- $storedFile = StoredFile::Recall($id);
- if (is_null($storedFile) || PEAR::isError($storedFile)) {
- return $storedFile;
- }
- $ac2 = StoredFile::CopyOf($storedFile, $nid);
- //$ac2->setName(M2tree::GetObjName($nid));
- break;
- case "File":
- default:
- }
- return $nid;
- }
+// protected static function CopyObj($id, $newParid, $after=NULL)
+// {
+// switch (BasicStor::GetObjType($id)) {
+// case "audioclip":
+// case "playlist":
+// case "webstream":
+// $storedFile = StoredFile::Recall($id);
+// if (is_null($storedFile) || PEAR::isError($storedFile)) {
+// return $storedFile;
+// }
+// $ac2 = StoredFile::CopyOf($storedFile, $nid);
+// //$ac2->setName(M2tree::GetObjName($nid));
+// break;
+// case "File":
+// default:
+// }
+// return $nid;
+// }
/**
@@ -2065,50 +2068,50 @@ class BasicStor {
* Unconditional delete
* @return true|PEAR_Error
*/
- public static function RemoveObj($id, $forced=FALSE)
- {
- $ot = BasicStor::GetObjType($id);
- if (PEAR::isError($ot)) {
- return $ot;
- }
- switch ($ot) {
- case "audioclip":
- case "playlist":
- case "webstream":
- $storedFile = StoredFile::Recall($id);
- if (is_null($storedFile)) {
- return TRUE;
- }
- if (PEAR::isError($storedFile)) {
- return $storedFile;
- }
- if ($storedFile->isEdited() && !$forced) {
- return PEAR::raiseError(
- 'BasicStor::RemoveObj(): is edited'
- );
- }
- if ($storedFile->isAccessed() && !$forced) {
- return PEAR::raiseError(
- 'BasicStor::RemoveObj(): is accessed'
- );
- }
- $storedFile->delete();
- break;
- case "File":
-// case "Folder":
-// case "Replica":
- break;
- default:
- return PEAR::raiseError(
- "BasicStor::bsDeleteFile: unknown obj type ($ot)"
- );
- }
- $res = Alib::RemoveObj($id);
- if (PEAR::isError($res)) {
- return $res;
- }
- return TRUE;
- }
+// public static function RemoveObj($id, $forced=FALSE)
+// {
+// $ot = BasicStor::GetObjType($id);
+// if (PEAR::isError($ot)) {
+// return $ot;
+// }
+// switch ($ot) {
+// case "audioclip":
+// case "playlist":
+// case "webstream":
+// $storedFile = StoredFile::Recall($id);
+// if (is_null($storedFile)) {
+// return TRUE;
+// }
+// if (PEAR::isError($storedFile)) {
+// return $storedFile;
+// }
+// if ($storedFile->isEdited() && !$forced) {
+// return PEAR::raiseError(
+// 'BasicStor::RemoveObj(): is edited'
+// );
+// }
+// if ($storedFile->isAccessed() && !$forced) {
+// return PEAR::raiseError(
+// 'BasicStor::RemoveObj(): is accessed'
+// );
+// }
+// $storedFile->delete();
+// break;
+// case "File":
+//// case "Folder":
+//// case "Replica":
+// break;
+// default:
+// return PEAR::raiseError(
+// "BasicStor::bsDeleteFile: unknown obj type ($ot)"
+// );
+// }
+// $res = Alib::RemoveObj($id);
+// if (PEAR::isError($res)) {
+// return $res;
+// }
+// return TRUE;
+// }
/* ========================================================= misc methods */
@@ -2153,16 +2156,17 @@ class BasicStor {
*
* @return void
*/
- private function deleteFiles()
- {
- global $CC_CONFIG, $CC_DBC;
- $ids = $CC_DBC->getAll("SELECT id FROM ".$CC_CONFIG['filesTable']);
- if (is_array($ids)) {
- foreach ($ids as $i => $item) {
- $this->bsDeleteFile($item['id'], TRUE);
- }
- }
- }
+// private function deleteFiles()
+// {
+// global $CC_CONFIG, $CC_DBC;
+// $ids = $CC_DBC->getAll("SELECT id FROM ".$CC_CONFIG['filesTable']);
+// if (is_array($ids)) {
+// foreach ($ids as $i => $item) {
+// $f = StoredFile::Recall($item['id']);
+// $f->delete();
+// }
+// }
+// }
/**
diff --git a/backend/GreenBox.php b/backend/GreenBox.php
index 41bc81c79..a46ffa752 100644
--- a/backend/GreenBox.php
+++ b/backend/GreenBox.php
@@ -1,12 +1,11 @@
";
+}
require_once("BasicStor.php");
if (isset($WHITE_SCREEN_OF_DEATH) && $WHITE_SCREEN_OF_DEATH) {
echo __FILE__.':line '.__LINE__.": Loaded BasicStor
";
}
-require_once("LocStor.php");
-if (isset($WHITE_SCREEN_OF_DEATH) && $WHITE_SCREEN_OF_DEATH) {
- echo __FILE__.':line '.__LINE__.": Loaded LocStor
";
-}
require_once("Playlist.php");
require_once("Renderer.php");
require_once('Prefs.php');
@@ -51,7 +50,7 @@ class GreenBox extends BasicStor {
if (($res = BasicStor::Authorize('write', null, $p_sessionId)) !== TRUE) {
return $res;
}
- $storedFile = $this->bsPutFile($p_values);
+ $storedFile = StoredFile::Insert($p_values);
return $storedFile;
} // fn putFile
@@ -87,12 +86,11 @@ class GreenBox extends BasicStor {
"gunid" => $gunid,
"filetype" => "webstream"
);
- $storedFile = $this->bsPutFile($values);
+ $storedFile = StoredFile::Insert($values);
if (PEAR::isError($storedFile)) {
return $storedFile;
}
- $oid = $storedFile->getId();
- $r = $this->bsSetMetadataValue($oid, 'ls:url', $url);
+ $r = $storedFile->setMetadataValue('ls:url', $url);
if (PEAR::isError($r)) {
return $r;
}
@@ -152,13 +150,13 @@ class GreenBox extends BasicStor {
* Session id
* @return array
*/
- public function analyzeFile($id, $sessid='')
- {
- if (($res = BasicStor::Authorize('read', $id, $sessid)) !== TRUE) {
- return $res;
- }
- return $this->bsAnalyzeFile($id);
- } // fn analyzeFile
+// public function analyzeFile($id, $sessid='')
+// {
+// if (($res = BasicStor::Authorize('read', $id, $sessid)) !== TRUE) {
+// return $res;
+// }
+// return $this->bsAnalyzeFile($id);
+// }
/**
@@ -171,13 +169,13 @@ class GreenBox extends BasicStor {
* Session id
* @return boolean|PEAR_Error
*/
- public function renameFile($id, $newName, $sessid='')
- {
- if (($res = BasicStor::Authorize('write', $id, $sessid)) !== TRUE) {
- return $res;
- }
- return $this->bsRenameFile($id, $newName);
- } // fn renameFile
+// public function renameFile($id, $newName, $sessid='')
+// {
+// if (($res = BasicStor::Authorize('write', $id, $sessid)) !== TRUE) {
+// return $res;
+// }
+// return $this->bsRenameFile($id, $newName);
+// }
/**
@@ -193,23 +191,23 @@ class GreenBox extends BasicStor {
* session id
* @return TRUE|PEAR_Error
*/
- public function replaceFile($id, $mediaFileLP, $mdataFileLP, $sessid='')
- {
- if (($res = BasicStor::Authorize('write', $id, $sessid)) !== TRUE) {
- return $res;
- }
- return $this->bsReplaceFile($id, $mediaFileLP, $mdataFileLP);
- } // fn replaceFile
+// public function replaceFile($id, $mediaFileLP, $mdataFileLP, $sessid='')
+// {
+// if (($res = BasicStor::Authorize('write', $id, $sessid)) !== TRUE) {
+// return $res;
+// }
+// return $this->bsReplaceFile($id, $mediaFileLP, $mdataFileLP);
+// }
/**
* Delete file
*
* @param int $id
- * virt.file's local id
+ * local id
* @param int $sessid
* @param boolean $forced
- * if true don't use trash
+ * if true don't use trash -- now ignored
* @return true|PEAR_Error
*/
public function deleteFile($id, $sessid='', $forced=FALSE)
@@ -217,8 +215,9 @@ class GreenBox extends BasicStor {
if (($res = BasicStor::Authorize('write', $id, $sessid)) !== TRUE) {
return $res;
}
- return $this->bsDeleteFile($id, $forced);
- } // fn deleteFile
+ $f = StoredFile::Recall($id);
+ return $f->delete(true);
+ }
/* ------------------------------------------------------------- metadata */
@@ -260,7 +259,8 @@ class GreenBox extends BasicStor {
if (($res = BasicStor::Authorize('read', $id, $sessid)) !== TRUE) {
return $res;
}
- return $this->bsGetMetadata($id);
+ $f = StoredFile::Recall($id);
+ return $f->getMetadata();
}
@@ -345,8 +345,9 @@ class GreenBox extends BasicStor {
if (($res = BasicStor::Authorize('read', $id, $sessid)) !== TRUE) {
return $res;
}
- return $this->bsGetMetadataValue($id, $category);
- } // fn getMetadataValue
+ $f = StoredFile::Recall($id);
+ return $f->getMetadataValue($category);
+ }
/**
@@ -367,7 +368,8 @@ class GreenBox extends BasicStor {
if (($res = BasicStor::Authorize('write', $id, $sessid)) !== TRUE) {
return $res;
}
- return $this->bsSetMetadataValue($id, $category, $value);
+ $f = StoredFile::Recall($id);
+ return $f->setMetadataValue($category, $value);
} // fn setMetadataValue
@@ -560,7 +562,7 @@ class GreenBox extends BasicStor {
return;
$res = $pl->lock($sessid);
-
+
return $res;
}
@@ -743,10 +745,6 @@ class GreenBox extends BasicStor {
* current playtime (hh:mm:ss.ssssss)
* @param int $distance
* 0=current clip; 1=next clip ...
- * @param string $lang
- * xml:lang value for select language version
- * @param string $deflang
- * xml:lang for default language
* @return array of matching clip info:
*
";var_dump($data); - $playlists = array(); + $playlists = array(); if (is_array($data) && count($data) > 0) { foreach ($data as $dx) { - // Is this the first item in the playlist? + // Is this the first item in the playlist? $start = $dx['start']; // chop off subseconds - $start = substr($start, 0, 19); - - // Start time is the array key, needs to be in the format "YYYY-MM-DD-HH-mm-ss" - $pkey = Schedule::CcTimeToPypoTime($start); - $timestamp = strtotime($start); + $start = substr($start, 0, 19); + + // Start time is the array key, needs to be in the format "YYYY-MM-DD-HH-mm-ss" + $pkey = Schedule::CcTimeToPypoTime($start); + $timestamp = strtotime($start); $playlists[$pkey]['source'] = "PLAYLIST"; $playlists[$pkey]['x_ident'] = $dx["playlist_id"]; $playlists[$pkey]['subtype'] = '1'; // Just needs to be between 1 and 4 inclusive @@ -372,16 +391,16 @@ class Schedule { foreach ($playlists as &$playlist) { - $scheduleGroup = new ScheduleGroup($playlist["schedule_id"]); - $items = $scheduleGroup->getItems(); + $scheduleGroup = new ScheduleGroup($playlist["schedule_id"]); + $items = $scheduleGroup->getItems(); $medias = array(); $playlist['subtype'] = '1'; foreach ($items as $item) { - $storedFile = StoredFile::Recall($item["file_id"]); - $uri = $storedFile->getFileUrl(); + $storedFile = StoredFile::Recall($item["file_id"]); + $uri = $storedFile->getFileUrl(); $medias[] = array( - 'id' => $item["file_id"], + 'id' => $storedFile->getGunid(), //$item["file_id"], 'uri' => $uri, 'fade_in' => $item["fade_in"], 'fade_out' => $item["fade_out"], diff --git a/backend/StoredFile.php b/backend/StoredFile.php index d0fd7d78b..b5eb78c96 100644 --- a/backend/StoredFile.php +++ b/backend/StoredFile.php @@ -2,6 +2,53 @@ require_once("Playlist.php"); require_once(dirname(__FILE__)."/../3rd_party/getid3/var/getid3.php"); require_once("BasicStor.php"); +require_once("Schedule.php"); + +$g_metadata_xml_to_db_mapping = array( + "dc:format" => "format", + "ls:bitrate" => "bit_rate", + "ls:samplerate" => "sample_rate", + "dcterms:extent" => "length", + "dc:title" => "track_title", + "dc:description" => "comments", + "dc:type" => "genre", + "dc:creator" => "artist_name", + "dc:source" => "album_title", + "ls:channels" => "channels", + "ls:filename" => "name", + "ls:year" => "year", + "ls:url" => "url", + "ls:track_num" => "track_number", + "ls:mood" => "mood", + "ls:bpm" => "bpm", + "ls:disc_num" => "disc_number", + "ls:rating" => "rating", + "ls:encoded_by" => "encoded_by", + "dc:publisher" => "label", + "ls:composer" => "composer", + "ls:encoder" => "encoder", + "ls:crc" => "checksum", + "ls:lyrics" => "lyrics", + "ls:orchestra" => "orchestra", + "ls:conductor" => "conductor", + "ls:lyricist" => "lyricist", + "ls:originallyricist" => "original_lyricist", + "ls:radiostationname" => "radio_station_name", + "ls:audiofileinfourl" => "info_url", + "ls:artisturl" => "artist_url", + "ls:audiosourceurl" => "audio_source_url", + "ls:radiostationurl" => "radio_station_url", + "ls:buycdurl" => "buy_this_url", + "ls:isrcnumber" => "isrc_number", + "ls:catalognumber" => "catalog_number", + "ls:originalartist" => "original_artist", + "dc:rights" => "copyright", + "dcterms:temporal" => "report_datetime", + "dcterms:spatial" => "report_location", + "dcterms:entity" => "report_organization", + "dc:subject" => "subject", + "dc:contributor" => "contributor", + "dc:language" => "language"); /** * Track numbers in metadata tags can come in many formats: @@ -279,7 +326,7 @@ function camp_get_audio_metadata($p_filename, $p_testonly = false) */ class StoredFile { - // *** Variable stored in the database *** + // *** Variables stored in the database *** /** * @var int @@ -314,7 +361,7 @@ class StoredFile { private $mime; /** - * Can be 'playlist' or 'audioclip'. + * Can be 'audioclip'...others might be coming, like webstream. * * @var string */ @@ -381,18 +428,49 @@ class StoredFile { */ public function __construct($p_gunid=NULL) { - global $CC_CONFIG; - global $CC_DBC; $this->gunid = $p_gunid; if (empty($this->gunid)) { $this->gunid = StoredFile::generateGunid(); } - //$this->resDir = $this->_getResDir($this->gunid); - //$this->filepath = "{$this->resDir}/{$this->gunid}"; $this->exists = is_file($this->filepath) && is_readable($this->filepath); $this->md = $this->loadMetadata(); } + /** + * Convert XML name to database column name. Used for backwards compatibility + * with old code. + * + * @param string $p_category + * @return string|null + */ + public static function xmlCategoryToDbColumn($p_category) + { + global $g_metadata_xml_to_db_mapping; + if (array_key_exists($p_category, $g_metadata_xml_to_db_mapping)) { + return $g_metadata_xml_to_db_mapping[$p_category]; + } + return null; + } + + + /** + * Convert database column name to XML name. + * + * @param string $p_dbColumn + * @return string|null + */ + public static function dbColumnToXmlCatagory($p_dbColumn) + { + global $g_metadata_xml_to_db_mapping; + $str = array_search($p_dbColumn, $g_metadata_xml_to_db_mapping); + // make return value consistent with xmlCategoryToDbColumn() + if ($str === FALSE) { + $str = null; + } + return $str; + } + + /** * GUNID needs to be set before you call this function. * @@ -417,7 +495,7 @@ class StoredFile { } $compatibilityData = array(); foreach ($this->md as $key => $value) { - if ($xmlName = BasicStor::dbColumnToXmlCatagory($key)) { + if ($xmlName = StoredFile::dbColumnToXmlCatagory($key)) { $compatibilityData[$xmlName] = $value; } } @@ -435,7 +513,7 @@ class StoredFile { global $CC_CONFIG, $CC_DBC; foreach ($p_values as $category => $value) { $escapedValue = pg_escape_string($value); - $columnName = BasicStor::xmlCategoryToDbColumn($category); + $columnName = StoredFile::xmlCategoryToDbColumn($category); if (!is_null($columnName)) { $sql = "UPDATE ".$CC_CONFIG["filesTable"] ." SET $columnName='$escapedValue'" @@ -529,7 +607,6 @@ class StoredFile { // Insert record into the database $escapedName = pg_escape_string($storedFile->name); $escapedFtype = pg_escape_string($storedFile->ftype); - $CC_DBC->query("BEGIN"); $sql = "INSERT INTO ".$CC_CONFIG['filesTable'] ."(id, name, gunid, mime, state, ftype, mtime, md5)" ."VALUES ({$sqlId}, '{$escapedName}', " @@ -537,6 +614,7 @@ class StoredFile { ." '{$storedFile->mime}', 'incomplete', '$escapedFtype'," ." now(), '{$storedFile->md5}')"; //$_SESSION["debug"] .= "sql: ".$sql."
"; + //echo $sql."\n"; $res = $CC_DBC->query($sql); if (PEAR::isError($res)) { $CC_DBC->query("ROLLBACK"); @@ -548,16 +626,15 @@ class StoredFile { $sql = "SELECT currval('".$CC_CONFIG["filesSequence"]."_seq')"; $storedFile->id = $CC_DBC->getOne($sql); } - BasicStor::bsSetMetadataBatch($storedFile->id, $metadata); + $storedFile->setMetadataBatch($metadata); // Save media file $res = $storedFile->addFile($p_values['filepath'], $p_copyMedia); - if (PEAR::isError($res)) { - echo "StoredFile::Insert: ERROR adding file: '".$res->getMessage()."'\n"; - $CC_DBC->query("ROLLBACK"); + echo "StoredFile::Insert -- addFile(): '".$res->getMessage()."'\n"; return $res; } + if (empty($storedFile->mime)) { //echo "StoredFile::Insert: WARNING: Having to recalculate MIME value\n"; $storedFile->setMime($storedFile->getMime()); @@ -566,13 +643,6 @@ class StoredFile { // Save state $storedFile->setState('ready'); - // Commit changes - $res = $CC_DBC->query("COMMIT"); - if (PEAR::isError($res)) { - $CC_DBC->query("ROLLBACK"); - return $res; - } - // Recall the object to get all the proper values $storedFile = StoredFile::RecallByGunid($storedFile->gunid); return $storedFile; @@ -583,21 +653,21 @@ class StoredFile { * Should be supplied with only ONE parameter, all the rest should * be NULL. * - * @param int $p_oid - * local object id in the tree + * @param int $p_id + * local id * @param string $p_gunid * global unique id of file * @param string $p_md5sum - * MD5 sum of the file + * MD5 sum of the file * @return StoredFile|Playlist|NULL - * Return NULL if the object doesnt exist in the DB. + * Return NULL if the object doesnt exist in the DB. */ - public static function Recall($p_oid=null, $p_gunid=null, $p_md5sum=null) + public static function Recall($p_id=null, $p_gunid=null, $p_md5sum=null) { global $CC_DBC; global $CC_CONFIG; - if (!is_null($p_oid)) { - $cond = "id='".intval($p_oid)."'"; + if (!is_null($p_id)) { + $cond = "id='".intval($p_id)."'"; } elseif (!is_null($p_gunid)) { $cond = "gunid='$p_gunid'"; } elseif (!is_null($p_md5sum)) { @@ -605,31 +675,16 @@ class StoredFile { } else { return null; } - $sql = "SELECT id, gunid," - ." name, mime, ftype, state, currentlyaccessing, editedby, " - ." mtime, md5" + $sql = "SELECT *" ." FROM ".$CC_CONFIG['filesTable'] ." WHERE $cond"; //echo $sql; $row = $CC_DBC->getRow($sql); - if (PEAR::isError($row)) { + if (PEAR::isError($row) || is_null($row)) { return $row; } - if (is_null($row)) { - return null; - } $gunid = $row['gunid']; - if ($row['ftype'] == 'audioclip') { - $storedFile = new StoredFile($gunid); - } elseif ($row['ftype'] == 'playlist') { - $storedFile = new Playlist($gunid); - } else { // fallback - $storedFile = new StoredFile($gunid); - } - $storedFile->loadMetadata(); - //$storedFile->gunidBigint = $row['gunid_bigint']; - //$storedFile->md->gunidBigint = $row['gunid_bigint']; - $storedFile->md["gunid"] = $row['gunid']; + $storedFile = new StoredFile($gunid); $storedFile->id = $row['id']; $storedFile->name = $row['name']; $storedFile->mime = $row['mime']; @@ -639,6 +694,7 @@ class StoredFile { $storedFile->editedby = $row['editedby']; $storedFile->mtime = $row['mtime']; $storedFile->md5 = $row['md5']; + $storedFile->filepath = $row['filepath']; $storedFile->exists = TRUE; $storedFile->setFormat($row['ftype']); return $storedFile; @@ -757,6 +813,7 @@ class StoredFile { $sql = "UPDATE ".$CC_CONFIG["filesTable"] ." SET filepath='{$sqlPath}'" ." WHERE id={$this->id}"; + //echo $sql."\n"; $res = $CC_DBC->query($sql); if (PEAR::isError($res)) { return $res; @@ -803,25 +860,52 @@ class StoredFile { /** - * Delete media file from filesystem + * Delete media file from filesystem. + * You cant delete a file if it is being accessed. + * You cant delete a file if it is scheduled to be played in the future. + * The file will be removed from all playlists it is a part of. * * @return boolean|PEAR_Error */ public function deleteFile() { + global $CC_CONFIG; if (!$this->exists) { return FALSE; } - if (!file_exists($this->filepath) || @unlink($this->filepath)) { - $this->exists = FALSE; - return TRUE; - } else { - return PEAR::raiseError( - "StoredFile::deleteFile: unlink failed ({$this->filepath})", - GBERR_FILEIO + if ($this->isAccessed()) { + return PEAR::raiseError( + 'Cannot delete a file that is currently accessed.' ); } - return $this->exists; + + // Check if the file is scheduled to be played in the future + if (Schedule::IsFileScheduledInTheFuture($this->id)) { + return PEAR::raiseError( + 'Cannot delete a file that is scheduled in the future.' + ); + } + + // Delete it from all playlists + //Playlist::DeleteFileFromAllPlaylists($this->id); + + // Only delete the file from filesystem if it has been copied to the + // storage directory. (i.e. dont delete linked files) + if (substr($this->filepath, 0, strlen($CC_CONFIG["storageDir"])) == $CC_CONFIG["storageDir"]) { + // Delete the file + if (!file_exists($this->filepath) || @unlink($this->filepath)) { + $this->exists = FALSE; + return TRUE; + } else { + return PEAR::raiseError( + "StoredFile::deleteFile: unlink failed ({$this->filepath})", + GBERR_FILEIO + ); + } + } else { + $this->exists = FALSE; + return TRUE; + } } @@ -858,7 +942,7 @@ class StoredFile { "id" => $p_nid, "filename" => $p_src->name, "filepath" => $p_src->getRealFileName(), - "filetype" => BasicStor::GetType($p_src->gunid) + "filetype" => $p_src->getType() ); $storedFile = StoredFile::Insert($values); if (PEAR::isError($storedFile)) { @@ -884,42 +968,42 @@ class StoredFile { * 'file'|'string' * @return TRUE|PEAR_Error */ - public function replace($p_oid, $p_name, $p_localFilePath='', $p_metadata='', - $p_mdataLoc='file') - { - global $CC_CONFIG, $CC_DBC; - $CC_DBC->query("BEGIN"); - $res = $this->setName($p_name); - if (PEAR::isError($res)) { - $CC_DBC->query("ROLLBACK"); - return $res; - } - if ($p_localFilePath != '') { - $res = $this->setRawMediaData($p_localFilePath); - } else { - $res = $this->deleteFile(); - } - if (PEAR::isError($res)) { - $CC_DBC->query("ROLLBACK"); - return $res; - } - if ($p_metadata != '') { - $res = $this->setMetadata($p_metadata, $p_mdataLoc); - } else { -// $res = $this->md->delete(); - $res = $this->clearMetadata(); - } - if (PEAR::isError($res)) { - $CC_DBC->query("ROLLBACK"); - return $res; - } - $res = $CC_DBC->query("COMMIT"); - if (PEAR::isError($res)) { - $CC_DBC->query("ROLLBACK"); - return $res; - } - return TRUE; - } +// public function replace($p_oid, $p_name, $p_localFilePath='', $p_metadata='', +// $p_mdataLoc='file') +// { +// global $CC_CONFIG, $CC_DBC; +// $CC_DBC->query("BEGIN"); +// $res = $this->setName($p_name); +// if (PEAR::isError($res)) { +// $CC_DBC->query("ROLLBACK"); +// return $res; +// } +// if ($p_localFilePath != '') { +// $res = $this->setRawMediaData($p_localFilePath); +// } else { +// $res = $this->deleteFile(); +// } +// if (PEAR::isError($res)) { +// $CC_DBC->query("ROLLBACK"); +// return $res; +// } +// if ($p_metadata != '') { +// $res = $this->setMetadata($p_metadata, $p_mdataLoc); +// } else { +//// $res = $this->md->delete(); +// $res = $this->clearMetadata(); +// } +// if (PEAR::isError($res)) { +// $CC_DBC->query("ROLLBACK"); +// return $res; +// } +// $res = $CC_DBC->query("COMMIT"); +// if (PEAR::isError($res)) { +// $CC_DBC->query("ROLLBACK"); +// return $res; +// } +// return TRUE; +// } /** @@ -989,6 +1073,17 @@ class StoredFile { } + private static function NormalizeExtent($v) + { + if (!preg_match("|^\d{2}:\d{2}:\d{2}.\d{6}$|", $v)) { + $s = Playlist::playlistTimeToSeconds($v); + $t = Playlist::secondsToPlaylistTime($s); + return $t; + } + return $v; + } + + /** * Replace metadata with new XML file * @@ -1002,25 +1097,110 @@ class StoredFile { * (NULL = no validation) * @return boolean */ - public function setMetadata($p_metadata, $p_mdataLoc='file', $p_format=NULL) - { - global $CC_CONFIG, $CC_DBC; - $CC_DBC->query("BEGIN"); - $res = $this->md->replace($p_metadata, $p_mdataLoc, $p_format); - if (PEAR::isError($res)) { - $CC_DBC->query("ROLLBACK"); - return $res; - } -// $r = $this->md->regenerateXmlFile(); -// if (PEAR::isError($r)) { +// public function setMetadata($p_metadata, $p_mdataLoc='file', $p_format=NULL) +// { +// global $CC_CONFIG, $CC_DBC; +// $CC_DBC->query("BEGIN"); +// $res = $this->md->replace($p_metadata, $p_mdataLoc, $p_format); +// if (PEAR::isError($res)) { // $CC_DBC->query("ROLLBACK"); -// return $r; +// return $res; // } - $res = $CC_DBC->query("COMMIT"); +// $res = $CC_DBC->query("COMMIT"); +// if (PEAR::isError($res)) { +// return $res; +// } +// return TRUE; +// } + + /** + * Set metadata element value + * + * @param string $category + * Metadata element identification (e.g. dc:title) + * @param string $value + * value to store, if NULL then delete record + * @return boolean + */ + public function setMetadataValue($p_category, $p_value) + { + global $CC_CONFIG, $CC_DBC; + if (!is_string($p_category) || is_array($p_value)) { + return FALSE; + } + if ($p_category == 'dcterms:extent') { + $p_value = StoredFile::NormalizeExtent($p_value); + } + $columnName = StoredFile::xmlCategoryToDbColumn($p_category); // Get column name + + if (!is_null($columnName)) { + $escapedValue = pg_escape_string($p_value); + $sql = "UPDATE ".$CC_CONFIG["filesTable"] + ." SET $columnName='$escapedValue'" + ." WHERE id=$p_id"; + //var_dump($sql); + $res = $CC_DBC->query($sql); if (PEAR::isError($res)) { - return $res; + return $res; } + } + return TRUE; + } + + + /** + * Set metadata values in 'batch' mode + * + * @param array $values + * array of key/value pairs + * (e.g. 'dc:title'=>'New title') + * @return boolean + */ + public function setMetadataBatch($values) + { + global $CC_CONFIG, $CC_DBC; + if (!is_array($values)) { + $values = array($values); + } + if (count($values) == 0) { + return true; + } + foreach ($values as $category => $oneValue) { + $columnName = StoredFile::xmlCategoryToDbColumn($category); + if (!is_null($columnName)) { + if ($category == 'dcterms:extent') { + $oneValue = StoredFile::NormalizeExtent($oneValue); + } + // Since track_number is an integer, you cannot set + // it to be the empty string, so we NULL it instead. + if ($columnName == 'track_number' && empty($oneValue)) { + $sqlPart = "$columnName = NULL"; + } elseif (($columnName == 'length') && (strlen($oneValue) > 8)) { + // Postgres doesnt like it if you try to store really large hour + // values. TODO: We need to fix the underlying problem of getting the + // right values. + $parts = explode(':', $oneValue); + $hour = intval($parts[0]); + if ($hour > 24) { + continue; + } else { + $sqlPart = "$columnName = '$oneValue'"; + } + } else { + $escapedValue = pg_escape_string($oneValue); + $sqlPart = "$columnName = '$escapedValue'"; + } + $sqlValues[] = $sqlPart; + } + } + if (count($sqlValues)==0) { return TRUE; + } + $sql = "UPDATE ".$CC_CONFIG["filesTable"] + ." SET ".join(",", $sqlValues) + ." WHERE id=$id"; + $CC_DBC->query($sql); + return TRUE; } @@ -1034,6 +1214,20 @@ class StoredFile { return $this->md; } + /** + * Get one metadata value. + * + * @param string $p_name + * @return string + */ + public function getMetadataValue($p_name) + { + if (isset($this->md[$p_name])){ + return $this->md[$p_name]; + } else { + return ""; + } + } /** * Rename stored virtual file @@ -1135,7 +1329,7 @@ class StoredFile { * Delete stored virtual file * * @param boolean $p_deleteFile - * @see MetaData + * * @return TRUE|PEAR_Error */ public function delete($p_deleteFile = true) @@ -1147,10 +1341,6 @@ class StoredFile { return $res; } } -// $res = $this->md->delete(); -// if (PEAR::isError($res)) { -// return $res; -// } $sql = "SELECT to_hex(token)as token, ext " ." FROM ".$CC_CONFIG['accessTable'] ." WHERE gunid='{$this->gunid}'"; @@ -1178,27 +1368,25 @@ class StoredFile { return TRUE; } - /** - * Returns gunIds of the playlists the stored file is in. - * TODO update this to work with new tables. - */ - /* + /** + * Returns an array of playlist objects that this file is a part of. + * @return array + */ public function getPlaylists() { global $CC_CONFIG, $CC_DBC; - - $_SESSION['delete'] = "gunid: " . $this->gunid; - - $sql = "SELECT gunid " - ." FROM ".$CC_CONFIG['mdataTable'] - ." WHERE object='{$this->gunid}'"; - - $_SESSION['delete'] = $sql; - $playlists = $CC_DBC->getAll($sql); - + $sql = "SELECT playlist_id " + ." FROM ".$CC_CONFIG['playistTable'] + ." WHERE file_id='{$this->id}'"; + $ids = $CC_DBC->getAll($sql); + $playlists = array(); + if (is_array($ids) && count($ids) > 0) { + foreach ($ids as $id) { + $playlists[] = Playlist::Recall($id); + } + } return $playlists; } - */ /** @@ -1314,7 +1502,7 @@ class StoredFile { if (is_null($indb)) { return FALSE; } - if (BasicStor::GetType($this->gunid) == 'audioclip') { + if ($this->ftype == 'audioclip') { return $this->existsFile(); } return TRUE; @@ -1394,7 +1582,7 @@ class StoredFile { * * @return string */ - function getMime() + public function getMime() { $a = $this->analyzeFile(); if (PEAR::isError($a)) { @@ -1407,6 +1595,20 @@ class StoredFile { } + /** + * Convenience function. + * @return string + */ + public function getTitle() + { + return $this->md["title"]; + } + + public function getType() + { + return $this->ftype; + } + /** * Get storage-internal file state * @@ -1482,8 +1684,8 @@ class StoredFile { public function getFileUrl() { global $CC_CONFIG; - return "http://".$CC_CONFIG["storageUrlHost"].$CC_CONFIG["storageUrlPath"] - ."/stor/".substr($this->gunid, 0, 3)."/{$this->gunid}"; + return "http://".$CC_CONFIG["storageUrlHost"] + ."api/get_media.php?file_id={$this->gunid}"; } /** diff --git a/backend/Transport.php b/backend/Transport.php index 35776f62c..0c33877c8 100644 --- a/backend/Transport.php +++ b/backend/Transport.php @@ -1417,7 +1417,7 @@ class Transport "gunid" => $row['gunid'], "filetype" => "audioclip" ); - $storedFile = $this->gb->bsPutFile($values); + $storedFile = StoredFile::Insert($values); if (PEAR::isError($storedFile)) { $mdtrec->setLock(FALSE); return $storedFile; @@ -1473,7 +1473,7 @@ class Transport "gunid" => $row['gunid'], "filetype" => "playlist" ); - $storedFile = $this->gb->bsPutFile($values); + $storedFile = StoredFile::Insert($values); if (PEAR::isError($storedFile)) { return $storedFile; } diff --git a/backend/tests/AllTests.php b/backend/tests/AllTests.php index 2fb720ed7..30316e933 100644 --- a/backend/tests/AllTests.php +++ b/backend/tests/AllTests.php @@ -1,23 +1,25 @@ addTestSuite("BasicStorTest"); //$suite->addTestSuite("SchedulerTests"); //$suite->addTestSuite("SchedulerExportTests"); -//$suite->addTestSuite("PlayListTests"); +$suite->addTestSuite("PlaylistTests"); $result = PHPUnit::run($suite); echo $result->toString(); -?> \ No newline at end of file +?> diff --git a/backend/tests/PlayListTests.php b/backend/tests/PlaylistTests.php similarity index 81% rename from backend/tests/PlayListTests.php rename to backend/tests/PlaylistTests.php index 742841ae5..7509638a7 100644 --- a/backend/tests/PlayListTests.php +++ b/backend/tests/PlaylistTests.php @@ -10,7 +10,6 @@ Propel::init(dirname(__FILE__)."/../../backend/propel-db/build/conf/campcaster-c // Add the generated 'classes' directory to the include path set_include_path(dirname(__FILE__)."/../../backend/propel-db/build/classes" . PATH_SEPARATOR . get_include_path()); -//require_once(dirname(__FILE__).'/../../conf.php'); require_once('DB.php'); require_once('PHPUnit.php'); @@ -30,7 +29,7 @@ if (PEAR::isError($CC_DBC)) { } $CC_DBC->setFetchMode(DB_FETCHMODE_ASSOC); -class PlayListTests extends PHPUnit_TestCase { +class PlaylistTests extends PHPUnit_TestCase { private $greenbox; @@ -41,11 +40,11 @@ class PlayListTests extends PHPUnit_TestCase { function setup() { global $CC_CONFIG, $CC_DBC; $this->greenbox = new GreenBox(); - + } - + function testGBCreatePlaylist() { - + $pl = new Playlist(); $pl_id = $pl->create("create"); @@ -54,32 +53,32 @@ class PlayListTests extends PHPUnit_TestCase { return; } } - + function testGBLock() { $pl = new Playlist(); $pl_id = $pl->create("lock test"); - + $sessid = Alib::Login('root', 'q'); - + $res = $this->greenbox->lockPlaylistForEdit($pl_id, $sessid); - + if($res !== TRUE) { $this->fail("problems locking playlist for editing."); return; } } - + function testGBUnLock() { $pl = new Playlist(); $pl_id = $pl->create("unlock test"); - + $sessid = Alib::Login('root', 'q'); - + $this->greenbox->lockPlaylistForEdit($pl_id, $sessid); $res = $this->greenbox->releaseLockedPlaylist($pl_id, $sessid); - + if($res !== TRUE) { - $this->fail("problems unlocking playlist."); + $this->fail("problems unlocking playlist."); return; } } @@ -87,66 +86,77 @@ class PlayListTests extends PHPUnit_TestCase { function testGBSetPLMetaData() { $pl = new Playlist(); $pl_id = $pl->create("set meta data test"); - + $res = $this->greenbox->setPLMetadataValue($pl_id, "dc:title", "A Title"); - + if($res !== TRUE) { $this->fail("problems setting playlist metadata."); - return; - } + return; + } } - + function testGBGetPLMetaData() { $pl = new Playlist(); $name = "Testing"; $pl_id = $pl->create($name); - + $res = $this->greenbox->getPLMetadataValue($pl_id, "dc:title"); - + if($res !== $name) { - $this->fail("problems getting playlist metadata."); + $this->fail("problems getting playlist metadata."); return; - } + } } - + function testAddAudioClip() { + // Add a file + $values = array("filepath" => dirname(__FILE__)."/test10001.mp3"); + $this->storedFile = StoredFile::Insert($values, false); + + // Add a file + $values = array("filepath" => dirname(__FILE__)."/test10002.mp3"); + $this->storedFile2 = StoredFile::Insert($values, false); + $pl = new Playlist(); - $pl_id = $pl->create("Add"); - - $res = $this->greenbox->addAudioClipToPlaylist($pl_id, '1'); - + $pl_id = $pl->create("Playlist Unit Test ". uniqid()); + $res = $pl->addAudioClip($this->storedFile->getId()); if($res !== TRUE) { $this->fail("problems adding audioclip to playlist."); - return; - } + return; + } + $res = $pl->addAudioClip($this->storedFile2->getId()); + if($res !== TRUE) { + $this->fail("problems adding audioclip 2 to playlist."); + return; + } } - + function testMoveAudioClip() { $pl = new Playlist(); $pl_id = $pl->create("Move"); - + $this->greenbox->addAudioClipToPlaylist($pl_id, '1'); $this->greenbox->addAudioClipToPlaylist($pl_id, '2'); - + $res = $this->greenbox->moveAudioClipInPlaylist($pl_id, 0, 1); - + if($res !== TRUE) { $this->fail("problems moving audioclip in playlist."); - return; - } - } - + return; + } + } + function testDeleteAudioClip() { $pl = new Playlist(); $pl_id = $pl->create("Delete"); - + $this->greenbox->addAudioClipToPlaylist($pl_id, '1'); $res = $this->greenbox->delAudioClipFromPlaylist($pl_id, 0); - + if($res !== TRUE) { $this->fail("problems deleting audioclip from playlist."); - return; - } + return; + } } function testFadeInfo() { @@ -162,7 +172,6 @@ class PlayListTests extends PHPUnit_TestCase { return; } } - } -?> \ No newline at end of file +?> diff --git a/backend/tests/SchedulerTests.php b/backend/tests/SchedulerTests.php index 0e2eb6efd..bce58d42c 100644 --- a/backend/tests/SchedulerTests.php +++ b/backend/tests/SchedulerTests.php @@ -60,7 +60,7 @@ class SchedulerTests extends PHPUnit_TestCase { function testAddAndRemovePlaylist() { // Create a playlist $playlist = new Playlist(); - $playlist->create("Scheduler Unit Test"); + $playlist->create("Scheduler Unit Test ".uniqid()); $result = $playlist->addAudioClip($this->storedFile->getId()); $result = $playlist->addAudioClip($this->storedFile2->getId()); $result = $playlist->addAudioClip($this->storedFile2->getId()); @@ -76,7 +76,7 @@ class SchedulerTests extends PHPUnit_TestCase { $this->fail("Wrong number of items added."); } $items = $group->getItems(); - if ($items[1]["starts"] != "2010-11-11 01:30:34.231") { + if (!is_array($items) || ($items[1]["starts"] != "2010-11-11 01:30:34.231")) { $this->fail("Wrong start time for 2nd item."); } diff --git a/backend/tests/BasicStorTests.php b/backend/tests/StoredFileTests.php similarity index 82% rename from backend/tests/BasicStorTests.php rename to backend/tests/StoredFileTests.php index af1df3264..327825c76 100644 --- a/backend/tests/BasicStorTests.php +++ b/backend/tests/StoredFileTests.php @@ -1,7 +1,7 @@ setFetchMode(DB_FETCHMODE_ASSOC); -class BasicStorTest extends PHPUnit_TestCase { +class StoredFileTest extends PHPUnit_TestCase { - private $greenbox; - -// function __construct($name) { -// parent::__construct($name); -// } + function __construct($name) { + parent::__construct($name); + } function setup() { - $this->greenbox = new GreenBox(); } function testGetAudioMetadata() { @@ -53,11 +50,13 @@ class BasicStorTest extends PHPUnit_TestCase { } $values = array("filepath" => $filePath); - $storedFile = $this->greenbox->bsPutFile($values, false); + // Insert and link to file, dont copy it + $storedFile = 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)) { $this->fail("StoredFile not created correctly. id = ".$id); diff --git a/htmlUI/ui_base.inc.php b/htmlUI/ui_base.inc.php index 5d1b7c678..b3335b484 100644 --- a/htmlUI/ui_base.inc.php +++ b/htmlUI/ui_base.inc.php @@ -269,7 +269,8 @@ class uiBase $this->id = $this->gb->storId; } if (!is_null($this->id)) { - $this->type = Greenbox::getFileType($this->id); + $f = StoredFile::Recall($this->id); + $this->type = $f->getType(); } } @@ -481,35 +482,35 @@ class uiBase * local ID of file * @param string $format */ - public function analyzeFile($id, $format) - { - $ia = $this->gb->analyzeFile($id, $this->sessid); - $s = $ia['playtime_seconds']; - $extent = date('H:i:s', floor($s)-date('Z')).substr(number_format($s, 6), strpos(number_format($s, 6), '.')); - - if ($format=='text') { - return ""; - } - return FALSE; - } // fn analyzeFile +// public function analyzeFile($id, $format) +// { +// $ia = $this->gb->analyzeFile($id, $this->sessid); +// $s = $ia['playtime_seconds']; +// $extent = date('H:i:s', floor($s)-date('Z')).substr(number_format($s, 6), strpos(number_format($s, 6), '.')); +// +// if ($format=='text') { +// return "".var_export($ia, TRUE).""; +// } +// return FALSE; +// } - public function toHex($gunid) - { - global $CC_DBC; - $res = $CC_DBC->query("SELECT to_hex($gunid)"); - $row = $res->fetchRow(); - return $row['to_hex']; - } +// public function toHex($gunid) +// { +// global $CC_DBC; +// $res = $CC_DBC->query("SELECT to_hex($gunid)"); +// $row = $res->fetchRow(); +// return $row['to_hex']; +// } - public function toInt8($gunid) - { - global $CC_DBC; - $res = $CC_DBC->query("SELECT x'$gunid'::bigint"); - $row = $res->fetchRow(); - return $row['int8']; - } +// public function toInt8($gunid) +// { +// global $CC_DBC; +// $res = $CC_DBC->query("SELECT x'$gunid'::bigint"); +// $row = $res->fetchRow(); +// return $row['int8']; +// } /** @@ -540,17 +541,17 @@ class uiBase public function getMetaInfo($id) { - $type = strtolower(GreenBox::getFileType($id)); - + $media = StoredFile::Recall($id); + $type = strtolower($media->getType()); $data = array('id' => $id, - 'gunid' => BasicStor::GunidFromId($id), - 'title' => $this->getMetadataValue($id, UI_MDATA_KEY_TITLE), - 'creator' => $this->getMetadataValue($id, UI_MDATA_KEY_CREATOR), - 'duration' => $this->getMetadataValue($id, UI_MDATA_KEY_DURATION), + 'gunid' => $media->getGunid(), + 'title' => $media->getMetadataValue($id, UI_MDATA_KEY_TITLE), + 'creator' => $media->getMetadataValue($id, UI_MDATA_KEY_CREATOR), + 'duration' => $media->getMetadataValue($id, UI_MDATA_KEY_DURATION), 'type' => $type, - 'source' => $type == 'audioclip' ? $this->getMetadataValue($id, UI_MDATA_KEY_SOURCE) : NULL, - 'bitRate' => $type == 'audioclip' ? $this->getMetadataValue($id, UI_MDATA_KEY_BITRATE) : NULL, - 'sampleRate' => $type == 'audioclip' ? $this->getMetadataValue($id, UI_MDATA_KEY_SAMPLERATE) : NULL, + 'source' => $type == 'audioclip' ? $media->getMetadataValue($id, UI_MDATA_KEY_SOURCE) : NULL, + 'bitRate' => $type == 'audioclip' ? $media->getMetadataValue($id, UI_MDATA_KEY_BITRATE) : NULL, + 'sampleRate' => $type == 'audioclip' ? $media->getMetadataValue($id, UI_MDATA_KEY_SAMPLERATE) : NULL, ); return ($data); } diff --git a/htmlUI/ui_browser.class.php b/htmlUI/ui_browser.class.php index 02bd35642..ea5461e07 100644 --- a/htmlUI/ui_browser.class.php +++ b/htmlUI/ui_browser.class.php @@ -2,7 +2,6 @@ /** * @package Campcaster * @subpackage htmlUI - */ class uiBrowser extends uiBase { @@ -389,8 +388,8 @@ class uiBrowser extends uiBase { function listen2Audio($clipid) { global $CC_CONFIG; - $id = BasicStor::IdFromGunid($clipid); - $type = Greenbox::getFileType($id); + $media = StoredFile::RecallByGunid($clipid); + $type = $media->getType(); if (1) { header("Location: http://{$_SERVER['SERVER_NAME']}".$CC_CONFIG['accessRawAudioUrl']."?sessid={$this->sessid}&id=$clipid\n"); diff --git a/htmlUI/ui_browser.php b/htmlUI/ui_browser.php index b0e17d0e6..cfa1e6405 100644 --- a/htmlUI/ui_browser.php +++ b/htmlUI/ui_browser.php @@ -137,20 +137,21 @@ if (isset($_REQUEST['popup']) && is_array($_REQUEST['popup'])){ break; case "PL.downloadExportedFile": - $exportedPlaylist = $uiBrowser->gb->exportPlaylistOpen($uiBrowser->sessid, - BasicStor::GunidFromId($_REQUEST['id']), - $_REQUEST['playlisttype'], - $_REQUEST['exporttype']=='playlistOnly'?true:false); - $fp = fopen($exportedPlaylist['fname'],'r'); - if (is_resource($fp)) { - header("Content-Type: application/octet-stream"); - header("Content-Length: " . filesize($exportedPlaylist['fname'])); - header('Content-Disposition: attachment; filename="playlist.tar"'); - header("Content-Transfer-Encoding: binary\n"); - fpassthru($fp); - $uiBrowser->gb->exportPlaylistClose($exportedPlaylist['token']); - } - //$Smarty->display('popup/PLAYLIST.downloadExportedFile.tpl'); + +// $exportedPlaylist = $uiBrowser->gb->exportPlaylistOpen($uiBrowser->sessid, +// BasicStor::GunidFromId($_REQUEST['id']), +// $_REQUEST['playlisttype'], +// $_REQUEST['exporttype']=='playlistOnly'?true:false); +// $fp = fopen($exportedPlaylist['fname'],'r'); +// if (is_resource($fp)) { +// header("Content-Type: application/octet-stream"); +// header("Content-Length: " . filesize($exportedPlaylist['fname'])); +// header('Content-Disposition: attachment; filename="playlist.tar"'); +// header("Content-Transfer-Encoding: binary\n"); +// fpassthru($fp); +// $uiBrowser->gb->exportPlaylistClose($exportedPlaylist['token']); +// } +// //$Smarty->display('popup/PLAYLIST.downloadExportedFile.tpl'); break; case "SCHEDULER.addItem": @@ -354,10 +355,10 @@ if ($uiBrowser->userid) { $Smarty->assign('showFile', TRUE); break; - case "_analyzeFile": - $Smarty->assign('_analyzeFile', $uiBrowser->analyzeFile($uiBrowser->id, 'text')); - $Smarty->assign('showFile', TRUE); - break; +// case "_analyzeFile": +// $Smarty->assign('_analyzeFile', $uiBrowser->analyzeFile($uiBrowser->id, 'text')); +// $Smarty->assign('showFile', TRUE); +// break; case "changeStationPrefs": $Smarty->assign('dynform', $uiBrowser->changeStationPrefs($ui_fmask['stationPrefs'])); diff --git a/htmlUI/ui_handler.class.php b/htmlUI/ui_handler.class.php index 6c6f6b50f..0a82c40e5 100644 --- a/htmlUI/ui_handler.class.php +++ b/htmlUI/ui_handler.class.php @@ -124,7 +124,7 @@ class uiHandler extends uiBase { $metadata['ls:filename'] = basename($audio_file); } - // bsSetMetadataBatch doesnt like these values + // setMetadataBatch doesnt like these values unset($metadata['audio']); unset($metadata['playtime_seconds']); @@ -141,7 +141,7 @@ class uiHandler extends uiBase { die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": ' + $storedFile->getMessage() + '}}'); } - $result = $this->gb->bsSetMetadataBatch($storedFile->getId(), $metadata); + $result = $storedFile->setMetadataBatch($metadata); return $storedFile->getId(); } @@ -263,12 +263,6 @@ class uiHandler extends uiBase { $id = $formdata['id']; $folderId = $formdata['folderId']; - if (Greenbox::getFileType($folderId) != 'Folder') { - $this->_retMsg('The target is not a folder.'); - $this->redirUrl = UI_BROWSER."?act=fileList"; - return FALSE; - } - if (!$this->_validateForm($formdata, $mask)) { $this->redirUrl = UI_BROWSER."?act=editFile&id=".$id; return FALSE; @@ -301,7 +295,7 @@ class uiHandler extends uiBase { $metadata['ls:filename'] = $formdata['mediafile']['name']; } - // bsSetMetadataBatch doesnt like these values + // setMetadataBatch doesnt like these values unset($metadata['audio']); unset($metadata['playtime_seconds']); @@ -326,7 +320,7 @@ class uiHandler extends uiBase { return FALSE; } - $result = $this->gb->bsSetMetadataBatch($storedFile->getId(), $metadata); + $result = $storedFile->setMetadataBatch($metadata); $this->redirUrl = UI_BROWSER."?act=addFileMData&id=".$storedFile->getId(); $this->_retMsg('Audioclip has been uploaded successfully.'); @@ -353,45 +347,45 @@ class uiHandler extends uiBase { * @param unknown_type $langid * @return void */ - function translateMetadata($id, $langid=UI_DEFAULT_LANGID) - { - include(dirname(__FILE__).'/formmask/metadata.inc.php'); - - $ia = $this->gb->analyzeFile($id, $this->sessid); - if (PEAR::isError($ia)) { - $this->_retMsg($ia->getMessage()); - return; - } - // This is really confusing: the import script does not do it - // this way. Which way is the right way? - $this->setMetadataValue($id, UI_MDATA_KEY_DURATION, Playlist::secondsToPlaylistTime($ia['playtime_seconds'])); -// $this->setMetadataValue($id, UI_MDATA_KEY_FORMAT, UI_MDATA_VALUE_FORMAT_FILE); - - // some data from raw audio -// if (isset($ia['audio']['channels'])) { -// $this->setMetadataValue($id, UI_MDATA_KEY_CHANNELS, $ia['audio']['channels']); +// function translateMetadata($id, $langid=UI_DEFAULT_LANGID) +// { +// include(dirname(__FILE__).'/formmask/metadata.inc.php'); +// +// $ia = $this->gb->analyzeFile($id, $this->sessid); +// if (PEAR::isError($ia)) { +// $this->_retMsg($ia->getMessage()); +// return; // } -// if (isset($ia['audio']['sample_rate'])) { -// $this->setMetadataValue($id, UI_MDATA_KEY_SAMPLERATE, $ia['audio']['sample_rate']); +// // This is really confusing: the import script does not do it +// // this way. Which way is the right way? +// $this->setMetadataValue($id, UI_MDATA_KEY_DURATION, Playlist::secondsToPlaylistTime($ia['playtime_seconds'])); +//// $this->setMetadataValue($id, UI_MDATA_KEY_FORMAT, UI_MDATA_VALUE_FORMAT_FILE); +// +// // some data from raw audio +//// if (isset($ia['audio']['channels'])) { +//// $this->setMetadataValue($id, UI_MDATA_KEY_CHANNELS, $ia['audio']['channels']); +//// } +//// if (isset($ia['audio']['sample_rate'])) { +//// $this->setMetadataValue($id, UI_MDATA_KEY_SAMPLERATE, $ia['audio']['sample_rate']); +//// } +//// if (isset($ia['audio']['bitrate'])) { +//// $this->setMetadataValue($id, UI_MDATA_KEY_BITRATE, $ia['audio']['bitrate']); +//// } +//// if (isset($ia['audio']['codec'])) { +//// $this->setMetadataValue($id, UI_MDATA_KEY_ENCODER, $ia['audio']['codec']); +//// } +// +// // from id3 Tags +// // loop main, music, talk +// foreach ($mask['pages'] as $key => $val) { +// // loop through elements +// foreach ($mask['pages'][$key] as $k => $v) { +// if (isset($v['element']) && isset($ia[$v['element']])) { +// $this->setMetadataValue($id, $v['element'], $ia[$v['element']], $langid); +// } +// } // } -// if (isset($ia['audio']['bitrate'])) { -// $this->setMetadataValue($id, UI_MDATA_KEY_BITRATE, $ia['audio']['bitrate']); -// } -// if (isset($ia['audio']['codec'])) { -// $this->setMetadataValue($id, UI_MDATA_KEY_ENCODER, $ia['audio']['codec']); -// } - - // from id3 Tags - // loop main, music, talk - foreach ($mask['pages'] as $key => $val) { - // loop through elements - foreach ($mask['pages'][$key] as $k => $v) { - if (isset($v['element']) && isset($ia[$v['element']])) { - $this->setMetadataValue($id, $v['element'], $ia[$v['element']], $langid); - } - } - } - } +// } /** @@ -403,13 +397,8 @@ class uiHandler extends uiBase { function addWebstream($formdata, $mask) { $id = $formdata['id']; - $folderId = $formdata['folderId']; + //$folderId = $formdata['folderId']; - if (Greenbox::getFileType($folderId) != 'Folder') { - $this->_retMsg ('The target is not a folder.'); - $this->redirUrl = UI_BROWSER."?act=fileList"; - return FALSE; - } if (!$this->_validateForm($formdata, $mask)) { $this->redirUrl = UI_BROWSER."?act=editWebstream&id=".$id; return FALSE; @@ -534,16 +523,13 @@ class uiHandler extends uiBase { } foreach ($ids as $id) { - if (Greenbox::getFileType($id) == 'playlist') { - $r = $this->gb->deletePlaylist($id, $this->sessid); - } else { - $r = $this->gb->deleteFile($id, $this->sessid); - } + $media = StoredFile::Recall($id); + $r = $media->delete(); - if (PEAR::isError($r)) { - $this->_retMsg($r->getMessage()); - return FALSE; - } + if (PEAR::isError($r)) { + $this->_retMsg($r->getMessage()); + return FALSE; + } } return TRUE; diff --git a/htmlUI/ui_playlist.class.php b/htmlUI/ui_playlist.class.php index 7b1de5c35..7be533bbe 100644 --- a/htmlUI/ui_playlist.class.php +++ b/htmlUI/ui_playlist.class.php @@ -11,7 +11,7 @@ class uiPlaylist public $activeId; public $title; public $duration; - + private $Base; private $reloadUrl; private $redirectUrl; @@ -33,10 +33,10 @@ class uiPlaylist public function setReload($url=NULL) { if($url) - $this->Base->redirUrl = $url; + $this->Base->redirUrl = $url; else $this->Base->redirUrl = $this->reloadUrl; - + } // fn setReload @@ -65,7 +65,7 @@ class uiPlaylist public function getActiveArr() - { + { if (!$this->activeId) { return FALSE; } @@ -91,7 +91,7 @@ class uiPlaylist if ($this->activeId) { $this->release(); } - + $userid = $this->Base->gb->playlistIsAvailable($plid, $this->Base->sessid); if ($userid !== TRUE) { if (UI_WARNING) { @@ -107,10 +107,10 @@ class uiPlaylist $this->Base->_retMsg('Unable to open playlist "$1".', $this->Base->getMetadataValue($plid, UI_MDATA_KEY_TITLE)); return FALSE; } - + $this->Base->gb->savePref($this->Base->sessid, UI_PL_ACCESSTOKEN_KEY, $plid); $this->activeId = $plid; - + if ($msg && UI_VERBOSE) { $this->Base->_retMsg('Playlist "$1" opened.', $this->Base->getMetadataValue($plid, UI_MDATA_KEY_TITLE)); } @@ -120,7 +120,7 @@ class uiPlaylist public function release($msg=TRUE) - { + { // release PL // delete PL from session if (!$this->activeId) { @@ -139,12 +139,9 @@ class uiPlaylist } return FALSE; } - if ($msg && UI_VERBOSE) { - $this->Base->_retMsg('Playlist "$1" released.', $this->Base->getMetadataValue(BasicStor::IdFromGunid($plgunid), UI_MDATA_KEY_TITLE)); - } $this->activeId = NULL; $this->Base->gb->delPref($this->Base->sessid, UI_PL_ACCESSTOKEN_KEY); - + return TRUE; } // fn release @@ -164,16 +161,16 @@ class uiPlaylist public function loadLookedFromPref() { if (is_string($plid = $this->Base->gb->loadPref($this->Base->sessid, UI_PL_ACCESSTOKEN_KEY))) { - + if (!$this->Base->gb->existsPlaylist($plid)) { $this->Base->gb->delPref($this->Base->sessid, UI_PL_ACCESSTOKEN_KEY); $this->Base->_retMsg('Playlist not found in database.'); $this->Base->redirUrl = UI_BROWSER.'?popup[]=_2PL.simpleManagement&popup[]=_close'; return FALSE; } - + $this->activeId = $plid; - + $this->Base->redirUrl = UI_BROWSER.'?popup[]=_2PL.simpleManagement&popup[]=_close'; return TRUE; } @@ -195,7 +192,7 @@ class uiPlaylist $cliplength = NULL; $cueIn = NULL; $cueIn = NULL; - + /* gstreamer bug: Warning: The clipEnd can't be bigger than ninety nine percent (99%) of the clipLength, @@ -208,14 +205,14 @@ class uiPlaylist $this->Base->_retMsg('No item(s) selected.'); } return FALSE; - } + } if (!is_array($elemIds)) { $elemIds = array($elemIds); - } + } if (isset($duration)) { $length = sprintf('%02d', $duration['H']).':'.sprintf('%02d', $duration['i']).':'.sprintf('%02d', $duration['s']).'.000000'; } - + foreach ($elemIds as $elemId) { $r = $this->Base->gb->addAudioClipToPlaylist($this->activeId, $elemId, $pos, $fadeIn, $fadeOut, $cliplength, $cueIn, $cueOut); if (PEAR::isError($r)) { @@ -226,9 +223,9 @@ class uiPlaylist return FALSE; } } - + $this->Base->SCRATCHPAD->reloadActivePLMetadata($this->activeId); - + return TRUE; } // fn addItem @@ -243,20 +240,20 @@ class uiPlaylist } if (!is_array($positions)) $positions = array($positions); - + //so the automatic updating of playlist positioning doesn't affect removal. sort($positions); $positions = array_reverse($positions); - + foreach ($positions as $pos) { if ($this->Base->gb->delAudioClipFromPlaylist($this->activeId, $pos) !== TRUE) { $this->Base->_retMsg('Cannot remove item from playlist.'); return FALSE; } } - + $this->Base->SCRATCHPAD->reloadActivePLMetadata($this->activeId); - + return TRUE; } // fn removeItem @@ -274,14 +271,14 @@ class uiPlaylist // create PL // activate // add clip if $id is set - + if ($this->activeId) { $this->release(); } - + $datetime = strftime('%Y-%m-%d %H:%M:%S'); $plid = $this->Base->gb->createPlaylist($datetime, $this->Base->sessid); - + if (!$plid) { $this->Base->_retMsg('Cannot create playlist.'); return FALSE; @@ -290,7 +287,7 @@ class uiPlaylist $this->Base->gb->setPLMetadataValue($plid, UI_MDATA_KEY_CREATOR, $this->Base->login); $this->Base->gb->setPLMetadataValue($plid, UI_MDATA_KEY_DESCRIPTION, tra('created at $1', $datetime)); - + if ($this->activate($plid)===FALSE) { $this->Base->_retMsg('Cannot activate playlist.'); return FALSE; @@ -300,14 +297,14 @@ class uiPlaylist return FALSE; } } - + return $plid; } // fn create public function moveItem($oldPos, $newPos) { $response = array(); - + $r = $this->Base->gb->moveAudioClipInPlaylist($this->activeId, $oldPos, $newPos); if (PEAR::isError($r) || $r === FALSE) { $response["error"] = "Failed to Move file."; @@ -315,9 +312,9 @@ class uiPlaylist $response["newPos"] = $newPos; } else{ - $response["error"] = FALSE; + $response["error"] = FALSE; } - + die(json_encode($response)); } // fn moveItem @@ -325,22 +322,22 @@ class uiPlaylist public function setClipLength($pos, $cueIn, $cueOut) { $response = array(); - + $res = $this->Base->gb->changeClipLength($this->activeId, $pos, $cueIn, $cueOut); $response = $res; - + die(json_encode($response)); } - + public function setFadeLength($pos, $fadeIn, $fadeOut) { $response = array(); - + $res = $this->Base->gb->changeFadeInfo($this->activeId, $pos, $fadeIn, $fadeOut); - + $response = $res; - + die(json_encode($response)); } // fn setFade @@ -353,7 +350,7 @@ class uiPlaylist foreach ($mask['playlist'] as $k=>$v) { $mask['playlist'][$k]['element'] = uiBase::formElementEncode($v['element']); - + $getval = $this->Base->gb->getPLMetadataValue($id, $v['element'], $langid); if ($getval) { $mask['playlist'][$k]['default'] = $getval; @@ -398,9 +395,9 @@ class uiPlaylist } else { $this->Base->redirUrl = UI_BROWSER."?act=PL.editMetaData&id=$id&curr_langid=".$formdata['target_langid']; } - + foreach ($mask['playlist'] as $k=>$v) { - + $formdata[uiBase::formElementEncode($v['element'])] ? $mData[uiBase::formElementDecode($v['element'])] = $formdata[uiBase::formElementEncode($v['element'])] : NULL; } @@ -419,7 +416,7 @@ class uiPlaylist } if (UI_VERBOSE) { $this->Base->_retMsg('Metadata saved.'); - } + } $this->Base->SCRATCHPAD->reloadMetadata(); } // fn editMetadata @@ -429,7 +426,7 @@ class uiPlaylist { $id = $this->activeId; $this->release(FALSE); - + $res = $this->Base->gb->deletePlaylist($id); if ($res === TRUE) { return $id; @@ -438,7 +435,7 @@ class uiPlaylist $this->Base->_retMsg('Cannot delete this playlist.'); return FALSE; } // fn deleteActive - + public function delete($id) { $res = $this->Base->gb->deletePlaylist($id); diff --git a/htmlUI/ui_scheduler.class.php b/htmlUI/ui_scheduler.class.php index e2cb4d5a2..d317d7f6d 100644 --- a/htmlUI/ui_scheduler.class.php +++ b/htmlUI/ui_scheduler.class.php @@ -209,7 +209,7 @@ class uiScheduler extends uiCalendar { // $hour = $arr['hour']; // $minute = $arr['minute']; // $second = $arr['second']; - + extract($arr); if (isset($today)) { @@ -456,25 +456,6 @@ class uiScheduler extends uiCalendar { return $items; } // fn getDayEntrys - /* - function getDayHourlyEntrys($year, $month, $day) - { - $date = $year.'-'.$month.'-'.$day; - $arr = $this->displayScheduleMethod($date.' 00:00:00', $date.' 23:59:59.999999'); - if (!count($arr)) - return FALSE; - foreach ($arr as $key => $val) { - $items[date('H', self::datetimeToTimestamp($val['start']))][]= array ( - 'start' => substr($val['start'], strpos($val['start'], 'T')+1), - 'end' => substr($val['end'], strpos($val['end'], 'T') + 1), - 'title' => $this->Base->getMetadataValue(BasicStor::IdFromGunid($val['playlistId']), UI_MDATA_KEY_TITLE), - 'creator' => $this->Base->getMetadataValue(BasicStor::IdFromGunid($val['playlistId']), UI_MDATA_KEY_CREATOR), - ); - } - #print_r($items); - return $items; - } - */ private function getDayUsage($year, $month, $day) { @@ -487,11 +468,12 @@ class uiScheduler extends uiCalendar { } foreach ($arr as $key => $val) { - $id = BasicStor::IdFromGunid($val['playlistId']); - $arr[$key]['title'] = $this->Base->getMetadataValue($id, UI_MDATA_KEY_TITLE); - $arr[$key]['creator'] = $this->Base->getMetadataValue($id, UI_MDATA_KEY_CREATOR); - $arr[$key]['pos'] = self::datetimeToTimestamp($val['start']); - $arr[$key]['span'] = date('H', self::datetimeToTimestamp($val['end'])) - date('H', self::datetimeToTimestamp($val['start'])) +1; + $pl = Playlist::Recall($val['playlistId']); + //$id = BasicStor::IdFromGunid($val['playlistId']); + $arr[$key]['title'] = $pl->getName(); //$this->Base->getMetadataValue($id, UI_MDATA_KEY_TITLE); + $arr[$key]['creator'] = $pl->getPLMetaData("dc:title");// $this->Base->getMetadataValue($id, UI_MDATA_KEY_CREATOR); + $arr[$key]['pos'] = self::datetimeToTimestamp($val['start']); + $arr[$key]['span'] = date('H', self::datetimeToTimestamp($val['end'])) - date('H', self::datetimeToTimestamp($val['start'])) +1; } return $arr; } // fn getDayUsage @@ -595,7 +577,7 @@ class uiScheduler extends uiCalendar { } return TRUE; - } // fn copyPlfromSP + } /** @@ -707,22 +689,27 @@ class uiScheduler extends uiCalendar { { // just use methods which work without valid authentification $c_pl = self::getScheduledPlaylist(); + $pl = Playlist::Recall($c_pl['playlistId']); + $n_clip = null; if ($c_clip = $this->getClipFromCurrent($c_pl, 0)) { $n_clip = $this->getClipFromCurrent($c_pl, 1); } + $nextClip = StoredFile::Recall($n_clip); $u_clip = null; $u_pl_start = null; if ($u_pl = self::getScheduledPlaylist(2)) { $u_clip = $this->getClipFromPlaylist($u_pl); $u_pl_start = explode(':', date('H:i:s', self::datetimeToTimestamp($u_pl['start']))); } + $upcomingClip = StoredFile::Recall($u_pl['playlistId']); return array( 'current' => $c_clip ? 1 : 0, 'current.title' => addcslashes($c_clip['title'], "'"), - 'current.pltitle' => addcslashes($this->Base->getMetadataValue(BasicStor::IdFromGunid($c_pl['playlistId']), UI_MDATA_KEY_TITLE), "'"), - 'current.elapsed.h' => $c_clip['elapsed']['h'], + //'current.pltitle' => addcslashes($this->Base->getMetadataValue(BasicStor::IdFromGunid($c_pl['playlistId']), UI_MDATA_KEY_TITLE), "'"), + 'current.pltitle' => addcslashes($pl->getName(), "'"), + 'current.elapsed.h' => $c_clip['elapsed']['h'], 'current.elapsed.m' => $c_clip['elapsed']['m'], 'current.elapsed.s' => $c_clip['elapsed']['s'], 'current.duration.h' => $c_clip['duration']['h'], @@ -731,15 +718,17 @@ class uiScheduler extends uiCalendar { 'next' => $n_clip ? 1 : 0, 'next.title' => $n_clip ? addcslashes($n_clip['title'], "'") : "", - 'next.pltitle' => addcslashes($this->Base->getMetadataValue($n_clip, UI_MDATA_KEY_TITLE), "'"), - 'next.duration.h' => $n_clip ? $n_clip['duration']['h'] : 0, + //'next.pltitle' => addcslashes($this->Base->getMetadataValue($n_clip, UI_MDATA_KEY_TITLE), "'"), + 'next.pltitle' => addcslashes($nextClip->getTitle(), "'"), + 'next.duration.h' => $n_clip ? $n_clip['duration']['h'] : 0, 'next.duration.m' => $n_clip ? $n_clip['duration']['m'] : 0, 'next.duration.s' => $n_clip ? $n_clip['duration']['s'] : 0, 'upcoming' => $u_pl ? 1 : 0, 'upcoming.title' => addcslashes($u_clip['title'], "'"), - 'upcoming.pltitle' => addcslashes($this->Base->getMetadataValue(BasicStor::IdFromGunid($u_pl['playlistId']), UI_MDATA_KEY_TITLE), "'"), - 'upcoming.duration.h' => $u_clip['duration']['h'], + //'upcoming.pltitle' => addcslashes($this->Base->getMetadataValue(BasicStor::IdFromGunid($u_pl['playlistId']), UI_MDATA_KEY_TITLE), "'"), + 'upcoming.pltitle' => addcslashes($upcomingClip->getName(), "'"), + 'upcoming.duration.h' => $u_clip['duration']['h'], 'upcoming.duration.m' => $u_clip['duration']['m'], 'upcoming.duration.s' => $u_clip['duration']['s'], 'upcoming.plstart.h' => $u_pl_start[0], diff --git a/htmlUI/ui_scratchpad.class.php b/htmlUI/ui_scratchpad.class.php index 44e26a468..23e261393 100644 --- a/htmlUI/ui_scratchpad.class.php +++ b/htmlUI/ui_scratchpad.class.php @@ -77,12 +77,12 @@ class uiScratchPad // get the scratchpad list $arr = explode(' ', $spData); $maxLength = $this->Base->STATIONPREFS[UI_SCRATCHPAD_MAXLENGTH_KEY]; - $arr = array_slice($arr, 0, $maxLength); + $arr = array_slice($arr, 0, $maxLength); foreach ($arr as $item) { //for audiofiles. list($type, $savedId) = explode(":", $item); - - if($type === 'pl') { + + if($type === 'pl') { $id = $savedId; if ($i = $this->Base->getPLMetaInfo($id)) { $this->items[] = $i; @@ -91,9 +91,10 @@ class uiScratchPad else { $gunid = $savedId; if (preg_match('/[0-9]{1,20}/', $gunid)) { - $id = BasicStor::IdFromGunid($this->Base->toHex($gunid)); - if ($id != FALSE) { - if ($i = $this->Base->getMetaInfo($id)) { + $f = StoredFile::RecallByGunid($gunid); + //$id = BasicStor::IdFromGunid($this->Base->toHex($gunid)); + if (!PEAR::isError($f)) { + if ($i = $this->Base->getMetaInfo($f->getId())) { $this->items[] = $i; } } @@ -115,7 +116,7 @@ class uiScratchPad $str .= 'pl:'.$val['id'].' '; } else { - $str .= 'ac:'.$this->Base->toInt8($val['gunid']).' '; + $str .= 'ac:'.$val['gunid'].' '; } } $this->Base->gb->savePref($this->Base->sessid, UI_SCRATCHPAD_KEY, $str); @@ -264,7 +265,7 @@ class uiScratchPad $this->items[$key] = $this->Base->getMetaInfo($val['id']); } } - + public function reloadActivePLMetadata($id) { foreach ($this->items as $key => $val) { @@ -274,6 +275,6 @@ class uiScratchPad } } } - + } // class uiScratchPad ?> diff --git a/htmlUI/ui_transfers.class.php b/htmlUI/ui_transfers.class.php index 92c44c301..c5696e226 100644 --- a/htmlUI/ui_transfers.class.php +++ b/htmlUI/ui_transfers.class.php @@ -155,8 +155,9 @@ class uiTransfers function upload2Hub($id) { - $gunid = BasicStor::GunidFromId($id); - $type = BasicStor::GetType($gunid); + $media = StoredFile::Recall($id); + $gunid = $media->getGunid(); + $type = $media->getType(); switch ($type) { case 'audioClip': diff --git a/htmlUI/ui_twitter.class.php b/htmlUI/ui_twitter.class.php index 506fc5cf9..8955f3393 100644 --- a/htmlUI/ui_twitter.class.php +++ b/htmlUI/ui_twitter.class.php @@ -365,10 +365,12 @@ class uiTwitter { return FALSE; } + $f = StoredFile::RecallByGunid($clip['gunid']); + $pl = Playlist::Recall($pl['playlistId']); return array( - 'tracktitle' => $this->Base->gb->getMetadataValue(BasicStor::IdFromGunid($clip['gunid']), UI_MDATA_KEY_TITLE, $this->Base->sessid), - 'trackartist' => $this->Base->gb->getMetadataValue(BasicStor::IdFromGunid($clip['gunid']), UI_MDATA_KEY_CREATOR, $this->Base->sessid), - 'playlisttitle' => $this->Base->gb->getMetadataValue(BasicStor::IdFromGunid($pl['playlistId']), UI_MDATA_KEY_TITLE, $this->Base->sessid), + 'tracktitle' => $f->getMetadataValue(UI_MDATA_KEY_TITLE), //$this->Base->gb->getMetadataValue(BasicStor::IdFromGunid($clip['gunid']), UI_MDATA_KEY_TITLE, $this->Base->sessid), + 'trackartist' => $f->getMetadataValue(UI_MDATA_KEY_CREATOR), // $this->Base->gb->getMetadataValue(BasicStor::IdFromGunid($clip['gunid']), UI_MDATA_KEY_CREATOR, $this->Base->sessid), + 'playlisttitle' => $pl->getName() //$this->Base->gb->getMetadataValue(BasicStor::IdFromGunid($pl['playlistId']), UI_MDATA_KEY_TITLE, $this->Base->sessid), ); } diff --git a/utils/campcaster-backup.php b/utils/campcaster-backup.php index 71c1cc89d..9443f60c5 100644 --- a/utils/campcaster-backup.php +++ b/utils/campcaster-backup.php @@ -26,16 +26,9 @@ function admDumpFolder(&$bs, $fid, $ind='') // echo $name->getMessage(); // exit; // } - $type = BasicStor::GetObjType($fid); - if (PEAR::isError($type)) { - echo $type->getMessage(); - exit; - } - $gunid = BasicStor::GunidFromId($fid); - if (PEAR::isError($gunid)) { - echo $gunid->getMessage(); - exit; - } + $media = StoredFile::Recall($fid); + $type = $media->getType(); + $gunid = $media->getGunid(); $pars = array(); if ($gunid) { $pars['id']="$gunid"; diff --git a/utils/campcaster-import.php b/utils/campcaster-import.php index e4e0f5d67..05459acb1 100644 --- a/utils/campcaster-import.php +++ b/utils/campcaster-import.php @@ -209,9 +209,9 @@ function camp_import_audio_file($p_filepath, $p_importMode = null, $p_testOnly = "filepath" => $p_filepath, "md5" => $md5sum, ); - $storedFile = $greenbox->bsPutFile($values, $doCopyFiles); + $storedFile = StoredFile::Insert($values, $doCopyFiles); if (PEAR::isError($storedFile)) { - import_err($storedFile, "Error in bsPutFile()"); + import_err($storedFile, "Error in StoredFile::Insert()"); echo var_export($metadata)."\n"; return; } diff --git a/utils/restore.php b/utils/restore.php index 0e70ee7e5..cb2b266bb 100644 --- a/utils/restore.php +++ b/utils/restore.php @@ -70,7 +70,7 @@ function ls_restore_restoreObject($obj, /*$parid,*/ $reallyInsert=TRUE){ "gunid" => $obj['gunid'], "filetype" => strtolower($obj['type']) ); - $r = $bs->bsPutFile($values); + $r = StoredFile::Insert($values); ls_restore_checkErr($r, __LINE__); } break;".var_export($ia, TRUE)."