From 8014f94c581bfa0c96f0c367b6dd6ef4f2fcdbea Mon Sep 17 00:00:00 2001 From: "paul.baranowski" Date: Thu, 18 Nov 2010 14:39:03 -0500 Subject: [PATCH] Fixed whitespace to standard coding conventions. --- api/schedule.php | 10 +- backend/AccessRecur.php | 90 +- backend/Alib.php | 262 +- backend/Backup.php | 90 +- backend/BasicStor.php | 1984 +++++++------- backend/GreenBox.php | 2432 ++++++++--------- backend/LocStor.php | 562 ++-- backend/Playlist.php | 791 +++--- backend/Prefs.php | 73 +- backend/Renderer.php | 76 +- backend/Restore.php | 180 +- backend/Schedule.php | 717 ++--- backend/SmilPlaylist.php | 74 +- backend/StoredFile.php | 896 +++--- backend/Transport.php | 1348 ++++----- backend/TransportRecord.php | 44 +- backend/Validator.php | 52 +- backend/XmlParser.php | 60 +- .../classes/campcaster/CcPlaylistcontents.php | 47 +- .../build/classes/campcaster/Common.php | 30 +- backend/xmlrpc/xrLocStor.php | 8 +- htmlUI/Input.php | 302 +- htmlUI/twitter.class.php | 107 +- htmlUI/ui_base.inc.php | 135 +- htmlUI/ui_browse.class.php | 78 +- htmlUI/ui_handler.class.php | 442 +-- htmlUI/ui_handler.php | 694 ++--- htmlUI/ui_playlist.class.php | 72 +- htmlUI/ui_scratchpad.class.php | 94 +- htmlUI/ui_subjects.class.php | 32 +- install/install.php | 62 +- install/installInit.php | 12 +- utils/CleanStor.php | 84 +- utils/campcaster-backup.php | 162 +- utils/campcaster-import.php | 40 +- 35 files changed, 6072 insertions(+), 6070 deletions(-) diff --git a/api/schedule.php b/api/schedule.php index 14f9247bf..a004d57ca 100644 --- a/api/schedule.php +++ b/api/schedule.php @@ -6,17 +6,17 @@ require_once('../backend/Schedule.php'); $api_key = $_GET['api_key']; if(!in_array($api_key, $CC_CONFIG["apiKey"])) { - header('HTTP/1.0 401 Unauthorized'); - print 'You are not allowed to access this resource.'; - exit; + header('HTTP/1.0 401 Unauthorized'); + print 'You are not allowed to access this resource.'; + exit; } PEAR::setErrorHandling(PEAR_ERROR_RETURN); $CC_DBC = DB::connect($CC_CONFIG['dsn'], TRUE); if (PEAR::isError($CC_DBC)) { - echo "ERROR: ".$CC_DBC->getMessage()." ".$CC_DBC->getUserInfo()."\n"; - exit(1); + echo "ERROR: ".$CC_DBC->getMessage()." ".$CC_DBC->getUserInfo()."\n"; + exit(1); } $CC_DBC->setFetchMode(DB_FETCHMODE_ASSOC); $from = $_GET["from"]; diff --git a/backend/AccessRecur.php b/backend/AccessRecur.php index 6e0fd7931..ae78c8807 100644 --- a/backend/AccessRecur.php +++ b/backend/AccessRecur.php @@ -26,22 +26,22 @@ class AccessRecur { $ppa = new AccessRecur($ls, $sessid); $r = $ls->accessPlaylist($sessid, $plid, FALSE, $parent); if (PEAR::isError($r)) { - return $r; + return $r; } $plRes = $r; $r = StoredFile::RecallByGunid($plid); if (is_null($r) || PEAR::isError($r)) { - return $r; + return $r; } $ac = $r; $r = $ac->md->genPhpArray(); if (PEAR::isError($r)) { - return $r; + return $r; } $pla = $r; $r = $ppa->processPlaylist($pla, $plRes['token']); if (PEAR::isError($r)) { - return $r; + return $r; } $plRes['content'] = $r; return $plRes; @@ -58,14 +58,14 @@ class AccessRecur { WHERE parent=x'{$token}'::bigint "); if (PEAR::isError($r)) { - return $r; + return $r; } $arr = $r; foreach ($arr as $i => $item) { extract($item); // token2, gunid $r = BasicStor::GetType($gunid); if (PEAR::isError($r)) { - return $r; + return $r; } $ftype = $r; # echo "$ftype/$token2\n"; @@ -73,23 +73,23 @@ class AccessRecur { case "audioclip": $r = $ppa->ls->releaseRawAudioData($ppa->sessid, $token2); if (PEAR::isError($r)) { - return $r; + return $r; } # var_dump($r); - break; + break; case "playlist": $r = $ppa->releasePlaylist($ppa->ls, $ppa->sessid, $token2); if (PEAR::isError($r)) { - return $r; + return $r; } # var_dump($r); - break; + break; default: } } $r = $ppa->ls->releasePlaylist($ppa->sessid, $token, FALSE); if (PEAR::isError($r)) { - return $r; + return $r; } return $r; } @@ -103,11 +103,11 @@ class AccessRecur { case "playlistElement": $r = $this->processPlaylistElement($ple, $parent); if (PEAR::isError($r)) { - return $r; + return $r; } // $res = array_merge($res, $r); $res[] = $r; - break; + break; default: } } @@ -119,7 +119,7 @@ class AccessRecur { { $r = $this->ls->accessRawAudioData($this->sessid, $gunid, $parent); if (PEAR::isError($r)) { - return $r; + return $r; } return $r; } @@ -132,48 +132,48 @@ class AccessRecur { case "audioClip": $r = $this->processAudioClip($ac['attrs']['id'], $parent); if (PEAR::isError($r)) { - return $r; + return $r; } return $r; case "playlist": -// if(empty($ac['children'])){ - $r = $this->accessPlaylist($this->ls, $this->sessid, - $ac['attrs']['id'], $parent); - if (PEAR::isError($r)) { - if ($r->getCode() != GBERR_NOTF) { - return $r; - } else { - $r = $this->processPlaylist($ac, $parent); - if (PEAR::isError($r)) { - return $r; - } - $r = array( + // if(empty($ac['children'])){ + $r = $this->accessPlaylist($this->ls, $this->sessid, + $ac['attrs']['id'], $parent); + if (PEAR::isError($r)) { + if ($r->getCode() != GBERR_NOTF) { + return $r; + } else { + $r = $this->processPlaylist($ac, $parent); + if (PEAR::isError($r)) { + return $r; + } + $r = array( 'content' => $r, 'url' => NULL, 'token' => NULL, 'chsum' => NULL, 'size' => NULL, 'warning' => 'inline playlist?', - ); - } + ); } - return $r; -/* - }else{ - $r = $this->processPlaylist($ac, $parent); - if(PEAR::isError($r)) return $r; - $res = array( - 'content' => $r, - 'url' => NULL, - 'token' => NULL, - 'chsum' => NULL, - 'size' => NULL, - 'warning' => 'inline playlist', - ); - return $res; } -*/ - break; + return $r; + /* + }else{ + $r = $this->processPlaylist($ac, $parent); + if(PEAR::isError($r)) return $r; + $res = array( + 'content' => $r, + 'url' => NULL, + 'token' => NULL, + 'chsum' => NULL, + 'size' => NULL, + 'warning' => 'inline playlist', + ); + return $res; + } + */ + break; default: } } diff --git a/backend/Alib.php b/backend/Alib.php index 8fa7c51a9..b9e16d6ca 100644 --- a/backend/Alib.php +++ b/backend/Alib.php @@ -38,7 +38,7 @@ class Alib { } $userid = Subjects::GetSubjId($login); $sql = "INSERT INTO ".$CC_CONFIG['sessTable']." (sessid, userid, login, ts)" - ." VALUES('$sessid', '$userid', '$login', now())"; + ." VALUES('$sessid', '$userid', '$login', now())"; $r = $CC_DBC->query($sql); if (PEAR::isError($r)) { return $r; @@ -60,12 +60,12 @@ class Alib { $ct = Alib::CheckAuthToken($sessid); if ($ct === FALSE) { return PEAR::raiseError("Alib::logout: not logged ($sessid)", - ALIBERR_NOTLOGGED, PEAR_ERROR_RETURN); + ALIBERR_NOTLOGGED, PEAR_ERROR_RETURN); } elseif (PEAR::isError($ct)) { return $ct; } else { $sql = "DELETE FROM ".$CC_CONFIG['sessTable'] - ." WHERE sessid='$sessid'"; + ." WHERE sessid='$sessid'"; $r = $CC_DBC->query($sql); if (PEAR::isError($r)) { return $r; @@ -85,7 +85,7 @@ class Alib { { global $CC_CONFIG, $CC_DBC; $sql = "SELECT count(*) as cnt FROM ".$CC_CONFIG['sessTable'] - ." WHERE sessid='$sessid'"; + ." WHERE sessid='$sessid'"; $c = $CC_DBC->getOne($sql); return ($c == 1 ? TRUE : (PEAR::isError($c) ? $c : FALSE )); } //fn checkAuthToken @@ -97,18 +97,18 @@ class Alib { * @param string $sessid * @return TRUE|PEAR_Error */ -// public function setAuthToken($sessid) -// { -// $r = $this->checkAuthToken($sessid); -// if (PEAR::isError($r)) { -// return $r; -// } -// if (!$r) { -// return PEAR::raiseError("ALib::setAuthToken: invalid token ($sessid)"); -// } -// //$this->sessid = $sessid; -// return TRUE; -// } // fn setAuthToken + // public function setAuthToken($sessid) + // { + // $r = $this->checkAuthToken($sessid); + // if (PEAR::isError($r)) { + // return $r; + // } + // if (!$r) { + // return PEAR::raiseError("ALib::setAuthToken: invalid token ($sessid)"); + // } + // //$this->sessid = $sessid; + // return TRUE; + // } // fn setAuthToken /* -------------------------------------------------------- authorization */ @@ -130,7 +130,7 @@ class Alib { global $CC_CONFIG, $CC_DBC; $permid = $CC_DBC->nextId($CC_CONFIG['permSequence']); $sql = "INSERT INTO ".$CC_CONFIG['permTable']." (permid, subj, action, obj, type)" - ." VALUES ($permid, $sid, '$action', $oid, '$type')"; + ." VALUES ($permid, $sid, '$action', $oid, '$type')"; $r = $CC_DBC->query($sql); if (PEAR::isError($r)) { return($r); @@ -213,85 +213,85 @@ class Alib { */ public static function CheckPerm($sid, $action, $oid=NULL) { - return TRUE; -// global $CC_DBC; -// global $CC_CONFIG; -// if (!is_numeric($sid)) { -// return FALSE; -// } -//// if (is_null($oid) or $oid=='') { -//// $oid = M2tree::GetRootNode(); -//// } -//// if (PEAR::isError($oid)) { -//// return $oid; -//// } -// if (!is_numeric($oid)) { -// return FALSE; -// } -// // query construction -// // shortcuts: -// // p: permTable, -// // s: subjTable, m smembTable, -// // t: treeTable ts: structTable, -// // c: classTable, cm: cmembTable -// // main query elements: -// $q_flds = "m.level , p.subj, s.login, action, p.type, p.obj"; -// $q_from = $CC_CONFIG['permTable']." p "; -// // joins for solving users/groups: -// $q_join = "LEFT JOIN ".$CC_CONFIG['subjTable']." s ON s.id=p.subj "; -// $q_join .= "LEFT JOIN ".$CC_CONFIG['smembTable']." m ON m.gid=p.subj "; -// $q_cond = "p.action in('_all', '$action') AND -// (s.id=$sid OR m.uid=$sid) "; -// // coalesce -1 for higher priority of nongroup rows: -// // action DESC order for lower priority of '_all': -// $q_ordb = "ORDER BY coalesce(m.level,-1), action DESC, p.type DESC"; -// $q_flds0 = $q_flds; -// $q_from0 = $q_from; -// $q_join0 = $q_join; -// $q_cond0 = $q_cond; -// $q_ordb0 = $q_ordb; -// // joins for solving object tree: -// $q_flds .= ", t.name, ts.level as tlevel"; -// //$q_join .= "LEFT JOIN ".$CC_CONFIG['treeTable']." t ON t.id=p.obj "; -// //$q_join .= "LEFT JOIN ".$CC_CONFIG['structTable']." ts ON ts.parid=p.obj "; -// //$q_cond .= " AND (t.id=$oid OR ts.objid=$oid)"; -// // action DESC order is hack for lower priority of '_all': -// $q_ordb = "ORDER BY coalesce(ts.level,0), m.level, action DESC, p.type DESC"; -// // query by tree: -// $query1 = "SELECT $q_flds FROM $q_from $q_join WHERE $q_cond $q_ordb"; -// $r1 = $CC_DBC->getAll($query1); -// if (PEAR::isError($r1)) { -// return($r1); -// } -// // if there is row with type='A' on the top => permit -// //$AllowedByTree = -// // (is_array($r1) && count($r1)>0 && $r1[0]['type']=='A'); -// //$DeniedByTree = -// // (is_array($r1) && count($r1)>0 && $r1[0]['type']=='D'); -// -// if (!USE_ALIB_CLASSES) { -// return $AllowedbyTree; -// } -// -// // joins for solving object classes: -// $q_flds = $q_flds0.", c.cname "; -// $q_join = $q_join0."LEFT JOIN ".$CC_CONFIG['classTable']." c ON c.id=p.obj "; -// $q_join .= "LEFT JOIN ".$CC_CONFIG['cmembTable']." cm ON cm.cid=p.obj "; -// $q_cond = $q_cond0." AND (c.id=$oid OR cm.objid=$oid)"; -// $q_ordb = $q_ordb0; -// // query by class: -// $query2 = "SELECT $q_flds FROM $q_from $q_join WHERE $q_cond $q_ordb"; -// $r2 = $CC_DBC->getAll($query2); -// if (PEAR::isError($r2)) { -// return $r2; -// } -// $AllowedByClass = -// (is_array($r2) && count($r2)>0 && $r2[0]['type']=='A'); -// // not used now: -// // $DeniedByClass = -// // (is_array($r2) && count($r2)>0 && $r2[0]['type']=='D'); -// $res = ($AllowedByTree || (!$DeniedByTree && $AllowedByClass)); -// return $res; + return TRUE; + // global $CC_DBC; + // global $CC_CONFIG; + // if (!is_numeric($sid)) { + // return FALSE; + // } + //// if (is_null($oid) or $oid=='') { + //// $oid = M2tree::GetRootNode(); + //// } + //// if (PEAR::isError($oid)) { + //// return $oid; + //// } + // if (!is_numeric($oid)) { + // return FALSE; + // } + // // query construction + // // shortcuts: + // // p: permTable, + // // s: subjTable, m smembTable, + // // t: treeTable ts: structTable, + // // c: classTable, cm: cmembTable + // // main query elements: + // $q_flds = "m.level , p.subj, s.login, action, p.type, p.obj"; + // $q_from = $CC_CONFIG['permTable']." p "; + // // joins for solving users/groups: + // $q_join = "LEFT JOIN ".$CC_CONFIG['subjTable']." s ON s.id=p.subj "; + // $q_join .= "LEFT JOIN ".$CC_CONFIG['smembTable']." m ON m.gid=p.subj "; + // $q_cond = "p.action in('_all', '$action') AND + // (s.id=$sid OR m.uid=$sid) "; + // // coalesce -1 for higher priority of nongroup rows: + // // action DESC order for lower priority of '_all': + // $q_ordb = "ORDER BY coalesce(m.level,-1), action DESC, p.type DESC"; + // $q_flds0 = $q_flds; + // $q_from0 = $q_from; + // $q_join0 = $q_join; + // $q_cond0 = $q_cond; + // $q_ordb0 = $q_ordb; + // // joins for solving object tree: + // $q_flds .= ", t.name, ts.level as tlevel"; + // //$q_join .= "LEFT JOIN ".$CC_CONFIG['treeTable']." t ON t.id=p.obj "; + // //$q_join .= "LEFT JOIN ".$CC_CONFIG['structTable']." ts ON ts.parid=p.obj "; + // //$q_cond .= " AND (t.id=$oid OR ts.objid=$oid)"; + // // action DESC order is hack for lower priority of '_all': + // $q_ordb = "ORDER BY coalesce(ts.level,0), m.level, action DESC, p.type DESC"; + // // query by tree: + // $query1 = "SELECT $q_flds FROM $q_from $q_join WHERE $q_cond $q_ordb"; + // $r1 = $CC_DBC->getAll($query1); + // if (PEAR::isError($r1)) { + // return($r1); + // } + // // if there is row with type='A' on the top => permit + // //$AllowedByTree = + // // (is_array($r1) && count($r1)>0 && $r1[0]['type']=='A'); + // //$DeniedByTree = + // // (is_array($r1) && count($r1)>0 && $r1[0]['type']=='D'); + // + // if (!USE_ALIB_CLASSES) { + // return $AllowedbyTree; + // } + // + // // joins for solving object classes: + // $q_flds = $q_flds0.", c.cname "; + // $q_join = $q_join0."LEFT JOIN ".$CC_CONFIG['classTable']." c ON c.id=p.obj "; + // $q_join .= "LEFT JOIN ".$CC_CONFIG['cmembTable']." cm ON cm.cid=p.obj "; + // $q_cond = $q_cond0." AND (c.id=$oid OR cm.objid=$oid)"; + // $q_ordb = $q_ordb0; + // // query by class: + // $query2 = "SELECT $q_flds FROM $q_from $q_join WHERE $q_cond $q_ordb"; + // $r2 = $CC_DBC->getAll($query2); + // if (PEAR::isError($r2)) { + // return $r2; + // } + // $AllowedByClass = + // (is_array($r2) && count($r2)>0 && $r2[0]['type']=='A'); + // // not used now: + // // $DeniedByClass = + // // (is_array($r2) && count($r2)>0 && $r2[0]['type']=='D'); + // $res = ($AllowedByTree || (!$DeniedByTree && $AllowedByClass)); + // return $res; } // fn CheckPerm @@ -326,7 +326,7 @@ class Alib { } if (is_null($uid)){ return $CC_DBC->raiseError("Alib::removeSubj: Subj not found ($login)", - ALIBERR_NOTEXISTS, PEAR_ERROR_RETURN); + ALIBERR_NOTEXISTS, PEAR_ERROR_RETURN); } $r = Alib::RemovePerm(NULL, $uid); if (PEAR::isError($r)) { @@ -354,7 +354,7 @@ class Alib { if (is_null($r)){ return PEAR::raiseError("Alib::GetSessLogin:". " invalid session id ($sessid)", - ALIBERR_NOTEXISTS, PEAR_ERROR_RETURN); + ALIBERR_NOTEXISTS, PEAR_ERROR_RETURN); } return $r; } // fn GetSessLogin @@ -377,7 +377,7 @@ class Alib { if (is_null($r)) { return PEAR::raiseError("Alib::getSessUserId:". " invalid session id ($p_sessid)", - ALIBERR_NOTEXISTS, PEAR_ERROR_RETURN); + ALIBERR_NOTEXISTS, PEAR_ERROR_RETURN); } return $r; } // fn getSessUserId @@ -394,7 +394,7 @@ class Alib { { global $CC_CONFIG, $CC_DBC; $sql = "SELECT s.login, p.* FROM ".$CC_CONFIG['permTable']." p, ".$CC_CONFIG['subjTable']." s" - ." WHERE s.id=p.subj AND p.obj=$id"; + ." WHERE s.id=p.subj AND p.obj=$id"; return $CC_DBC->getAll($sql); } // fn GetObjPerms @@ -409,11 +409,11 @@ class Alib { { global $CC_CONFIG, $CC_DBC; $sql = "SELECT *" - ." FROM ".$CC_CONFIG['permTable'] - ." WHERE p.subj=$sid"; -// $sql = "SELECT t.name, t.type as otype , p.*" -// ." FROM ".$CC_CONFIG['permTable']." p, ".$CC_CONFIG['treeTable']." t" -// ." WHERE t.id=p.obj AND p.subj=$sid"; + ." FROM ".$CC_CONFIG['permTable'] + ." WHERE p.subj=$sid"; + // $sql = "SELECT t.name, t.type as otype , p.*" + // ." FROM ".$CC_CONFIG['permTable']." p, ".$CC_CONFIG['treeTable']." t" + // ." WHERE t.id=p.obj AND p.subj=$sid"; $a1 = $CC_DBC->getAll($sql); return $a1; } // fn GetSubjPerms @@ -463,7 +463,7 @@ class Alib { for ($c = 1; $c > 0; ){ $sessid = md5(uniqid(rand())); $sql = "SELECT count(*) FROM ".$CC_CONFIG['sessTable'] - ." WHERE sessid='$sessid'"; + ." WHERE sessid='$sessid'"; $c = $CC_DBC->getOne($sql); if (PEAR::isError($c)) { return $c; @@ -488,19 +488,19 @@ class Alib { { global $CC_CONFIG, $CC_DBC; $sql = "SELECT s.login, p.action, p.type" - ." FROM ".$CC_CONFIG['permTable']." p, ".$CC_CONFIG['subjTable']." s" - ." WHERE s.id=p.subj" - ." ORDER BY p.permid"; + ." FROM ".$CC_CONFIG['permTable']." p, ".$CC_CONFIG['subjTable']." s" + ." WHERE s.id=p.subj" + ." ORDER BY p.permid"; $arr = $CC_DBC->getAll($sql); if (PEAR::isError($arr)) { return $arr; } $r = $ind.join(', ', array_map(create_function('$v', 'return "{$v[\'login\']}/{$v[\'action\']}/{$v[\'type\']}";' - ), - $arr - ))."\n"; - return $r; + ), + $arr + ))."\n"; + return $r; } // fn dumpPerms @@ -532,16 +532,16 @@ class Alib { $s =& $tdata['subjects']; $CC_DBC->setErrorHandling(PEAR_ERROR_PRINT); $perms = array( - array($s['root'], '_all', $t['root'], 'A'), - array($s['test1'], '_all', $t['pa'], 'A'), - array($s['test1'], 'read', $t['s2b'], 'D'), - array($s['test2'], 'addChilds', $t['pa'], 'D'), - array($s['test2'], 'read', $t['i2'], 'A'), - array($s['test2'], 'edit', $t['s1a'], 'A'), - array($s['test1'], 'addChilds', $t['s2a'], 'D'), - array($s['test1'], 'addChilds', $t['s2c'], 'D'), - array($s['gr2'], 'addChilds', $t['i2'], 'A'), - array($s['test3'], '_all', $t['t1'], 'D'), + array($s['root'], '_all', $t['root'], 'A'), + array($s['test1'], '_all', $t['pa'], 'A'), + array($s['test1'], 'read', $t['s2b'], 'D'), + array($s['test2'], 'addChilds', $t['pa'], 'D'), + array($s['test2'], 'read', $t['i2'], 'A'), + array($s['test2'], 'edit', $t['s1a'], 'A'), + array($s['test1'], 'addChilds', $t['s2a'], 'D'), + array($s['test1'], 'addChilds', $t['s2c'], 'D'), + array($s['gr2'], 'addChilds', $t['i2'], 'A'), + array($s['test3'], '_all', $t['t1'], 'D'), ); if (USE_ALIB_CLASSES){ $perms[] = array($s['test3'], 'read', $c['cl_sa'], 'D'); @@ -587,14 +587,14 @@ class Alib { return $r; } $test_dump = $r. - (Alib::CheckPerm( - $tdata['subjects']['test1'], 'read', - $tdata['tree']['t1'] - )? 'yes':'no').", ". - (Alib::CheckPerm( - $tdata['subjects']['test1'], 'addChilds', - $tdata['tree']['i2'] - )? 'yes':'no')."\n" + (Alib::CheckPerm( + $tdata['subjects']['test1'], 'read', + $tdata['tree']['t1'] + )? 'yes':'no').", ". + (Alib::CheckPerm( + $tdata['subjects']['test1'], 'addChilds', + $tdata['tree']['i2'] + )? 'yes':'no')."\n" ; Alib::RemovePerm($tdata['perms'][1]); Alib::RemovePerm($tdata['perms'][3]); diff --git a/backend/Backup.php b/backend/Backup.php index 211faa362..c05500264 100755 --- a/backend/Backup.php +++ b/backend/Backup.php @@ -132,7 +132,7 @@ class Backup // get ids (and real filenames) which files match with criteria $srch = $this->gb->localSearch($this->criteria,$this->sessid); if (PEAR::isError($srch)) { - return $srch; + return $srch; } $this->setIDs($srch); @@ -167,7 +167,7 @@ class Backup return array('token'=>$this->token); } else { - return false; + return false; } } @@ -229,7 +229,7 @@ class Backup unlink($this->statusFile); unlink($this->tmpFile); if (is_file($this->tmpName)) { - unlink($this->tmpName); + unlink($this->tmpName); } return !is_file($this->tmpFile); } @@ -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.'); + // } } @@ -337,10 +337,10 @@ class Backup $this->addLogItem("-I- ".date("Ymd-H:i:s")." doIt\n"); } $command = dirname(__FILe__)."/../bin/backup.sh" - ." {$this->tmpDir}" - ." {$this->tmpFile}" - ." {$this->statusFile}" - ." >> {$this->logFile} &"; + ." {$this->tmpDir}" + ." {$this->tmpFile}" + ." {$this->statusFile}" + ." >> {$this->logFile} &"; $res = system("$command"); sleep(2); if ($this->loglevel=='debug') { @@ -438,7 +438,7 @@ class Backup { $acc = BasicStor::bsAccess($this->tmpFile, BACKUP_EXT, null, ACCESS_TYPE); if (PEAR::isError($acc)) { - return $acc; + return $acc; } $this->token = $acc['token']; } @@ -484,4 +484,4 @@ class Backup } } // classs Backup -?> +?> diff --git a/backend/BasicStor.php b/backend/BasicStor.php index 22cd01bbf..ed517eabd 100644 --- a/backend/BasicStor.php +++ b/backend/BasicStor.php @@ -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; -// } + // 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. */ @@ -329,7 +329,7 @@ class BasicStor { * array with: seekable filehandle, access token */ public static function bsAccess($realFname, $ext, $gunid, $type='access', - $parent='0', $owner=NULL) + $parent='0', $owner=NULL) { global $CC_CONFIG, $CC_DBC; if (!is_null($gunid)) { @@ -338,17 +338,17 @@ class BasicStor { $token = StoredFile::CreateGunid(); if (!is_null($realFname)) { $linkFname = $CC_CONFIG['accessDir']."/$token.$ext"; - //broken links are ignored by the player, do not worry about it here -/* if (!is_file($realFname) && !is_link($realFname)) { - return PEAR::raiseError( - "BasicStor::bsAccess: real file not found ($realFname)", - GBERR_FILEIO); + //broken links are ignored by the player, do not worry about it here + /* if (!is_file($realFname) && !is_link($realFname)) { + return PEAR::raiseError( + "BasicStor::bsAccess: real file not found ($realFname)", + GBERR_FILEIO); } -*/ + */ if (! @symlink($realFname, $linkFname)) { return PEAR::raiseError( "BasicStor::bsAccess: symlink create failed ($linkFname)", - GBERR_FILEIO); + GBERR_FILEIO); } } else { $linkFname = NULL; @@ -423,7 +423,7 @@ class BasicStor { if(! @unlink($linkFname)){ return PEAR::raiseError( "BasicStor::bsRelease: unlink failed ($linkFname)", - GBERR_FILEIO); + GBERR_FILEIO); } } $CC_DBC->query("BEGIN"); @@ -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 @@ -998,35 +998,35 @@ class BasicStor { $ops = array('full'=>"='%s'", 'partial'=>"ILIKE '%%%s%%'", 'prefix'=>"ILIKE '%s%%'", '<'=>"< '%s'", '='=>"= '%s'", '>'=>"> '%s'", '<='=>"<= '%s'", '>='=>">= '%s'" - ); - $whereArr = array(); - if (is_array($conditions)) { - foreach ($conditions as $cond) { - $columnName = StoredFile::xmlCategoryToDbColumn($cond['cat']); - $op = strtolower($cond['op']); - $value = $cond['val']; - if (!empty($value)) { - $splittedQn = XML_Util::splitQualifiedName($catQn); - $catNs = $splittedQn['namespace']; - $cat = $splittedQn['localPart']; - $opVal = sprintf($ops[$op], pg_escape_string($value)); - // retype for timestamp value - if ($cat == 'mtime') { - switch ($op) { - case 'partial': - case 'prefix': - break; - default: - $retype = "::timestamp with time zone"; - $opVal = "$retype $opVal$retype"; + ); + $whereArr = array(); + if (is_array($conditions)) { + foreach ($conditions as $cond) { + $columnName = StoredFile::xmlCategoryToDbColumn($cond['cat']); + $op = strtolower($cond['op']); + $value = $cond['val']; + if (!empty($value)) { + $splittedQn = XML_Util::splitQualifiedName($catQn); + $catNs = $splittedQn['namespace']; + $cat = $splittedQn['localPart']; + $opVal = sprintf($ops[$op], pg_escape_string($value)); + // retype for timestamp value + if ($cat == 'mtime') { + switch ($op) { + case 'partial': + case 'prefix': + break; + default: + $retype = "::timestamp with time zone"; + $opVal = "$retype $opVal$retype"; + } } + $sqlCond = " {$columnName} {$opVal}\n"; + $whereArr[] = $sqlCond; } - $sqlCond = " {$columnName} {$opVal}\n"; - $whereArr[] = $sqlCond; } } - } - return $whereArr; + return $whereArr; } /** @@ -1104,8 +1104,8 @@ class BasicStor { $orderByAllowedValues = array('dc:creator', 'dc:source', 'dc:title', 'dcterms:extent', "ls:track_num"); $orderByDefaults = array('dc:creator', 'dc:source', 'dc:title'); if ((!isset($criteria['orderby'])) - || (is_array($criteria['orderby']) && (count($criteria['orderby'])==0))) { - // default ORDER BY + || (is_array($criteria['orderby']) && (count($criteria['orderby'])==0))) { + // default ORDER BY // PaulB: track number removed because it doesnt work yet because // if track_num is not an integer (e.g. bad metadata like "1/20", // or if the field is blank) the SQL statement gives an error. @@ -1148,7 +1148,7 @@ class BasicStor { // Build WHERE clause $whereClause = ""; if (!is_null($filetype)) { - $whereClause .= "WHERE (ftype='$filetype')"; + $whereClause .= "WHERE (ftype='$filetype')"; } else { $whereClause .= "WHERE (ftype is NOT NULL)"; @@ -1164,9 +1164,9 @@ class BasicStor { // Final query //"dcterms:extent" => "length", - //"dc:title" => "track_title", - //"dc:creator" => "artist_name", - //dc:description + //"dc:title" => "track_title", + //"dc:creator" => "artist_name", + //dc:description global $g_metadata_xml_to_db_mapping; $plSelect = "SELECT "; @@ -1207,17 +1207,17 @@ class BasicStor { $sql .= $whereClause; if ($orderby) { - $sql .= " ORDER BY ".join(",", $orderBySql); + $sql .= " ORDER BY ".join(",", $orderBySql); } $_SESSION["debugsql"] = $sql; $res = $CC_DBC->getAll($sql); if (PEAR::isError($res)) { - return $res; + return $res; } if (!is_array($res)) { - $res = array(); + $res = array(); } $count = count($res); @@ -1266,83 +1266,83 @@ class BasicStor { "dc:title" => "name", "dc:creator" => "creator", "dc:description" => "description" - ); + ); - $category = strtolower($category); - $columnName = StoredFile::xmlCategoryToDbColumn($category); - if (is_null($columnName)) { - return new PEAR_Error(__FILE__.":".__LINE__." -- could not map XML category to DB column."); - } - $sql = "SELECT DISTINCT $columnName FROM ".$CC_CONFIG["filesTable"]; - $limitPart = ($limit != 0 ? " LIMIT $limit" : '' ). - ($offset != 0 ? " OFFSET $offset" : '' ); - $countRowsSql = "SELECT COUNT(DISTINCT $columnName) FROM ".$CC_CONFIG["filesTable"]; + $category = strtolower($category); + $columnName = StoredFile::xmlCategoryToDbColumn($category); + if (is_null($columnName)) { + return new PEAR_Error(__FILE__.":".__LINE__." -- could not map XML category to DB column."); + } + $sql = "SELECT DISTINCT $columnName FROM ".$CC_CONFIG["filesTable"]; + $limitPart = ($limit != 0 ? " LIMIT $limit" : '' ). + ($offset != 0 ? " OFFSET $offset" : '' ); + $countRowsSql = "SELECT COUNT(DISTINCT $columnName) FROM ".$CC_CONFIG["filesTable"]; - //$_SESSION["br"] = "in Browse Category: ".$category; - $cnt = $CC_DBC->GetOne($countRowsSql); - if (PEAR::isError($cnt)) { - return $cnt; - } - $res = $CC_DBC->getCol($sql.$limitPart); - if (PEAR::isError($res)) { - return $res; - } - if (!is_array($res)) { - $res = array(); - } + //$_SESSION["br"] = "in Browse Category: ".$category; + $cnt = $CC_DBC->GetOne($countRowsSql); + if (PEAR::isError($cnt)) { + return $cnt; + } + $res = $CC_DBC->getCol($sql.$limitPart); + if (PEAR::isError($res)) { + return $res; + } + if (!is_array($res)) { + $res = array(); + } - if (array_key_exists($category, $pl_cat) && $category !== "dcterms:extent") { - $columnName = $pl_cat[$category]; + if (array_key_exists($category, $pl_cat) && $category !== "dcterms:extent") { + $columnName = $pl_cat[$category]; - $sql = "SELECT DISTINCT $columnName FROM ".$CC_CONFIG["playListTable"]; - $limitPart = ($limit != 0 ? " LIMIT $limit" : '' ). - ($offset != 0 ? " OFFSET $offset" : '' ); - $countRowsSql = "SELECT COUNT(DISTINCT $columnName) FROM ".$CC_CONFIG["playListTable"]; + $sql = "SELECT DISTINCT $columnName FROM ".$CC_CONFIG["playListTable"]; + $limitPart = ($limit != 0 ? " LIMIT $limit" : '' ). + ($offset != 0 ? " OFFSET $offset" : '' ); + $countRowsSql = "SELECT COUNT(DISTINCT $columnName) FROM ".$CC_CONFIG["playListTable"]; - $pl_cnt = $CC_DBC->GetOne($countRowsSql); - if (PEAR::isError($cnt)) { - return $cnt; - } - $pl_res = $CC_DBC->getCol($sql.$limitPart); - if (PEAR::isError($res)) { - return $pl_res; - } - if (!is_array($pl_res)) { - $pl_res = array(); - } + $pl_cnt = $CC_DBC->GetOne($countRowsSql); + if (PEAR::isError($cnt)) { + return $cnt; + } + $pl_res = $CC_DBC->getCol($sql.$limitPart); + if (PEAR::isError($res)) { + return $pl_res; + } + if (!is_array($pl_res)) { + $pl_res = array(); + } - $res = array_merge($res, $pl_res); - $res = array_slice($res, 0, $limit); - $cnt = $cnt + $pl_cnt; - } - else if ($category === "dcterms:extent") { - $columnName = $pl_cat[$category]; + $res = array_merge($res, $pl_res); + $res = array_slice($res, 0, $limit); + $cnt = $cnt + $pl_cnt; + } + else if ($category === "dcterms:extent") { + $columnName = $pl_cat[$category]; - $limitPart = ($limit != 0 ? " LIMIT $limit" : '' ). - ($offset != 0 ? " OFFSET $offset" : '' ); + $limitPart = ($limit != 0 ? " LIMIT $limit" : '' ). + ($offset != 0 ? " OFFSET $offset" : '' ); - $sql = "SELECT DISTINCT length AS $columnName FROM ".$CC_CONFIG["playListTimeView"]; + $sql = "SELECT DISTINCT length AS $columnName FROM ".$CC_CONFIG["playListTimeView"]; - $countRowsSql = "SELECT COUNT(DISTINCT length) FROM ".$CC_CONFIG["playListTimeView"]; + $countRowsSql = "SELECT COUNT(DISTINCT length) FROM ".$CC_CONFIG["playListTimeView"]; - $pl_cnt = $CC_DBC->GetOne($countRowsSql); - if (PEAR::isError($cnt)) { + $pl_cnt = $CC_DBC->GetOne($countRowsSql); + if (PEAR::isError($cnt)) { return $cnt; - } - $pl_res = $CC_DBC->getCol($sql.$limitPart); - if (PEAR::isError($res)) { + } + $pl_res = $CC_DBC->getCol($sql.$limitPart); + if (PEAR::isError($res)) { return $pl_res; - } - if (!is_array($pl_res)) { + } + if (!is_array($pl_res)) { $pl_res = array(); - } + } - $res = array_merge($res, $pl_res); - $res = array_slice($res, 0, $limit); - $cnt = $cnt + $pl_cnt; - } + $res = array_merge($res, $pl_res); + $res = array_slice($res, 0, $limit); + $cnt = $cnt + $pl_cnt; + } - return array('results'=>$res, 'cnt'=>$cnt); + return array('results'=>$res, 'cnt'=>$cnt); } @@ -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 = 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; -// } + // 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; -// } -// $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; -// } + // 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,25 +1734,25 @@ class BasicStor { * Local object id * @return string|PEAR_Error */ -// public static function GetObjType($p_id) -// { -// $type = "unknown"; -// $f = StoredFile::Recall($p_id); -// return $f->getType(); + // 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; -// } + // $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; + // } /** @@ -1779,12 +1779,12 @@ class BasicStor { if (PEAR::isError($res)) { return $res; } -// $res = Subjects::AddSubjectToGroup($login, $CC_CONFIG['AllGr']); -// if (PEAR::isError($res)) { -// return $res; -// } - } - return $uid; + // $res = Subjects::AddSubjectToGroup($login, $CC_CONFIG['AllGr']); + // if (PEAR::isError($res)) { + // return $res; + // } + } + return $uid; } @@ -1862,13 +1862,13 @@ class BasicStor { $acts = array($acts); } $perm = true; -// foreach ($acts as $i => $action) { -// $res = Alib::CheckPerm($userid, $action, $pars[$i]); -// if (PEAR::isError($res)) { -// return $res; -// } -// $perm = $perm && $res; -// } + // foreach ($acts as $i => $action) { + // $res = Alib::CheckPerm($userid, $action, $pars[$i]); + // if (PEAR::isError($res)) { + // return $res; + // } + // $perm = $perm && $res; + // } if ($perm) { return TRUE; } @@ -1886,14 +1886,14 @@ 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). * * @param string $p_gunid @@ -1901,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'"); + // } /** @@ -1917,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); + // } /** @@ -1945,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; + // } /** @@ -1964,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 @@ -2038,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; + // } /** @@ -2068,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 */ @@ -2156,17 +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) { -// $f = StoredFile::Recall($item['id']); -// $f->delete(); -// } -// } -// } + // 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(); + // } + // } + // } /** @@ -2182,5 +2182,5 @@ class BasicStor { fclose($fp); } -} // class BasicStor -?> \ No newline at end of file + } // class BasicStor + ?> \ No newline at end of file diff --git a/backend/GreenBox.php b/backend/GreenBox.php index a46ffa752..d990cc2db 100644 --- a/backend/GreenBox.php +++ b/backend/GreenBox.php @@ -72,7 +72,7 @@ class GreenBox extends BasicStor { * @exception PEAR::error */ public function storeWebstream($fileName, $mdataFileLP, $sessid='', - $gunid=NULL, $url) + $gunid=NULL, $url) { if (($res = BasicStor::Authorize('write', null, $sessid)) !== TRUE) { return $res; @@ -85,16 +85,16 @@ class GreenBox extends BasicStor { "metadata" => $mdataFileLP, "gunid" => $gunid, "filetype" => "webstream" - ); - $storedFile = StoredFile::Insert($values); - if (PEAR::isError($storedFile)) { - return $storedFile; - } - $r = $storedFile->setMetadataValue('ls:url', $url); - if (PEAR::isError($r)) { - return $r; - } - return $oid; + ); + $storedFile = StoredFile::Insert($values); + if (PEAR::isError($storedFile)) { + return $storedFile; + } + $r = $storedFile->setMetadataValue('ls:url', $url); + if (PEAR::isError($r)) { + return $r; + } + return $oid; } // fn storeWebstream @@ -107,19 +107,19 @@ class GreenBox extends BasicStor { * session id * @return string access token */ -// function accessFile($id, $sessid='') -// { -// if (($res = BasicStor::Authorize('read', $id, $sessid)) !== TRUE) { -// return $res; -// } -// $gunid = BasicStor::GunidFromId($id); -// $r = BasicStor::bsAccess(NULL, '', $gunid, 'access'); -// if (PEAR::isError($r)) { -// return $r; -// } -// $token = $r['token']; -// return $token; -// } // fn accessFile + // function accessFile($id, $sessid='') + // { + // if (($res = BasicStor::Authorize('read', $id, $sessid)) !== TRUE) { + // return $res; + // } + // $gunid = BasicStor::GunidFromId($id); + // $r = BasicStor::bsAccess(NULL, '', $gunid, 'access'); + // if (PEAR::isError($r)) { + // return $r; + // } + // $token = $r['token']; + // return $token; + // } // fn accessFile /** @@ -131,14 +131,14 @@ class GreenBox extends BasicStor { * session id * @return boolean */ -// function releaseFile($token, $sessid='') -// { -// $r = BasicStor::bsRelease($token, 'access'); -// if (PEAR::isError($r)) { -// return $r; -// } -// return FALSE; -// } // fn releaseFile + // function releaseFile($token, $sessid='') + // { + // $r = BasicStor::bsRelease($token, 'access'); + // if (PEAR::isError($r)) { + // return $r; + // } + // return FALSE; + // } // fn releaseFile /** @@ -150,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); -// } + // public function analyzeFile($id, $sessid='') + // { + // if (($res = BasicStor::Authorize('read', $id, $sessid)) !== TRUE) { + // return $res; + // } + // return $this->bsAnalyzeFile($id); + // } /** @@ -169,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); -// } + // public function renameFile($id, $newName, $sessid='') + // { + // if (($res = BasicStor::Authorize('write', $id, $sessid)) !== TRUE) { + // return $res; + // } + // return $this->bsRenameFile($id, $newName); + // } /** @@ -191,13 +191,13 @@ 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); -// } + // public function replaceFile($id, $mediaFileLP, $mdataFileLP, $sessid='') + // { + // if (($res = BasicStor::Authorize('write', $id, $sessid)) !== TRUE) { + // return $res; + // } + // return $this->bsReplaceFile($id, $mediaFileLP, $mdataFileLP); + // } /** @@ -235,13 +235,13 @@ class GreenBox extends BasicStor { * session id * @return boolean|PEAR_Error */ -// public function replaceMetadata($id, $mdata, $mdataLoc='file', $sessid='') -// { -// if (($res = BasicStor::Authorize('write', $id, $sessid)) !== TRUE) { -// return $res; -// } -// return $this->bsReplaceMetadata($id, $mdata, $mdataLoc); -// } // fn replaceMetadata + // public function replaceMetadata($id, $mdata, $mdataLoc='file', $sessid='') + // { + // if (($res = BasicStor::Authorize('write', $id, $sessid)) !== TRUE) { + // return $res; + // } + // return $this->bsReplaceMetadata($id, $mdata, $mdataLoc); + // } // fn replaceMetadata /** @@ -288,7 +288,7 @@ class GreenBox extends BasicStor { } return $storedFile->md; -// $arr = $storedFile->md->genPhpArray(); + // $arr = $storedFile->md->genPhpArray(); $md = FALSE; foreach ($arr['children'] as $i=>$a) { if ($a['elementname'] == 'metadata'){ @@ -299,7 +299,7 @@ class GreenBox extends BasicStor { if ($md === FALSE) { return PEAR::raiseError( "GreenBox::getMetadataArray: no metadata container found" - ); + ); } $res = array(); foreach ($md['children'] as $el) { @@ -337,7 +337,7 @@ class GreenBox extends BasicStor { * */ public function getMetadataValue($id, $category, $sessid='', - $lang=NULL, $deflang=NULL) + $lang=NULL, $deflang=NULL) { if (!is_numeric($id)) { return null; @@ -485,7 +485,7 @@ class GreenBox extends BasicStor { $pl = Playlist::Recall($id); if($pl === FALSE) - return FALSE; + return FALSE; $res = $pl->setPLMetaData($category, $value, $lang); @@ -497,7 +497,7 @@ class GreenBox extends BasicStor { $pl = Playlist::Recall($id); if($pl === FALSE) - return FALSE; + return FALSE; $res = $pl->getPLMetaData($category); @@ -514,1213 +514,1213 @@ class GreenBox extends BasicStor { * @return string * XML */ -// function getPlaylistXml($id, $sessid) -// { -// return $this->getMetadata($id, $sessid); -// } // fn getPlaylistXml + // function getPlaylistXml($id, $sessid) + // { + // return $this->getMetadata($id, $sessid); + // } // fn getPlaylistXml - /** - * Return playlist as hierarchical PHP hash-array - * - * @param int $id - * local object id - * @param string $sessid - * session ID - * @return array - */ - public function getPlaylistArray($id) - { - $pl = Playlist::Recall($id); - if ($pl === FALSE) { - return FALSE; - } + /** + * Return playlist as hierarchical PHP hash-array + * + * @param int $id + * local object id + * @param string $sessid + * session ID + * @return array + */ + public function getPlaylistArray($id) + { + $pl = Playlist::Recall($id); + if ($pl === FALSE) { + return FALSE; + } - $res = $pl->getContents(); + $res = $pl->getContents(); - if(is_null($res)) + if(is_null($res)) return array(); - return $res; - } // fn getPlaylistArray + return $res; + } // fn getPlaylistArray - /** - * Mark playlist as edited and return edit token - * - * @param int $id - * local object id - * @param string $sessid - * session ID - * @return string - * playlist access token - */ - public function lockPlaylistForEdit($id, $sessid) { - $pl = Playlist::Recall($id); + /** + * Mark playlist as edited and return edit token + * + * @param int $id + * local object id + * @param string $sessid + * session ID + * @return string + * playlist access token + */ + public function lockPlaylistForEdit($id, $sessid) { + $pl = Playlist::Recall($id); - if($pl === FALSE) + if($pl === FALSE) return; - $res = $pl->lock($sessid); + $res = $pl->lock($sessid); - return $res; - } - - - /** - * clear edit flag. - * - * @param string $sessid - * session ID - * @return string gunid - */ - public function releaseLockedPlaylist($id, $sessid) { - $pl = Playlist::Recall($id); - - if($pl === FALSE) - return FALSE; - - $res = $pl->unlock($sessid); - return $res; - } - - - /** - * Add audioclip specified by local id to the playlist - * - * @param string $token - * playlist access token - * @param string $acId - * local ID of added file - * @param string $sessid - * session ID - * @param string $fadeIn - * in time format hh:mm:ss.ssssss - * @param string $fadeOut - * in time format hh:mm:ss.ssssss - * @param string $length - * length in extent format - - * for webstream (or for overrule length of audioclip) - * @param string $clipstart - * optional clipstart time format hh:mm:ss.ssssss - relative to begin - * @param string $clipend - * optional $clipend time format hh:mm:ss.ssssss - relative to begin - * @return boolean, true if added. - */ - public function addAudioClipToPlaylist($id, $acId, $pos=NULL, $fadeIn=NULL, $fadeOut=NULL, $cliplength=NULL, $cueIn=NULL, $cueOut=NULL) - { - $pl = Playlist::Recall($id); - if ($pl === FALSE) { - return FALSE; - } - - $res = $pl->addAudioClip($acId, $pos, $fadeIn, $fadeOut, $cliplength, $cueIn, $cueOut); - - return $res; - } // fn addAudioClipToPlaylist - - - /** - * Remove audioclip from playlist - * - * @param string $id - * playlist id - * @param int $pos - * position of element in playlist to delete. - * @return boolean, true if deleted. - * @todo rename this function to "deleteAudioClipFromPlaylist" - */ - public function delAudioClipFromPlaylist($id, $pos) - { - $pl = Playlist::Recall($id); - if ($pl === FALSE) { - return FALSE; - } - - $res = $pl->delAudioClip($pos); - if($res === FALSE) - return FALSE; - - return TRUE; - } - - /** - * Move audioClip to the new position in the playlist. - * - * This method may change id attributes of playlistElements and/or - * fadeInfo. - * - * @param string $id - * playlist id - * @param id $oldPos - * old position in playlist - * @param int $newPos - * new position in playlist - * @return boolean - */ - public function moveAudioClipInPlaylist($id, $oldPos, $newPos) - { - $pl = Playlist::Recall($id); - if ($pl === FALSE) { - return FALSE; - } - - $res = $pl->moveAudioClip($oldPos, $newPos); - - return $res; - } - - /** - * Change fadeInfo values - * - * @param string $id - * playlist id - * @param string $fadeIn - * in time format hh:mm:ss.ssssss - * @param string $fadeOut - * in time format hh:mm:ss.ssssss - * @return boolean - */ - public function changeFadeInfo($id, $pos, $fadeIn, $fadeOut) - { - $pl = Playlist::Recall($id); - if ($pl === FALSE) { - return FALSE; - } - - $res = $pl->changeFadeInfo($pos, $fadeIn, $fadeOut); - - return $res; - } - - /** - * Change cueIn/cueOut values for playlist element - * - * @param string $id - * playlist id - * @param string $cueIn - * in time format hh:mm:ss.ssssss - * @param string $cueOut - * in time format hh:mm:ss.ssssss - * relative to begin - * @param sessid $string - * session ID - * @return boolean or pear error object - */ - public function changeClipLength($id, $pos, $cueIn, $cueOut) - { - $pl = Playlist::Recall($id); - if ($pl === FALSE) { - return FALSE; - } - - $res = $pl->changeClipLength($pos, $cueIn, $cueOut); - - return $res; - } - - /** - * Delete a Playlist metafile. - * - * @param int $id - * local id - * @param string $sessid - * session ID - * @return boolean - */ - public function deletePlaylist($id) - { - return Playlist::Delete($id); - - } - - /** - * Find info about clip at specified offset in playlist. - * - * @param string $sessid - * session id - * @param string $plid - * playlist global unique id - * @param string $offset - * current playtime (hh:mm:ss.ssssss) - * @param int $distance - * 0=current clip; 1=next clip ... - * @return array of matching clip info: - * - */ - public function displayPlaylistClipAtOffset($sessid, $plid, $offset, $distance=0) - { - $pl = Playlist::Recall($plid); - if (is_null($pl) || PEAR::isError($pl)) { - return $pl; - } - $res = $pl->displayPlaylistClipAtOffset($offset, $distance); - if (PEAR::isError($res)) { return $res; } - $res['title'] = NULL; - $f = StoredFile::RecallByGunid($res['gunid']); - if (PEAR::isError($f)) { - return $f; - } - $res['title'] = $f->getMetadataValue("dc:title"); - $res['playlist_title'] = NULL; - $pl = Playlist::Recall($plid); - $res['playlist'] = $pl->getName(); - - return $res; - } - /** - * Create a tarfile with playlist export - playlist and all matching - * sub-playlists and media files (if desired) - * - * @param string $sessid - * string, session ID - * @param array $plids - * array of strings, playlist global unique IDs - * (one gunid is accepted too) - * @param string $type - * playlist format, values: lspl | smil | m3u - * @param boolean $standalone - * if only playlist should be exported or - * with all related files - * @return hasharray with fields: - * fname string: readable fname, - * token string: access token - */ - public function exportPlaylistOpen($sessid, $plids, $type='lspl', $standalone=FALSE) - { - return $this->bsExportPlaylistOpen($plids, $type, !$standalone); - } // fn exportPlaylistOpen + /** + * clear edit flag. + * + * @param string $sessid + * session ID + * @return string gunid + */ + public function releaseLockedPlaylist($id, $sessid) { + $pl = Playlist::Recall($id); - - /** - * Close playlist export previously opened by the exportPlaylistOpen method - * - * @param string $token - * access token obtained from exportPlaylistOpen - * method call - * @return TRUE|PEAR_Error - */ - public function exportPlaylistClose($token) - { - return $this->bsExportPlaylistClose($token); - } // fn exportPlaylistClose - - - /** - * Open writable handle for import playlist in LS Archive format - * - * @param string $sessid - * session id - * @param string $chsum - * md5 checksum of imported file - * @return hasharray with: - * fname string: writable local filename - * token string: put token - */ - public function importPlaylistOpen($sessid, $chsum='') - { - $userid = GreenBox::GetSessUserId($sessid); - if (PEAR::isError($userid)) { - return $userid; - } - $r = $this->bsOpenPut($chsum, NULL, $userid); - if (PEAR::isError($r)) { - return $r; - } - return $r; - } // fn importPlaylistOpen - - - /** - * Close import-handle and import playlist - * - * @param string $token - * import token obtained by importPlaylistOpen method - * @return int - * result file local id (or error object) - */ - public function importPlaylistClose($token) - { - $arr = $this->bsClosePut($token); - if (PEAR::isError($arr)) { - return $arr; - } - $fname = $arr['fname']; - $owner = $arr['owner']; - $res = $this->bsImportPlaylist($fname, $owner); - if (file_exists($fname)) { - @unlink($fname); - } - return $res; - } // fn importPlaylistClose - - - /** - * Check whether a Playlist metafile with the given playlist ID exists. - * - * @param int $id - * local id - * @param string $sessid - * session ID - * @return boolean - */ - public function existsPlaylist($id) - { - $pl = Playlist::Recall($id); - if ($pl === FALSE) { + if($pl === FALSE) return FALSE; - } - return TRUE; - } // fn existsPlaylist - - - /** - * Check whether a Playlist metafile with the given playlist ID - * is available for editing, i.e., exists and is not marked as - * beeing edited. - * - * @param int $id - * local id - * @param string $sessid - * session ID - * @return TRUE|int - * id of user editing it - */ - public function playlistIsAvailable($id, $sessid) - { - $pl = Playlist::Recall($id); - if ($pl === FALSE) { - return FALSE; - } - - $res = $pl->isEdited(); - - if($res !== FALSE) + $res = $pl->unlock($sessid); return $res; - - return TRUE; - } // fn playlistIsAvailable - - - /* ---------------------------------------------- time conversion methods */ - /** - * Convert playlist time value to float seconds - * - * @param string $plt - * playlist time value (HH:mm:ss.dddddd) - * @return int - * seconds - */ - public function playlistTimeToSeconds($plt) - { - return Playlist::playlistTimeToSeconds($plt); - } - - - /** - * Convert float seconds value to playlist time format - * - * @param int $s0 - * seconds - * @return string - * time in playlist time format (HH:mm:ss.dddddd) - */ - public static function secondsToPlaylistTime($s0) - { - return Playlist::secondsToPlaylistTime($s0); - } // fn secondsToPlaylistTime - - - /* ------------------------------------------------------- render methods */ - /** - * Render playlist to ogg file (open handle) - * - * @param string $sessid - * session id - * @param string $plid - * playlist gunid - * @return string $token - * render token - */ - public function renderPlaylistToFileOpen($sessid, $plid) - { - $r = Renderer::rnRender2FileOpen($this, $plid); - if (PEAR::isError($r)) { - return $r; } - return $r; - } // fn renderPlaylistToFileOpen - /** - * Render playlist to ogg file (check results) - * - * @param string $token - * render token - * @return hasharray: - * status : string - susccess | working | fault - * tmpfile : string - filepath to result temporary file - */ - public function renderPlaylistToFileCheck($token) - { - $r = Renderer::rnRender2FileCheck($this, $token); - if (PEAR::isError($r)) { - return $r; + /** + * Add audioclip specified by local id to the playlist + * + * @param string $token + * playlist access token + * @param string $acId + * local ID of added file + * @param string $sessid + * session ID + * @param string $fadeIn + * in time format hh:mm:ss.ssssss + * @param string $fadeOut + * in time format hh:mm:ss.ssssss + * @param string $length + * length in extent format - + * for webstream (or for overrule length of audioclip) + * @param string $clipstart + * optional clipstart time format hh:mm:ss.ssssss - relative to begin + * @param string $clipend + * optional $clipend time format hh:mm:ss.ssssss - relative to begin + * @return boolean, true if added. + */ + public function addAudioClipToPlaylist($id, $acId, $pos=NULL, $fadeIn=NULL, $fadeOut=NULL, $cliplength=NULL, $cueIn=NULL, $cueOut=NULL) + { + $pl = Playlist::Recall($id); + if ($pl === FALSE) { + return FALSE; + } + + $res = $pl->addAudioClip($acId, $pos, $fadeIn, $fadeOut, $cliplength, $cueIn, $cueOut); + + return $res; + } // fn addAudioClipToPlaylist + + + /** + * Remove audioclip from playlist + * + * @param string $id + * playlist id + * @param int $pos + * position of element in playlist to delete. + * @return boolean, true if deleted. + * @todo rename this function to "deleteAudioClipFromPlaylist" + */ + public function delAudioClipFromPlaylist($id, $pos) + { + $pl = Playlist::Recall($id); + if ($pl === FALSE) { + return FALSE; + } + + $res = $pl->delAudioClip($pos); + if($res === FALSE) + return FALSE; + + return TRUE; } - return array('status'=>$r['status'], 'tmpfile'=>$r['tmpfile']); - } // fn renderPlaylistToFileCheck + /** + * Move audioClip to the new position in the playlist. + * + * This method may change id attributes of playlistElements and/or + * fadeInfo. + * + * @param string $id + * playlist id + * @param id $oldPos + * old position in playlist + * @param int $newPos + * new position in playlist + * @return boolean + */ + public function moveAudioClipInPlaylist($id, $oldPos, $newPos) + { + $pl = Playlist::Recall($id); + if ($pl === FALSE) { + return FALSE; + } - /** - * Render playlist to ogg file (list results) - * - * @param string $status - * success | working | fault - * if this parameter is not set, then return with all unclosed - * @return array of hasharray: - * status : string - susccess | working | fault - * tmpfile : string - filepath to result temporary file - */ - public function renderPlaylistToFileList($status='') - { - return Renderer::rnRender2FileList($this, $status); - } // fn renderPlaylistToFileList + $res = $pl->moveAudioClip($oldPos, $newPos); - - /** - * Render playlist to ogg file (close handle) - * - * @param string $token - * render token - * @return boolean - * status - */ - public function renderPlaylistToFileClose($token) - { - $r = Renderer::rnRender2FileClose($this, $token); - if (PEAR::isError($r)) { - return $r; + return $res; } - return array(TRUE); - } // fn renderPlaylistToFileClose + /** + * Change fadeInfo values + * + * @param string $id + * playlist id + * @param string $fadeIn + * in time format hh:mm:ss.ssssss + * @param string $fadeOut + * in time format hh:mm:ss.ssssss + * @return boolean + */ + public function changeFadeInfo($id, $pos, $fadeIn, $fadeOut) + { + $pl = Playlist::Recall($id); + if ($pl === FALSE) { + return FALSE; + } - /** - * Render playlist to storage media clip (open handle) - * - * @param string $sessid - * session id - * @param string $plid - * playlist gunid - * @return string - * render token - */ - public function renderPlaylistToStorageOpen($sessid, $plid) - { - $owner = GreenBox::getSessUserId($sessid); - if (PEAR::isError($owner)) { - return $owner; + $res = $pl->changeFadeInfo($pos, $fadeIn, $fadeOut); + + return $res; } - $r = Renderer::rnRender2FileOpen($this, $plid, $owner); - if (PEAR::isError($r)) { - return $r; + + /** + * Change cueIn/cueOut values for playlist element + * + * @param string $id + * playlist id + * @param string $cueIn + * in time format hh:mm:ss.ssssss + * @param string $cueOut + * in time format hh:mm:ss.ssssss + * relative to begin + * @param sessid $string + * session ID + * @return boolean or pear error object + */ + public function changeClipLength($id, $pos, $cueIn, $cueOut) + { + $pl = Playlist::Recall($id); + if ($pl === FALSE) { + return FALSE; + } + + $res = $pl->changeClipLength($pos, $cueIn, $cueOut); + + return $res; } - return $r; - } // fn renderPlaylistToStorageOpen + /** + * Delete a Playlist metafile. + * + * @param int $id + * local id + * @param string $sessid + * session ID + * @return boolean + */ + public function deletePlaylist($id) + { + return Playlist::Delete($id); - /** - * Render playlist to storage media clip (check results) - * - * @param string $token - * render token - * @return hasharray: - * status : string - susccess | working | fault - * gunid : string - gunid of result file - */ - public function renderPlaylistToStorageCheck($token) - { - $r = Renderer::rnRender2StorageCheck($this, $token); - if (PEAR::isError($r)) { - return $r; } - return $r; - } // fn renderPlaylistToStorageCheck + /** + * Find info about clip at specified offset in playlist. + * + * @param string $sessid + * session id + * @param string $plid + * playlist global unique id + * @param string $offset + * current playtime (hh:mm:ss.ssssss) + * @param int $distance + * 0=current clip; 1=next clip ... + * @return array of matching clip info: + * + */ + public function displayPlaylistClipAtOffset($sessid, $plid, $offset, $distance=0) + { + $pl = Playlist::Recall($plid); + if (is_null($pl) || PEAR::isError($pl)) { + return $pl; + } + $res = $pl->displayPlaylistClipAtOffset($offset, $distance); + if (PEAR::isError($res)) { + return $res; + } + $res['title'] = NULL; + $f = StoredFile::RecallByGunid($res['gunid']); + if (PEAR::isError($f)) { + return $f; + } + $res['title'] = $f->getMetadataValue("dc:title"); + $res['playlist_title'] = NULL; + $pl = Playlist::Recall($plid); + $res['playlist'] = $pl->getName(); - /** - * Render playlist to RSS file (open handle) - * - * @param string $sessid - * session id - * @param string $plid - * playlist gunid - * @return string - * render token - */ - public function renderPlaylistToRSSOpen($sessid, $plid) - { - $token = '123456789abcdeff'; - $fakeFile = $CC_CONFIG['accessDir']."/$token.rss"; - file_put_contents($fakeFile, "fake rendered file"); - return array('token'=>$token); - } // fn renderPlaylistToRSSOpen - - - /** - * Render playlist to RSS file (check results) - * - * @param string $token - * render token - * @return hasharray: - * status : string - susccess | working | fault - * tmpfile : string - filepath to result temporary file - */ - public function renderPlaylistToRSSCheck($token) - { - $fakeFile = $CC_CONFIG['accessDir']."/$token.rss"; - if ($token != '123456789abcdeff' || !file_exists($fakeFile)){ - return PEAR::raiseError( - "renderPlaylistToRSSCheck: invalid token ($token)" - ); + return $res; } - return array( - 'status'=> 'success', - 'tmpfile' => $fakeFile, - ); - } // fn renderPlaylistToRSSCheck - /** - * Render playlist to RSS file (list results) - * - * @param string $status - * success | working | fault - * @return array of hasharray: - * status : string - susccess | working | fault - * tmpfile : string - filepath to result temporary file - */ -// function renderPlaylistToRSSList($status='') -// { -// $dummytokens = array ('123456789abcdeff'); -// foreach ($dummytokens as $token) { -// $r[] = $this->renderPlaylistToRSSCheck($token); -// } -// return $r; -// } // fn renderPlaylistToRSSList + /** + * Create a tarfile with playlist export - playlist and all matching + * sub-playlists and media files (if desired) + * + * @param string $sessid + * string, session ID + * @param array $plids + * array of strings, playlist global unique IDs + * (one gunid is accepted too) + * @param string $type + * playlist format, values: lspl | smil | m3u + * @param boolean $standalone + * if only playlist should be exported or + * with all related files + * @return hasharray with fields: + * fname string: readable fname, + * token string: access token + */ + public function exportPlaylistOpen($sessid, $plids, $type='lspl', $standalone=FALSE) + { + return $this->bsExportPlaylistOpen($plids, $type, !$standalone); + } // fn exportPlaylistOpen - /** - * Render playlist to RSS file (close handle) - * - * @param string $token - * render token - * @return boolean - * status - */ - public function renderPlaylistToRSSClose($token) - { - if ($token != '123456789abcdeff'){ - return PEAR::raiseError( - "GreenBox::renderPlaylistToRSSClose: invalid token" - ); - } - $fakeFile = $CC_CONFIG['accessDir']."/$token.rss"; - unlink($fakeFile); - return TRUE; - } // fn renderPlaylistToRSSClose + /** + * Close playlist export previously opened by the exportPlaylistOpen method + * + * @param string $token + * access token obtained from exportPlaylistOpen + * method call + * @return TRUE|PEAR_Error + */ + public function exportPlaylistClose($token) + { + return $this->bsExportPlaylistClose($token); + } // fn exportPlaylistClose - /*================================================= storage admin methods */ - /* ------------------------------------------------------- backup methods */ - /** - * Create backup of storage (open handle) - * - * @param string $sessid - * session id - * @param struct $criteria - * see search criteria - * @return array - * token : string - backup token - */ - public function createBackupOpen($sessid, $criteria='') - { - $bu = new Backup($this); - if (PEAR::isError($bu)) { - return $bu; - } - return $bu->openBackup($sessid,$criteria); - } // fn createBackupOpen - - - /** - * Create backup of storage (check results) - * - * @param string $token - * backup token - * @return hasharray with field: - * status : string - susccess | working | fault - * faultString: string - description of fault - * token : stirng - backup token - * url : string - access url - */ - public function createBackupCheck($token) - { - $bu = new Backup($this); - if (PEAR::isError($bu)) { - return $bu; - } - return $bu->checkBackup($token); - } // fn createBackupCheck - - - /** - * Create backup of storage (list results) - * - * @param string $sessid - * session id - * @param string $stat - * if this parameter is not set, then return with all unclosed backups - * @return array of hasharray with field: - * status : string - susccess | working | fault - * token : stirng - backup token - * url : string - access url - */ - public function createBackupList($sessid, $stat='') - { - $bu = new Backup($this); - if (PEAR::isError($bu)) { - return $bu; - } - return $bu->listBackups($stat); - } // fn createBackupList - - - /** - * Create backup of storage (close handle) - * - * @param string $token - * backup token - * @return boolean - * status - */ - public function createBackupClose($token) - { - $bu = new Backup($this); - if (PEAR::isError($bu)) { - return $bu; - } - return $bu->closeBackup($token); - } // fn createBackupClose - - - /* ===================================================== restore funcitons*/ - /** - * Restore a backup file - * - * @param string $sessid - * session id - * @param string $filename - * backup file path - * @return string - * restore token - */ - public function backupRestoreOpen($sessid, $filename) - { - $rs = new Restore($this); - if (PEAR::isError($rs)) { - return $rs; - } - return $rs->openRestore($sessid,$filename); - } // fn backupRestoreOpen - - - /** - * Check status of backup restore - * - * @param string $token - * restore token - * @return hasharray - * fields: - * token: string - restore token - * status: string - working | fault | success - * faultString: string - description of fault - */ - public function backupRestoreCheck($token) - { - $rs = new Restore($this); - if (PEAR::isError($rs)) { - return $rs; - } - return $rs->checkRestore($token); - } // fn backupRestoreCheck - - - /** - * Close a restore procedure - * - * @param string $token - * restore token - * @return boolean - * is success - */ - public function backupRestoreClose($token) { - $rs = new Restore($this); - if (PEAR::isError($rs)) { - return $rs; - } - return $rs->closeRestore($token); - } // fn backupRestoreClose - - /* ============================================== methods for preferences */ - - /** - * Read preference record by session id - * - * @param string $sessid - * session id - * @param string $key - * preference key - * @return string - * preference value - */ - public function loadPref($sessid, $key) - { - $pr = new Prefs($this); - $res = $pr->loadPref($sessid, $key); - return $res; - } // fn loadPref - - - /** - * Save preference record by session id - * - * @param string $sessid - * session id - * @param string $key - * preference key - * @param string $value - * preference value - * @return boolean - */ - public function savePref($sessid, $key, $value) - { - $pr = new Prefs($this); - $res = $pr->savePref($sessid, $key, $value); - return $res; - } // fn savePref - - - /** - * Delete preference record by session id - * - * @param string $sessid - * session id - * @param string $key - * preference key - * @return boolean - */ - public function delPref($sessid, $key) - { - $pr = new Prefs($this); - $res = $pr->delPref($sessid, $key); - return $res; - } // fn delPref - - - /** - * Read group preference record - * - * @param string $sessid - * session id - * @param string $group - * group name - * @param string $key - * preference key - * @return string - * preference value - */ - public function loadGroupPref($group, $key) - { - $pr = new Prefs($this); - $res = $pr->loadGroupPref($group, $key); - return $res; - } // fn loadGroupPref - - - /** - * Save group preference record - * - * @param string $sessid - * session id - * @param string $group - * group name - * @param string $key - * preference key - * @param string $value - * preference value - * @return boolean - */ - public function saveGroupPref($sessid, $group, $key, $value) - { - $pr = new Prefs($this); - $res = $pr->saveGroupPref($sessid, $group, $key, $value); - return $res; - } // fn saveGroupPref - - - /** - * Delete group preference record - * - * @param string $sessid - * session id - * @param string $group - * group name - * @param string $key - * preference key - * @return boolean - */ - public function delGroupPref($sessid, $group, $key) - { - $pr = new Prefs($this); - $res = $pr->delGroupPref($sessid, $group, $key); - return $res; - } // fn delGroupPref - - - /* =================================================== networking methods */ - /* ------------------------------------------------------- common methods */ - /** - * Common "check" method for transports - * - * @param string $trtok - * transport token - * @return array with fields: - * trtype: string - audioclip | playlist | search | file - * state: string - transport state - * direction: string - up | down - * expectedsize: int - file size in bytes - * realsize: int - currently transported bytes - * expectedchsum: string - orginal file checksum - * realchsum: string - transported file checksum - * ... ? - */ - public function getTransportInfo($trtok) - { - $tr = new Transport($this); - return $tr->getTransportInfo($trtok); - } // fn getTransportInfo - - - /** - * Turn transports on/off, optionaly return current state. - * - * @param string $sessid - * session id - * @param boolean $onOff - * optional (if not used, current state is returned) - * @return boolean - * previous state - */ - public function turnOnOffTransports($sessid, $onOff=NULL) - { - $tr = new Transport($this); - return $tr->turnOnOffTransports($sessid, $onOff); - } // fn turnOnOffTransports - - - /** - * Pause, resume or cancel transport - * - * @param string $trtok - * transport token - * @param string $action - * pause | resume | cancel - * @return string - * resulting transport state - */ - public function doTransportAction($trtok, $action) - { - $tr = new Transport($this); - $res = $tr->doTransportAction($trtok, $action); - return $res; - } // fn doTransportAction - - - /* ------------------------ methods for ls-archive-format file transports */ - /** - * Open async file transfer from local storageServer to network hub, - * file should be ls-archive-format file. - * - * @param string $filePath - * local path to uploaded file - * @return string - * transport token - */ - public function uploadFile2Hub($filePath) - { - $tr = new Transport($this); - return $tr->uploadFile2Hub($filePath); - } // fn uploadFile2Hub - - - /** - * Get list of prepared transfers initiated by hub - * - * @return array of structs/hasharrays with fields: - * trtok: string transport token - * ... ? - */ - public function getHubInitiatedTransfers() - { - $tr = new Transport($this); - return $tr->getHubInitiatedTransfers(); - } // fn getHubInitiatedTransfers - - - /** - * Start of download initiated by hub - * - * @param string $trtok - * transport token obtained from - * the getHubInitiatedTransfers method - * @return string - * transport token - */ - public function startHubInitiatedTransfer($trtok) - { - $tr = new Transport($this); - return $tr->startHubInitiatedTransfer($trtok); - } // fn startHubInitiatedTransfer - - - /* ------------- special methods for audioClip/webstream object transport */ - - /** - * Start upload of audioClip/webstream/playlist from local storageServer - * to hub - * - * @param string $gunid - * global unique id of object being transported - * @param boolean $withContent - * if true, transport playlist content too - * @return string - * transport token - * @todo rename this function "uploadToHub" - */ - public function upload2Hub($gunid, $withContent=FALSE) - { - $tr = new Transport($this); - return $tr->upload2Hub($gunid, $withContent); - } // fn upload2Hub - - - /** - * Start download of audioClip/webstream/playlist from hub to local - * storageServer - * - * @param string $sessid - * session id - * @param string $gunid - * global unique id of playlist being transported - * @param boolean $withContent - * if true, transport playlist content too - * @return string - * transport token - */ - public function downloadFromHub($sessid, $gunid, $withContent=TRUE){ - $uid = GreenBox::getSessUserId($sessid); - if (PEAR::isError($uid)) { - return $uid; - } - $tr = new Transport($this); - return $tr->downloadFromHub($uid, $gunid, $withContent); - } // fn downloadFromHub - - - /* ------------------------------------------------ global-search methods */ - /** - * Start search job on network hub - * - * @param array $criteria - * criteria format (see localSearch) - * @return string - * transport token - */ - public function globalSearch($criteria) - { - $tr = new Transport($this); - //return $tr->globalSearch($criteria); - return $tr->remoteSearch($criteria); - } - - - /** - * Get results from search job on network hub - * - * @param string $trtok - * transport token - * @param boolean $andClose - * if TRUE, close transport token - * @return array - * search result format (see localSearch) - */ -// public function getSearchResults($trtok, $andClose=TRUE) -// { -// $tr = new Transport($this); -// return $tr->getSearchResults($trtok, $andClose); -// } // fn getSearchResults - - - /* ========================================================= info methods */ - /** - * Check if file gunid exists in the storage and - * user have permission to read it - * - * @param string $sessid - * session id - * @param string $gunid - * @param string $ftype - * internal file type - * @return string|PEAR_Error - */ - public function existsFile($sessid, $gunid, $ftype=NULL) - { - if (($res = BasicStor::Authorize('read', $id, $sessid)) !== TRUE) { - return $res; - } - $f = StoredFile::RecallByGunid($gunid); - return $f->existsFile(); - } // fn existsFile - - - /* ==================================================== redefined methods */ - /** - * Get user id from session id - * - * This redefinition only simulate old (bad) behaviour - returns NULL - * for wrong sessid (code ALIBERR_NOTEXISTS). - * HtmlUI depends on it. - * - * @param string $sessid - * @return int|null|PEAR_Error - */ - public static function GetSessUserId($sessid) - { - $r = Alib::GetSessUserId($sessid); - if (PEAR::isError($r)) { - if ($r->getCode() == ALIBERR_NOTEXISTS) { - return NULL; - } else { + /** + * Open writable handle for import playlist in LS Archive format + * + * @param string $sessid + * session id + * @param string $chsum + * md5 checksum of imported file + * @return hasharray with: + * fname string: writable local filename + * token string: put token + */ + public function importPlaylistOpen($sessid, $chsum='') + { + $userid = GreenBox::GetSessUserId($sessid); + if (PEAR::isError($userid)) { + return $userid; + } + $r = $this->bsOpenPut($chsum, NULL, $userid); + if (PEAR::isError($r)) { return $r; } - } - return $r; - } // fn getSessUserId + return $r; + } // fn importPlaylistOpen - /** - * Change user password. - * - * ('superuser mode'= superuser is changing some password without - * knowledge of the old password) - * - * @param string $login - * @param string $oldpass - * old password - * (should be null or empty for 'superuser mode') - * @param string $pass - * @param string $sessid - * session id, required for 'superuser mode' - * @return boolean/err - */ - public function passwd($login, $oldpass=null, $pass='', $sessid='') - { - if (is_null($oldpass) || ($oldpass == '') ) { - if (($res = BasicStor::Authorize('subjects', $this->rootId, $sessid)) !== TRUE) { - sleep(2); - return $res; - } else { - $oldpass = null; + /** + * Close import-handle and import playlist + * + * @param string $token + * import token obtained by importPlaylistOpen method + * @return int + * result file local id (or error object) + */ + public function importPlaylistClose($token) + { + $arr = $this->bsClosePut($token); + if (PEAR::isError($arr)) { + return $arr; } - } else { - if (FALSE === Subjects::Authenticate($login, $oldpass)) { - sleep(2); + $fname = $arr['fname']; + $owner = $arr['owner']; + $res = $this->bsImportPlaylist($fname, $owner); + if (file_exists($fname)) { + @unlink($fname); + } + return $res; + } // fn importPlaylistClose + + + /** + * Check whether a Playlist metafile with the given playlist ID exists. + * + * @param int $id + * local id + * @param string $sessid + * session ID + * @return boolean + */ + public function existsPlaylist($id) + { + $pl = Playlist::Recall($id); + if ($pl === FALSE) { + return FALSE; + } + + return TRUE; + } // fn existsPlaylist + + + /** + * Check whether a Playlist metafile with the given playlist ID + * is available for editing, i.e., exists and is not marked as + * beeing edited. + * + * @param int $id + * local id + * @param string $sessid + * session ID + * @return TRUE|int + * id of user editing it + */ + public function playlistIsAvailable($id, $sessid) + { + $pl = Playlist::Recall($id); + if ($pl === FALSE) { + return FALSE; + } + + $res = $pl->isEdited(); + + if($res !== FALSE) + return $res; + + return TRUE; + } // fn playlistIsAvailable + + + /* ---------------------------------------------- time conversion methods */ + /** + * Convert playlist time value to float seconds + * + * @param string $plt + * playlist time value (HH:mm:ss.dddddd) + * @return int + * seconds + */ + public function playlistTimeToSeconds($plt) + { + return Playlist::playlistTimeToSeconds($plt); + } + + + /** + * Convert float seconds value to playlist time format + * + * @param int $s0 + * seconds + * @return string + * time in playlist time format (HH:mm:ss.dddddd) + */ + public static function secondsToPlaylistTime($s0) + { + return Playlist::secondsToPlaylistTime($s0); + } // fn secondsToPlaylistTime + + + /* ------------------------------------------------------- render methods */ + /** + * Render playlist to ogg file (open handle) + * + * @param string $sessid + * session id + * @param string $plid + * playlist gunid + * @return string $token + * render token + */ + public function renderPlaylistToFileOpen($sessid, $plid) + { + $r = Renderer::rnRender2FileOpen($this, $plid); + if (PEAR::isError($r)) { + return $r; + } + return $r; + } // fn renderPlaylistToFileOpen + + + /** + * Render playlist to ogg file (check results) + * + * @param string $token + * render token + * @return hasharray: + * status : string - susccess | working | fault + * tmpfile : string - filepath to result temporary file + */ + public function renderPlaylistToFileCheck($token) + { + $r = Renderer::rnRender2FileCheck($this, $token); + if (PEAR::isError($r)) { + return $r; + } + return array('status'=>$r['status'], 'tmpfile'=>$r['tmpfile']); + } // fn renderPlaylistToFileCheck + + + /** + * Render playlist to ogg file (list results) + * + * @param string $status + * success | working | fault + * if this parameter is not set, then return with all unclosed + * @return array of hasharray: + * status : string - susccess | working | fault + * tmpfile : string - filepath to result temporary file + */ + public function renderPlaylistToFileList($status='') + { + return Renderer::rnRender2FileList($this, $status); + } // fn renderPlaylistToFileList + + + /** + * Render playlist to ogg file (close handle) + * + * @param string $token + * render token + * @return boolean + * status + */ + public function renderPlaylistToFileClose($token) + { + $r = Renderer::rnRender2FileClose($this, $token); + if (PEAR::isError($r)) { + return $r; + } + return array(TRUE); + } // fn renderPlaylistToFileClose + + + /** + * Render playlist to storage media clip (open handle) + * + * @param string $sessid + * session id + * @param string $plid + * playlist gunid + * @return string + * render token + */ + public function renderPlaylistToStorageOpen($sessid, $plid) + { + $owner = GreenBox::getSessUserId($sessid); + if (PEAR::isError($owner)) { + return $owner; + } + $r = Renderer::rnRender2FileOpen($this, $plid, $owner); + if (PEAR::isError($r)) { + return $r; + } + return $r; + } // fn renderPlaylistToStorageOpen + + + /** + * Render playlist to storage media clip (check results) + * + * @param string $token + * render token + * @return hasharray: + * status : string - susccess | working | fault + * gunid : string - gunid of result file + */ + public function renderPlaylistToStorageCheck($token) + { + $r = Renderer::rnRender2StorageCheck($this, $token); + if (PEAR::isError($r)) { + return $r; + } + return $r; + } // fn renderPlaylistToStorageCheck + + + /** + * Render playlist to RSS file (open handle) + * + * @param string $sessid + * session id + * @param string $plid + * playlist gunid + * @return string + * render token + */ + public function renderPlaylistToRSSOpen($sessid, $plid) + { + $token = '123456789abcdeff'; + $fakeFile = $CC_CONFIG['accessDir']."/$token.rss"; + file_put_contents($fakeFile, "fake rendered file"); + return array('token'=>$token); + } // fn renderPlaylistToRSSOpen + + + /** + * Render playlist to RSS file (check results) + * + * @param string $token + * render token + * @return hasharray: + * status : string - susccess | working | fault + * tmpfile : string - filepath to result temporary file + */ + public function renderPlaylistToRSSCheck($token) + { + $fakeFile = $CC_CONFIG['accessDir']."/$token.rss"; + if ($token != '123456789abcdeff' || !file_exists($fakeFile)){ return PEAR::raiseError( - "GreenBox::passwd: access denied (oldpass)", GBERR_DENY); + "renderPlaylistToRSSCheck: invalid token ($token)" + ); } - } - $res = Subjects::Passwd($login, $oldpass, $pass); - if (PEAR::isError($res)) { - return $res; - } - return TRUE; - } // fn passwd + return array( + 'status'=> 'success', + 'tmpfile' => $fakeFile, + ); + } // fn renderPlaylistToRSSCheck - /** - * Insert permission record - * - * @param int $sid - * local user/group id - * @param string $action - * @param int $oid - * local object id - * @param char $type - * 'A'|'D' (allow/deny) - * @param string $sessid - * session id - * @return int - * local permission id - */ - public function addPerm($sid, $action, $oid, $type='A', $sessid='') - { - if (($res = BasicStor::Authorize('editPerms', $oid, $sessid)) !== TRUE) { - return $res; - } - return Alib::AddPerm($sid, $action, $oid, $type); - } // fn addPerm + /** + * Render playlist to RSS file (list results) + * + * @param string $status + * success | working | fault + * @return array of hasharray: + * status : string - susccess | working | fault + * tmpfile : string - filepath to result temporary file + */ + // function renderPlaylistToRSSList($status='') + // { + // $dummytokens = array ('123456789abcdeff'); + // foreach ($dummytokens as $token) { + // $r[] = $this->renderPlaylistToRSSCheck($token); + // } + // return $r; + // } // fn renderPlaylistToRSSList - /** - * Remove permission record - * - * @param int $permid - * local permission id - * @param int $subj - * local user/group id - * @param int $obj - * local object id - * @param string $sessid - * session id - * @return boolean/error - */ - public function removePerm($permid=NULL, $subj=NULL, $obj=NULL, $sessid='') - { - if (!is_null($permid)) { - $oid = Alib::GetPermOid($permid); - if (PEAR::isError($oid)) { - return $oid; + /** + * Render playlist to RSS file (close handle) + * + * @param string $token + * render token + * @return boolean + * status + */ + public function renderPlaylistToRSSClose($token) + { + if ($token != '123456789abcdeff'){ + return PEAR::raiseError( + "GreenBox::renderPlaylistToRSSClose: invalid token" + ); } - if (!is_null($oid)) { - if (($res = BasicStor::Authorize('editPerms', $oid, $sessid)) !== TRUE) { - return $res; + $fakeFile = $CC_CONFIG['accessDir']."/$token.rss"; + unlink($fakeFile); + return TRUE; + } // fn renderPlaylistToRSSClose + + + /*================================================= storage admin methods */ + /* ------------------------------------------------------- backup methods */ + /** + * Create backup of storage (open handle) + * + * @param string $sessid + * session id + * @param struct $criteria + * see search criteria + * @return array + * token : string - backup token + */ + public function createBackupOpen($sessid, $criteria='') + { + $bu = new Backup($this); + if (PEAR::isError($bu)) { + return $bu; + } + return $bu->openBackup($sessid,$criteria); + } // fn createBackupOpen + + + /** + * Create backup of storage (check results) + * + * @param string $token + * backup token + * @return hasharray with field: + * status : string - susccess | working | fault + * faultString: string - description of fault + * token : stirng - backup token + * url : string - access url + */ + public function createBackupCheck($token) + { + $bu = new Backup($this); + if (PEAR::isError($bu)) { + return $bu; + } + return $bu->checkBackup($token); + } // fn createBackupCheck + + + /** + * Create backup of storage (list results) + * + * @param string $sessid + * session id + * @param string $stat + * if this parameter is not set, then return with all unclosed backups + * @return array of hasharray with field: + * status : string - susccess | working | fault + * token : stirng - backup token + * url : string - access url + */ + public function createBackupList($sessid, $stat='') + { + $bu = new Backup($this); + if (PEAR::isError($bu)) { + return $bu; + } + return $bu->listBackups($stat); + } // fn createBackupList + + + /** + * Create backup of storage (close handle) + * + * @param string $token + * backup token + * @return boolean + * status + */ + public function createBackupClose($token) + { + $bu = new Backup($this); + if (PEAR::isError($bu)) { + return $bu; + } + return $bu->closeBackup($token); + } // fn createBackupClose + + + /* ===================================================== restore funcitons*/ + /** + * Restore a backup file + * + * @param string $sessid + * session id + * @param string $filename + * backup file path + * @return string + * restore token + */ + public function backupRestoreOpen($sessid, $filename) + { + $rs = new Restore($this); + if (PEAR::isError($rs)) { + return $rs; + } + return $rs->openRestore($sessid,$filename); + } // fn backupRestoreOpen + + + /** + * Check status of backup restore + * + * @param string $token + * restore token + * @return hasharray + * fields: + * token: string - restore token + * status: string - working | fault | success + * faultString: string - description of fault + */ + public function backupRestoreCheck($token) + { + $rs = new Restore($this); + if (PEAR::isError($rs)) { + return $rs; + } + return $rs->checkRestore($token); + } // fn backupRestoreCheck + + + /** + * Close a restore procedure + * + * @param string $token + * restore token + * @return boolean + * is success + */ + public function backupRestoreClose($token) { + $rs = new Restore($this); + if (PEAR::isError($rs)) { + return $rs; + } + return $rs->closeRestore($token); + } // fn backupRestoreClose + + /* ============================================== methods for preferences */ + + /** + * Read preference record by session id + * + * @param string $sessid + * session id + * @param string $key + * preference key + * @return string + * preference value + */ + public function loadPref($sessid, $key) + { + $pr = new Prefs($this); + $res = $pr->loadPref($sessid, $key); + return $res; + } // fn loadPref + + + /** + * Save preference record by session id + * + * @param string $sessid + * session id + * @param string $key + * preference key + * @param string $value + * preference value + * @return boolean + */ + public function savePref($sessid, $key, $value) + { + $pr = new Prefs($this); + $res = $pr->savePref($sessid, $key, $value); + return $res; + } // fn savePref + + + /** + * Delete preference record by session id + * + * @param string $sessid + * session id + * @param string $key + * preference key + * @return boolean + */ + public function delPref($sessid, $key) + { + $pr = new Prefs($this); + $res = $pr->delPref($sessid, $key); + return $res; + } // fn delPref + + + /** + * Read group preference record + * + * @param string $sessid + * session id + * @param string $group + * group name + * @param string $key + * preference key + * @return string + * preference value + */ + public function loadGroupPref($group, $key) + { + $pr = new Prefs($this); + $res = $pr->loadGroupPref($group, $key); + return $res; + } // fn loadGroupPref + + + /** + * Save group preference record + * + * @param string $sessid + * session id + * @param string $group + * group name + * @param string $key + * preference key + * @param string $value + * preference value + * @return boolean + */ + public function saveGroupPref($sessid, $group, $key, $value) + { + $pr = new Prefs($this); + $res = $pr->saveGroupPref($sessid, $group, $key, $value); + return $res; + } // fn saveGroupPref + + + /** + * Delete group preference record + * + * @param string $sessid + * session id + * @param string $group + * group name + * @param string $key + * preference key + * @return boolean + */ + public function delGroupPref($sessid, $group, $key) + { + $pr = new Prefs($this); + $res = $pr->delGroupPref($sessid, $group, $key); + return $res; + } // fn delGroupPref + + + /* =================================================== networking methods */ + /* ------------------------------------------------------- common methods */ + /** + * Common "check" method for transports + * + * @param string $trtok + * transport token + * @return array with fields: + * trtype: string - audioclip | playlist | search | file + * state: string - transport state + * direction: string - up | down + * expectedsize: int - file size in bytes + * realsize: int - currently transported bytes + * expectedchsum: string - orginal file checksum + * realchsum: string - transported file checksum + * ... ? + */ + public function getTransportInfo($trtok) + { + $tr = new Transport($this); + return $tr->getTransportInfo($trtok); + } // fn getTransportInfo + + + /** + * Turn transports on/off, optionaly return current state. + * + * @param string $sessid + * session id + * @param boolean $onOff + * optional (if not used, current state is returned) + * @return boolean + * previous state + */ + public function turnOnOffTransports($sessid, $onOff=NULL) + { + $tr = new Transport($this); + return $tr->turnOnOffTransports($sessid, $onOff); + } // fn turnOnOffTransports + + + /** + * Pause, resume or cancel transport + * + * @param string $trtok + * transport token + * @param string $action + * pause | resume | cancel + * @return string + * resulting transport state + */ + public function doTransportAction($trtok, $action) + { + $tr = new Transport($this); + $res = $tr->doTransportAction($trtok, $action); + return $res; + } // fn doTransportAction + + + /* ------------------------ methods for ls-archive-format file transports */ + /** + * Open async file transfer from local storageServer to network hub, + * file should be ls-archive-format file. + * + * @param string $filePath + * local path to uploaded file + * @return string + * transport token + */ + public function uploadFile2Hub($filePath) + { + $tr = new Transport($this); + return $tr->uploadFile2Hub($filePath); + } // fn uploadFile2Hub + + + /** + * Get list of prepared transfers initiated by hub + * + * @return array of structs/hasharrays with fields: + * trtok: string transport token + * ... ? + */ + public function getHubInitiatedTransfers() + { + $tr = new Transport($this); + return $tr->getHubInitiatedTransfers(); + } // fn getHubInitiatedTransfers + + + /** + * Start of download initiated by hub + * + * @param string $trtok + * transport token obtained from + * the getHubInitiatedTransfers method + * @return string + * transport token + */ + public function startHubInitiatedTransfer($trtok) + { + $tr = new Transport($this); + return $tr->startHubInitiatedTransfer($trtok); + } // fn startHubInitiatedTransfer + + + /* ------------- special methods for audioClip/webstream object transport */ + + /** + * Start upload of audioClip/webstream/playlist from local storageServer + * to hub + * + * @param string $gunid + * global unique id of object being transported + * @param boolean $withContent + * if true, transport playlist content too + * @return string + * transport token + * @todo rename this function "uploadToHub" + */ + public function upload2Hub($gunid, $withContent=FALSE) + { + $tr = new Transport($this); + return $tr->upload2Hub($gunid, $withContent); + } // fn upload2Hub + + + /** + * Start download of audioClip/webstream/playlist from hub to local + * storageServer + * + * @param string $sessid + * session id + * @param string $gunid + * global unique id of playlist being transported + * @param boolean $withContent + * if true, transport playlist content too + * @return string + * transport token + */ + public function downloadFromHub($sessid, $gunid, $withContent=TRUE){ + $uid = GreenBox::getSessUserId($sessid); + if (PEAR::isError($uid)) { + return $uid; + } + $tr = new Transport($this); + return $tr->downloadFromHub($uid, $gunid, $withContent); + } // fn downloadFromHub + + + /* ------------------------------------------------ global-search methods */ + /** + * Start search job on network hub + * + * @param array $criteria + * criteria format (see localSearch) + * @return string + * transport token + */ + public function globalSearch($criteria) + { + $tr = new Transport($this); + //return $tr->globalSearch($criteria); + return $tr->remoteSearch($criteria); + } + + + /** + * Get results from search job on network hub + * + * @param string $trtok + * transport token + * @param boolean $andClose + * if TRUE, close transport token + * @return array + * search result format (see localSearch) + */ + // public function getSearchResults($trtok, $andClose=TRUE) + // { + // $tr = new Transport($this); + // return $tr->getSearchResults($trtok, $andClose); + // } // fn getSearchResults + + + /* ========================================================= info methods */ + /** + * Check if file gunid exists in the storage and + * user have permission to read it + * + * @param string $sessid + * session id + * @param string $gunid + * @param string $ftype + * internal file type + * @return string|PEAR_Error + */ + public function existsFile($sessid, $gunid, $ftype=NULL) + { + if (($res = BasicStor::Authorize('read', $id, $sessid)) !== TRUE) { + return $res; + } + $f = StoredFile::RecallByGunid($gunid); + return $f->existsFile(); + } // fn existsFile + + + /* ==================================================== redefined methods */ + /** + * Get user id from session id + * + * This redefinition only simulate old (bad) behaviour - returns NULL + * for wrong sessid (code ALIBERR_NOTEXISTS). + * HtmlUI depends on it. + * + * @param string $sessid + * @return int|null|PEAR_Error + */ + public static function GetSessUserId($sessid) + { + $r = Alib::GetSessUserId($sessid); + if (PEAR::isError($r)) { + if ($r->getCode() == ALIBERR_NOTEXISTS) { + return NULL; + } else { + return $r; } } - } - $res = Alib::RemovePerm($permid, $subj, $obj); - return $res; - } // fn removePerm + return $r; + } // fn getSessUserId -} // class GreenBox -?> \ No newline at end of file + + /** + * Change user password. + * + * ('superuser mode'= superuser is changing some password without + * knowledge of the old password) + * + * @param string $login + * @param string $oldpass + * old password + * (should be null or empty for 'superuser mode') + * @param string $pass + * @param string $sessid + * session id, required for 'superuser mode' + * @return boolean/err + */ + public function passwd($login, $oldpass=null, $pass='', $sessid='') + { + if (is_null($oldpass) || ($oldpass == '') ) { + if (($res = BasicStor::Authorize('subjects', $this->rootId, $sessid)) !== TRUE) { + sleep(2); + return $res; + } else { + $oldpass = null; + } + } else { + if (FALSE === Subjects::Authenticate($login, $oldpass)) { + sleep(2); + return PEAR::raiseError( + "GreenBox::passwd: access denied (oldpass)", GBERR_DENY); + } + } + $res = Subjects::Passwd($login, $oldpass, $pass); + if (PEAR::isError($res)) { + return $res; + } + return TRUE; + } // fn passwd + + + /** + * Insert permission record + * + * @param int $sid + * local user/group id + * @param string $action + * @param int $oid + * local object id + * @param char $type + * 'A'|'D' (allow/deny) + * @param string $sessid + * session id + * @return int + * local permission id + */ + public function addPerm($sid, $action, $oid, $type='A', $sessid='') + { + if (($res = BasicStor::Authorize('editPerms', $oid, $sessid)) !== TRUE) { + return $res; + } + return Alib::AddPerm($sid, $action, $oid, $type); + } // fn addPerm + + + /** + * Remove permission record + * + * @param int $permid + * local permission id + * @param int $subj + * local user/group id + * @param int $obj + * local object id + * @param string $sessid + * session id + * @return boolean/error + */ + public function removePerm($permid=NULL, $subj=NULL, $obj=NULL, $sessid='') + { + if (!is_null($permid)) { + $oid = Alib::GetPermOid($permid); + if (PEAR::isError($oid)) { + return $oid; + } + if (!is_null($oid)) { + if (($res = BasicStor::Authorize('editPerms', $oid, $sessid)) !== TRUE) { + return $res; + } + } + } + $res = Alib::RemovePerm($permid, $subj, $obj); + return $res; + } // fn removePerm + + } // class GreenBox + ?> \ No newline at end of file diff --git a/backend/LocStor.php b/backend/LocStor.php index a5762b6ab..fa0956f3b 100644 --- a/backend/LocStor.php +++ b/backend/LocStor.php @@ -50,7 +50,7 @@ class LocStor extends BasicStor { * {url:writable URL for HTTP PUT, token:access token} */ protected function storeAudioClipOpen($sessid, $gunid, $metadata, - $fname, $chsum, $ftype='audioclip') + $fname, $chsum, $ftype='audioclip') { // Check the gunid format if (!BasicStor::CheckGunid($gunid)) { @@ -79,7 +79,7 @@ class LocStor extends BasicStor { if ($storedFile->isAccessed()) { return PEAR::raiseError( 'LocStor::storeAudioClipOpen: is accessed' - ); + ); } $res = $storedFile->replace($oid, $storedFile->getName(), '', $metadata, 'string'); if (PEAR::isError($res)) { @@ -182,7 +182,7 @@ class LocStor extends BasicStor { protected function storeWebstream($sessid, $gunid, $metadata, $fname, $url) { $a = $this->storeAudioClipOpen( - $sessid, $gunid, $metadata, $fname, md5(''), 'webstream'); + $sessid, $gunid, $metadata, $fname, md5(''), 'webstream'); if (PEAR::isError($a)) { return $a; } @@ -267,7 +267,7 @@ class LocStor extends BasicStor { if (is_null($id) || !$ex) { return PEAR::raiseError( "LocStor::downloadRawAudioDataOpen: gunid not found ($gunid)", - GBERR_NOTF + GBERR_NOTF ); } if (($res = BasicStor::Authorize('read', $id, $sessid)) !== TRUE) { @@ -304,8 +304,8 @@ class LocStor extends BasicStor { */ protected function downloadMetadataOpen($sessid, $gunid) { -// $res = $this->existsAudioClip($sessid, $gunid); -// if(PEAR::isError($res)) return $res; + // $res = $this->existsAudioClip($sessid, $gunid); + // if(PEAR::isError($res)) return $res; $media = StoredFile::RecallByGunid($gunid) $id = $media->getGunid(); if (is_null($id)) { @@ -414,7 +414,7 @@ class LocStor extends BasicStor { * * * @see BasicStor::localSearch - */ + */ public function searchMetadata($sessid, $criteria) { if (($res = BasicStor::Authorize('read', $this->storId, $sessid)) !== TRUE) { @@ -592,7 +592,7 @@ class LocStor extends BasicStor { if ($ex) { return PEAR::raiseError( 'LocStor::createPlaylist: already exists' - ); + ); } $tmpFname = uniqid(''); if (($res = BasicStor::Authorize('write', null, $sessid)) !== TRUE) { @@ -608,7 +608,7 @@ class LocStor extends BasicStor { $fname = "newFile.xml"; } $storedFile->setName($fname); - $storedFile->setState('ready'); + $storedFile->setState('ready'); $storedFile->setMime('application/smil'); return $storedFile->gunid; } @@ -634,12 +634,12 @@ class LocStor extends BasicStor { if (!$ex) { return PEAR::raiseError( 'LocStor::editPlaylist: playlist not exists' - ); + ); } if ($this->isEdited($playlistId) !== FALSE) { return PEAR::raiseError( 'LocStor::editPlaylist: playlist already edited' - ); + ); } $storedFile =& StoredFile::RecallByGunid($playlistId); if (is_null($storedFile) || PEAR::isError($storedFile)) { @@ -753,7 +753,7 @@ class LocStor extends BasicStor { } return PEAR::raiseError( 'LocStor::deletePlaylist: playlist not exists', - GBERR_FILENEX + GBERR_FILENEX ); } $storedFile =& StoredFile::RecallByGunid($playlistId); @@ -791,32 +791,32 @@ class LocStor extends BasicStor { * } */ public function accessPlaylist($sessid, $playlistId, $recursive=FALSE, $parent='0') -// { -// if ($recursive) { -// require_once("AccessRecur.php"); -// $r = AccessRecur::accessPlaylist($this, $sessid, $playlistId); -// if (PEAR::isError($r)) { -// return $r; -// } -// return $r; -// } -// $ex = $this->existsPlaylist($sessid, $playlistId); -// if (PEAR::isError($ex)) { -// return $ex; -// } -// if (!$ex) { -// return PEAR::raiseError( -// "LocStor::accessPlaylist: playlist not found ($playlistId)", -// GBERR_NOTF -// ); -// } -// $id = BasicStor::IdFromGunid($playlistId); -// if (($res = BasicStor::Authorize('read', $id, $sessid)) !== TRUE) { -// return $res; -// } -// $res = $this->bsOpenDownload($id, 'metadata', $parent); -// #unset($res['filename']); -// return $res; + // { + // if ($recursive) { + // require_once("AccessRecur.php"); + // $r = AccessRecur::accessPlaylist($this, $sessid, $playlistId); + // if (PEAR::isError($r)) { + // return $r; + // } + // return $r; + // } + // $ex = $this->existsPlaylist($sessid, $playlistId); + // if (PEAR::isError($ex)) { + // return $ex; + // } + // if (!$ex) { + // return PEAR::raiseError( + // "LocStor::accessPlaylist: playlist not found ($playlistId)", + // GBERR_NOTF + // ); + // } + // $id = BasicStor::IdFromGunid($playlistId); + // if (($res = BasicStor::Authorize('read', $id, $sessid)) !== TRUE) { + // return $res; + // } + // $res = $this->bsOpenDownload($id, 'metadata', $parent); + // #unset($res['filename']); + // return $res; } @@ -983,7 +983,7 @@ class LocStor extends BasicStor { if (!$ex) { return PEAR::raiseError( 'LocStor::playlistIsAvailable: playlist not exists' - ); + ); } $ie = $this->isEdited($playlistId); if ($ie === FALSE) { @@ -1159,7 +1159,7 @@ class LocStor extends BasicStor { if ($token != '123456789abcdeff') { return PEAR::raiseError( "LocStor::renderPlaylistToRSSClose: invalid token" - ); + ); } $fakeFile = $CC_CONFIG['accessDir']."/$token.rss"; unlink($fakeFile); @@ -1192,7 +1192,7 @@ class LocStor extends BasicStor { if ($r === FALSE) { return PEAR::raiseError( "LocStor::createBackupOpen: false returned from Backup" - ); + ); } return $r; } @@ -1351,12 +1351,12 @@ class LocStor extends BasicStor { * status: string - working | fault | success */ protected function restoreBackupClose($token) { - require_once('Restore.php'); - $rs = new Restore($this); - if (PEAR::isError($rs)) { - return $rs; - } - return $rs->closeRestore($token); + require_once('Restore.php'); + $rs = new Restore($this); + if (PEAR::isError($rs)) { + return $rs; + } + return $rs->closeRestore($token); } @@ -1387,11 +1387,11 @@ class LocStor extends BasicStor { { $owner = Alib::GetSessUserId($sessid); if (PEAR::isError($owner)) { - return $owner; + return $owner; } $res = $this->bsOpenPut($chsum, NULL, $owner); if (PEAR::isError($res)) { - return $res; + return $res; } return array('url'=>$res['url'], 'token'=>$res['token']); } @@ -1412,7 +1412,7 @@ class LocStor extends BasicStor { { $res = $this->bsClosePut($token); if (PEAR::isError($res)) { - return $res; + return $res; } extract($res); // fname, owner switch ($trtype) { @@ -1420,11 +1420,11 @@ class LocStor extends BasicStor { $mdtoken = $pars['mdpdtoken']; $res = $this->bsClosePut($mdtoken); if (PEAR::isError($res)) { - return $res; + return $res; } $mdfname = $res['fname']; if ($gunid == '') { - $gunid = NULL; + $gunid = NULL; } $values = array( "filename" => $pars['name'], @@ -1432,45 +1432,45 @@ class LocStor extends BasicStor { "metadata" => $mdfname, "gunid" => $pars['gunid'], "filetype" => "audioclip" - ); - $storedFile = StoredFile::Insert($values); - if (PEAR::isError($storedFile)) { - return $storedFile; - } - $res = $storedFile->getId(); - @unlink($fname); - @unlink($mdfname); - break; + ); + $storedFile = StoredFile::Insert($values); + if (PEAR::isError($storedFile)) { + return $storedFile; + } + $res = $storedFile->getId(); + @unlink($fname); + @unlink($mdfname); + break; case "playlist": if ($gunid == '') { - $gunid = NULL; + $gunid = NULL; } $values = array( "filename" => $pars['name'], "metadata" => $fname, "gunid" => $pars['gunid'], "filetype" => "playlist" - ); - $storedFile = StoredFile::Insert($values); - if (PEAR::isError($storedFile)) { - return $storedFile; - } - $res = $storedFile->getId(); - @unlink($fname); - break; + ); + $storedFile = StoredFile::Insert($values); + if (PEAR::isError($storedFile)) { + return $storedFile; + } + $res = $storedFile->getId(); + @unlink($fname); + break; case "playlistPkg": $chsum = md5_file($fname); // importPlaylistOpen: $res = $this->bsOpenPut($chsum, NULL, $owner); if (PEAR::isError($res)) { - return $res; + return $res; } $dest = $res['fname']; $token = $res['token']; copy($fname, $dest); $r = $this->importPlaylistClose($token); if (PEAR::isError($r)) { - return $r; + return $r; } @unlink($fname); return $r; @@ -1481,14 +1481,14 @@ class LocStor extends BasicStor { @unlink($fname); $results = $this->localSearch($criteria); if (PEAR::isError($results)) { - return $results; + return $results; } $realfile = tempnam($this->accessDir, 'searchjob_'); @chmod($realfile, 0660); $len = file_put_contents($realfile, serialize($results)); $acc = BasicStor::bsAccess($realfile, '', NULL, 'download'); if (PEAR::isError($acc)) { - return $acc; + return $acc; } $url = BasicStor::GetUrlPart()."access/".basename($acc['fname']); $chsum = md5_file($realfile); @@ -1523,227 +1523,227 @@ class LocStor extends BasicStor { */ function downloadOpen($sessid, $trtype, $pars=array()) { -// global $CC_CONFIG; -// switch ($trtype) { -// case "unknown": -// case "audioclip": -// case "metadata": -// case "playlist": -// case "playlistPkg": -// if (!isset($pars['gunid'])) { -// return PEAR::raiseError("Archive::downloadOpen: gunid not set"); -// } -// break; -// } -// $gunid = $pars['gunid']; -// // resolve trtype by object type: -// if ( ($trtype == 'unknown') || ($trtype == 'playlistPkg') ) { -// $media = StoredFile::RecallByGunid($gunid); -// $trtype2 = $media->getType(); -// if (PEAR::isError($trtype2)) { -// return $trtype2; -// } -// // required with content: -// $trtype = ( ($trtype2 == 'playlist') && ($trtype == 'playlistPkg') ? -// 'playlistPkg' : $trtype2); -// //return PEAR::raiseError("Archive::downloadOpen: TT=$trtype TT2=$trtype2 G=$gunid"); -// } -// switch ($trtype) { -// case "audioclip": -// $res = $this->downloadRawAudioDataOpen($sessid, $gunid); -// break; -// case "metadata": -// $res = $this->downloadMetadataOpen($sessid, $gunid); -// break; -// case "playlist": -// $res = $this->accessPlaylist($sessid, $gunid); -// break; -// case "playlistPkg": -// $res = $this->bsExportPlaylistOpen($gunid); -// if (PEAR::isError($res)) { -// return $res; -// } -// $tmpn = tempnam($CC_CONFIG['transDir'], 'plExport_'); -// $plfpath = "$tmpn.lspl"; -// copy($res['fname'], $plfpath); -// $res = $this->bsExportPlaylistClose($res['token']); -// if (PEAR::isError($res)) { -// return $res; -// } -// $fname = "transported_playlist.lspl"; -// $id = BasicStor::IdFromGunid($gunid); -// $acc = BasicStor::bsAccess($plfpath, 'lspl', NULL, 'download'); -// if (PEAR::isError($acc)) { -// return $acc; -// } -// $url = BasicStor::GetUrlPart()."access/".basename($acc['fname']); -// $chsum = md5_file($plfpath); -// $size = filesize($plfpath); -// $res = array( -// 'url'=>$url, 'token'=>$acc['token'], -// 'chsum'=>$chsum, 'size'=>$size, -// 'filename'=>$fname -// ); -// break; -// case "searchjob": -// $res = $pars; -// break; -// case "file": -// $res = array(); -// break; -// default: -// return PEAR::raiseError("Archive::downloadOpen: NotImpl ($trtype)"); -// } -// if (PEAR::isError($res)) { -// return $res; -// } -// switch ($trtype) { -// case "audioclip": -// case "metadata": -// case "playlist": -// case "playlistPkg": -// $f = StoredFile::RecallByGunid($gunid); -// $title = $f->getTitle(); -// break; -// case "searchjob": -// $title = 'searchjob'; -// break; -// case "file": -// $title = 'regular file'; -// break; -// default: -// } -// $res['title'] = $title; -// $res['trtype'] = $trtype; -// return $res; - } + // global $CC_CONFIG; + // switch ($trtype) { + // case "unknown": + // case "audioclip": + // case "metadata": + // case "playlist": + // case "playlistPkg": + // if (!isset($pars['gunid'])) { + // return PEAR::raiseError("Archive::downloadOpen: gunid not set"); + // } + // break; + // } + // $gunid = $pars['gunid']; + // // resolve trtype by object type: + // if ( ($trtype == 'unknown') || ($trtype == 'playlistPkg') ) { + // $media = StoredFile::RecallByGunid($gunid); + // $trtype2 = $media->getType(); + // if (PEAR::isError($trtype2)) { + // return $trtype2; + // } + // // required with content: + // $trtype = ( ($trtype2 == 'playlist') && ($trtype == 'playlistPkg') ? + // 'playlistPkg' : $trtype2); + // //return PEAR::raiseError("Archive::downloadOpen: TT=$trtype TT2=$trtype2 G=$gunid"); + // } + // switch ($trtype) { + // case "audioclip": + // $res = $this->downloadRawAudioDataOpen($sessid, $gunid); + // break; + // case "metadata": + // $res = $this->downloadMetadataOpen($sessid, $gunid); + // break; + // case "playlist": + // $res = $this->accessPlaylist($sessid, $gunid); + // break; + // case "playlistPkg": + // $res = $this->bsExportPlaylistOpen($gunid); + // if (PEAR::isError($res)) { + // return $res; + // } + // $tmpn = tempnam($CC_CONFIG['transDir'], 'plExport_'); + // $plfpath = "$tmpn.lspl"; + // copy($res['fname'], $plfpath); + // $res = $this->bsExportPlaylistClose($res['token']); + // if (PEAR::isError($res)) { + // return $res; + // } + // $fname = "transported_playlist.lspl"; + // $id = BasicStor::IdFromGunid($gunid); + // $acc = BasicStor::bsAccess($plfpath, 'lspl', NULL, 'download'); + // if (PEAR::isError($acc)) { + // return $acc; + // } + // $url = BasicStor::GetUrlPart()."access/".basename($acc['fname']); + // $chsum = md5_file($plfpath); + // $size = filesize($plfpath); + // $res = array( + // 'url'=>$url, 'token'=>$acc['token'], + // 'chsum'=>$chsum, 'size'=>$size, + // 'filename'=>$fname + // ); + // break; + // case "searchjob": + // $res = $pars; + // break; + // case "file": + // $res = array(); + // break; + // default: + // return PEAR::raiseError("Archive::downloadOpen: NotImpl ($trtype)"); + // } + // if (PEAR::isError($res)) { + // return $res; + // } + // switch ($trtype) { + // case "audioclip": + // case "metadata": + // case "playlist": + // case "playlistPkg": + // $f = StoredFile::RecallByGunid($gunid); + // $title = $f->getTitle(); + // break; + // case "searchjob": + // $title = 'searchjob'; + // break; + // case "file": + // $title = 'regular file'; + // break; + // default: + // } + // $res['title'] = $title; + // $res['trtype'] = $trtype; + // return $res; + } - /** - * Close download transport - * - * @param string $token - * transport token - * @param string $trtype - * transport type - * @return array - * hasharray with: - * url string: writable URL - * token string: PUT token - */ - function downloadClose($token, $trtype) - { - switch ($trtype) { - case "audioclip": - $res = $this->downloadRawAudioDataClose($token); - if (PEAR::isError($res)) { - return $res; - } - return $res; - case "metadata": - $res = $this->downloadMetadataClose($token); - return $res; - case "playlist": - $res = $this->releasePlaylist(NULL/*$sessid*/, $token); - return $res; - case "playlistPkg": - $res = BasicStor::bsRelease($token, 'download'); - if (PEAR::isError($res)) { - return $res; - } - $realFname = $r['realFname']; - @unlink($realFname); - if (preg_match("|(plExport_[^\.]+)\.lspl$|", $realFname, $va)) { - list(,$tmpn) = $va; - $tmpn = $CC_CONFIG['transDir']."/$tmpn"; - if (file_exists($tmpn)) { - @unlink($tmpn); + /** + * Close download transport + * + * @param string $token + * transport token + * @param string $trtype + * transport type + * @return array + * hasharray with: + * url string: writable URL + * token string: PUT token + */ + function downloadClose($token, $trtype) + { + switch ($trtype) { + case "audioclip": + $res = $this->downloadRawAudioDataClose($token); + if (PEAR::isError($res)) { + return $res; } - } - return $res; - case "searchjob": - $res = BasicStor::bsRelease($token, 'download'); - return $res; - case "file": - return array(); - default: - return PEAR::raiseError("Archive::downloadClose: NotImpl ($trtype)"); + return $res; + case "metadata": + $res = $this->downloadMetadataClose($token); + return $res; + case "playlist": + $res = $this->releasePlaylist(NULL/*$sessid*/, $token); + return $res; + case "playlistPkg": + $res = BasicStor::bsRelease($token, 'download'); + if (PEAR::isError($res)) { + return $res; + } + $realFname = $r['realFname']; + @unlink($realFname); + if (preg_match("|(plExport_[^\.]+)\.lspl$|", $realFname, $va)) { + list(,$tmpn) = $va; + $tmpn = $CC_CONFIG['transDir']."/$tmpn"; + if (file_exists($tmpn)) { + @unlink($tmpn); + } + } + return $res; + case "searchjob": + $res = BasicStor::bsRelease($token, 'download'); + return $res; + case "file": + return array(); + default: + return PEAR::raiseError("Archive::downloadClose: NotImpl ($trtype)"); + } } - } - /** - * Prepare hub initiated transport - * - * @param string $target - * hostname of transport target - * @param string $trtype - * transport type - * @param string $direction - * 'up' | 'down' - * @param array $pars - * transport parameters - * @return mixed - */ - function prepareHubInitiatedTransfer( + /** + * Prepare hub initiated transport + * + * @param string $target + * hostname of transport target + * @param string $trtype + * transport type + * @param string $direction + * 'up' | 'down' + * @param array $pars + * transport parameters + * @return mixed + */ + function prepareHubInitiatedTransfer( $target, $trtype='file', $direction='up',$pars=array()) - { - $tr = new Transport($this); - $trec = TransportRecord::create($tr, $trtype, $direction, + { + $tr = new Transport($this); + $trec = TransportRecord::create($tr, $trtype, $direction, array_merge($pars, array('target'=>$target))); - if (PEAR::isError($trec)) { - return $trec; + if (PEAR::isError($trec)) { + return $trec; + } + return TRUE; } - return TRUE; - } - /** - * List hub initiated transports - * - * @param string $target - * hostname of transport target - * @param string $direction - * 'up' | 'down' - * @param string $trtok - * transport token - * @return mixed - */ - function listHubInitiatedTransfers( + /** + * List hub initiated transports + * + * @param string $target + * hostname of transport target + * @param string $direction + * 'up' | 'down' + * @param string $trtok + * transport token + * @return mixed + */ + function listHubInitiatedTransfers( $target=NULL, $direction=NULL, $trtok=NULL) - { - $tr = new Transport($this); - $res = $tr->getTransports($direction, $target, $trtok); - return $res; - } - - - /** - * Set state of hub initiated transport - * - * @param string $target - * hostname of transport target - * @param string $trtok - * transport token - * @param string $state - * transport state - * @return TransportRecord|PEAR_Error - */ - function setHubInitiatedTransfer($target, $trtok, $state) - { - $tr = new Transport($this); - $trec = TransportRecord::recall($tr, $trtok); - if (PEAR::isError($trec)) { - return $trec; + { + $tr = new Transport($this); + $res = $tr->getTransports($direction, $target, $trtok); + return $res; } - $r = $trec->setState($state); - if (PEAR::isError($r)) { - return $r; - } - return $trec; - } - /* ==================================================== auxiliary methods */ + + /** + * Set state of hub initiated transport + * + * @param string $target + * hostname of transport target + * @param string $trtok + * transport token + * @param string $state + * transport state + * @return TransportRecord|PEAR_Error + */ + function setHubInitiatedTransfer($target, $trtok, $state) + { + $tr = new Transport($this); + $trec = TransportRecord::recall($tr, $trtok); + if (PEAR::isError($trec)) { + return $trec; + } + $r = $trec->setState($state); + if (PEAR::isError($r)) { + return $r; + } + return $trec; + } + + /* ==================================================== auxiliary methods */ } // class LocStor ?> \ No newline at end of file diff --git a/backend/Playlist.php b/backend/Playlist.php index af8e81ced..bc13938b4 100644 --- a/backend/Playlist.php +++ b/backend/Playlist.php @@ -14,47 +14,47 @@ define('INDCH', ' '); */ class Playlist { - // *** Variable stored in the database *** + // *** Variable stored in the database *** - /** - * @var int - */ - private $id; + /** + * @var int + */ + private $id; - /** - * @var string - */ - private $name; + /** + * @var string + */ + private $name; - /** - * Can be 'ready', 'edited', 'incomplete'. - * - * @var string - */ - private $state; + /** + * Can be 'ready', 'edited', 'incomplete'. + * + * @var string + */ + private $state; - /** - * @var int - */ - private $currentlyaccessing; + /** + * @var int + */ + private $currentlyaccessing; - /** - * @var int - */ - private $editedby; + /** + * @var int + */ + private $editedby; - /** - * @var timestamp - */ - private $mtime; + /** + * @var timestamp + */ + private $mtime; - /** - * @var MetaData - */ - public $md; + /** + * @var MetaData + */ + public $md; - //using propel's phpNames. - private $categories = array("dc:title" => "DbName", "dc:creator" => "DbCreator", "dc:description" => "DbDescription", "dcterms:extent" => "length"); + //using propel's phpNames. + private $categories = array("dc:title" => "DbName", "dc:creator" => "DbCreator", "dc:description" => "DbDescription", "dcterms:extent" => "length"); public function __construct($p_gunid=NULL) @@ -64,31 +64,31 @@ class Playlist { public static function Insert($p_values) { - // Create the StoredPlaylist object + // Create the StoredPlaylist object $storedPlaylist = new Playlist(); $storedPlaylist->name = isset($p_values['filename']) ? $p_values['filename'] : date("H:i:s"); - $storedPlaylist->mtime = new DateTime("now"); + $storedPlaylist->mtime = new DateTime("now"); - $pl = new CcPlaylist(); - $pl->setDbName($storedPlaylist->name); - $pl->setDbState("incomplete"); - $pl->setDbMtime($storedPlaylist->mtime); - $pl->save(); + $pl = new CcPlaylist(); + $pl->setDbName($storedPlaylist->name); + $pl->setDbState("incomplete"); + $pl->setDbMtime($storedPlaylist->mtime); + $pl->save(); - $storedPlaylist->id = $pl->getDbId(); + $storedPlaylist->id = $pl->getDbId(); $storedPlaylist->setState('ready'); - return $storedPlaylist->id; + return $storedPlaylist->id; } public static function Delete($id) { - $pl = CcPlaylistQuery::create()->findPK($id); - if($pl === NULL) + $pl = CcPlaylistQuery::create()->findPK($id); + if($pl === NULL) return FALSE; - $pl->delete(); - return TRUE; + $pl->delete(); + return TRUE; } @@ -98,11 +98,11 @@ class Playlist { */ public static function DeleteFileFromAllPlaylists($p_fileId) { - CcPlaylistcontentsQuery::create()->filterByDbFileId($p_fileId)->delete(); + CcPlaylistcontentsQuery::create()->filterByDbFileId($p_fileId)->delete(); } - /** + /** * Fetch instance of Playlist object.
* * @param string $id @@ -113,8 +113,8 @@ class Playlist { public static function Recall($id) { $pl = CcPlaylistQuery::create()->findPK($id); - if($pl === NULL) - return FALSE; + if($pl === NULL) + return FALSE; $storedPlaylist = new Playlist(); $storedPlaylist->id = $pl->getDbId(); @@ -127,7 +127,7 @@ class Playlist { return $storedPlaylist; } - /** + /** * Rename stored virtual playlist * * @param string $p_newname @@ -137,18 +137,18 @@ class Playlist { { $pl = CcPlaylistQuery::create()->findPK($this->id); - if($pl === NULL) - return FALSE; + if($pl === NULL) + return FALSE; - $pl->setDbName($p_newname); - $pl->setDbMtime(new DateTime("now")); - $pl->save(); + $pl->setDbName($p_newname); + $pl->setDbMtime(new DateTime("now")); + $pl->save(); $this->name = $p_newname; return TRUE; } - /** + /** * Get mnemonic playlist name * * @param string $p_gunid @@ -162,12 +162,12 @@ class Playlist { } $pl = CcPlaylistQuery::create()->findPK($id); if($pl === NULL) - return FALSE; + return FALSE; return $pl->getDbName(); } - /** + /** * Set state of virtual playlist * * @param string $p_state @@ -180,23 +180,23 @@ class Playlist { { $pl = CcPlaylistQuery::create()->findPK($this->id); - if($pl === NULL) - return FALSE; + if($pl === NULL) + return FALSE; - $pl->setDbState($p_state); - $pl->setDbMtime(new DateTime("now")); + $pl->setDbState($p_state); + $pl->setDbMtime(new DateTime("now")); - $eb = (!is_null($p_editedby) ? $p_editedby : NULL); - $pl->setDbEditedby($eb); + $eb = (!is_null($p_editedby) ? $p_editedby : NULL); + $pl->setDbEditedby($eb); - $pl->save(); + $pl->save(); $this->state = $p_state; $this->editedby = $p_editedby; return TRUE; } - /** + /** * Get storage-internal file state * * @param string $p_gunid @@ -211,10 +211,10 @@ class Playlist { } $pl = CcPlaylistQuery::create()->findPK($id); - if($pl === NULL) - return FALSE; + if($pl === NULL) + return FALSE; - return $pl->getDbState(); + return $pl->getDbState(); } /** @@ -223,18 +223,18 @@ class Playlist { /* public function isScheduled() { - global $CC_CONFIG, $CC_DBC; + global $CC_CONFIG, $CC_DBC; - $sql = "SELECT * " - ." FROM ".$CC_CONFIG['scheduleTable'] - ." WHERE ends > now() and playlist=x'{$this->gunid}'::bigint"; - $scheduled = $CC_DBC->getAll($sql); + $sql = "SELECT * " + ." FROM ".$CC_CONFIG['scheduleTable'] + ." WHERE ends > now() and playlist=x'{$this->gunid}'::bigint"; + $scheduled = $CC_DBC->getAll($sql); - return $scheduled; - } - */ + return $scheduled; + } + */ - /** + /** * Returns true if virtual file is currently in use.
* Static or dynamic call is possible. * @@ -249,14 +249,14 @@ class Playlist { } $pl = CcPlaylistQuery::create()->findPK($id); - if (is_null($pl)) { + if (is_null($pl)) { return PEAR::raiseError( "StoredPlaylist::isAccessed: invalid id ($id)", - GBERR_FOBJNEX + GBERR_FOBJNEX ); - } + } - return ($pl->getDbCurrentlyaccessing() > 0); + return ($pl->getDbCurrentlyaccessing() > 0); } /** @@ -274,7 +274,8 @@ class Playlist { return FALSE; } -/** + + /** * Set playlist edit flag * * @param string $p_playlistId @@ -309,7 +310,7 @@ class Playlist { return TRUE; } - /** + /** * Return local ID of virtual file. * * @return int @@ -321,11 +322,11 @@ class Playlist { private function getNextPos() { $res = CcPlaylistQuery::create() - ->findPK($this->id) - ->computeLastPosition(); + ->findPK($this->id) + ->computeLastPosition(); if(is_null($res)) - return 0; + return 0; return $res + 1; } @@ -337,13 +338,13 @@ class Playlist { public function getContents() { $files = array(); $rows = CcPlaylistcontentsQuery::create() - ->joinWith('CcFiles') - ->orderByDbPosition() - ->filterByDbPlaylistId($this->id) - ->find(); + ->joinWith('CcFiles') + ->orderByDbPosition() + ->filterByDbPlaylistId($this->id) + ->find(); foreach ($rows as $row) { - $files[] = $row->toArray(BasePeer::TYPE_FIELDNAME, true, true); + $files[] = $row->toArray(BasePeer::TYPE_FIELDNAME, true, true); } return $files; @@ -351,11 +352,11 @@ class Playlist { public function getLength() { $res = CcPlaylistQuery::create() - ->findPK($this->id) - ->computeLength(); + ->findPK($this->id) + ->computeLength(); if(is_null($res)) - return '00:00:00.000000'; + return '00:00:00.000000'; return $res; } @@ -392,7 +393,7 @@ class Playlist { if ($val && $this->isEdited() !== FALSE) { return PEAR::raiseError( 'Playlist::lock: playlist already locked' - ); + ); } $r = $this->setEditFlag($val, $sessid, $subjid); return $r; @@ -438,29 +439,29 @@ class Playlist { //get audio clip. $media = StoredFile::Recall($p_mediaId); if (is_null($media) || PEAR::isError($media)) { - return $media; + return $media; } // get information about audioClip -// $acInfo = $this->getAudioClipInfo($ac); -// if (PEAR::isError($acInfo)) { -// return $acInfo; -// } -// extract($acInfo); // 'acGunid', 'acLen', 'acTit', 'elType' + // $acInfo = $this->getAudioClipInfo($ac); + // if (PEAR::isError($acInfo)) { + // return $acInfo; + // } + // extract($acInfo); // 'acGunid', 'acLen', 'acTit', 'elType' $metadata = $media->getMetadata(); $length = $metadata["length"]; if (!is_null($p_clipLength)) { - $length = $p_clipLength; + $length = $p_clipLength; } // insert at end of playlist. if (is_null($p_position)) - $p_position = $this->getNextPos(); + $p_position = $this->getNextPos(); if (PEAR::isError($p_position)) { - return $p_position; + return $p_position; } - // insert default values if parameter was empty + // insert default values if parameter was empty $p_cuein = !is_null($p_cuein) ? $p_cuein : '00:00:00.000000'; $p_cueout = !is_null($p_cueout) ? $p_cueout : $length; @@ -475,7 +476,7 @@ class Playlist { $res = $this->insertPlaylistElement($this->id, $p_mediaId, $p_position, $p_clipLength, $p_cuein, $p_cueout, $p_fadeIn, $p_fadeOut); if (PEAR::isError($res)) { - return $res; + return $res; } return TRUE; } @@ -491,21 +492,21 @@ class Playlist { public function delAudioClip($pos) { if($pos < 0 || $pos >= $this->getNextPos()) - return FALSE; + return FALSE; $row = CcPlaylistcontentsQuery::create() - ->filterByDbPlaylistId($this->id) - ->filterByDbPosition($pos) - ->findOne(); + ->filterByDbPlaylistId($this->id) + ->filterByDbPosition($pos) + ->findOne(); if(is_null($row)) - return FALSE; + return FALSE; $row->delete(); return $row; } - /** + /** * Move audioClip to the new position in the playlist * * @param int $oldPos @@ -517,15 +518,15 @@ class Playlist { public function moveAudioClip($oldPos, $newPos) { if($newPos < 0 || $newPos >= $this->getNextPos() || $oldPos < 0 || $oldPos >= $this->getNextPos()) - return FALSE; + return FALSE; $row = $this->delAudioClip($oldPos); if($row === FALSE) - return FALSE; + return FALSE; $res = $this->addAudioClip($row->getDbFileId(), $newPos, $row->getDbFadein(), $row->getDbFadeout(), $row->getDbCliplength(), $row->getDbCuein(), $row->getDbCueout()); if($res !== TRUE) - return FALSE; + return FALSE; return TRUE; } @@ -552,9 +553,9 @@ class Playlist { } $row = CcPlaylistcontentsQuery::create() - ->filterByDbPlaylistId($this->id) - ->filterByDbPosition($pos) - ->findOne(); + ->filterByDbPlaylistId($this->id) + ->filterByDbPosition($pos) + ->findOne(); $clipLength = $row->getDbCliplength(); @@ -622,10 +623,10 @@ class Playlist { } $row = CcPlaylistcontentsQuery::create() - ->joinWith(CcFiles) - ->filterByDbPlaylistId($this->id) - ->filterByDbPosition($pos) - ->findOne(); + ->joinWith(CcFiles) + ->filterByDbPlaylistId($this->id) + ->filterByDbPosition($pos) + ->findOne(); $oldCueIn = $row->getDBCuein(); $oldCueOut = $row->getDbCueout(); @@ -653,7 +654,7 @@ class Playlist { $row->setDbCuein($cueIn); $row->setDbCueout($cueOut); $row->setDBCliplength(Playlist::secondsToPlaylistTime(Playlist::playlistTimeToSeconds($cueOut) - - Playlist::playlistTimeToSeconds($cueIn))); + - Playlist::playlistTimeToSeconds($cueIn))); } else if(!is_null($cueIn)) { @@ -665,7 +666,7 @@ class Playlist { $row->setDbCuein($cueIn); $row->setDBCliplength(Playlist::secondsToPlaylistTime(Playlist::playlistTimeToSeconds($oldCueOut) - - Playlist::playlistTimeToSeconds($cueIn))); + - Playlist::playlistTimeToSeconds($cueIn))); } else if(!is_null($cueOut)) { @@ -685,7 +686,7 @@ class Playlist { $row->setDbCueout($cueOut); $row->setDBCliplength(Playlist::secondsToPlaylistTime(Playlist::playlistTimeToSeconds($cueOut) - - Playlist::playlistTimeToSeconds($oldCueIn))); + - Playlist::playlistTimeToSeconds($oldCueIn))); } $cliplength = $row->getDbCliplength(); @@ -778,10 +779,10 @@ class Playlist { { $arr = preg_split('/:/', $plt); if (isset($arr[2])) { - return (intval($arr[0])*60 + intval($arr[1]))*60 + floatval($arr[2]); + return (intval($arr[0])*60 + intval($arr[1]))*60 + floatval($arr[2]); } if (isset($arr[1])) { - return intval($arr[0])*60 + floatval($arr[1]); + return intval($arr[0])*60 + floatval($arr[1]); } return floatval($arr[0]); } @@ -865,29 +866,29 @@ class Playlist { *
  • elType string - audioClip | playlist
  • * */ -// private function getAudioClipInfo($p_media) -// { -// $ac_id = $p_media->getId(); -// -// $r = $p_media->getMetadataValue('dcterms:extent'); -// if (isset($r)) { -// $acLen = $r; -// } else { -// $acLen = '00:00:00.000000'; -// } -// -// $r = $p_media->getMetadataValue('dc:title'); -// if (isset($r)) { -// $acTit = $r; -// } else { -// $acTit = $acGunid; -// } -// $elType = $p_media->getType(); -// $trTbl = array('audioclip'=>'audioClip', 'webstream'=>'audioClip','playlist'=>'playlist'); -// $elType = $trTbl[$elType]; -// -// return compact('acGunid', 'acLen', 'acTit', 'elType'); -// } + // private function getAudioClipInfo($p_media) + // { + // $ac_id = $p_media->getId(); + // + // $r = $p_media->getMetadataValue('dcterms:extent'); + // if (isset($r)) { + // $acLen = $r; + // } else { + // $acLen = '00:00:00.000000'; + // } + // + // $r = $p_media->getMetadataValue('dc:title'); + // if (isset($r)) { + // $acTit = $r; + // } else { + // $acTit = $acGunid; + // } + // $elType = $p_media->getType(); + // $trTbl = array('audioclip'=>'audioClip', 'webstream'=>'audioClip','playlist'=>'playlist'); + // $elType = $trTbl[$elType]; + // + // return compact('acGunid', 'acLen', 'acTit', 'elType'); + // } /** @@ -927,9 +928,9 @@ class Playlist { private function insertPlaylistElement($plId, $fileId, $pos, $clipLength, $cuein, $cueout, $fadeIn=NULL, $fadeOut=NULL) { if(is_null($fadeIn)) - $fadeIn = '00:00:00.000'; + $fadeIn = '00:00:00.000'; if(is_null($fadeOut)) - $fadeOut = '00:00:00.000'; + $fadeOut = '00:00:00.000'; $row = new CcPlaylistcontents(); $row->setDbPlaylistId($plId); @@ -962,21 +963,21 @@ class Playlist { { $mid = $this->_getMidOrInsert('playlength', $parid, $newPlLen, 'A'); if (PEAR::isError($mid)) { - return $mid; + return $mid; } $r = $this->_setValueOrInsert( - $mid, $newPlLen, $parid, 'playlength', 'A'); + $mid, $newPlLen, $parid, 'playlength', 'A'); if (PEAR::isError($r)) { - return $r; + return $r; } $mid = $this->_getMidOrInsert('dcterms:extent', $metaParid, $newPlLen); if (PEAR::isError($mid)) { - return $mid; + return $mid; } $r = $this->_setValueOrInsert( - $mid, $newPlLen, $metaParid, 'dcterms:extent'); + $mid, $newPlLen, $metaParid, 'dcterms:extent'); if (PEAR::isError($r)) { - return $r; + return $r; } return TRUE; } @@ -1020,26 +1021,26 @@ class PlaylistElement { // cycle over tags inside playlistElement foreach ($this->plEl['children'] as $j => $acFi) { switch ($acFi['elementname']) { - case "playlist": - $plInfo['type'] = 'playlist'; - break; - case "audioClip": - $plInfo['type'] = 'audioClip'; - break; - } - switch ($acFi['elementname']) { - case "playlist": - case "audioClip": - $plInfo['acLen'] = $acFi['attrs']['playlength']; - $plInfo['acLenS'] = Playlist::playlistTimeToSeconds($plInfo['acLen']); - $plInfo['acGunid'] = $acFi['attrs']['id']; - break; - case "fadeInfo": - $plInfo['fadeIn'] = $acFi['attrs']['fadeIn']; - $plInfo['fadeInS'] = Playlist::playlistTimeToSeconds($plInfo['fadeIn']); - $plInfo['fadeOut'] = $acFi['attrs']['fadeOut']; - $plInfo['fadeOutS'] = Playlist::playlistTimeToSeconds($plInfo['fadeOut']); - break; + case "playlist": + $plInfo['type'] = 'playlist'; + break; + case "audioClip": + $plInfo['type'] = 'audioClip'; + break; + } + switch ($acFi['elementname']) { + case "playlist": + case "audioClip": + $plInfo['acLen'] = $acFi['attrs']['playlength']; + $plInfo['acLenS'] = Playlist::playlistTimeToSeconds($plInfo['acLen']); + $plInfo['acGunid'] = $acFi['attrs']['id']; + break; + case "fadeInfo": + $plInfo['fadeIn'] = $acFi['attrs']['fadeIn']; + $plInfo['fadeInS'] = Playlist::playlistTimeToSeconds($plInfo['fadeIn']); + $plInfo['fadeOut'] = $acFi['attrs']['fadeOut']; + $plInfo['fadeOutS'] = Playlist::playlistTimeToSeconds($plInfo['fadeOut']); + break; } $plInfo['clipStart'] = $this->plEl['attrs']['clipStart']; $plInfo['clipStartS'] = Playlist::playlistTimeToSeconds($this->plEl['attrs']['clipStart']); @@ -1071,19 +1072,19 @@ class PlaylistTagExport case "playlistElement": $r = PlaylistElementExport::OutputToSmil($pl, $ple, $ind4); if (PEAR::isError($r)) { - return $r; + return $r; } if (!is_null($r)) { - $res .= $r; + $res .= $r; } break; case "metadata": $r = PlaylistMetadataExport::OutputToSmil($pl, $ple, $ind4); if (PEAR::isError($r)) { - return $r; + return $r; } if (!is_null($r)) { - $res .= $r; + $res .= $r; } break; default: @@ -1109,12 +1110,12 @@ class PlaylistTagExport case"playlistElement": $r = PlaylistElementExport::OutputToM3u($pl, $ple); if (PEAR::isError($r)) { - return $r; + return $r; } if (!is_null($r)) { - $res .= $r; + $res .= $r; } - break; + break; } } $res = "#EXTM3U\n$res"; @@ -1132,21 +1133,21 @@ class PlaylistTagExport case "playlistElement": $r = PlaylistElementExport::OutputToRss($pl, $ple, $ind3); if (PEAR::isError($r)) { - return $r; + return $r; } if (!is_null($r)) { - $res .= $r; + $res .= $r; } - break; + break; case "metadata": $r = PlaylistMetadataExport::OutputToRss($pl, $ple, $ind3); if (PEAR::isError($r)) { - return $r; + return $r; } if (!is_null($r)) { - $res .= $r; + $res .= $r; } - break; + break; default: } } @@ -1182,33 +1183,33 @@ class PlaylistElementExport { case "audioClip": $r = PlaylistAudioClipExport::OutputToSmil($pl, $ac, $ind2); if (PEAR::isError($r)) { - return $r; + return $r; } if (!is_null($r)) { - $acOrPl = $r; + $acOrPl = $r; } break; case "playlist": $gunid = $ac['attrs']['id']; $pl2 = StoredFile::RecallByGunid($gunid); if (is_null($pl2) || PEAR::isError($pl2)) { - return $pl2; + return $pl2; } $r = $pl2->outputToSmil(FALSE); if (PEAR::isError($r)) { - return $r; + return $r; } if (!is_null($r)) { - $acOrPl = $r; + $acOrPl = $r; } break; case "fadeInfo": $r = PlaylistFadeInfoExport::OutputToSmil($pl, $ac, $ind2); if (PEAR::isError($r)) { - return $r; + return $r; } if (!is_null($r)) { - $finfo = $r; + $finfo = $r; } break; default: @@ -1236,245 +1237,245 @@ class PlaylistElementExport { "{$ind3}fill = \"freeze\"\n". "{$ind2}/>\n" ; - } - } - $src = $acOrPl['src']; - $str = "$ind" : " />"). + } + } + $src = $acOrPl['src']; + $str = "$ind" : " />"). " ". "\n"; - return $str; - } - - - public static function OutputToM3u(&$pl, $ple, $ind='') - { - $acOrPl = NULL; - foreach ($ple['children'] as $ac) { - switch ($ac['elementname']) { - case "audioClip": - $r = PlaylistAudioClipExport::OutputToM3u($pl, $ac); - if (PEAR::isError($r)) { - return $r; - } - if (!is_null($r)) { - $acOrPl = $r; - } - break; - case "playlist": - $gunid = $ac['attrs']['id']; - $pl2 = StoredFile::RecallByGunid($gunid); - if (is_null($pl2) || PEAR::isError($pl2)) { - return $pl2; - } - $r = $pl2->outputToM3u(FALSE); - if (PEAR::isError($r)) { - return $r; - } - if (!is_null($r)) { - $acOrPl = $r; - } - break; + return $str; } - } - if (is_null($acOrPl)) { - return ''; - } - $playlength = ceil(Playlist::playlistTimeToSeconds($acOrPl['playlength'])); - $title = $acOrPl['title']; - $uri = (isset($acOrPl['uri']) ? $acOrPl['uri'] : '???' ); - $res = "#EXTINF: $playlength, $title\n"; - $res .= "$uri\n"; - return $res; - } - public static function OutputToRss(&$pl, $ple, $ind='') - { - $acOrPl = NULL; - $ind2 = $ind.INDCH; - $anim = ''; - foreach ($ple['children'] as $ac) { - switch ($ac['elementname']) { - case "audioClip": - $r = PlaylistAudioClipExport::OutputToRss($pl, $ac, $ind2); - if (PEAR::isError($r)) { - return $r; + public static function OutputToM3u(&$pl, $ple, $ind='') + { + $acOrPl = NULL; + foreach ($ple['children'] as $ac) { + switch ($ac['elementname']) { + case "audioClip": + $r = PlaylistAudioClipExport::OutputToM3u($pl, $ac); + if (PEAR::isError($r)) { + return $r; + } + if (!is_null($r)) { + $acOrPl = $r; + } + break; + case "playlist": + $gunid = $ac['attrs']['id']; + $pl2 = StoredFile::RecallByGunid($gunid); + if (is_null($pl2) || PEAR::isError($pl2)) { + return $pl2; + } + $r = $pl2->outputToM3u(FALSE); + if (PEAR::isError($r)) { + return $r; + } + if (!is_null($r)) { + $acOrPl = $r; + } + break; } - if (!is_null($r)) { - $acOrPl = $r; - } - break; - case "playlist": - $gunid = $ac['attrs']['id']; - $pl2 = StoredFile::RecallByGunid($gunid); - if (is_null($pl2) || PEAR::isError($pl2)) { - return $pl2; - } - $r = $pl2->outputToRss(FALSE); - if (PEAR::isError($r)) { - return $r; - } - if (!is_null($r)) { - $acOrPl = $r; - } - break; - case "fadeInfo": - break; - default: - return PEAR::raiseError( + } + if (is_null($acOrPl)) { + return ''; + } + $playlength = ceil(Playlist::playlistTimeToSeconds($acOrPl['playlength'])); + $title = $acOrPl['title']; + $uri = (isset($acOrPl['uri']) ? $acOrPl['uri'] : '???' ); + $res = "#EXTINF: $playlength, $title\n"; + $res .= "$uri\n"; + return $res; + } + + + public static function OutputToRss(&$pl, $ple, $ind='') + { + $acOrPl = NULL; + $ind2 = $ind.INDCH; + $anim = ''; + foreach ($ple['children'] as $ac) { + switch ($ac['elementname']) { + case "audioClip": + $r = PlaylistAudioClipExport::OutputToRss($pl, $ac, $ind2); + if (PEAR::isError($r)) { + return $r; + } + if (!is_null($r)) { + $acOrPl = $r; + } + break; + case "playlist": + $gunid = $ac['attrs']['id']; + $pl2 = StoredFile::RecallByGunid($gunid); + if (is_null($pl2) || PEAR::isError($pl2)) { + return $pl2; + } + $r = $pl2->outputToRss(FALSE); + if (PEAR::isError($r)) { + return $r; + } + if (!is_null($r)) { + $acOrPl = $r; + } + break; + case "fadeInfo": + break; + default: + return PEAR::raiseError( "PlaylistElementExport::OutputToRss:". " unknown tag {$ac['elementname']}" - ); - } - } - $title = (isset($acOrPl['title']) ? htmlspecialchars($acOrPl['title']) : '' ); - $desc = (isset($acOrPl['desc']) ? htmlspecialchars($acOrPl['desc']) : '' ); - $link = htmlspecialchars($acOrPl['src']); - $desc = ''; - $str = "$ind\n". + ); + } + } + $title = (isset($acOrPl['title']) ? htmlspecialchars($acOrPl['title']) : '' ); + $desc = (isset($acOrPl['desc']) ? htmlspecialchars($acOrPl['desc']) : '' ); + $link = htmlspecialchars($acOrPl['src']); + $desc = ''; + $str = "$ind\n". "$ind2$title\n". "$ind2$desc\n". "$ind2$link\n". "$ind\n"; - return $str; - } -} - - -/** - * @package Campcaster - * @subpackage StorageServer - * @copyright 2010 Sourcefabric O.P.S. - * @license http://www.gnu.org/licenses/gpl.txt - * @todo Rename this class to PlaylistAudioClip (notice the caps) - */ -class PlaylistAudioClipExport -{ - - public static function OutputToSmil(&$pl, $plac, $ind='') - { - $gunid = $plac['attrs']['id']; - $ac = StoredFile::RecallByGunid($gunid); - if (is_null($ac) || PEAR::isError($ac)) { - return $ac; + return $str; + } } - $RADext = $ac->getFileExtension(); - if (PEAR::isError($RADext)) { - return $RADext; - } - return array( + + + /** + * @package Campcaster + * @subpackage StorageServer + * @copyright 2010 Sourcefabric O.P.S. + * @license http://www.gnu.org/licenses/gpl.txt + * @todo Rename this class to PlaylistAudioClip (notice the caps) + */ + class PlaylistAudioClipExport + { + + public static function OutputToSmil(&$pl, $plac, $ind='') + { + $gunid = $plac['attrs']['id']; + $ac = StoredFile::RecallByGunid($gunid); + if (is_null($ac) || PEAR::isError($ac)) { + return $ac; + } + $RADext = $ac->getFileExtension(); + if (PEAR::isError($RADext)) { + return $RADext; + } + return array( 'type' => 'audioclip', 'gunid' => $gunid, 'src' => AC_URL_RELPATH."$gunid.$RADext", 'playlength' => $plac['attrs']['playlength'], - ); - } + ); + } - public static function OutputToM3u(&$pl, $plac, $ind='') - { - $gunid = $plac['attrs']['id']; - $ac = StoredFile::RecallByGunid($gunid); - if (is_null($ac) || PEAR::isError($ac)) { - return $ac; - } - $RADext = $ac->getFileExtension(); - if (PEAR::isError($RADext)) { - return $RADext; - } - return array( + public static function OutputToM3u(&$pl, $plac, $ind='') + { + $gunid = $plac['attrs']['id']; + $ac = StoredFile::RecallByGunid($gunid); + if (is_null($ac) || PEAR::isError($ac)) { + return $ac; + } + $RADext = $ac->getFileExtension(); + if (PEAR::isError($RADext)) { + return $RADext; + } + return array( 'playlength' => $plac['attrs']['playlength'], 'title' => $plac['attrs']['title'], 'uri' => AC_URL_RELPATH."$gunid.$RADext", - ); - } + ); + } - public static function OutputToRss(&$pl, $plac, $ind='') - { - $id = $plac['attrs']['id']; - $playlist = Playlist::Recall($id); - if (is_null($playlist) || PEAR::isError($playlist)) { - return $playlist; - } - $RADext = $playlist->getFileExtension(); - if (PEAR::isError($RADext)) { - return $RADext; - } - $title = $playlist->getName(); - $desc = $playlist->getPLMetaData("dc:description"); - return array( + public static function OutputToRss(&$pl, $plac, $ind='') + { + $id = $plac['attrs']['id']; + $playlist = Playlist::Recall($id); + if (is_null($playlist) || PEAR::isError($playlist)) { + return $playlist; + } + $RADext = $playlist->getFileExtension(); + if (PEAR::isError($RADext)) { + return $RADext; + } + $title = $playlist->getName(); + $desc = $playlist->getPLMetaData("dc:description"); + return array( 'type' => 'audioclip', 'gunid' => $id, 'src' => "http://XXX/YY/$id.$RADext", 'playlength' => $plac['attrs']['playlength'], 'title' => $title, 'desc' => $desc, - ); - } -} + ); + } + } -/** - * @package Campcaster - * @subpackage StorageServer - * @copyright 2010 Sourcefabric O.P.S. - * @license http://www.gnu.org/licenses/gpl.txt - * @todo Rename this class "PlaylistFadeInfo" (notive the caps) - */ -class PlaylistFadeInfoExport -{ + /** + * @package Campcaster + * @subpackage StorageServer + * @copyright 2010 Sourcefabric O.P.S. + * @license http://www.gnu.org/licenses/gpl.txt + * @todo Rename this class "PlaylistFadeInfo" (notive the caps) + */ + class PlaylistFadeInfoExport + { - public static function OutputToSmil(&$pl, $plfi, $ind='') - { - $r = array( + public static function OutputToSmil(&$pl, $plfi, $ind='') + { + $r = array( 'fi'=>$plfi['attrs']['fadeIn'], 'fo'=>$plfi['attrs']['fadeOut'], - ); - return $r; - } + ); + return $r; + } - public static function OutputToM3u(&$pl, $plfa, $ind='') - { - return ''; - } + public static function OutputToM3u(&$pl, $plfa, $ind='') + { + return ''; + } - public static function OutputToRss(&$pl, $plfa, $ind='') - { - return ''; - } + public static function OutputToRss(&$pl, $plfa, $ind='') + { + return ''; + } -} + } -/** - * @package Campcaster - * @subpackage StorageServer - * @copyright 2010 Sourcefabric O.P.S. - * @license http://www.gnu.org/licenses/gpl.txt - * @todo Rename this class to PlaylistMetadata (notice the caps) - */ -class PlaylistMetadataExport -{ - public static function OutputToSmil(&$pl, $md, $ind='') - { - return NULL; - } + /** + * @package Campcaster + * @subpackage StorageServer + * @copyright 2010 Sourcefabric O.P.S. + * @license http://www.gnu.org/licenses/gpl.txt + * @todo Rename this class to PlaylistMetadata (notice the caps) + */ + class PlaylistMetadataExport + { + public static function OutputToSmil(&$pl, $md, $ind='') + { + return NULL; + } - public static function OutputToM3u(&$pl, $md, $ind='') - { - return NULL; - } + public static function OutputToM3u(&$pl, $md, $ind='') + { + return NULL; + } - public static function OutputToRss(&$pl, $md, $ind='') - { - return NULL; - } -} + public static function OutputToRss(&$pl, $md, $ind='') + { + return NULL; + } + } -?> + ?> diff --git a/backend/Prefs.php b/backend/Prefs.php index 49f0dc6c9..c51a75402 100644 --- a/backend/Prefs.php +++ b/backend/Prefs.php @@ -44,19 +44,19 @@ class Prefs { { $subjid = GreenBox::GetSessUserId($sessid); if (PEAR::isError($subjid)) { - return $subjid; + return $subjid; } if (is_null($subjid)) { return PEAR::raiseError("Prefs::loadPref: invalid session id", - GBERR_SESS); + GBERR_SESS); } $val = $this->readVal($subjid, $key); if (PEAR::isError($val)) { - return $val; + return $val; } if ($val === FALSE) { return PEAR::raiseError("Prefs::loadPref: invalid preference key", - GBERR_PREF); + GBERR_PREF); } return $val; } @@ -77,20 +77,19 @@ class Prefs { { $subjid = GreenBox::GetSessUserId($sessid); if (PEAR::isError($subjid)) { - return $subjid; + return $subjid; } if (is_null($subjid)) { - return PEAR::raiseError("Prefs::savePref: invalid session id", - GBERR_SESS); + return PEAR::raiseError("Prefs::savePref: invalid session id", GBERR_SESS); } $r = $this->update($subjid, $key, $value); if (PEAR::isError($r)) { - return $r; + return $r; } if ($r === FALSE) { $r = $this->insert($subjid, $key, $value); if (PEAR::isError($r)) { - return $r; + return $r; } } return TRUE; @@ -110,19 +109,17 @@ class Prefs { { $subjid = GreenBox::GetSessUserId($sessid); if (PEAR::isError($subjid)) { - return $subjid; + return $subjid; } if (is_null($subjid)) { - return PEAR::raiseError("Prefs::delPref: invalid session id", - GBERR_SESS); + return PEAR::raiseError("Prefs::delPref: invalid session id", GBERR_SESS); } $r = $this->delete($subjid, $key); if (PEAR::isError($r)) { - return $r; + return $r; } if ($r === FALSE) { - return PEAR::raiseError("Prefs::delPref: invalid preference key", - GBERR_PREF); + return PEAR::raiseError("Prefs::delPref: invalid preference key", GBERR_PREF); } return TRUE; } @@ -146,7 +143,7 @@ class Prefs { // if sessid is would be used here fix Transport::cronCallMethod ! $subjid = Subjects::GetSubjId($group); if (PEAR::isError($subjid)) { - return $subjid; + return $subjid; } if (is_null($subjid)) { return PEAR::raiseError( @@ -154,7 +151,7 @@ class Prefs { } $val = $this->readVal($subjid, $key); if (PEAR::isError($val)) { - return $val; + return $val; } if ($val === FALSE) { if ($returnErrorIfKeyNotExists) { @@ -185,7 +182,7 @@ class Prefs { { $uid = GreenBox::GetSessUserId($sessid); if (PEAR::isError($uid)) { - return $uid; + return $uid; } if (is_null($uid)) { return PEAR::raiseError( @@ -193,7 +190,7 @@ class Prefs { } $gid = Subjects::GetSubjId($group); if (PEAR::isError($gid)) { - return $gid; + return $gid; } if (is_null($gid)) { return PEAR::raiseError( @@ -201,7 +198,7 @@ class Prefs { } $memb = Subjects::IsMemberOf($uid, $gid); if (PEAR::isError($memb)) { - return $memb; + return $memb; } if (!$memb) { return PEAR::raiseError( @@ -209,12 +206,12 @@ class Prefs { } $r = $this->update($gid, $key, $value); if (PEAR::isError($r)) { - return $r; + return $r; } if ($r === FALSE) { $r = $this->insert($gid, $key, $value); if (PEAR::isError($r)) { - return $r; + return $r; } } return TRUE; @@ -235,7 +232,7 @@ class Prefs { { $uid = GreenBox::GetSessUserId($sessid); if (PEAR::isError($uid)) { - return $uid; + return $uid; } if (is_null($uid)) { return PEAR::raiseError( @@ -243,7 +240,7 @@ class Prefs { } $gid = Subjects::GetSubjId($group); if (PEAR::isError($gid)) { - return $gid; + return $gid; } if (is_null($gid)) { return PEAR::raiseError( @@ -251,7 +248,7 @@ class Prefs { } $memb = Subjects::IsMemberOf($uid, $gid); if (PEAR::isError($memb)) { - return $memb; + return $memb; } if (!$memb) { return PEAR::raiseError( @@ -259,7 +256,7 @@ class Prefs { } $r = $this->delete($gid, $key); if (PEAR::isError($r)) { - return $r; + return $r; } if ($r === FALSE) { return PEAR::raiseError( @@ -287,7 +284,7 @@ class Prefs { global $CC_CONFIG, $CC_DBC; $id = $CC_DBC->nextId($CC_CONFIG['prefSequence']); if (PEAR::isError($id)) { - return $id; + return $id; } $r = $CC_DBC->query(" INSERT INTO ".$CC_CONFIG['prefTable']." @@ -296,7 +293,7 @@ class Prefs { ($id, $subjid, '$keystr', '$valstr') "); if (PEAR::isError($r)) { - return $r; + return $r; } return $id; } @@ -320,10 +317,10 @@ class Prefs { WHERE subjid=$subjid AND keystr='$keystr' "); if (PEAR::isError($val)) { - return $val; + return $val; } if (is_null($val)) { - return FALSE; + return FALSE; } return $val; } @@ -345,10 +342,10 @@ class Prefs { WHERE subjid=$subjid "); if (PEAR::isError($res)) { - return $res; + return $res; } if (is_null($res)) { - return FALSE; + return FALSE; } return $res; } @@ -374,10 +371,10 @@ class Prefs { WHERE subjid=$subjid AND keystr='$keystr' "); if (PEAR::isError($r)) { - return $r; + return $r; } if ($CC_DBC->affectedRows() < 1) { - return FALSE; + return FALSE; } return TRUE; } @@ -400,10 +397,10 @@ class Prefs { WHERE subjid=$subjid AND keystr='$keystr' "); if (PEAR::isError($r)) { - return $r; + return $r; } if ($CC_DBC->affectedRows() < 1) { - return FALSE; + return FALSE; } return TRUE; } @@ -422,7 +419,7 @@ class Prefs { $testVal = 'abcDef 0123 ěščřžýáíé ĚŠČŘŽÝÁÍÉ'; $r = savePref($sessid, $testKey, $testVal); if (PEAR::isError($r)) { - return $r; + return $r; } $val = loadPref($sessid, $testKey); if ($val != $testVal) { @@ -431,7 +428,7 @@ class Prefs { } $r = savePref($sessid, $testKey, ''); if (PEAR::isError($r)) { - return $r; + return $r; } $val = loadPref($sessid, $testKey); if ($val != $testVal) { diff --git a/backend/Renderer.php b/backend/Renderer.php index 720d71397..81d636b70 100644 --- a/backend/Renderer.php +++ b/backend/Renderer.php @@ -35,12 +35,12 @@ class Renderer // recall playlist: $pl = StoredFile::RecallByGunid($plid); if (is_null($pl) || PEAR::isError($pl)) { - return $pl; + return $pl; } // smil export: $smil = $pl->outputToSmil(); if (PEAR::isError($smil)) { - return $smil; + return $smil; } // temporary file for smil: $tmpn = tempnam($CC_CONFIG['bufferDir'], 'plRender_'); @@ -56,7 +56,7 @@ class Renderer // open access to output file: /*gunid*/ /*parent*/ $acc = BasicStor::bsAccess($outf, RENDER_EXT, $plid, 'render', 0, $owner); if (PEAR::isError($acc)) { - return $acc; + return $acc; } extract($acc); $statf = Renderer::getStatusFile($gb, $token); @@ -70,7 +70,7 @@ class Renderer if ($res === FALSE) { return PEAR::raiseError( 'Renderer::rnRender2File: Error running renderer' - ); + ); } return array('token'=>$token); } @@ -93,7 +93,7 @@ class Renderer if (!file_exists($statf)) { return PEAR::raiseError( 'Renderer::rnRender2FileCheck: Invalid token' - ); + ); } $status = trim(file_get_contents($statf)); $url = Renderer::getUrl($gb, $token); @@ -142,7 +142,7 @@ class Renderer global $CC_CONFIG; $r = BasicStor::bsRelease($token, 'render'); if (PEAR::isError($r)) { - return $r; + return $r; } $realOgg = $r['realFname']; $tmpn = $CC_CONFIG['bufferDir']."/".basename($realOgg, '.'.RENDER_EXT); @@ -171,7 +171,7 @@ class Renderer { $r = Renderer::rnRender2FileCheck($gb, $token); if (PEAR::isError($r)) { - return $r; + return $r; } $status = $r['status']; $res = array('status' => $status, 'gunid'=>'NULL'); @@ -182,7 +182,7 @@ class Renderer case "success": $r = Renderer::rnRender2StorageCore($gb, $token); if (PEAR::isError($r)) { - return $r; + return $r; } $res['gunid'] = $r['gunid']; break; @@ -205,36 +205,36 @@ class Renderer */ function rnRender2StorageCore(&$gb, $token) { -// $r = BasicStor::bsRelease($token, 'render'); -// if (PEAR::isError($r)) { -// return $r; -// } -// $realOgg = $r['realFname']; -// $owner = $r['owner']; -// $gunid = $r['gunid']; -// $fileName = 'rendered_playlist'; -// $id = BasicStor::IdFromGunid($gunid); -// if (PEAR::isError($id)) { -// return $id; -// } -// $mdata = ''; -// foreach (array('dc:title', 'dcterms:extent', 'dc:creator', 'dc:description') as $item) { -// $val = $gb->bsGetMetadataValue($id, $item); -// $mdata .= " <$item>$val\n"; -// } -// $mdata = "\n \n$mdata \n\n"; -// //$mdata = "\n \n$mdata0\n\n\n"; -// $values = array( -// "filename" => $fileName, -// "filepath" => $realOgg, -// "metadata" => $mdata, -// "filetype" => "audioclip" -// ); -// $storedFile = $gb->bsPutFile($values); -// if (PEAR::isError($storedFile)) { -// return $storedFile; -// } -// return array('gunid' => $storedFile->getGunid()); + // $r = BasicStor::bsRelease($token, 'render'); + // if (PEAR::isError($r)) { + // return $r; + // } + // $realOgg = $r['realFname']; + // $owner = $r['owner']; + // $gunid = $r['gunid']; + // $fileName = 'rendered_playlist'; + // $id = BasicStor::IdFromGunid($gunid); + // if (PEAR::isError($id)) { + // return $id; + // } + // $mdata = ''; + // foreach (array('dc:title', 'dcterms:extent', 'dc:creator', 'dc:description') as $item) { + // $val = $gb->bsGetMetadataValue($id, $item); + // $mdata .= " <$item>$val\n"; + // } + // $mdata = "\n \n$mdata \n\n"; + // //$mdata = "\n \n$mdata0\n\n\n"; + // $values = array( + // "filename" => $fileName, + // "filepath" => $realOgg, + // "metadata" => $mdata, + // "filetype" => "audioclip" + // ); + // $storedFile = $gb->bsPutFile($values); + // if (PEAR::isError($storedFile)) { + // return $storedFile; + // } + // return array('gunid' => $storedFile->getGunid()); } diff --git a/backend/Restore.php b/backend/Restore.php index afb7c01f3..892c0f19f 100644 --- a/backend/Restore.php +++ b/backend/Restore.php @@ -61,7 +61,7 @@ class Restore { $this->token = null; $this->logFile = $CC_CONFIG['bufferDir'].'/'.$this->ACCESS_TYPE.'.log'; if ($this->loglevel == 'debug') { - $this->addLogItem("-I- ".date("Ymd-H:i:s")." construct\n"); + $this->addLogItem("-I- ".date("Ymd-H:i:s")." construct\n"); } } @@ -131,9 +131,9 @@ class Restore { } $r['status'] = $stat; if ($stat=='fault') { - $r['faultString'] = $message; + $r['faultString'] = $message; } else { - $r['faultString'] = ''; + $r['faultString'] = ''; } return $r; } else { @@ -193,8 +193,8 @@ class Restore { //simple check of archive format if (is_dir($this->tmpDir.'audioClip/') && - is_dir($this->tmpDir.'meta-inf/') && - is_dir($this->tmpDir.'playlist/')) { + is_dir($this->tmpDir.'meta-inf/') && + is_dir($this->tmpDir.'playlist/')) { //search metafiles $this->metafiles = $this->getMetaFiles(); #$this->addLogItem('metafiles:'.print_r($this->metafiles,true)); @@ -205,15 +205,15 @@ class Restore { $this->addLogItem("-E- ".date("Ymd-H:i:s"). " startRestore - addFileToStorage \n". "(".$put->getMessage()."/".$put->getUserInfo().")\n" - ); - file_put_contents($this->statusFile, 'fault|'.$put->getMessage()."/".$put->getUserInfo()); - return; + ); + file_put_contents($this->statusFile, 'fault|'.$put->getMessage()."/".$put->getUserInfo()); + return; } } } else { $this->addLogItem("-E- ".date("Ymd-H:i:s")." startRestore - invalid archive format\n"); - file_put_contents($this->statusFile, 'fault|invalid archive format'); - return; + file_put_contents($this->statusFile, 'fault|invalid archive format'); + return; } file_put_contents($this->statusFile, 'success'); // unlink($backupfile); @@ -238,13 +238,13 @@ class Restore { $playlists = scandir($this->tmpDir.'playlist/'); for ($i = 0; $i < count($audioclips); $i++) { if (strpos($audioclips[$i],'xml')!==false) - $r[] = array('file' => $this->tmpDir.'audioClip/'.$audioclips[$i], + $r[] = array('file' => $this->tmpDir.'audioClip/'.$audioclips[$i], 'type' => 'audioClip', 'id' => str_replace('.xml','',$audioclips[$i])); } for ($i = 0; $i < count($playlists); $i++) { if (strpos($playlists[$i],'xml') !== false) - $r[] = array('file' => $this->tmpDir.'playlist/'.$playlists[$i], + $r[] = array('file' => $this->tmpDir.'playlist/'.$playlists[$i], 'type' => 'playlist', 'id' => str_replace('.xml','',$playlists[$i])); } @@ -265,83 +265,83 @@ class Restore { * @return mixed * true if success or PEAR_error */ -// function addFileToStorage($file,$type,$gunid) -// { -// if ($this->loglevel=='debug') { -// $this->addLogItem("-I- ".date("Ymd-H:i:s")." addFileToStorage - file:$file | type:$type | id:$gunid\n"); -// } -// require_once("XmlParser.php"); -// $tree = XmlParser::parse($file); -// $mediaFileLP = str_replace('.xml','',$file); -// $mediaFileLP = ($type=='audioClip' && is_file($mediaFileLP))?$mediaFileLP:''; -// $ex = $this->gb->existsFile($this->sessid,$gunid); -// if (PEAR::isError($ex)) { -// $this->addLogItem("-E- ".date("Ymd-H:i:s"). -// " addFileToStorage - existsFile($gunid) ". -// "(".$ex->getMessage()."/".$ex->getUserInfo().")\n" -// ); -// } -// if (!PEAR::isError($ex) && $ex) { // file is exists in storage server -// //replace it -// $id = BasicStor::IdFromGunid($gunid); -// $replace = $this->gb->replaceFile( -// $id, # id int, virt.file's local id -// $mediaFileLP, # mediaFileLP string, local path of media file -// $file, # mdataFileLP string, local path of metadata file -// $this->sessid); # sessid string, session id -// if (PEAR::isError($replace)) { -// $this->addLogItem("-E- ".date("Ymd-H:i:s"). -// " addFileToStorage - replaceFile Error ". -// "(".$replace->getMessage()."/".$replace->getUserInfo().")\n" -// ); -// file_put_contents($this->statusFile, 'fault|'.$replace->getMessage()."/".$replace->getUserInfo()); -// return $replace; -// } -// #$this->addLogItem("replace it \n"); -// } else { -// // add as new -// $name = $tree->children[0]->children[0]->content; -// if (empty($name)) { -// $name = $tree->attrs['title']->val; -// } -// if (empty($name)) { -// $name = '???'; -// } -// if ($this->loglevel=='debug') { -// $this->addLogItem("-I- ".date("Ymd-H:i:s")." putFile\n". -// "$name, $mediaFileLP, $file, {$this->sessid}, $gunid, $type \n" -// ); -// } -// $values = array( -// "filename" => $name, -// "filepath" => $mediaFileLP, -// "metadata" => $file, -// "gunid" => $gunid, -// "filetype" => $type -// ); -// $put = $this->gb->putFile($values, $this->sessid); -// //$this->addLogItem("add as new \n"); -// if (PEAR::isError($put)) { -// $this->addLogItem("-E- ".date("Ymd-H:i:s"). -// " addFileToStorage - putFile Error ". -// "(".$put->getMessage()."/".$put->getUserInfo().")\n" -// ."\n---\n".file_get_contents($file)."\n---\n" -// ); -// file_put_contents($this->statusFile, 'fault|'.$put->getMessage()."/".$put->getUserInfo()); -// //$this->addLogItem("Error Object: ".print_r($put,true)."\n"); -// return $put; -// } -// } -// $ac = StoredFile::RecallByGunid($gunid); -// if (is_null($ac) || PEAR::isError($ac)) { -// return $ac; -// } -// $res = $ac->setState('ready'); -// if (PEAR::isError($res)) { -// return $res; -// } -// return true; -// } + // function addFileToStorage($file,$type,$gunid) + // { + // if ($this->loglevel=='debug') { + // $this->addLogItem("-I- ".date("Ymd-H:i:s")." addFileToStorage - file:$file | type:$type | id:$gunid\n"); + // } + // require_once("XmlParser.php"); + // $tree = XmlParser::parse($file); + // $mediaFileLP = str_replace('.xml','',$file); + // $mediaFileLP = ($type=='audioClip' && is_file($mediaFileLP))?$mediaFileLP:''; + // $ex = $this->gb->existsFile($this->sessid,$gunid); + // if (PEAR::isError($ex)) { + // $this->addLogItem("-E- ".date("Ymd-H:i:s"). + // " addFileToStorage - existsFile($gunid) ". + // "(".$ex->getMessage()."/".$ex->getUserInfo().")\n" + // ); + // } + // if (!PEAR::isError($ex) && $ex) { // file is exists in storage server + // //replace it + // $id = BasicStor::IdFromGunid($gunid); + // $replace = $this->gb->replaceFile( + // $id, # id int, virt.file's local id + // $mediaFileLP, # mediaFileLP string, local path of media file + // $file, # mdataFileLP string, local path of metadata file + // $this->sessid); # sessid string, session id + // if (PEAR::isError($replace)) { + // $this->addLogItem("-E- ".date("Ymd-H:i:s"). + // " addFileToStorage - replaceFile Error ". + // "(".$replace->getMessage()."/".$replace->getUserInfo().")\n" + // ); + // file_put_contents($this->statusFile, 'fault|'.$replace->getMessage()."/".$replace->getUserInfo()); + // return $replace; + // } + // #$this->addLogItem("replace it \n"); + // } else { + // // add as new + // $name = $tree->children[0]->children[0]->content; + // if (empty($name)) { + // $name = $tree->attrs['title']->val; + // } + // if (empty($name)) { + // $name = '???'; + // } + // if ($this->loglevel=='debug') { + // $this->addLogItem("-I- ".date("Ymd-H:i:s")." putFile\n". + // "$name, $mediaFileLP, $file, {$this->sessid}, $gunid, $type \n" + // ); + // } + // $values = array( + // "filename" => $name, + // "filepath" => $mediaFileLP, + // "metadata" => $file, + // "gunid" => $gunid, + // "filetype" => $type + // ); + // $put = $this->gb->putFile($values, $this->sessid); + // //$this->addLogItem("add as new \n"); + // if (PEAR::isError($put)) { + // $this->addLogItem("-E- ".date("Ymd-H:i:s"). + // " addFileToStorage - putFile Error ". + // "(".$put->getMessage()."/".$put->getUserInfo().")\n" + // ."\n---\n".file_get_contents($file)."\n---\n" + // ); + // file_put_contents($this->statusFile, 'fault|'.$put->getMessage()."/".$put->getUserInfo()); + // //$this->addLogItem("Error Object: ".print_r($put,true)."\n"); + // return $put; + // } + // } + // $ac = StoredFile::RecallByGunid($gunid); + // if (is_null($ac) || PEAR::isError($ac)) { + // return $ac; + // } + // $res = $ac->setState('ready'); + // if (PEAR::isError($res)) { + // return $res; + // } + // return true; + // } /** @@ -433,4 +433,4 @@ class Restore { } } // class Restore -?> +?> diff --git a/backend/Schedule.php b/backend/Schedule.php index 3defc158f..9953697f1 100644 --- a/backend/Schedule.php +++ b/backend/Schedule.php @@ -4,402 +4,407 @@ require_once("BasicStor.php"); class ScheduleGroup { - private $groupId; + private $groupId; - public function __construct($p_groupId = null) { - $this->groupId = $p_groupId; - } + public function __construct($p_groupId = null) { + $this->groupId = $p_groupId; + } - /** - * Convert a date to an ID by stripping out all characters - * and padding with zeros. - * - * @param string $p_dateStr - */ - public static function dateToId($p_dateStr) { - $p_dateStr = str_replace(":", "", $p_dateStr); - $p_dateStr = str_replace(" ", "", $p_dateStr); - $p_dateStr = str_replace(".", "", $p_dateStr); - $p_dateStr = str_replace("-", "", $p_dateStr); - $p_dateStr = substr($p_dateStr, 0, 17); - $p_dateStr = str_pad($p_dateStr, 17, "0"); - return $p_dateStr; - } + /** + * Convert a date to an ID by stripping out all characters + * and padding with zeros. + * + * @param string $p_dateStr + */ + public static function dateToId($p_dateStr) { + $p_dateStr = str_replace(":", "", $p_dateStr); + $p_dateStr = str_replace(" ", "", $p_dateStr); + $p_dateStr = str_replace(".", "", $p_dateStr); + $p_dateStr = str_replace("-", "", $p_dateStr); + $p_dateStr = substr($p_dateStr, 0, 17); + $p_dateStr = str_pad($p_dateStr, 17, "0"); + return $p_dateStr; + } - /** - * Add the two times together, return the result. - * - * @param string $p_baseTime - * Specified as YYYY-MM-DD HH:MM:SS - * - * @param string $p_addTime - * Specified as HH:MM:SS.nnnnnn - * - * @return string - * The end time, to the nearest second. - */ -// protected function calculateEndTime($p_startTime, $p_trackTime) { -// $p_trackTime = substr($p_startTime, 0, ); -// $start = new DateTime(); -// $interval = new DateInterval() -// -// } + /** + * Add the two times together, return the result. + * + * @param string $p_baseTime + * Specified as YYYY-MM-DD HH:MM:SS + * + * @param string $p_addTime + * Specified as HH:MM:SS.nnnnnn + * + * @return string + * The end time, to the nearest second. + */ + // protected function calculateEndTime($p_startTime, $p_trackTime) { + // $p_trackTime = substr($p_startTime, 0, ); + // $start = new DateTime(); + // $interval = new DateInterval() + // + // } - /** - * Add a music clip or playlist to the schedule. - * - * @param $p_datetime - * In the format YYYY-MM-DD HH:MM:SS.mmmmmm - * @param $p_audioFileId - * (optional, either this or $p_playlistId must be set) DB ID of the audio file - * @param $p_playlistId - * (optional, either this of $p_audioFileId must be set) DB ID of the playlist - * @param $p_options - * Does nothing at the moment. - * - * @return int|PEAR_Error - * Return PEAR_Error if the item could not be added. - * Error code 555 is a scheduling conflict. - */ - public function add($p_datetime, $p_audioFileId = null, $p_playlistId = null, $p_options = null) { - global $CC_CONFIG, $CC_DBC; - if (!is_null($p_audioFileId)) { - // Schedule a single audio track + /** + * Add a music clip or playlist to the schedule. + * + * @param $p_datetime + * In the format YYYY-MM-DD HH:MM:SS.mmmmmm + * @param $p_audioFileId + * (optional, either this or $p_playlistId must be set) DB ID of the audio file + * @param $p_playlistId + * (optional, either this of $p_audioFileId must be set) DB ID of the playlist + * @param $p_options + * Does nothing at the moment. + * + * @return int|PEAR_Error + * Return PEAR_Error if the item could not be added. + * Error code 555 is a scheduling conflict. + */ + public function add($p_datetime, $p_audioFileId = null, $p_playlistId = null, $p_options = null) { + global $CC_CONFIG, $CC_DBC; + if (!is_null($p_audioFileId)) { + // Schedule a single audio track - // Load existing track - $track = StoredFile::Recall($p_audioFileId); - if (is_null($track)) { - return new PEAR_Error("Could not find audio track."); - } + // Load existing track + $track = StoredFile::Recall($p_audioFileId); + if (is_null($track)) { + return new PEAR_Error("Could not find audio track."); + } - // Check if there are any conflicts with existing entries - $metadata = $track->getMetadata(); - $length = trim($metadata["length"]); - if (empty($length)) { - return new PEAR_Error("Length is empty."); - } - if (!Schedule::isScheduleEmptyInRange($p_datetime, $length)) { - return new PEAR_Error("Schedule conflict.", 555); - } + // Check if there are any conflicts with existing entries + $metadata = $track->getMetadata(); + $length = trim($metadata["length"]); + if (empty($length)) { + return new PEAR_Error("Length is empty."); + } + if (!Schedule::isScheduleEmptyInRange($p_datetime, $length)) { + return new PEAR_Error("Schedule conflict.", 555); + } - // Insert into the table - $this->groupId = $CC_DBC->GetOne("SELECT nextval('schedule_group_id_seq')"); - $id = $this->dateToId($p_datetime); - $sql = "INSERT INTO ".$CC_CONFIG["scheduleTable"] - ." (id, playlist_id, starts, ends, clip_length, group_id, file_id)" - ." VALUES ($id, 0, TIMESTAMP '$p_datetime', " - ." (TIMESTAMP '$p_datetime' + INTERVAL '$length')," - ." '$length'," - ." {$this->groupId}, $p_audioFileId)"; - $result = $CC_DBC->query($sql); - if (PEAR::isError($result)) { - var_dump($sql); - return $result; - } - return $this->groupId; + // Insert into the table + $this->groupId = $CC_DBC->GetOne("SELECT nextval('schedule_group_id_seq')"); + $id = $this->dateToId($p_datetime); + $sql = "INSERT INTO ".$CC_CONFIG["scheduleTable"] + ." (id, playlist_id, starts, ends, clip_length, group_id, file_id)" + ." VALUES ($id, 0, TIMESTAMP '$p_datetime', " + ." (TIMESTAMP '$p_datetime' + INTERVAL '$length')," + ." '$length'," + ." {$this->groupId}, $p_audioFileId)"; + $result = $CC_DBC->query($sql); + if (PEAR::isError($result)) { + var_dump($sql); + return $result; + } + return $this->groupId; - } elseif (!is_null($p_playlistId)){ - // Schedule a whole playlist + } elseif (!is_null($p_playlistId)){ + // Schedule a whole playlist - // Load existing playlist - $playlist = Playlist::Recall($p_playlistId); - if (is_null($playlist)) { - return new PEAR_Error("Could not find playlist."); - } + // Load existing playlist + $playlist = Playlist::Recall($p_playlistId); + if (is_null($playlist)) { + return new PEAR_Error("Could not find playlist."); + } - // Check if there are any conflicts with existing entries - $length = trim($playlist->getLength()); - if (empty($length)) { - return new PEAR_Error("Length is empty."); - } - if (!Schedule::isScheduleEmptyInRange($p_datetime, $length)) { - return new PEAR_Error("Schedule conflict.", 555); - } + // Check if there are any conflicts with existing entries + $length = trim($playlist->getLength()); + var_dump($length); + if (empty($length)) { + return new PEAR_Error("Length is empty."); + } + if (!Schedule::isScheduleEmptyInRange($p_datetime, $length)) { + return new PEAR_Error("Schedule conflict.", 555); + } - // Insert all items into the schedule - $this->groupId = $CC_DBC->GetOne("SELECT nextval('schedule_group_id_seq')"); - $id = $this->dateToId($p_datetime); - $itemStartTime = $p_datetime; + // Insert all items into the schedule + $this->groupId = $CC_DBC->GetOne("SELECT nextval('schedule_group_id_seq')"); + $id = $this->dateToId($p_datetime); + $itemStartTime = $p_datetime; - $plItems = $playlist->getContents(); - foreach ($plItems as $row) { - $trackLength = $row["cliplength"]; - $sql = "INSERT INTO ".$CC_CONFIG["scheduleTable"] - ." (id, playlist_id, starts, ends, group_id, file_id," - ." clip_length, cue_in, cue_out, fade_in, fade_out)" - ." VALUES ($id, $p_playlistId, TIMESTAMP '$itemStartTime', " - ." (TIMESTAMP '$itemStartTime' + INTERVAL '$trackLength')," - ." '{$this->groupId}', '{$row['file_id']}', '$trackLength', '{$row['cuein']}'," - ." '{$row['cueout']}', '{$row['fadein']}','{$row['fadeout']}')"; - $result = $CC_DBC->query($sql); - if (PEAR::isError($result)) { - var_dump($sql); - return $result; + $plItems = $playlist->getContents(); + var_dump($plItems); + foreach ($plItems as $row) { + $trackLength = $row["cliplength"]; + var_dump($trackLength); + $sql = "INSERT INTO ".$CC_CONFIG["scheduleTable"] + ." (id, playlist_id, starts, ends, group_id, file_id," + ." clip_length, cue_in, cue_out, fade_in, fade_out)" + ." VALUES ($id, $p_playlistId, TIMESTAMP '$itemStartTime', " + ." (TIMESTAMP '$itemStartTime' + INTERVAL '$trackLength')," + ." '{$this->groupId}', '{$row['file_id']}', '$trackLength', '{$row['cuein']}'," + ." '{$row['cueout']}', '{$row['fadein']}','{$row['fadeout']}')"; + $result = $CC_DBC->query($sql); + if (PEAR::isError($result)) { + var_dump($sql); + return $result; + } + $itemStartTime = $CC_DBC->getOne("SELECT TIMESTAMP '$itemStartTime' + INTERVAL '$trackLength'"); + $id = $this->dateToId($itemStartTime); + } + return $this->groupId; } - $itemStartTime = $CC_DBC->getOne("SELECT TIMESTAMP '$itemStartTime' + INTERVAL '$trackLength'"); - $id = $this->dateToId($itemStartTime); - } - return $this->groupId; } - } - public function addAfter($p_groupId, $p_audioFileId) { - global $CC_CONFIG, $CC_DBC; - // Get the end time for the given entry - $sql = "SELECT ends FROM ".$CC_CONFIG["scheduleTable"] - ." WHERE group_id=$p_groupId"; - $startTime = $CC_DBC->GetOne($sql); - return $this->add($startTime, $p_audioFileId); - } - - public function update() { - - } - - /** - * Remove the group from the schedule. - * Note: does not check if it is in the past, you can remove anything. - * - * @return boolean - * TRUE on success, false if there is no group ID defined. - */ - public function remove() { - global $CC_CONFIG, $CC_DBC; - if (is_null($this->groupId) || !is_numeric($this->groupId)) { - return false; + public function addAfter($p_groupId, $p_audioFileId) { + global $CC_CONFIG, $CC_DBC; + // Get the end time for the given entry + $sql = "SELECT ends FROM ".$CC_CONFIG["scheduleTable"] + ." WHERE group_id=$p_groupId"; + $startTime = $CC_DBC->GetOne($sql); + return $this->add($startTime, $p_audioFileId); } - $sql = "DELETE FROM ".$CC_CONFIG["scheduleTable"] - ." WHERE group_id = ".$this->groupId; - return $CC_DBC->query($sql); - } + public function update() { - /** - * Return the number of items in this group. - * @return string - */ - public function count() { - global $CC_CONFIG, $CC_DBC; - $sql = "SELECT COUNT(*) FROM {$CC_CONFIG['scheduleTable']}" - ." WHERE group_id={$this->groupId}"; - return $CC_DBC->GetOne($sql); - } + } - /* - * Return the list of items in this group as a 2D array. - * @return array - */ - public function getItems() { - global $CC_CONFIG, $CC_DBC; - $sql = "SELECT * FROM {$CC_CONFIG['scheduleTable']}" - ." WHERE group_id={$this->groupId}"; - return $CC_DBC->GetAll($sql); - } + /** + * Remove the group from the schedule. + * Note: does not check if it is in the past, you can remove anything. + * + * @return boolean + * TRUE on success, false if there is no group ID defined. + */ + public function remove() { + global $CC_CONFIG, $CC_DBC; + if (is_null($this->groupId) || !is_numeric($this->groupId)) { + return false; + } + $sql = "DELETE FROM ".$CC_CONFIG["scheduleTable"] + ." WHERE group_id = ".$this->groupId; - public function reschedule($toDateTime) { - global $CC_CONFIG, $CC_DBC; -// $sql = "UPDATE ".$CC_CONFIG["scheduleTable"]. " SET id=, starts=,ends=" - } + return $CC_DBC->query($sql); + } + + /** + * Return the number of items in this group. + * @return string + */ + public function count() { + global $CC_CONFIG, $CC_DBC; + $sql = "SELECT COUNT(*) FROM {$CC_CONFIG['scheduleTable']}" + ." WHERE group_id={$this->groupId}"; + return $CC_DBC->GetOne($sql); + } + + /* + * Return the list of items in this group as a 2D array. + * @return array + */ + public function getItems() { + global $CC_CONFIG, $CC_DBC; + $sql = "SELECT * FROM {$CC_CONFIG['scheduleTable']}" + ." WHERE group_id={$this->groupId}"; + return $CC_DBC->GetAll($sql); + } + + public function reschedule($toDateTime) { + global $CC_CONFIG, $CC_DBC; + // $sql = "UPDATE ".$CC_CONFIG["scheduleTable"]. " SET id=, starts=,ends=" + } } class Schedule { - function __construct() { + function __construct() { - } - - /** - * Return true if there is nothing in the schedule for the given times. - * - * @param string $p_datetime - * @param string $p_length - * - * @return boolean|PEAR_Error - */ - public static function isScheduleEmptyInRange($p_datetime, $p_length) { - global $CC_CONFIG, $CC_DBC; - if (empty($p_length)) { - return new PEAR_Error("Schedule::isSchedulerEmptyInRange: param p_length is empty."); } - $sql = "SELECT COUNT(*) FROM ".$CC_CONFIG["scheduleTable"] - ." WHERE (starts >= '$p_datetime') " - ." AND (ends <= (TIMESTAMP '$p_datetime' + INTERVAL '$p_length'))"; - //$_SESSION["debug"] = $sql; - $count = $CC_DBC->GetOne($sql); - return ($count == '0'); - } -// public function onAddTrackToPlaylist($playlistId, $audioTrackId) { -// -// } -// -// public function onRemoveTrackFromPlaylist($playlistId, $audioTrackId) { -// -// } - - /** - * Return TRUE if file is going to be played in the future. - * - * @param string $p_fileId - */ - public function IsFileScheduledInTheFuture($p_fileId) - { - global $CC_CONFIG, $CC_DBC; - $sql = "SELECT COUNT(*) FROM ".$CC_CONFIG["scheduleTable"] - ." WHERE file_id = {$p_fileId} AND starts > NOW()"; - $count = $CC_DBC->GetOne($sql); - if (is_numeric($count) && ($count != '0')) { - return TRUE; - } else { - return FALSE; + /** + * Return true if there is nothing in the schedule for the given times. + * + * @param string $p_datetime + * @param string $p_length + * + * @return boolean|PEAR_Error + */ + public static function isScheduleEmptyInRange($p_datetime, $p_length) { + global $CC_CONFIG, $CC_DBC; + if (empty($p_length)) { + return new PEAR_Error("Schedule::isSchedulerEmptyInRange: param p_length is empty."); + } + $sql = "SELECT COUNT(*) FROM ".$CC_CONFIG["scheduleTable"] + ." WHERE (starts >= '$p_datetime') " + ." AND (ends <= (TIMESTAMP '$p_datetime' + INTERVAL '$p_length'))"; + //$_SESSION["debug"] = $sql; + var_dump($sql); + $count = $CC_DBC->GetOne($sql); + var_dump($count); + return ($count == '0'); + } + + // public function onAddTrackToPlaylist($playlistId, $audioTrackId) { + // + // } + // + // public function onRemoveTrackFromPlaylist($playlistId, $audioTrackId) { + // + // } + + /** + * Return TRUE if file is going to be played in the future. + * + * @param string $p_fileId + */ + public function IsFileScheduledInTheFuture($p_fileId) + { + global $CC_CONFIG, $CC_DBC; + $sql = "SELECT COUNT(*) FROM ".$CC_CONFIG["scheduleTable"] + ." WHERE file_id = {$p_fileId} AND starts > NOW()"; + $count = $CC_DBC->GetOne($sql); + if (is_numeric($count) && ($count != '0')) { + return TRUE; + } else { + return FALSE; + } } - } - /** - * Returns array indexed numberically of: - * "playlistId"/"playlist_id" (aliases to the same thing) - * "start"/"starts" (aliases to the same thing) as YYYY-MM-DD HH:MM:SS.nnnnnn - * "end"/"ends" (aliases to the same thing) as YYYY-MM-DD HH:MM:SS.nnnnnn - * "group_id"/"id" (aliases to the same thing) - * "clip_length" (for playlists only, this is the length of the entire playlist) - * "name" (playlist only) - * "creator" (playlist only) - * "file_id" (audioclip only) - * "count" (number of items in the playlist, always 1 for audioclips. - * Note that playlists with one item will also have count = 1. - * - * @param string $p_fromDateTime - * In the format YYYY-MM-DD HH:MM:SS.nnnnnn - * @param string $p_toDateTime - * In the format YYYY-MM-DD HH:MM:SS.nnnnnn - * @param boolean $p_playlistsOnly - * Retreive playlists as a single item. - * @return array - * Returns empty array if nothing found - */ - public static function GetItems($p_fromDateTime, $p_toDateTime, $p_playlistsOnly = true) { - global $CC_CONFIG, $CC_DBC; - $rows = array(); - if (!$p_playlistsOnly) { - $sql = "SELECT * FROM ".$CC_CONFIG["scheduleTable"] + /** + * Returns array indexed numberically of: + * "playlistId"/"playlist_id" (aliases to the same thing) + * "start"/"starts" (aliases to the same thing) as YYYY-MM-DD HH:MM:SS.nnnnnn + * "end"/"ends" (aliases to the same thing) as YYYY-MM-DD HH:MM:SS.nnnnnn + * "group_id"/"id" (aliases to the same thing) + * "clip_length" (for playlists only, this is the length of the entire playlist) + * "name" (playlist only) + * "creator" (playlist only) + * "file_id" (audioclip only) + * "count" (number of items in the playlist, always 1 for audioclips. + * Note that playlists with one item will also have count = 1. + * + * @param string $p_fromDateTime + * In the format YYYY-MM-DD HH:MM:SS.nnnnnn + * @param string $p_toDateTime + * In the format YYYY-MM-DD HH:MM:SS.nnnnnn + * @param boolean $p_playlistsOnly + * Retreive playlists as a single item. + * @return array + * Returns empty array if nothing found + */ + public static function GetItems($p_fromDateTime, $p_toDateTime, $p_playlistsOnly = true) { + global $CC_CONFIG, $CC_DBC; + $rows = array(); + if (!$p_playlistsOnly) { + $sql = "SELECT * FROM ".$CC_CONFIG["scheduleTable"] ." WHERE (starts >= TIMESTAMP '$p_fromDateTime') " ." AND (ends <= TIMESTAMP '$p_toDateTime')"; - $rows = $CC_DBC->GetAll($sql); - foreach ($rows as &$row) { - $row["count"] = "1"; - $row["playlistId"] = $row["playlist_id"]; - $row["start"] = $row["starts"]; - $row["end"] = $row["ends"]; - $row["id"] = $row["group_id"]; - } - } else { - $sql = "SELECT MIN(name) AS name, MIN(creator) AS creator, group_id, " - ." SUM(clip_length) AS clip_length," - ." MIN(file_id) AS file_id, COUNT(*) as count," - ." MIN(playlist_id) AS playlist_id, MIN(starts) AS starts, MAX(ends) AS ends" - ." FROM ".$CC_CONFIG["scheduleTable"] - ." LEFT JOIN ".$CC_CONFIG["playListTable"]." ON playlist_id = ".$CC_CONFIG["playListTable"].".id" - ." WHERE (starts >= TIMESTAMP '$p_fromDateTime') AND (ends <= TIMESTAMP '$p_toDateTime')" - ." GROUP BY group_id" - ." ORDER BY starts"; - //var_dump($sql); - $rows = $CC_DBC->GetAll($sql); - if (!PEAR::isError($rows)) { - foreach ($rows as &$row) { - $row["playlistId"] = $row["playlist_id"]; - $row["start"] = $row["starts"]; - $row["end"] = $row["ends"]; - $row["id"] = $row["group_id"]; + $rows = $CC_DBC->GetAll($sql); + foreach ($rows as &$row) { + $row["count"] = "1"; + $row["playlistId"] = $row["playlist_id"]; + $row["start"] = $row["starts"]; + $row["end"] = $row["ends"]; + $row["id"] = $row["group_id"]; + } + } else { + $sql = "SELECT MIN(name) AS name, MIN(creator) AS creator, group_id, " + ." SUM(clip_length) AS clip_length," + ." MIN(file_id) AS file_id, COUNT(*) as count," + ." MIN(playlist_id) AS playlist_id, MIN(starts) AS starts, MAX(ends) AS ends" + ." FROM ".$CC_CONFIG["scheduleTable"] + ." LEFT JOIN ".$CC_CONFIG["playListTable"]." ON playlist_id = ".$CC_CONFIG["playListTable"].".id" + ." WHERE (starts >= TIMESTAMP '$p_fromDateTime') AND (ends <= TIMESTAMP '$p_toDateTime')" + ." GROUP BY group_id" + ." ORDER BY starts"; + //var_dump($sql); + $rows = $CC_DBC->GetAll($sql); + if (!PEAR::isError($rows)) { + foreach ($rows as &$row) { + $row["playlistId"] = $row["playlist_id"]; + $row["start"] = $row["starts"]; + $row["end"] = $row["ends"]; + $row["id"] = $row["group_id"]; + } + } } - } + return $rows; } - return $rows; - } - public function getSchedulerTime() { + public function getSchedulerTime() { - } + } - public function getCurrentlyPlaying() { + public function getCurrentlyPlaying() { - } + } - public function getNextItem($nextCount = 1) { + public function getNextItem($nextCount = 1) { - } + } - public function getStatus() { + public function getStatus() { - } + } - private static function CcTimeToPypoTime($p_time) { - $p_time = substr($p_time, 0, 19); - $p_time = str_replace(" ", "-", $p_time); - $p_time = str_replace(":", "-", $p_time); - return $p_time; - } + private static function CcTimeToPypoTime($p_time) { + $p_time = substr($p_time, 0, 19); + $p_time = str_replace(" ", "-", $p_time); + $p_time = str_replace(":", "-", $p_time); + return $p_time; + } - private static function PypoTimeToCcTime($p_time) { - $t = explode("-", $p_time); - return $t[0]."-".$t[1]."-".$t[2]." ".$t[3].":".$t[4].":00"; - } + private static function PypoTimeToCcTime($p_time) { + $t = explode("-", $p_time); + return $t[0]."-".$t[1]."-".$t[2]." ".$t[3].":".$t[4].":00"; + } - /** - * Export the schedule in json formatted for pypo (the liquidsoap scheduler) - * - * @param string $range - * In the format "YYYY-MM-DD HH:mm:ss" - * @param string $source - * In the format "YYYY-MM-DD HH:mm:ss" - */ - public static function ExportRangeAsJson($p_fromDateTime, $p_toDateTime) - { - global $CC_CONFIG, $CC_DBC; - $range_start = Schedule::PypoTimeToCcTime($p_fromDateTime); - $range_end = Schedule::PypoTimeToCcTime($p_toDateTime); - $range_dt = array('start' => $range_start, 'end' => $range_end); - //var_dump($range_dt); + /** + * Export the schedule in json formatted for pypo (the liquidsoap scheduler) + * + * @param string $range + * In the format "YYYY-MM-DD HH:mm:ss" + * @param string $source + * In the format "YYYY-MM-DD HH:mm:ss" + */ + public static function ExportRangeAsJson($p_fromDateTime, $p_toDateTime) + { + global $CC_CONFIG, $CC_DBC; + $range_start = Schedule::PypoTimeToCcTime($p_fromDateTime); + $range_end = Schedule::PypoTimeToCcTime($p_toDateTime); + $range_dt = array('start' => $range_start, 'end' => $range_end); + //var_dump($range_dt); - // Scheduler wants everything in a playlist - $data = Schedule::GetItems($range_start, $range_end, true); - //echo "
    ";var_dump($data);
    -  	$playlists = array();
    +        // Scheduler wants everything in a playlist
    +        $data = Schedule::GetItems($range_start, $range_end, true);
    +        //echo "
    ";var_dump($data);
    +        $playlists = array();
     
    -		if (is_array($data) && count($data) > 0)
    -		{
    -			foreach ($data as $dx)
    -			{
    -		    // Is this the first item in the playlist?
    -				$start = $dx['start'];
    -				// chop off subseconds
    -        $start = substr($start, 0, 19);
    +        if (is_array($data) && count($data) > 0)
    +        {
    +            foreach ($data as $dx)
    +            {
    +                // 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);
    -				$playlists[$pkey]['source'] = "PLAYLIST";
    -				$playlists[$pkey]['x_ident'] = $dx["playlist_id"];
    -				$playlists[$pkey]['subtype'] = '1'; // Just needs to be between 1 and 4 inclusive
    -				$playlists[$pkey]['timestamp'] = $timestamp;
    -				$playlists[$pkey]['duration'] = $dx['clip_length'];
    -				$playlists[$pkey]['played'] = '0';
    -				$playlists[$pkey]['schedule_id'] = $dx['group_id'];
    -			}
    -		}
    +                // 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
    +                $playlists[$pkey]['timestamp'] = $timestamp;
    +                $playlists[$pkey]['duration'] = $dx['clip_length'];
    +                $playlists[$pkey]['played'] = '0';
    +                $playlists[$pkey]['schedule_id'] = $dx['group_id'];
    +            }
    +        }
     
    -		foreach ($playlists as &$playlist)
    -		{
    -	    $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();
    -				$medias[] = array(
    +        foreach ($playlists as &$playlist)
    +        {
    +            $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();
    +                $medias[] = array(
     					'id' => $storedFile->getGunid(), //$item["file_id"],
     					'uri' => $uri,
     					'fade_in' => $item["fade_in"],
    @@ -407,18 +412,18 @@ class Schedule {
     					'fade_cross' => 0,
     					'cue_in' => $item["cue_in"],
     					'cue_out' => $item["cue_out"],
    -					);
    -			}
    -			$playlist['medias'] = $medias;
    -		}
    +                );
    +            }
    +            $playlist['medias'] = $medias;
    +        }
     
    -		$result = array();
    -		$result['status'] = array('range' => $range_dt, 'version' => 0.2);
    -		$result['playlists'] = $playlists;
    -		$result['check'] = 1;
    +        $result = array();
    +        $result['status'] = array('range' => $range_dt, 'version' => 0.2);
    +        $result['playlists'] = $playlists;
    +        $result['check'] = 1;
     
    -		print json_encode($result);
    -	}
    +        print json_encode($result);
    +    }
     
     }
     
    diff --git a/backend/SmilPlaylist.php b/backend/SmilPlaylist.php
    index dc4ca7f78..739667dc8 100644
    --- a/backend/SmilPlaylist.php
    +++ b/backend/SmilPlaylist.php
    @@ -58,24 +58,24 @@ class SmilPlaylist {
             }
             $lspl = SmilPlaylist::convert2lspl($gb, $path, $gunids, $parr);
             if (PEAR::isError($lspl)) {
    -        	return $lspl;
    +            return $lspl;
             }
             require_once("Playlist.php");
             $pl =& Playlist::create($gb, $plid, "imported_SMIL");
             if (PEAR::isError($pl)) {
    -        	return $pl;
    +            return $pl;
             }
             $r = $pl->lock($gb, $subjid);
             if (PEAR::isError($r)) {
    -        	return $r;
    +            return $r;
             }
             $r = $pl->setMetadata($lspl, 'string', 'playlist');
             if (PEAR::isError($r)) {
    -        	return $r;
    +            return $r;
             }
             $r = $pl->unlock($gb);
             if (PEAR::isError($r)) {
    -        	return $r;
    +            return $r;
             }
             return $pl;
         }
    @@ -99,7 +99,7 @@ class SmilPlaylist {
             extract($parr);
             $tree = SmilPlaylist::parse($data);
             if (PEAR::isError($tree)) {
    -        	return $tree;
    +            return $tree;
             }
             if ($tree->name != 'smil') {
                 return PEAR::raiseError("SmilPlaylist::parse: smil tag expected");
    @@ -107,11 +107,11 @@ class SmilPlaylist {
             if (isset($tree->children[1])) {
                 return PEAR::raiseError(sprintf(
                     "SmilPlaylist::parse: unexpected tag %s in tag smil",
    -                $tree->children[1]->name
    +            $tree->children[1]->name
                 ));
             }
             $res = SmilPlaylistBodyElement::convert2lspl(
    -            $gb, $tree->children[0], &$gunids, $parr);
    +        $gb, $tree->children[0], &$gunids, $parr);
             return $res;
         }
     
    @@ -136,13 +136,13 @@ class SmilPlaylistBodyElement {
             if (isset($tree->children[1])) {
                 return PEAR::raiseError(sprintf(
                     "SmilPlaylist::parse: unexpected tag %s in tag body",
    -                $tree->children[1]->name
    +            $tree->children[1]->name
                 ));
             }
             $res = SmilPlaylistParElement::convert2lspl(
    -            $gb, $tree->children[0], &$gunids, $parr, $ind2);
    +        $gb, $tree->children[0], &$gunids, $parr, $ind2);
             if (PEAR::isError($res)) {
    -        	return $res;
    +            return $res;
             }
             $title = basename($rPath);
             $playlength = '0';
    @@ -165,7 +165,7 @@ class SmilPlaylistBodyElement {
      */
     class SmilPlaylistParElement {
     
    -	public static function convert2lspl(&$gb, &$tree, &$gunids, $parr, $ind='')
    +    public static function convert2lspl(&$gb, &$tree, &$gunids, $parr, $ind='')
         {
             extract($parr);
             if ($tree->name != 'par') {
    @@ -176,7 +176,7 @@ class SmilPlaylistParElement {
                 $ch =& $tree->children[$i];
                 $r = SmilPlaylistAudioElement::convert2lspl($gb, $ch, &$gunids, $parr, $ind.INDCH);
                 if (PEAR::isError($r)) {
    -            	return $r;
    +                return $r;
                 }
                 $res .= $r;
             }
    @@ -204,7 +204,7 @@ class SmilPlaylistAudioElement {
             if (isset($tree->children[2])) {
                 return PEAR::raiseError(sprintf(
                     "SmilPlaylist::parse: unexpected tag %s in tag audio",
    -                $tree->children[2]->name
    +            $tree->children[2]->name
                 ));
             }
             $res = ''; $fadeIn = 0; $fadeOut = 0;
    @@ -212,7 +212,7 @@ class SmilPlaylistAudioElement {
                 $ch =& $tree->children[$i];
                 $r = SmilPlaylistAnimateElement::convert2lspl($gb, $ch, &$gunids, $parr, $ind2);
                 if (PEAR::isError($r)) {
    -            	return $r;
    +                return $r;
                 }
                 switch ($r['type']) {
                     case "fadeIn":  $fadeIn  = $r['val']; break;
    @@ -225,7 +225,7 @@ class SmilPlaylistAudioElement {
                 $fadeOut = Playlist::secondsToPlaylistTime($fadeOut);
                 $fInfo   = "$ind2\n";
             } else {
    -        	$fInfo = '';
    +            $fInfo = '';
             }
             $plElGunid  = StoredFile::CreateGunid();
             $acGunid     = $gunid;
    @@ -238,19 +238,19 @@ class SmilPlaylistAudioElement {
                     case "m3u":
                         $type = 'playlist';
                         $acId = $gb->bsImportPlaylistRaw($gunid,
    -                        $aPath, $uri, $ext, $gunids, $subjid);
    +                    $aPath, $uri, $ext, $gunids, $subjid);
                         if (PEAR::isError($acId)) {
    -                    	return $r;
    +                        return $r;
                         }
    -                   //break;
    +                    //break;
                     default:
                         $ac = StoredFile::RecallByGunid($gunid);
                         if (is_null($ac) || PEAR::isError($ac)) {
    -                    	return $ac;
    +                        return $ac;
                         }
                         $r = $ac->md->getMetadataElement('dcterms:extent');
                         if (PEAR::isError($r)) {
    -                    	return $r;
    +                        return $r;
                         }
                         $playlength = $r[0]['value'];
                 }
    @@ -263,7 +263,7 @@ class SmilPlaylistAudioElement {
             $clipLength = Playlist::secondsToPlaylistTime($tree->attrs['clipLength']->val);
             $res = "$ind\n".
                 "$ind2<$type id=\"$acGunid\" playlength=\"$playlength\" title=\"$title\"/>\n".
    -            $fInfo.
    +        $fInfo.
                 "$ind\n";
             return $res;
         }
    @@ -278,35 +278,35 @@ class SmilPlaylistAudioElement {
      */
     class SmilPlaylistAnimateElement {
     
    -	public static function convert2lspl(&$gb, &$tree, &$gunids, $parr, $ind='')
    -	{
    +    public static function convert2lspl(&$gb, &$tree, &$gunids, $parr, $ind='')
    +    {
             extract($parr);
             if ($tree->name != 'animate') {
                 return PEAR::raiseError("SmilPlaylist::parse: animate tag expected");
             }
             if ($tree->attrs['attributeName']->val == 'soundLevel' &&
    -            $tree->attrs['from']->val == '0%' &&
    -            $tree->attrs['to']->val == '100%' &&
    -            $tree->attrs['calcMode']->val == 'linear' &&
    -            $tree->attrs['fill']->val == 'freeze' &&
    -            $tree->attrs['begin']->val == '0s' &&
    -            preg_match("|^([0-9.]+)s$|", $tree->attrs['end']->val, $va)
    +        $tree->attrs['from']->val == '0%' &&
    +        $tree->attrs['to']->val == '100%' &&
    +        $tree->attrs['calcMode']->val == 'linear' &&
    +        $tree->attrs['fill']->val == 'freeze' &&
    +        $tree->attrs['begin']->val == '0s' &&
    +        preg_match("|^([0-9.]+)s$|", $tree->attrs['end']->val, $va)
             ) {
                 return array('type'=>'fadeIn', 'val'=>intval($va[1]));
             }
             if ($tree->attrs['attributeName']->val == 'soundLevel' &&
    -            $tree->attrs['from']->val == '100%' &&
    -            $tree->attrs['to']->val == '0%' &&
    -            $tree->attrs['calcMode']->val == 'linear' &&
    -            $tree->attrs['fill']->val == 'freeze' &&
    -            preg_match("|^([0-9.]+)s$|", $tree->attrs['begin']->val, $vaBegin) &&
    -            preg_match("|^([0-9.]+)s$|", $tree->attrs['end']->val, $vaEnd)
    +        $tree->attrs['from']->val == '100%' &&
    +        $tree->attrs['to']->val == '0%' &&
    +        $tree->attrs['calcMode']->val == 'linear' &&
    +        $tree->attrs['fill']->val == 'freeze' &&
    +        preg_match("|^([0-9.]+)s$|", $tree->attrs['begin']->val, $vaBegin) &&
    +        preg_match("|^([0-9.]+)s$|", $tree->attrs['end']->val, $vaEnd)
             ) {
                 return array('type'=>'fadeOut', 'val'=>($vaEnd[1] - $vaBegin[1]));
             }
             return PEAR::raiseError(
                 "SmilPlaylistAnimateElement::convert2lspl: animate parameters too general"
    -        );
    +            );
         }
     } // class SmilPlaylistAnimateElement
     
    diff --git a/backend/StoredFile.php b/backend/StoredFile.php
    index a1c65dcd1..fdd18fc80 100644
    --- a/backend/StoredFile.php
    +++ b/backend/StoredFile.php
    @@ -7,18 +7,18 @@ require_once("Schedule.php");
     $g_metadata_xml_to_db_mapping = array(
         "dc:format" => "format",
         "ls:bitrate" => "bit_rate",
    -  	"ls:samplerate" => "sample_rate",
    +    "ls:samplerate" => "sample_rate",
         "dcterms:extent" => "length",
    -		"dc:title" => "track_title",
    -		"dc:description" => "comments",
    -		"dc:type" => "genre",
    -		"dc:creator" => "artist_name",
    +    "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: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",
    @@ -146,118 +146,118 @@ function camp_get_audio_metadata($p_filename, $p_testonly = false)
         $getID3 = new getID3();
         $infoFromFile = $getID3->analyze($p_filename);
         if (PEAR::isError($infoFromFile)) {
    -    	return $infoFromFile;
    +        return $infoFromFile;
         }
         if (isset($infoFromFile['error'])) {
    -    	return new PEAR_Error(array_pop($infoFromFile['error']));
    +        return new PEAR_Error(array_pop($infoFromFile['error']));
         }
         if (!$infoFromFile['bitrate']) {
    -    	return new PEAR_Error("File given is not an audio file.");
    +        return new PEAR_Error("File given is not an audio file.");
         }
     
         if ($p_testonly) {
    -    	print_r($infoFromFile);
    +        print_r($infoFromFile);
         }
    -	$titleKey = 'dc:title';
    -	$flds = array(
    -	    'dc:format' => array(
    -	        array('path'=>"['mime_type']", 'ignoreEnc'=>TRUE),
    -	    ),
    -	    'ls:bitrate' => array(
    -	        array('path'=>"['bitrate']", 'ignoreEnc'=>TRUE),
    -	        array('path'=>"['audio']['bitrate']", 'ignoreEnc'=>TRUE),
    -	    ),
    -	    'ls:samplerate' => array(
    -	       array('path'=>"['audio']['sample_rate']", 'ignoreEnc'=>TRUE),
    -	    ),
    -	    'ls:encoder' => array(
    -	       array('path'=>"['audio']['codec']", 'ignoreEnc'=>TRUE),
    -	    ),
    -	    'dcterms:extent'=> array(
    -	        array('path'=>"['playtime_seconds']", 'ignoreEnc'=>TRUE),
    -	    ),
    -	    'ls:composer'=> array(
    -	        array('path'=>"['id3v2']['comments']['composer']", 'dataPath'=>"[0]", 'ignoreEnc'=>TRUE),
    -	        array('path'=>"['id3v2']['TCOM'][0]", 'dataPath'=>"['data']", 'encPath'=>"['encoding']"),
    -	        array('path'=>"['tags']['id3v2']['composer']", 'dataPath'=>"[0]", 'ignoreEnc'=>TRUE),
    -	        array('path'=>"['ogg']['comments']['composer']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    -	        array('path'=>"['tags']['vorbiscomment']['composer']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    -	    ),
    -	    'dc:description'=> array(
    -	        array('path'=>"['id3v1']['comments']['comment']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    -	        array('path'=>"['id3v2']['comments']['comments']", 'dataPath'=>"[0]", 'ignoreEnc'=>TRUE),
    -	        array('path'=>"['id3v2']['COMM'][0]", 'dataPath'=>"['data']", 'encPath'=>"['encoding']"),
    -	        array('path'=>"['tags']['id3v2']['comments']", 'dataPath'=>"[0]", 'ignoreEnc'=>TRUE),
    -	        array('path'=>"['ogg']['comments']['comment']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    -	        array('path'=>"['tags']['vorbiscomment']['comment']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    -	    ),
    -	    'dc:type'=> array(
    -	        array('path'=>"['id3v1']", 'dataPath'=>"['genre']", 'encPath'=>"['encoding']"),
    -	        array('path'=>"['id3v2']['comments']['content_type']", 'dataPath'=>"[0]", 'ignoreEnc'=>TRUE),
    -	        array('path'=>"['id3v2']['TCON'][0]", 'dataPath'=>"['data']", 'encPath'=>"['encoding']"),
    -	        array('path'=>"['ogg']['comments']['genre']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    -	        array('path'=>"['tags']['vorbiscomment']['genre']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    -	    ),
    -	    'dc:title' => array(
    -	        array('path'=>"['id3v2']['comments']['title']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    -	        array('path'=>"['id3v2']['TIT2'][0]", 'dataPath'=>"['data']", 'encPath'=>"['encoding']"),
    -	        array('path'=>"['id3v2']['TT2'][0]", 'dataPath'=>"['data']", 'encPath'=>"['encoding']"),
    -	        array('path'=>"['id3v1']", 'dataPath'=>"['title']", 'encPath'=>"['encoding']"),
    -	        array('path'=>"['ogg']['comments']['title']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    -	        array('path'=>"['tags']['vorbiscomment']['title']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    -	    ),
    -	    'dc:creator' => array(
    -	        array('path'=>"['id3v2']['comments']['artist']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    -	        array('path'=>"['id3v2']['TPE1'][0]", 'dataPath'=>"['data']", 'encPath'=>"['encoding']"),
    -	        array('path'=>"['id3v2']['TP1'][0]", 'dataPath'=>"['data']", 'encPath'=>"['encoding']"),
    -	        array('path'=>"['id3v1']", 'dataPath'=>"['artist']", 'encPath'=>"['encoding']"),
    -	        array('path'=>"['ogg']['comments']['artist']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    -	        array('path'=>"['tags']['vorbiscomment']['artist']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    -	    ),
    -	    'dc:source' => array(
    -	        array('path'=>"['id3v2']['comments']['album']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    -	        array('path'=>"['id3v2']['TALB'][0]", 'dataPath'=>"['data']", 'encPath'=>"['encoding']"),
    -	        array('path'=>"['id3v2']['TAL'][0]", 'dataPath'=>"['data']", 'encPath'=>"['encoding']"),
    -	        array('path'=>"['ogg']['comments']['album']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    -	        array('path'=>"['tags']['vorbiscomment']['album']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    -	    ),
    -	    'ls:encoded_by'	=> array(
    -	        array('path'=>"['id3v2']['TENC'][0]", 'dataPath'=>"['data']", 'encPath'=>"['encoding']"),
    -	        array('path'=>"['id3v2']['TEN'][0]", 'dataPath'=>"['data']", 'encPath'=>"['encoding']"),
    -	        array('path'=>"['ogg']['comments']['encoded-by']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    -	        array('path'=>"['tags']['vorbiscomment']['encoded-by']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    -	    ),
    -	    'ls:track_num' => array(
    -	        array('path'=>"['id3v2']['TRCK'][0]", 'dataPath'=>"['data']", 'encPath'=>"['encoding']"),
    -	        array('path'=>"['id3v2']['TRK'][0]", 'dataPath'=>"['data']", 'encPath'=>"['encoding']"),
    -	        array('path'=>"['ogg']['comments']['tracknumber']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    -	        array('path'=>"['tags']['vorbiscomment']['tracknumber']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    -	    ),
    -//	    'ls:genre'	    => array(
    -//	        array('path'=>"['id3v1']", 'dataPath'=>"['genre']", 'encPath'=>"['encoding']"),
    -//	        array('path'=>"['id3v2']['TCON'][0]", 'dataPath'=>"['data']", 'encPath'=>"['encoding']"),
    -//	        array('path'=>"['id3v2']['comments']['content_type']", 'dataPath'=>"[0]", 'ignoreEnc'=>TRUE),
    -//	        array('path'=>"['ogg']['comments']['genre']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    -//	        array('path'=>"['tags']['vorbiscomment']['genre']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    -//	    ),
    -	    'ls:channels' => array(
    -	        array('path'=>"['audio']['channels']", 'ignoreEnc'=>TRUE),
    -	    ),
    -	    'ls:year' => array(
    -	    	array('path'=>"['comments']['date']"),
    -	        array('path'=>"['ogg']['comments']['date']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    -	        array('path'=>"['tags']['vorbiscomment']['date']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    -	    ),
    -	    'ls:filename' => array(
    -	        array('path'=>"['filename']"),
    -	    ),
    -	);
    +    $titleKey = 'dc:title';
    +    $flds = array(
    +        'dc:format' => array(
    +            array('path'=>"['mime_type']", 'ignoreEnc'=>TRUE),
    +        ),
    +        'ls:bitrate' => array(
    +            array('path'=>"['bitrate']", 'ignoreEnc'=>TRUE),
    +            array('path'=>"['audio']['bitrate']", 'ignoreEnc'=>TRUE),
    +            ),
    +        'ls:samplerate' => array(
    +            array('path'=>"['audio']['sample_rate']", 'ignoreEnc'=>TRUE),
    +        ),
    +        'ls:encoder' => array(
    +            array('path'=>"['audio']['codec']", 'ignoreEnc'=>TRUE),
    +        ),
    +        'dcterms:extent'=> array(
    +            array('path'=>"['playtime_seconds']", 'ignoreEnc'=>TRUE),
    +        ),
    +        'ls:composer'=> array(
    +            array('path'=>"['id3v2']['comments']['composer']", 'dataPath'=>"[0]", 'ignoreEnc'=>TRUE),
    +            array('path'=>"['id3v2']['TCOM'][0]", 'dataPath'=>"['data']", 'encPath'=>"['encoding']"),
    +            array('path'=>"['tags']['id3v2']['composer']", 'dataPath'=>"[0]", 'ignoreEnc'=>TRUE),
    +            array('path'=>"['ogg']['comments']['composer']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    +            array('path'=>"['tags']['vorbiscomment']['composer']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    +        ),
    +        'dc:description'=> array(
    +            array('path'=>"['id3v1']['comments']['comment']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    +            array('path'=>"['id3v2']['comments']['comments']", 'dataPath'=>"[0]", 'ignoreEnc'=>TRUE),
    +            array('path'=>"['id3v2']['COMM'][0]", 'dataPath'=>"['data']", 'encPath'=>"['encoding']"),
    +            array('path'=>"['tags']['id3v2']['comments']", 'dataPath'=>"[0]", 'ignoreEnc'=>TRUE),
    +            array('path'=>"['ogg']['comments']['comment']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    +            array('path'=>"['tags']['vorbiscomment']['comment']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    +        ),
    +        'dc:type'=> array(
    +            array('path'=>"['id3v1']", 'dataPath'=>"['genre']", 'encPath'=>"['encoding']"),
    +            array('path'=>"['id3v2']['comments']['content_type']", 'dataPath'=>"[0]", 'ignoreEnc'=>TRUE),
    +            array('path'=>"['id3v2']['TCON'][0]", 'dataPath'=>"['data']", 'encPath'=>"['encoding']"),
    +            array('path'=>"['ogg']['comments']['genre']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    +            array('path'=>"['tags']['vorbiscomment']['genre']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    +        ),
    +        'dc:title' => array(
    +            array('path'=>"['id3v2']['comments']['title']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    +            array('path'=>"['id3v2']['TIT2'][0]", 'dataPath'=>"['data']", 'encPath'=>"['encoding']"),
    +            array('path'=>"['id3v2']['TT2'][0]", 'dataPath'=>"['data']", 'encPath'=>"['encoding']"),
    +            array('path'=>"['id3v1']", 'dataPath'=>"['title']", 'encPath'=>"['encoding']"),
    +            array('path'=>"['ogg']['comments']['title']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    +            array('path'=>"['tags']['vorbiscomment']['title']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    +        ),
    +        'dc:creator' => array(
    +            array('path'=>"['id3v2']['comments']['artist']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    +            array('path'=>"['id3v2']['TPE1'][0]", 'dataPath'=>"['data']", 'encPath'=>"['encoding']"),
    +            array('path'=>"['id3v2']['TP1'][0]", 'dataPath'=>"['data']", 'encPath'=>"['encoding']"),
    +            array('path'=>"['id3v1']", 'dataPath'=>"['artist']", 'encPath'=>"['encoding']"),
    +            array('path'=>"['ogg']['comments']['artist']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    +            array('path'=>"['tags']['vorbiscomment']['artist']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    +        ),
    +        'dc:source' => array(
    +            array('path'=>"['id3v2']['comments']['album']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    +            array('path'=>"['id3v2']['TALB'][0]", 'dataPath'=>"['data']", 'encPath'=>"['encoding']"),
    +            array('path'=>"['id3v2']['TAL'][0]", 'dataPath'=>"['data']", 'encPath'=>"['encoding']"),
    +            array('path'=>"['ogg']['comments']['album']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    +            array('path'=>"['tags']['vorbiscomment']['album']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    +        ),
    +        'ls:encoded_by'	=> array(
    +            array('path'=>"['id3v2']['TENC'][0]", 'dataPath'=>"['data']", 'encPath'=>"['encoding']"),
    +            array('path'=>"['id3v2']['TEN'][0]", 'dataPath'=>"['data']", 'encPath'=>"['encoding']"),
    +            array('path'=>"['ogg']['comments']['encoded-by']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    +            array('path'=>"['tags']['vorbiscomment']['encoded-by']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    +        ),
    +        'ls:track_num' => array(
    +            array('path'=>"['id3v2']['TRCK'][0]", 'dataPath'=>"['data']", 'encPath'=>"['encoding']"),
    +            array('path'=>"['id3v2']['TRK'][0]", 'dataPath'=>"['data']", 'encPath'=>"['encoding']"),
    +            array('path'=>"['ogg']['comments']['tracknumber']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    +            array('path'=>"['tags']['vorbiscomment']['tracknumber']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    +        ),
    +    //	    'ls:genre'	    => array(
    +    //	        array('path'=>"['id3v1']", 'dataPath'=>"['genre']", 'encPath'=>"['encoding']"),
    +    //	        array('path'=>"['id3v2']['TCON'][0]", 'dataPath'=>"['data']", 'encPath'=>"['encoding']"),
    +    //	        array('path'=>"['id3v2']['comments']['content_type']", 'dataPath'=>"[0]", 'ignoreEnc'=>TRUE),
    +    //	        array('path'=>"['ogg']['comments']['genre']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    +    //	        array('path'=>"['tags']['vorbiscomment']['genre']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    +    //	    ),
    +        'ls:channels' => array(
    +            array('path'=>"['audio']['channels']", 'ignoreEnc'=>TRUE),
    +        ),
    +        'ls:year' => array(
    +            array('path'=>"['comments']['date']"),
    +            array('path'=>"['ogg']['comments']['date']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    +            array('path'=>"['tags']['vorbiscomment']['date']", 'dataPath'=>"[0]", 'encPath'=>"['encoding']"),
    +        ),
    +        'ls:filename' => array(
    +            array('path'=>"['filename']"),
    +        ),
    +    );
         $mdata = array();
         if (isset($infoFromFile['audio'])) {
    -    	$mdata['audio'] = $infoFromFile['audio'];
    +        $mdata['audio'] = $infoFromFile['audio'];
         }
         if (isset($infoFromFile['playtime_seconds'])) {
    -		$mdata['playtime_seconds'] = $infoFromFile['playtime_seconds'];
    +        $mdata['playtime_seconds'] = $infoFromFile['playtime_seconds'];
         }
     
         $titleHaveSet = FALSE;
    @@ -265,7 +265,7 @@ function camp_get_audio_metadata($p_filename, $p_testonly = false)
             foreach ($getid3keys as $getid3key) {
                 $path = $getid3key["path"];
                 $ignoreEnc = isset($getid3key["ignoreEnc"])?
    -                $getid3key["ignoreEnc"]:FALSE;
    +            $getid3key["ignoreEnc"]:FALSE;
                 $dataPath = isset($getid3key["dataPath"])?$getid3key["dataPath"]:"";
                 $encPath = isset($getid3key["encPath"])?$getid3key["encPath"]:"";
                 $enc = "UTF-8";
    @@ -281,7 +281,7 @@ function camp_get_audio_metadata($p_filename, $p_testonly = false)
                         $encodedElement = "\$infoFromFile$path$encPath";
                         eval("\$encodedElementExists = isset($encodedElement);");
                         if ($encodedElementExists) {
    -                    	eval("\$enc = $encodedElement;");
    +                        eval("\$enc = $encodedElement;");
                         }
                     }
     
    @@ -290,19 +290,19 @@ function camp_get_audio_metadata($p_filename, $p_testonly = false)
                         $data = camp_parse_track_number($data);
                     }
                     camp_add_metadata($mdata, $key, $data, $enc);
    -		        if ($key == $titleKey) {
    -		        	$titleHaveSet = TRUE;
    -		        }
    +                if ($key == $titleKey) {
    +                    $titleHaveSet = TRUE;
    +                }
                     break;
                 }
             }
         }
         if ($p_testonly) {
    -    	var_dump($mdata);
    +        var_dump($mdata);
         }
     
         if (!$titleHaveSet || trim($mdata[$titleKey]) == '') {
    -    	camp_add_metadata($mdata, $titleKey, basename($p_filename));
    +        camp_add_metadata($mdata, $titleKey, basename($p_filename));
         }
         return $mdata;
     }
    @@ -328,96 +328,96 @@ class StoredFile {
     
         // *** Variables stored in the database ***
     
    -	/**
    -	 * @var int
    -	 */
    -	private $id;
    +    /**
    +     * @var int
    +     */
    +    private $id;
     
    -	/**
    -	 * Unique ID for the file.  This is stored in HEX format.  It is
    -	 * converted to a bigint whenever it is used in a database call.
    -	 *
    -	 * @var string
    -	 */
    -	public $gunid;
    +    /**
    +     * Unique ID for the file.  This is stored in HEX format.  It is
    +     * converted to a bigint whenever it is used in a database call.
    +     *
    +     * @var string
    +     */
    +    public $gunid;
     
    -	/**
    -	 * The unique ID of the file as it is stored in the database.
    -	 * This is for debugging purposes and may not always exist in this
    -	 * class.
    -	 *
    -	 * @var string
    -	 */
    -	//private $gunidBigint;
    +    /**
    +     * The unique ID of the file as it is stored in the database.
    +     * This is for debugging purposes and may not always exist in this
    +     * class.
    +     *
    +     * @var string
    +     */
    +    //private $gunidBigint;
     
    -	/**
    -	 * @var string
    -	 */
    -	private $name;
    +    /**
    +     * @var string
    +     */
    +    private $name;
     
    -	/**
    -	 * @var string
    -	 */
    -	private $mime;
    +    /**
    +     * @var string
    +     */
    +    private $mime;
     
    -	/**
    -	 * Can be 'audioclip'...others might be coming, like webstream.
    -	 *
    -	 * @var string
    -	 */
    -	private $ftype;
    +    /**
    +     * Can be 'audioclip'...others might be coming, like webstream.
    +     *
    +     * @var string
    +     */
    +    private $ftype;
     
    -	/**
    -	 * Can be 'ready', 'edited', 'incomplete'.
    -	 *
    -	 * @var string
    -	 */
    -	private $state;
    +    /**
    +     * Can be 'ready', 'edited', 'incomplete'.
    +     *
    +     * @var string
    +     */
    +    private $state;
     
    -	/**
    -	 * @var int
    -	 */
    -	private $currentlyaccessing;
    +    /**
    +     * @var int
    +     */
    +    private $currentlyaccessing;
     
    -	/**
    -	 * @var int
    -	 */
    -	private $editedby;
    +    /**
    +     * @var int
    +     */
    +    private $editedby;
     
    -	/**
    -	 * @var timestamp
    -	 */
    -	private $mtime;
    +    /**
    +     * @var timestamp
    +     */
    +    private $mtime;
     
    -	/**
    -	 * @var string
    -	 */
    -	private $md5;
    +    /**
    +     * @var string
    +     */
    +    private $md5;
     
    -	/**
    -	 * @var string
    -	 */
    -	private $filepath;
    +    /**
    +     * @var string
    +     */
    +    private $filepath;
     
     
    -	// *** Variables NOT stored in the database ***
    +    // *** Variables NOT stored in the database ***
     
    -	/**
    -	 * Directory where the file is located.
    -	 *
    -	 * @var string
    -	 */
    -	private $resDir;
    +    /**
    +     * Directory where the file is located.
    +     *
    +     * @var string
    +     */
    +    private $resDir;
     
    -	/**
    -	 * @var boolean
    -	 */
    -	private $exists;
    +    /**
    +     * @var boolean
    +     */
    +    private $exists;
     
    -	/**
    -	 * @var MetaData
    -	 */
    -	public $md;
    +    /**
    +     * @var MetaData
    +     */
    +    public $md;
     
         /* ========================================================== constructor */
         /**
    @@ -433,8 +433,8 @@ class StoredFile {
                 $this->gunid = StoredFile::generateGunid();
             }
             else {
    -          $this->loadMetadata();
    -          $this->exists = is_file($this->filepath) && is_readable($this->filepath);
    +            $this->loadMetadata();
    +            $this->exists = is_file($this->filepath) && is_readable($this->filepath);
             }
         }
     
    @@ -442,7 +442,7 @@ class StoredFile {
          * For testing only, do not use.
          */
         public function __setGunid($p_guid) {
    -      $this->gunid = $p_guid;
    +        $this->gunid = $p_guid;
         }
     
         /**
    @@ -489,7 +489,7 @@ class StoredFile {
             global $CC_CONFIG, $CC_DBC;
             $escapedValue = pg_escape_string($this->gunid);
             $sql = "SELECT * FROM ".$CC_CONFIG["filesTable"]
    -              ." WHERE gunid='$escapedValue'";
    +        ." WHERE gunid='$escapedValue'";
             //var_dump($sql);
             $this->md = $CC_DBC->getRow($sql);
             //var_dump($this->md);
    @@ -528,8 +528,8 @@ class StoredFile {
                 $columnName = StoredFile::xmlCategoryToDbColumn($category);
                 if (!is_null($columnName)) {
                     $sql = "UPDATE ".$CC_CONFIG["filesTable"]
    -                      ." SET $columnName='$escapedValue'"
    -                      ." WHERE gunid = '".$this->gunid."'";
    +                ." SET $columnName='$escapedValue'"
    +                ." WHERE gunid = '".$this->gunid."'";
                     $CC_DBC->query($sql);
                 }
             }
    @@ -544,8 +544,8 @@ class StoredFile {
             foreach ($metadataColumns as $columnName) {
                 if (!is_null($columnName)) {
                     $sql = "UPDATE ".$CC_CONFIG["filesTable"]
    -                      ." SET $columnName=''"
    -                      ." WHERE gunid = '".$this->gunid."'";
    +                ." SET $columnName=''"
    +                ." WHERE gunid = '".$this->gunid."'";
                     $CC_DBC->query($sql);
                 }
             }
    @@ -575,7 +575,7 @@ class StoredFile {
             global $CC_CONFIG, $CC_DBC;
     
             if (!isset($p_values["filepath"])) {
    -          return new PEAR_Error("StoredFile::Insert: filepath not set.");
    +            return new PEAR_Error("StoredFile::Insert: filepath not set.");
             }
             if (!file_exists($p_values['filepath'])) {
                 return PEAR::raiseError("StoredFile::Insert: ".
    @@ -589,16 +589,16 @@ class StoredFile {
     
             // Get metadata
             if (isset($p_values["metadata"])) {
    -          $metadata = $p_values['metadata'];
    +            $metadata = $p_values['metadata'];
             } else {
    -          $metadata = camp_get_audio_metadata($p_values["filepath"]);
    +            $metadata = camp_get_audio_metadata($p_values["filepath"]);
             }
     
             $storedFile->name = isset($p_values['filename']) ? $p_values['filename'] : $p_values["filepath"];
    -      	$storedFile->id = isset($p_values['id']) && is_integer($p_values['id'])?(int)$p_values['id']:null;
    +        $storedFile->id = isset($p_values['id']) && is_integer($p_values['id'])?(int)$p_values['id']:null;
             // NOTE: POSTGRES-SPECIFIC KEYWORD "DEFAULT" BEING USED, WOULD BE "NULL" IN MYSQL
    -      	$sqlId = !is_null($storedFile->id)?"'".$storedFile->id."'":'DEFAULT';
    -      	$storedFile->ftype = isset($p_values['filetype']) ? strtolower($p_values['filetype']) : "audioclip";
    +        $sqlId = !is_null($storedFile->id)?"'".$storedFile->id."'":'DEFAULT';
    +        $storedFile->ftype = isset($p_values['filetype']) ? strtolower($p_values['filetype']) : "audioclip";
             $storedFile->mime = (isset($p_values["mime"]) ? $p_values["mime"] : NULL );
             // $storedFile->filepath = $p_values['filepath'];
             if (isset($p_values['md5'])) {
    @@ -611,7 +611,7 @@ class StoredFile {
             // Check for duplicates -- return duplicate
             $duplicate = StoredFile::RecallByMd5($storedFile->md5);
             if ($duplicate) {
    -          return $duplicate;
    +            return $duplicate;
             }
     
             $storedFile->exists = FALSE;
    @@ -620,11 +620,11 @@ class StoredFile {
             $escapedName = pg_escape_string($storedFile->name);
             $escapedFtype = pg_escape_string($storedFile->ftype);
             $sql = "INSERT INTO ".$CC_CONFIG['filesTable']
    -                ."(id, name, gunid, mime, state, ftype, mtime, md5)"
    -                ."VALUES ({$sqlId}, '{$escapedName}', "
    -                ." '{$storedFile->gunid}',"
    -                ." '{$storedFile->mime}', 'incomplete', '$escapedFtype',"
    -                ." now(), '{$storedFile->md5}')";
    +        ."(id, name, gunid, mime, state, ftype, mtime, md5)"
    +        ."VALUES ({$sqlId}, '{$escapedName}', "
    +        ." '{$storedFile->gunid}',"
    +        ." '{$storedFile->mime}', 'incomplete', '$escapedFtype',"
    +        ." now(), '{$storedFile->md5}')";
             //$_SESSION["debug"] .= "sql: ".$sql."
    "; //echo $sql."\n"; $res = $CC_DBC->query($sql); @@ -634,9 +634,9 @@ class StoredFile { } if (!is_integer($storedFile->id)) { - // NOTE: POSTGRES-SPECIFIC - $sql = "SELECT currval('".$CC_CONFIG["filesSequence"]."_seq')"; - $storedFile->id = $CC_DBC->getOne($sql); + // NOTE: POSTGRES-SPECIFIC + $sql = "SELECT currval('".$CC_CONFIG["filesSequence"]."_seq')"; + $storedFile->id = $CC_DBC->getOne($sql); } $storedFile->setMetadataBatch($metadata); @@ -688,8 +688,8 @@ class StoredFile { return null; } $sql = "SELECT *" - ." FROM ".$CC_CONFIG['filesTable'] - ." WHERE $cond"; + ." FROM ".$CC_CONFIG['filesTable'] + ." WHERE $cond"; //echo $sql; $row = $CC_DBC->getRow($sql); if (PEAR::isError($row) || is_null($row)) { @@ -751,8 +751,8 @@ class StoredFile { { global $CC_CONFIG, $CC_DBC; $sql = "SELECT gunid" - ." FROM ".$CC_CONFIG['accessTable'] - ." WHERE token=x'$p_token'::bigint"; + ." FROM ".$CC_CONFIG['accessTable'] + ." WHERE token=x'$p_token'::bigint"; $gunid = $CC_DBC->getOne($sql); if (PEAR::isError($gunid)) { return $gunid; @@ -796,7 +796,7 @@ class StoredFile { { global $CC_CONFIG, $CC_DBC; if ($this->exists) { - return FALSE; + return FALSE; } // for files downloaded from remote instance: if ($p_localFilePath == $this->filepath) { @@ -823,8 +823,8 @@ class StoredFile { $this->filepath = $dstFile; $sqlPath = pg_escape_string($this->filepath); $sql = "UPDATE ".$CC_CONFIG["filesTable"] - ." SET filepath='{$sqlPath}'" - ." WHERE id={$this->id}"; + ." SET filepath='{$sqlPath}'" + ." WHERE id={$this->id}"; //echo $sql."\n"; $res = $CC_DBC->query($sql); if (PEAR::isError($res)) { @@ -851,9 +851,9 @@ class StoredFile { } if ($this->exists) { - $r = $this->deleteFile(); + $r = $this->deleteFile(); if (PEAR::isError($r)) { - return $r; + return $r; } } return $this->addFile($p_localFilePath); @@ -883,19 +883,19 @@ class StoredFile { { global $CC_CONFIG; if (!$this->exists) { - return FALSE; + return FALSE; } if ($this->isAccessed()) { - return PEAR::raiseError( + return PEAR::raiseError( 'Cannot delete a file that is currently accessed.' - ); + ); } // Check if the file is scheduled to be played in the future if (Schedule::IsFileScheduledInTheFuture($this->id)) { - return PEAR::raiseError( + return PEAR::raiseError( 'Cannot delete a file that is scheduled in the future.' - ); + ); } // Delete it from all playlists @@ -911,12 +911,12 @@ class StoredFile { } else { return PEAR::raiseError( "StoredFile::deleteFile: unlink failed ({$this->filepath})", - GBERR_FILEIO + GBERR_FILEIO ); } } else { - $this->exists = FALSE; - return TRUE; + $this->exists = FALSE; + return TRUE; } } @@ -932,7 +932,7 @@ class StoredFile { public function analyzeFile() { if (!$this->exists) { - return FALSE; + return FALSE; } $ia = camp_get_audio_metadata($this->filepath); return $ia; @@ -980,42 +980,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; + // } /** @@ -1035,7 +1035,7 @@ class StoredFile { return $res; } $resultArray = - array('url'=>"file://{$res['fname']}", 'token'=>$res['token']); + array('url'=>"file://{$res['fname']}", 'token'=>$res['token']); return $resultArray; } @@ -1077,10 +1077,10 @@ class StoredFile { return $res; } } -// $r = $this->md->regenerateXmlFile(); -// if (PEAR::isError($r)) { -// return $r; -// } + // $r = $this->md->regenerateXmlFile(); + // if (PEAR::isError($r)) { + // return $r; + // } return TRUE; } @@ -1109,21 +1109,21 @@ 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; -// } -// $res = $CC_DBC->query("COMMIT"); -// if (PEAR::isError($res)) { -// return $res; -// } -// return TRUE; -// } + // 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; + // } + // $res = $CC_DBC->query("COMMIT"); + // if (PEAR::isError($res)) { + // return $res; + // } + // return TRUE; + // } /** * Set metadata element value @@ -1136,27 +1136,27 @@ class StoredFile { */ 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={$this->id}"; - //var_dump($sql); - $res = $CC_DBC->query($sql); - if (PEAR::isError($res)) { - return $res; + global $CC_CONFIG, $CC_DBC; + if (!is_string($p_category) || is_array($p_value)) { + return FALSE; } - } - return TRUE; + 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={$this->id}"; + //var_dump($sql); + $res = $CC_DBC->query($sql); + if (PEAR::isError($res)) { + return $res; + } + } + return TRUE; } @@ -1170,49 +1170,49 @@ class StoredFile { */ 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; + global $CC_CONFIG, $CC_DBC; + if (!is_array($values)) { + $values = array($values); } - } - if (count($sqlValues)==0) { + 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={$this->id}"; + $CC_DBC->query($sql); return TRUE; - } - $sql = "UPDATE ".$CC_CONFIG["filesTable"] - ." SET ".join(",", $sqlValues) - ." WHERE id={$this->id}"; - $CC_DBC->query($sql); - return TRUE; } @@ -1234,11 +1234,11 @@ class StoredFile { */ public function getMetadataValue($p_name) { - if (isset($this->md[$p_name])){ - return $this->md[$p_name]; - } else { - return ""; - } + if (isset($this->md[$p_name])){ + return $this->md[$p_name]; + } else { + return ""; + } } /** @@ -1252,8 +1252,8 @@ class StoredFile { global $CC_CONFIG, $CC_DBC; $escapedName = pg_escape_string($p_newname); $sql = "UPDATE ".$CC_CONFIG['filesTable'] - ." SET name='$escapedName', mtime=now()" - ." WHERE gunid='{$this->gunid}'"; + ." SET name='$escapedName', mtime=now()" + ." WHERE gunid='{$this->gunid}'"; $res = $CC_DBC->query($sql); if (PEAR::isError($res)) { return $res; @@ -1278,8 +1278,8 @@ class StoredFile { $escapedState = pg_escape_string($p_state); $eb = (!is_null($p_editedby) ? ", editedBy=$p_editedby" : ''); $sql = "UPDATE ".$CC_CONFIG['filesTable'] - ." SET state='$escapedState'$eb, mtime=now()" - ." WHERE gunid='{$this->gunid}'"; + ." SET state='$escapedState'$eb, mtime=now()" + ." WHERE gunid='{$this->gunid}'"; $res = $CC_DBC->query($sql); if (PEAR::isError($res)) { return $res; @@ -1304,8 +1304,8 @@ class StoredFile { } $escapedMime = pg_escape_string($p_mime); $sql = "UPDATE ".$CC_CONFIG['filesTable'] - ." SET mime='$escapedMime', mtime=now()" - ." WHERE gunid='{$this->gunid}'"; + ." SET mime='$escapedMime', mtime=now()" + ." WHERE gunid='{$this->gunid}'"; $res = $CC_DBC->query($sql); if (PEAR::isError($res)) { return $res; @@ -1326,8 +1326,8 @@ class StoredFile { global $CC_CONFIG, $CC_DBC; $escapedMd5 = pg_escape_string($p_md5sum); $sql = "UPDATE ".$CC_CONFIG['filesTable'] - ." SET md5='$escapedMd5', mtime=now()" - ." WHERE gunid='{$this->gunid}'"; + ." SET md5='$escapedMd5', mtime=now()" + ." WHERE gunid='{$this->gunid}'"; $res = $CC_DBC->query($sql); if (PEAR::isError($res)) { return $res; @@ -1354,8 +1354,8 @@ class StoredFile { } } $sql = "SELECT to_hex(token)as token, ext " - ." FROM ".$CC_CONFIG['accessTable'] - ." WHERE gunid='{$this->gunid}'"; + ." FROM ".$CC_CONFIG['accessTable'] + ." WHERE gunid='{$this->gunid}'"; $tokens = $CC_DBC->getAll($sql); if (is_array($tokens)) { foreach ($tokens as $i => $item) { @@ -1366,13 +1366,13 @@ class StoredFile { } } $sql = "DELETE FROM ".$CC_CONFIG['accessTable'] - ." WHERE gunid='{$this->gunid}'"; + ." WHERE gunid='{$this->gunid}'"; $res = $CC_DBC->query($sql); if (PEAR::isError($res)) { return $res; } $sql = "DELETE FROM ".$CC_CONFIG['filesTable'] - ." WHERE gunid='{$this->gunid}'"; + ." WHERE gunid='{$this->gunid}'"; $res = $CC_DBC->query($sql); if (PEAR::isError($res)) { return $res; @@ -1388,14 +1388,14 @@ class StoredFile { public function getPlaylists() { global $CC_CONFIG, $CC_DBC; $sql = "SELECT playlist_id " - ." FROM ".$CC_CONFIG['playistTable'] - ." WHERE file_id='{$this->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); - } + foreach ($ids as $id) { + $playlists[] = Playlist::Recall($id); + } } return $playlists; } @@ -1416,12 +1416,12 @@ class StoredFile { return ($this->currentlyaccessing > 0); } $sql = "SELECT currentlyAccessing FROM ".$CC_CONFIG['filesTable'] - ." WHERE gunid='$p_gunid'"; + ." WHERE gunid='$p_gunid'"; $ca = $CC_DBC->getOne($sql); if (is_null($ca)) { return PEAR::raiseError( "StoredFile::isAccessed: invalid gunid ($p_gunid)", - GBERR_FOBJNEX + GBERR_FOBJNEX ); } return ($ca > 0); @@ -1463,7 +1463,7 @@ class StoredFile { $p_playlistId = $this->gunid; } $sql = "SELECT editedBy FROM ".$CC_CONFIG['filesTable'] - ." WHERE gunid='$p_playlistId'"; + ." WHERE gunid='$p_playlistId'"; $ca = $CC_DBC->getOne($sql); if (PEAR::isError($ca)) { return $ca; @@ -1505,8 +1505,8 @@ class StoredFile { { global $CC_CONFIG, $CC_DBC; $sql = "SELECT gunid " - ." FROM ".$CC_CONFIG['filesTable'] - ." WHERE gunid='{$this->gunid}'"; + ." FROM ".$CC_CONFIG['filesTable'] + ." WHERE gunid='{$this->gunid}'"; $indb = $CC_DBC->getRow($sql); if (PEAR::isError($indb)) { return $indb; @@ -1527,15 +1527,15 @@ class StoredFile { */ public static function generateGunid() { - return md5(uniqid("", true)); + return md5(uniqid("", true)); -// $ip = (isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : ''); -// $initString = microtime().$ip.rand(); -// $hash = md5($initString); -// // non-negative int8 -// $hsd = substr($hash, 0, 1); -// $res = dechex(hexdec($hsd)>>1).substr($hash, 1, 15); -// return StoredFile::NormalizeGunid($res); + // $ip = (isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : ''); + // $initString = microtime().$ip.rand(); + // $hash = md5($initString); + // // non-negative int8 + // $hsd = substr($hash, 0, 1); + // $res = dechex(hexdec($hsd)>>1).substr($hash, 1, 15); + // return StoredFile::NormalizeGunid($res); } @@ -1544,10 +1544,10 @@ class StoredFile { * * @return string */ -// public static function NormalizeGunid($p_gunid) -// { -// return str_pad($p_gunid, 16, "0", STR_PAD_LEFT); -// } + // public static function NormalizeGunid($p_gunid) + // { + // return str_pad($p_gunid, 16, "0", STR_PAD_LEFT); + // } /** @@ -1598,10 +1598,10 @@ class StoredFile { { $a = $this->analyzeFile(); if (PEAR::isError($a)) { - return $a; + return $a; } if (isset($a['dc:format'])) { - return $a['dc:format']; + return $a['dc:format']; } return ''; } @@ -1613,12 +1613,12 @@ class StoredFile { */ public function getTitle() { - return $this->md["title"]; + return $this->md["title"]; } public function getType() { - return $this->ftype; + return $this->ftype; } /** @@ -1636,7 +1636,7 @@ class StoredFile { return $this->state; } $sql = "SELECT state FROM ".$CC_CONFIG['filesTable'] - ." WHERE gunid='$p_gunid'"; + ." WHERE gunid='$p_gunid'"; return $CC_DBC->getOne($sql); } @@ -1655,7 +1655,7 @@ class StoredFile { return $this->name; } $sql = "SELECT name FROM ".$CC_CONFIG['filesTable'] - ." WHERE gunid='$p_gunid'"; + ." WHERE gunid='$p_gunid'"; return $CC_DBC->getOne($sql); } @@ -1666,64 +1666,64 @@ class StoredFile { * * @return string */ -// private function _getResDir() -// { -// global $CC_CONFIG, $CC_DBC; -// $resDir = $CC_CONFIG['storageDir']."/".substr($this->gunid, 0, 3); -// //$this->gb->debugLog("$resDir"); -// // see Transport::_getResDir too for resDir name create code -// if (!is_dir($resDir)) { -// mkdir($resDir, 02775); -// chmod($resDir, 02775); -// } -// return $resDir; -// } + // private function _getResDir() + // { + // global $CC_CONFIG, $CC_DBC; + // $resDir = $CC_CONFIG['storageDir']."/".substr($this->gunid, 0, 3); + // //$this->gb->debugLog("$resDir"); + // // see Transport::_getResDir too for resDir name create code + // if (!is_dir($resDir)) { + // mkdir($resDir, 02775); + // chmod($resDir, 02775); + // } + // return $resDir; + // } - /** - * Get real filename of raw media data - * - * @return string - */ - public function getRealFileName() - { - return $this->filepath; - } + /** + * Get real filename of raw media data + * + * @return string + */ + public function getRealFileName() + { + return $this->filepath; + } - /** - * Get the URL to access this file. - */ - public function getFileUrl() - { - global $CC_CONFIG; - return "http://".$CC_CONFIG["storageUrlHost"] - ."api/get_media.php?file_id={$this->gunid}"; - } + /** + * Get the URL to access this file. + */ + public function getFileUrl() + { + global $CC_CONFIG; + return "http://".$CC_CONFIG["storageUrlHost"] + ."api/get_media.php?file_id={$this->gunid}"; + } - /** - * Get real filename of metadata file - * - * @return string - * @see MetaData - */ - public function getRealMetadataFileName() - { - //return $this->md->getFileName(); - return $this->md["name"]; - } + /** + * Get real filename of metadata file + * + * @return string + * @see MetaData + */ + public function getRealMetadataFileName() + { + //return $this->md->getFileName(); + return $this->md["name"]; + } - /** - * Create and return name for temporary symlink. - * - * @todo Should be more unique - * @return string - */ - private function _getAccessFileName($p_token, $p_ext='EXT') - { - global $CC_CONFIG; - return $CC_CONFIG['accessDir']."/$p_token.$p_ext"; - } + /** + * Create and return name for temporary symlink. + * + * @todo Should be more unique + * @return string + */ + private function _getAccessFileName($p_token, $p_ext='EXT') + { + global $CC_CONFIG; + return $CC_CONFIG['accessDir']."/$p_token.$p_ext"; + } -} // class StoredFile -?> \ No newline at end of file + } // class StoredFile + ?> \ No newline at end of file diff --git a/backend/Transport.php b/backend/Transport.php index 0c33877c8..31405e26f 100644 --- a/backend/Transport.php +++ b/backend/Transport.php @@ -50,11 +50,11 @@ class Transport */ public $gb; - /** - * File name - * @var string - */ - private $cronJobScript; + /** + * File name + * @var string + */ + private $cronJobScript; /** * wget --read-timeout parameter [s] @@ -72,7 +72,7 @@ class Transport * wget --limit-rate parameter */ private $downLimitRate = NULL; -# private $downLimitRate = 500; + # private $downLimitRate = 500; /** * wget -t parameter @@ -109,7 +109,7 @@ class Transport * @var int */ private $upLimitRate = NULL; -# private $upLimitRate = 500; + # private $upLimitRate = 500; /** @@ -122,9 +122,9 @@ class Transport { $this->gb =& $gb; $this->cronJobScript = realpath( - dirname(__FILE__). + dirname(__FILE__). '/../../storageServer/var/cron/transportCronJob.php' - ); + ); } @@ -154,27 +154,27 @@ class Transport { $trec = TransportRecord::recall($this, $trtok); if (PEAR::isError($trec)) { - return $trec; + return $trec; } $res = array(); foreach (array( 'trtype', 'state', 'direction', 'expectedsize', 'realsize', 'expectedsum', 'realsum', 'title', 'errmsg' - ) as $k) { - $res[$k] = ( isset($trec->row[$k]) ? $trec->row[$k] : NULL ); - } - if ( ($trec->row['direction'] == 'down') && file_exists($trec->row['localfile']) ){ - $res['realsize'] = filesize($trec->row['localfile']); - $res['realsum'] = $this->_chsum($trec->row['localfile']); - } - if ( ($trec->row['direction'] == 'up') ){ - $check = $this->uploadCheck($trec->row['pdtoken']); - if (!PEAR::isError($check)) { - $res['realsize'] = $check['size']; - $res['realsum'] = $check['realsum']; + ) as $k) { + $res[$k] = ( isset($trec->row[$k]) ? $trec->row[$k] : NULL ); } - } - return $res; + if ( ($trec->row['direction'] == 'down') && file_exists($trec->row['localfile']) ){ + $res['realsize'] = filesize($trec->row['localfile']); + $res['realsum'] = $this->_chsum($trec->row['localfile']); + } + if ( ($trec->row['direction'] == 'up') ){ + $check = $this->uploadCheck($trec->row['pdtoken']); + if (!PEAR::isError($check)) { + $res['realsize'] = $check['size']; + $res['realsum'] = $check['realsum']; + } + } + return $res; } @@ -198,18 +198,18 @@ class Transport $res = $pr->loadGroupPref($group, $key); if (PEAR::isError($res)) { if ($res->getCode() !== GBERR_PREF) { - return $res; + return $res; } else { - $res = FALSE; // default + $res = FALSE; // default } } $state = !$res; if (is_null($onOff)) { - return $state; + return $state; } $res = $pr->saveGroupPref($sessid, $group, $key, !$onOff); if (PEAR::isError($res)) { - return $res; + return $res; } return $state; } @@ -229,7 +229,7 @@ class Transport { $trec = TransportRecord::recall($this, $trtok); if (PEAR::isError($trec)) { - return $trec; + return $trec; } if ($trec->getState() == 'closed') { return PEAR::raiseError( @@ -239,14 +239,14 @@ class Transport } switch ($action) { case 'pause'; - $newState = 'paused'; - break; + $newState = 'paused'; + break; case 'resume'; - $newState = 'waiting'; - break; + $newState = 'waiting'; + break; case 'cancel'; - $newState = 'closed'; - break; + $newState = 'closed'; + break; default: return PEAR::raiseError( "Transport::doTransportAction:". @@ -257,7 +257,7 @@ class Transport switch ($action) { case 'pause'; case 'cancel'; - $trec->killJob(); + $trec->killJob(); } return $res; } @@ -286,35 +286,35 @@ class Transport case "webstream": $storedFile = StoredFile::RecallByGunid($gunid); if (is_null($storedFile) || PEAR::isError($storedFile)) { - return $storedFile; + return $storedFile; } // handle metadata: $mdfpath = $storedFile->getRealMetadataFileName(); if (PEAR::isError($mdfpath)) { - return $mdfpath; + return $mdfpath; } $mdtrec = $this->_uploadGeneralFileToHub($mdfpath, 'metadata', - array_merge(array('gunid'=>$gunid, 'fname'=>'metadata',), $pars) + array_merge(array('gunid'=>$gunid, 'fname'=>'metadata',), $pars) ); if (PEAR::isError($mdtrec)) { - return $mdtrec; + return $mdtrec; } // handle raw media file: $fpath = $storedFile->getRealFileName(); if (PEAR::isError($fpath)) { - return $fpath; + return $fpath; } $fname = $storedFile->getName(); if (PEAR::isError($fname)) { - return $fname; + return $fname; } $trec = $this->_uploadGeneralFileToHub($fpath, 'audioclip', - array_merge(array( + array_merge(array( 'gunid'=>$gunid, 'fname'=>$fname, 'mdtrtok'=>$mdtrec->trtok, - ), $pars) + ), $pars) ); if (PEAR::isError($trec)) { - return $trec; + return $trec; } $this->startCronJobProcess($mdtrec->trtok); break; @@ -324,18 +324,18 @@ class Transport require_once("Playlist.php"); $pl = StoredFile::RecallByGunid($plid); if (is_null($pl) || PEAR::isError($pl)) { - return $pl; + return $pl; } $fname = $pl->getName(); if (PEAR::isError($fname)) { - return $fname; + return $fname; } if ($withContent) { $this->trLog("upload2Hub exportPlaylistOpen BEGIN: ".strftime("%H:%M:%S")); $res = $this->gb->bsExportPlaylistOpen($plid); $this->trLog("upload2Hub exportPlaylistOpen END: ".strftime("%H:%M:%S")); if (PEAR::isError($res)) { - return $res; + return $res; } $tmpn = tempnam($CC_CONFIG['transDir'], 'plExport_'); $plfpath = "$tmpn.lspl"; @@ -344,21 +344,21 @@ class Transport $this->trLog("upload2Hub end copy: ".strftime("%H:%M:%S")); $res = $this->gb->bsExportPlaylistClose($res['token']); if (PEAR::isError($res)) { - return $res; + return $res; } $fname = $fname.".lspl"; $trtype = 'playlistPkg'; } else { $plfpath = $pl->getRealMetadataFileName(); if (PEAR::isError($plfpath)) { - return $plfpath; + return $plfpath; } $trtype = 'playlist'; } $trec = $this->_uploadGeneralFileToHub($plfpath, $trtype, - array_merge(array('gunid'=>$plid,'fname'=>$fname,), $pars)); + array_merge(array('gunid'=>$plid,'fname'=>$fname,), $pars)); if (PEAR::isError($trec)) { - return $trec; + return $trec; } break; default: @@ -390,9 +390,9 @@ class Transport { $trtype = ($withContent ? 'playlistPkg' : 'unknown' ); $trec = TransportRecord::create($this, $trtype, 'down', - array_merge(array('gunid'=>$gunid, 'uid'=>$uid), $pars)); + array_merge(array('gunid'=>$gunid, 'uid'=>$uid), $pars)); if (PEAR::isError($trec)) { - return $trec; + return $trec; } $this->startCronJobProcess($trec->trtok); return $trec->trtok; @@ -447,33 +447,33 @@ class Transport * @return string * transport token */ -// function globalSearch($criteria, $resultMode='php', $pars=array()) -// { -// global $CC_CONFIG, $CC_DBC; -// // testing of hub availability and hub account configuration. -// // it makes searchjob not async - should be removed for real async -// $r = $this->loginToArchive(); -// if (PEAR::isError($r)) { -// switch(intval($r->getCode())) { -// case 802: -// return PEAR::raiseError("Can't login to Hub ({$r->getMessage()})", TRERR_XR_FAIL); -// case TRERR_XR_FAIL: -// return PEAR::raiseError("Can't connect to Hub ({$r->getMessage()})", TRERR_XR_FAIL); -// } -// return $r; -// } -// $this->logoutFromArchive($r); -// $criteria['resultMode'] = $resultMode; -// $localfile = tempnam($CC_CONFIG['transDir'], 'searchjob_'); -// @chmod($localfile, 0660); -// $len = file_put_contents($localfile, serialize($criteria)); -// $trec = $this->_uploadGeneralFileToHub($localfile, 'searchjob', $pars); -// if (PEAR::isError($trec)) { -// return $trec; -// } -// $this->startCronJobProcess($trec->trtok); -// return $trec->trtok; -// } + // function globalSearch($criteria, $resultMode='php', $pars=array()) + // { + // global $CC_CONFIG, $CC_DBC; + // // testing of hub availability and hub account configuration. + // // it makes searchjob not async - should be removed for real async + // $r = $this->loginToArchive(); + // if (PEAR::isError($r)) { + // switch(intval($r->getCode())) { + // case 802: + // return PEAR::raiseError("Can't login to Hub ({$r->getMessage()})", TRERR_XR_FAIL); + // case TRERR_XR_FAIL: + // return PEAR::raiseError("Can't connect to Hub ({$r->getMessage()})", TRERR_XR_FAIL); + // } + // return $r; + // } + // $this->logoutFromArchive($r); + // $criteria['resultMode'] = $resultMode; + // $localfile = tempnam($CC_CONFIG['transDir'], 'searchjob_'); + // @chmod($localfile, 0660); + // $len = file_put_contents($localfile, serialize($criteria)); + // $trec = $this->_uploadGeneralFileToHub($localfile, 'searchjob', $pars); + // if (PEAR::isError($trec)) { + // return $trec; + // } + // $this->startCronJobProcess($trec->trtok); + // return $trec->trtok; + // } /** @@ -486,60 +486,60 @@ class Transport * @return array * LS search result format (see localSearch) */ -// function getSearchResults($trtok, $andClose=TRUE) -// { -// $trec = TransportRecord::recall($this, $trtok); -// if (PEAR::isError($trec)) { -// return $trec; -// } -// $row = $trec->row; -// switch ($st = $trec->getState()) { -// case "failed": -// return PEAR::raiseError( -// "Transport::getSearchResults:". -// " global search or results transport failed". -// " ({$trec->row['errmsg']})" -// ); -// case "closed": -///* -// $res = file_get_contents($row['localfile']); -// $results = unserialize($res); -// return $results; -//*/ -// return PEAR::raiseError( -// "Transport::getSearchResults:". -// " closed transport token ($trtok)", TRERR_TOK -// ); -// case "finished": -// if ($row['direction'] == 'down') { -// // really finished -// $res = file_get_contents($row['localfile']); -// $results = unserialize($res); -// if ($andClose) { -// $ret = $this->xmlrpcCall('archive.downloadClose', -// array( -// 'token' => $row['pdtoken'] , -// 'trtype' => $row['trtype'] , -// )); -// if (PEAR::isError($ret)) { -// return $ret; -// } -// @unlink($row['localfile']); -// $r = $trec->close(); -// if (PEAR::isError($r)) { -// return $r; -// } -// } -// return $results; -// } -// // otherwise not really finished - only request upload finished -// default: -// return PEAR::raiseError( -// "Transport::getSearchResults: not finished ($st)", -// TRERR_NOTFIN -// ); -// } -// } + // function getSearchResults($trtok, $andClose=TRUE) + // { + // $trec = TransportRecord::recall($this, $trtok); + // if (PEAR::isError($trec)) { + // return $trec; + // } + // $row = $trec->row; + // switch ($st = $trec->getState()) { + // case "failed": + // return PEAR::raiseError( + // "Transport::getSearchResults:". + // " global search or results transport failed". + // " ({$trec->row['errmsg']})" + // ); + // case "closed": + ///* + // $res = file_get_contents($row['localfile']); + // $results = unserialize($res); + // return $results; + //*/ + // return PEAR::raiseError( + // "Transport::getSearchResults:". + // " closed transport token ($trtok)", TRERR_TOK + // ); + // case "finished": + // if ($row['direction'] == 'down') { + // // really finished + // $res = file_get_contents($row['localfile']); + // $results = unserialize($res); + // if ($andClose) { + // $ret = $this->xmlrpcCall('archive.downloadClose', + // array( + // 'token' => $row['pdtoken'] , + // 'trtype' => $row['trtype'] , + // )); + // if (PEAR::isError($ret)) { + // return $ret; + // } + // @unlink($row['localfile']); + // $r = $trec->close(); + // if (PEAR::isError($r)) { + // return $r; + // } + // } + // return $results; + // } + // // otherwise not really finished - only request upload finished + // default: + // return PEAR::raiseError( + // "Transport::getSearchResults: not finished ($st)", + // TRERR_NOTFIN + // ); + // } + // } /* ------------------------ methods for ls-archive-format file transports */ @@ -563,7 +563,7 @@ class Transport } $trec = $this->_uploadGeneralFileToHub($filePath, 'file', $pars); if (PEAR::isError($trec)) { - return $trec; + return $trec; } $this->startCronJobProcess($trec->trtok); return $trec->trtok; @@ -591,15 +591,15 @@ class Transport global $CC_CONFIG, $CC_DBC; $tmpn = tempnam($CC_CONFIG['transDir'], 'HITrans_'); $trec = TransportRecord::create($this, 'file', 'down', - array_merge(array( + array_merge(array( 'url' => $url, 'localfile' => $tmpn, 'expectedsum' => $chsum, 'expectedsize' => $size, - ), $pars) + ), $pars) ); if (PEAR::isError($trec)) { - return $trec; + return $trec; } $this->startCronJobProcess($trec->trtok); return array('trtok'=>$trec->trtok, 'localfile'=>$tmpn); @@ -616,9 +616,9 @@ class Transport function getHubInitiatedTransfers() { $ret = $this->xmlrpcCall('archive.listHubInitiatedTransfers', - array('target' => HOSTNAME)); + array('target' => HOSTNAME)); if (PEAR::isError($ret)) { - return $ret; + return $ret; } $res = array(); foreach ($ret as $it) { @@ -642,87 +642,87 @@ class Transport function startHubInitiatedTransfer($uid, $rtrtok) { $ret = $this->xmlrpcCall('archive.listHubInitiatedTransfers', - array( + array( 'target' => HOSTNAME, 'trtok' => $rtrtok, - )); + )); if (PEAR::isError($ret)) { - return $ret; + return $ret; } if (count($ret) != 1) { return PEAR::raiseError( "Transport::startHubInitiatedTransfer:". " wrong number of transports (".count($ret).")" - ); + ); } $ta = $ret[0]; // direction invertation to locstor point of view: $direction = ( $ta['direction']=='up' ? 'down' : 'up' ); $gunid = $ta['gunid']; switch ($direction) { - case "up": - switch ($ta['trtype']) { - case "audioclip": - case "playlist": - case "playlistPkg": - $trtok = $this->upload2Hub($gunid, TRUE, - array('rtrtok'=>$rtrtok)); - if (PEAR::isError($trtok)) { - return $trtok; - } - break; - //case "searchjob": break; // not supported yet - //case "file": break; // probably unusable - default: - return PEAR::raiseError( - "Transport::startHubInitiatedTransfer:". - " wrong direction / transport type combination". - " ({$ta['direction']}/{$ta['trtype']})" - ); - } - break; - case "down": - switch ($ta['trtype']) { - case "audioclip": - case "playlist": - case "playlistPkg": - $trtok = $this->downloadFromHub($uid, $gunid, TRUE, - array('rtrtok'=>$rtrtok)); - if (PEAR::isError($trtok)) { - return $trtok; - } - break; - //case "searchjob": break; // probably unusable - case "file": - $r = $this->downloadFileFromHub( - $ta['url'], $ta['expectedsum'], $ta['expectedsize'], + case "up": + switch ($ta['trtype']) { + case "audioclip": + case "playlist": + case "playlistPkg": + $trtok = $this->upload2Hub($gunid, TRUE, array('rtrtok'=>$rtrtok)); - if (PEAR::isError($r)) { - return $r; - } - extract($r); // trtok, localfile - break; - default: - return PEAR::raiseError( + if (PEAR::isError($trtok)) { + return $trtok; + } + break; + //case "searchjob": break; // not supported yet + //case "file": break; // probably unusable + default: + return PEAR::raiseError( "Transport::startHubInitiatedTransfer:". " wrong direction / transport type combination". " ({$ta['direction']}/{$ta['trtype']})" - ); - } - break; - default: - return PEAR::raiseError( + ); + } + break; + case "down": + switch ($ta['trtype']) { + case "audioclip": + case "playlist": + case "playlistPkg": + $trtok = $this->downloadFromHub($uid, $gunid, TRUE, + array('rtrtok'=>$rtrtok)); + if (PEAR::isError($trtok)) { + return $trtok; + } + break; + //case "searchjob": break; // probably unusable + case "file": + $r = $this->downloadFileFromHub( + $ta['url'], $ta['expectedsum'], $ta['expectedsize'], + array('rtrtok'=>$rtrtok)); + if (PEAR::isError($r)) { + return $r; + } + extract($r); // trtok, localfile + break; + default: + return PEAR::raiseError( + "Transport::startHubInitiatedTransfer:". + " wrong direction / transport type combination". + " ({$ta['direction']}/{$ta['trtype']})" + ); + } + break; + default: + return PEAR::raiseError( "Transport::startHubInitiatedTransfer: ???" - ); + ); } $ret = $this->xmlrpcCall('archive.setHubInitiatedTransfer', - array( + array( 'target' => HOSTNAME, 'trtok' => $rtrtok, 'state' => 'waiting', - )); + )); if (PEAR::isError($ret)) { - return $ret; + return $ret; } $this->startCronJobProcess($trtok); return $trtok; @@ -742,10 +742,10 @@ class Transport { global $CC_CONFIG; $res = $this->xmlrpcCall('locstor.login', - array( + array( 'login' => $CC_CONFIG['archiveAccountLogin'], 'pass' => $CC_CONFIG['archiveAccountPass'] - )); + )); if (PEAR::isError($res)) { return $res; } @@ -764,7 +764,7 @@ class Transport function logoutFromArchive($sessid) { $res = $this->xmlrpcCall('locstor.logout', - array('sessid'=>$sessid)); + array('sessid'=>$sessid)); return $res; } @@ -785,19 +785,19 @@ class Transport if (is_null($direction)) { $r = $this->cronMain('up'); if (PEAR::isError($r)) { - return $r; + return $r; } $r = $this->cronMain('down'); if (PEAR::isError($r)) { - return $r; + return $r; } return TRUE; } // fetch all opened transports $transports = $this->getTransports($direction); if (PEAR::isError($transports)) { - $this->trLog("cronMain: DB error"); - return FALSE; + $this->trLog("cronMain: DB error"); + return FALSE; } if (count($transports) == 0) { if (TR_LOG_LEVEL > 1) { @@ -828,9 +828,9 @@ class Transport { global $CC_CONFIG, $CC_DBC; if (TR_LOG_LEVEL > 2) { - $redirect = $CC_CONFIG['transDir']."/debug.log"; + $redirect = $CC_CONFIG['transDir']."/debug.log"; } else { - $redirect = "/dev/null"; + $redirect = "/dev/null"; } $redirect_escaped = escapeshellcmd($redirect); $command = "{$this->cronJobScript} {$trtok}"; @@ -860,7 +860,7 @@ class Transport global $CC_CONFIG; $trec = TransportRecord::recall($this, $trtok); if (PEAR::isError($trec)) { - return $trec; + return $trec; } $row = $trec->row; $state = $row['state']; @@ -903,9 +903,9 @@ class Transport $res = $pr->loadGroupPref($group, $key); if (PEAR::isError($res)) { if ($res->getCode() !== GBERR_PREF) { - return $res; + return $res; } else { - $res = FALSE; // default + $res = FALSE; // default } } // transfers turned off @@ -913,7 +913,7 @@ class Transport if ($res) { return PEAR::raiseError( "Transport::cronCallMethod: transfers turned off" - ); + ); } // NO break here! default: @@ -922,7 +922,7 @@ class Transport $pid = getmypid(); $r = $trec->setLock(TRUE, $pid); if (PEAR::isError($r)) { - return $r; + return $r; } $trec = TransportRecord::recall($this, $trtok); if (PEAR::isError($trec)) { @@ -954,7 +954,7 @@ class Transport // unlock the job: $r = $trec->setLock(FALSE); if (PEAR::isError($r)) { - return $r; + return $r; } // logout: $r = $this->logoutFromArchive($asessid); @@ -986,20 +986,20 @@ class Transport $trtok = $row['trtok']; $trec = TransportRecord::recall($this, $trtok); if (PEAR::isError($trec)) { - return $trec; + return $trec; } $ret = $this->xmlrpcCall('archive.uploadOpen', - array( + array( 'sessid' => $asessid , 'chsum' => $row['expectedsum'], - )); + )); if (PEAR::isError($ret)) { - return $ret; + return $ret; } $r = $trec->setState('waiting', - array('url'=>$ret['url'], 'pdtoken'=>$ret['token'])); + array('url'=>$ret['url'], 'pdtoken'=>$ret['token'])); if (PEAR::isError($r)) { - return $r; + return $r; } return TRUE; } @@ -1021,57 +1021,57 @@ class Transport $trtok = $row['trtok']; $trec = TransportRecord::recall($this, $trtok); if (PEAR::isError($trec)) { - return $trec; + return $trec; } $ret = $this->xmlrpcCall('archive.downloadOpen', - array( + array( 'sessid'=> $asessid, 'trtype'=> $row['trtype'], 'pars'=>array( 'gunid' => $row['gunid'], 'token' => $row['pdtoken'], - ), - )); + ), + )); if (PEAR::isError($ret)) { - return $ret; + return $ret; } $trtype = $ret['trtype']; $title = $ret['title']; $pars = array(); switch ($trtype) { -// case "searchjob": -// $r = $trec->setState('waiting', $pars); -// break; - case "file": - $r = $trec->setState('waiting',array_merge($pars, array( + // case "searchjob": + // $r = $trec->setState('waiting', $pars); + // break; + case "file": + $r = $trec->setState('waiting',array_merge($pars, array( 'trtype'=>$trtype, 'url'=>$ret['url'], 'pdtoken'=>$ret['token'], 'expectedsum'=>$ret['chsum'], 'expectedsize'=>$ret['size'], 'fname'=>$ret['filename'], 'localfile'=>$CC_CONFIG['transDir']."/$trtok", - ))); - break; - case "audioclip": - $mdtrec = TransportRecord::create($this, 'metadata', 'down', - array('gunid'=>$row['gunid'], 'uid'=>$row['uid'], ) - ); - if (PEAR::isError($mdtrec)) { - return $mdtrec; - } - $this->startCronJobProcess($mdtrec->trtok); - $pars = array('mdtrtok'=>$mdtrec->trtok); - // NO break here ! - default: - $r = $trec->setState('waiting',array_merge($pars, array( + ))); + break; + case "audioclip": + $mdtrec = TransportRecord::create($this, 'metadata', 'down', + array('gunid'=>$row['gunid'], 'uid'=>$row['uid'], ) + ); + if (PEAR::isError($mdtrec)) { + return $mdtrec; + } + $this->startCronJobProcess($mdtrec->trtok); + $pars = array('mdtrtok'=>$mdtrec->trtok); + // NO break here ! + default: + $r = $trec->setState('waiting',array_merge($pars, array( 'trtype'=>$trtype, 'url'=>$ret['url'], 'pdtoken'=>$ret['token'], 'expectedsum'=>$ret['chsum'], 'expectedsize'=>$ret['size'], 'fname'=>$ret['filename'], 'title'=>$title, 'localfile'=>$CC_CONFIG['transDir']."/$trtok", - ))); + ))); } if (PEAR::isError($r)) { - return $r; + return $r; } return TRUE; } @@ -1092,7 +1092,7 @@ class Transport $trtok = $row['trtok']; $check = $this->uploadCheck($row['pdtoken']); if (PEAR::isError($check)) { - return $check; + return $check; } // test filesize if (!file_exists($row['localfile'])) { @@ -1102,7 +1102,7 @@ class Transport } $trec = TransportRecord::recall($this, $trtok); if (PEAR::isError($trec)) { - return $trec; + return $trec; } $size = escapeshellarg($check['size']); $localfile = escapeshellarg($row['localfile']); @@ -1112,22 +1112,22 @@ class Transport " --speed-time {$this->upTrSpeedTime}". " --speed-limit {$this->upTrSpeedLimit}". " --connect-timeout {$this->upTrConnectTimeout}". - (!is_null($this->upLimitRate)? + (!is_null($this->upLimitRate)? " --limit-rate {$this->upLimitRate}" : ""). " -T $localfile $url"; $r = $trec->setState('pending', array(), 'waiting'); if (PEAR::isError($r)) { - return $r; + return $r; } if ($r === FALSE) { - return TRUE; + return TRUE; } $res = system($command, $status); // leave paused and closed transports $trec2 = TransportRecord::recall($this, $trtok); if (PEAR::isError($trec)) { - return $trec; + return $trec; } $state2 = $trec2->row['state']; if ($state2 == 'paused' || $state2 == 'closed' ) { @@ -1144,22 +1144,22 @@ class Transport if ($status == 0 || $status == 18 || $status == 28 || $status == 6 || $status == 7 || $status == 56) { $check = $this->uploadCheck($row['pdtoken']); if (PEAR::isError($check)) { - return $check; + return $check; } // test checksum if ($check['status'] == TRUE) { // finished $r = $trec->setState('finished', - array('realsum'=>$check['realsum'], 'realsize'=>$check['size'])); + array('realsum'=>$check['realsum'], 'realsize'=>$check['size'])); if (PEAR::isError($r)) { - return $r; + return $r; } } else { if (intval($check['size']) < $row['expectedsize']) { $r = $trec->setState('waiting', - array('realsum'=>$check['realsum'], 'realsize'=>$check['size'])); + array('realsum'=>$check['realsum'], 'realsize'=>$check['size'])); if (PEAR::isError($r)) { - return $r; + return $r; } } else { // wrong md5 at finish - TODO: start again @@ -1197,7 +1197,7 @@ class Transport // wget the file $trec = TransportRecord::recall($this, $trtok); if (PEAR::isError($trec)) { - return $trec; + return $trec; } $localfile = escapeshellarg($row['localfile']); $url = escapeshellarg($row['url']); @@ -1206,23 +1206,23 @@ class Transport " --read-timeout={$this->downTimeout}". " --waitretry={$this->downWaitretry}". " -t {$this->downRetries}". - (!is_null($this->downLimitRate)? + (!is_null($this->downLimitRate)? " --limit-rate={$this->downLimitRate}" : ""). " -O $localfile $url" ; $r = $trec->setState('pending', array(), 'waiting'); if (PEAR::isError($r)) { - return $r; + return $r; } if ($r === FALSE) { - return TRUE; + return TRUE; } $res = system($command, $status); // leave paused and closed transports $trec2 = TransportRecord::recall($this, $trtok); if (PEAR::isError($trec)) { - return $trec; + return $trec; } $state2 = $trec2->row['state']; if ($state2 == 'paused' || $state2 == 'closed' ) { @@ -1242,7 +1242,7 @@ class Transport if ($chsum == $row['expectedsum']) { // mark download as finished $r = $trec->setState('finished', - array('realsum'=>$chsum, 'realsize'=>$size)); + array('realsum'=>$chsum, 'realsize'=>$size)); if (PEAR::isError($r)) { return $r; } @@ -1250,7 +1250,7 @@ class Transport // bad checksum, retry from the scratch @unlink($row['localfile']); $r = $trec->setState('waiting', - array('realsum'=>$chsum, 'realsize'=>$size)); + array('realsum'=>$chsum, 'realsize'=>$size)); if (PEAR::isError($r)) { return $r; } @@ -1276,17 +1276,17 @@ class Transport $trtok = $row['trtok']; $trec = TransportRecord::recall($this, $trtok); if (PEAR::isError($trec)) { - return $trec; + return $trec; } // don't close metadata transport - audioclip will close it if ($row['trtype'] == 'metadata') { - return TRUE; + return TRUE; } // handle metadata transport on audioclip trtype: if ($row['trtype'] == 'audioclip') { $mdtrec = TransportRecord::recall($this, $trec->row['mdtrtok']); if (PEAR::isError($mdtrec)) { - return $mdtrec; + return $mdtrec; } switch ($mdtrec->row['state']) { case 'failed': @@ -1296,7 +1296,7 @@ class Transport " ({$this->trtok})" ); break; - // don't close transport with nonfinished metadata transport: + // don't close transport with nonfinished metadata transport: case 'init': case 'waiting': case 'pending': @@ -1306,18 +1306,18 @@ class Transport $mdpdtoken = $mdtrec->row['pdtoken']; } } else { - $mdpdtoken = NULL; + $mdpdtoken = NULL; } $ret = $this->xmlrpcCall('archive.uploadClose', - array( + array( 'token' => $row['pdtoken'] , 'trtype' => $row['trtype'], 'pars' => array( 'gunid' => $row['gunid'], 'name' => $row['fname'], 'mdpdtoken' => $mdpdtoken, - ), - )); + ), + )); if (PEAR::isError($ret)) { if ($row['trtype'] == 'audioclip') { $r2 = $mdtrec->close(); @@ -1325,29 +1325,29 @@ class Transport return $ret; } -// if ($row['trtype'] == 'searchjob') { -// @unlink($row['localfile']); -// $r = $trec->setState('init', array( -// 'direction' => 'down', -// 'pdtoken' => $ret['token'], -// 'expectedsum' => $ret['chsum'], -// 'expectedsize' => $ret['size'], -// 'url' => $ret['url'], -// 'realsize' => 0, -// )); -// $this->startCronJobProcess($trec->trtok); -// } else { - $r = $trec->close(); -// } + // if ($row['trtype'] == 'searchjob') { + // @unlink($row['localfile']); + // $r = $trec->setState('init', array( + // 'direction' => 'down', + // 'pdtoken' => $ret['token'], + // 'expectedsum' => $ret['chsum'], + // 'expectedsize' => $ret['size'], + // 'url' => $ret['url'], + // 'realsize' => 0, + // )); + // $this->startCronJobProcess($trec->trtok); + // } else { + $r = $trec->close(); + // } if (PEAR::isError($r)) { - return $r; + return $r; } switch ($row['trtype']) { case 'audioclip': // close metadata transport: $r = $mdtrec->close(); if (PEAR::isError($r)) { - return $r; + return $r; } break; case 'playlistPkg': @@ -1357,7 +1357,7 @@ class Transport if (preg_match("|/(plExport_[^\.]+)\.lspl$|", $ep, $va)) { list(,$tmpn) = $va; $tmpn = $CC_CONFIG['transDir']."/$tmpn"; if (file_exists($tmpn)) { - @unlink($tmpn); + @unlink($tmpn); } } @@ -1366,238 +1366,238 @@ class Transport } return TRUE; - } - - - /** - * Finish the download - * - * @param array $row - * row from getTransport results - * @param string $asessid - * session id (from network hub) - * @return mixed - * boolean TRUE or error object - */ - function cronDownloadFinished($row, $asessid) - { - $trtok = $row['trtok']; - $trec = TransportRecord::recall($this, $trtok); - if (PEAR::isError($trec)) { - return $trec; } - switch ($row['trtype']) { - case "audioclip": - $mdtrtok = $trec->row['mdtrtok']; - $mdtrec = TransportRecord::recall($this, $mdtrtok); - if (PEAR::isError($mdtrec)) { - return $mdtrec; - } - $pid = getmypid(); - $r = $mdtrec->setLock(TRUE, $pid); - if (PEAR::isError($r)) { - return $r; - } - switch ($mdtrec->row['state']) { - // don't close transport with nonfinished metadata transport: - case 'init': - case 'waiting': - case 'pending': - case 'paused': - $r = $mdtrec->setLock(FALSE); - if (PEAR::isError($r)) { - return $r; - } - return TRUE; - case 'finished': // metadata finished, close main transport - $values = array( + + + /** + * Finish the download + * + * @param array $row + * row from getTransport results + * @param string $asessid + * session id (from network hub) + * @return mixed + * boolean TRUE or error object + */ + function cronDownloadFinished($row, $asessid) + { + $trtok = $row['trtok']; + $trec = TransportRecord::recall($this, $trtok); + if (PEAR::isError($trec)) { + return $trec; + } + switch ($row['trtype']) { + case "audioclip": + $mdtrtok = $trec->row['mdtrtok']; + $mdtrec = TransportRecord::recall($this, $mdtrtok); + if (PEAR::isError($mdtrec)) { + return $mdtrec; + } + $pid = getmypid(); + $r = $mdtrec->setLock(TRUE, $pid); + if (PEAR::isError($r)) { + return $r; + } + switch ($mdtrec->row['state']) { + // don't close transport with nonfinished metadata transport: + case 'init': + case 'waiting': + case 'pending': + case 'paused': + $r = $mdtrec->setLock(FALSE); + if (PEAR::isError($r)) { + return $r; + } + return TRUE; + case 'finished': // metadata finished, close main transport + $values = array( "filename" => $row['fname'], "filepath" => $trec->row['localfile'], "metadata" => $mdtrec->row['localfile'], "gunid" => $row['gunid'], "filetype" => "audioclip" - ); - $storedFile = StoredFile::Insert($values); - if (PEAR::isError($storedFile)) { - $mdtrec->setLock(FALSE); - return $storedFile; - } - $res = $storedFile->getId(); - $ret = $this->xmlrpcCall('archive.downloadClose', + ); + $storedFile = StoredFile::Insert($values); + if (PEAR::isError($storedFile)) { + $mdtrec->setLock(FALSE); + return $storedFile; + } + $res = $storedFile->getId(); + $ret = $this->xmlrpcCall('archive.downloadClose', array( 'token' => $mdtrec->row['pdtoken'] , 'trtype' => 'metadata' , )); - if (PEAR::isError($ret)) { - $mdtrec->setLock(FALSE); - return $ret; - } - $r = $mdtrec->close(); - if (PEAR::isError($r)) { - $r2 = $mdtrec->setLock(FALSE); - return $r; - } - @unlink($trec->row['localfile']); - @unlink($mdtrec->row['localfile']); - break; - default: - $r = $mdtrec->setLock(FALSE); - return PEAR::raiseError("Transport::cronDownloadFinished:". + if (PEAR::isError($ret)) { + $mdtrec->setLock(FALSE); + return $ret; + } + $r = $mdtrec->close(); + if (PEAR::isError($r)) { + $r2 = $mdtrec->setLock(FALSE); + return $r; + } + @unlink($trec->row['localfile']); + @unlink($mdtrec->row['localfile']); + break; + default: + $r = $mdtrec->setLock(FALSE); + return PEAR::raiseError("Transport::cronDownloadFinished:". " metadata transport in wrong state: {$mdtrec->row['state']}". " ({$this->trtok})" - ); - } - $r = $mdtrec->setLock(FALSE); - if (PEAR::isError($r)) { - return $r; - } - break; - case "metadata": -// case "searchjob": - return TRUE; // don't close - getSearchResults should close it - break; - } - $ret = $this->xmlrpcCall('archive.downloadClose', + ); + } + $r = $mdtrec->setLock(FALSE); + if (PEAR::isError($r)) { + return $r; + } + break; + case "metadata": + // case "searchjob": + return TRUE; // don't close - getSearchResults should close it + break; + } + $ret = $this->xmlrpcCall('archive.downloadClose', array( 'token' => $row['pdtoken'] , 'trtype' => $row['trtype'] , )); - if (PEAR::isError($ret)) { - return $ret; - } - switch ($row['trtype']) { - case "playlist": - $values = array( + if (PEAR::isError($ret)) { + return $ret; + } + switch ($row['trtype']) { + case "playlist": + $values = array( "filename" => $row['fname'], "metadata" => $trec->row['localfile'], "gunid" => $row['gunid'], "filetype" => "playlist" - ); - $storedFile = StoredFile::Insert($values); - if (PEAR::isError($storedFile)) { - return $storedFile; - } - $res = $storedFile->getId(); - @unlink($row['localfile']); - break; - case "playlistPkg": - $subjid = $trec->row['uid']; - $fname = $trec->row['localfile']; - $res = $this->gb->bsImportPlaylist($fname, $subjid); - if (PEAR::isError($res)) { - return $res; - } - @unlink($fname); - break; - case "audioclip": - case "metadata": -// case "searchjob": - case "file": - break; - default: - return PEAR::raiseError("DEBUG: NotImpl ".var_export($row,TRUE)); - } - if (!is_null($rtrtok = $trec->row['rtrtok'])) { - $ret = $this->xmlrpcCall('archive.setHubInitiatedTransfer', + ); + $storedFile = StoredFile::Insert($values); + if (PEAR::isError($storedFile)) { + return $storedFile; + } + $res = $storedFile->getId(); + @unlink($row['localfile']); + break; + case "playlistPkg": + $subjid = $trec->row['uid']; + $fname = $trec->row['localfile']; + $res = $this->gb->bsImportPlaylist($fname, $subjid); + if (PEAR::isError($res)) { + return $res; + } + @unlink($fname); + break; + case "audioclip": + case "metadata": + // case "searchjob": + case "file": + break; + default: + return PEAR::raiseError("DEBUG: NotImpl ".var_export($row,TRUE)); + } + if (!is_null($rtrtok = $trec->row['rtrtok'])) { + $ret = $this->xmlrpcCall('archive.setHubInitiatedTransfer', array( 'target' => HOSTNAME, 'trtok' => $rtrtok, 'state' => 'closed', )); - if (PEAR::isError($ret)) { - return $ret; + if (PEAR::isError($ret)) { + return $ret; + } } + $r = $trec->close(); + if (PEAR::isError($r)) { + return $r; + } + return TRUE; } - $r = $trec->close(); - if (PEAR::isError($r)) { - return $r; - } - return TRUE; - } - /* ==================================================== auxiliary methods */ - /** - * Prepare upload for general file - * - * @param string $fpath - * local filepath of uploaded file - * @param string $trtype - * transport type - * @param array $pars - * default parameters (optional, internal use) - * @return object - transportRecord instance - */ - function _uploadGeneralFileToHub($fpath, $trtype, $pars=array()) - { - $chsum = $this->_chsum($fpath); - $size = filesize($fpath); - $trec = TransportRecord::create($this, $trtype, 'up', + /* ==================================================== auxiliary methods */ + /** + * Prepare upload for general file + * + * @param string $fpath + * local filepath of uploaded file + * @param string $trtype + * transport type + * @param array $pars + * default parameters (optional, internal use) + * @return object - transportRecord instance + */ + function _uploadGeneralFileToHub($fpath, $trtype, $pars=array()) + { + $chsum = $this->_chsum($fpath); + $size = filesize($fpath); + $trec = TransportRecord::create($this, $trtype, 'up', array_merge(array( 'localfile'=>$fpath, 'fname'=>basename($fpath), 'expectedsum'=>$chsum, 'expectedsize'=>$size ), $pars) - ); - if (PEAR::isError($trec)) { - return $trec; + ); + if (PEAR::isError($trec)) { + return $trec; + } + return $trec; } - return $trec; - } - /** - * Create new transport token - * - * @return string - * transport token - */ - function _createTransportToken() - { - $ip = (isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : ''); - $initString = microtime().$ip.rand()."org.mdlf.campcaster"; - $hash = md5($initString); - $res = substr($hash, 0, 16); - return $res; - } + /** + * Create new transport token + * + * @return string + * transport token + */ + function _createTransportToken() + { + $ip = (isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : ''); + $initString = microtime().$ip.rand()."org.mdlf.campcaster"; + $hash = md5($initString); + $res = substr($hash, 0, 16); + return $res; + } - /** - * Get all relevant transport records - * - * @param string $direction - * 'up' | 'down' - * @param string $target - * target hostname - * @param string $trtok - * transport token for specific query - * @return array - * array of transportRecords (as hasharrays) - */ - function getTransports($direction=NULL, $target=NULL, $trtok=NULL) - { - global $CC_CONFIG, $CC_DBC; - switch ($direction) { - case 'up': - $dirCond = "direction='up' AND"; - break; - case 'down': - $dirCond = "direction='down' AND"; - break; - default: - $dirCond = ''; - break; - } - if (is_null($target)) { - $targetCond = ""; - } else { - $targetCond = "target='$target' AND"; - } - if (is_null($trtok)) { - $trtokCond = ""; - } else { - $trtokCond = "trtok='$trtok' AND"; - } - $rows = $CC_DBC->getAll(" + /** + * Get all relevant transport records + * + * @param string $direction + * 'up' | 'down' + * @param string $target + * target hostname + * @param string $trtok + * transport token for specific query + * @return array + * array of transportRecords (as hasharrays) + */ + function getTransports($direction=NULL, $target=NULL, $trtok=NULL) + { + global $CC_CONFIG, $CC_DBC; + switch ($direction) { + case 'up': + $dirCond = "direction='up' AND"; + break; + case 'down': + $dirCond = "direction='down' AND"; + break; + default: + $dirCond = ''; + break; + } + if (is_null($target)) { + $targetCond = ""; + } else { + $targetCond = "target='$target' AND"; + } + if (is_null($trtok)) { + $trtokCond = ""; + } else { + $trtokCond = "trtok='$trtok' AND"; + } + $rows = $CC_DBC->getAll(" SELECT id, trtok, state, trtype, direction, to_hex(gunid)as gunid, to_hex(pdtoken)as pdtoken, @@ -1608,225 +1608,225 @@ class Transport state not in ('closed', 'failed', 'paused') ORDER BY start DESC "); - if (PEAR::isError($rows)) { - return $rows; + if (PEAR::isError($rows)) { + return $rows; + } + foreach ($rows as $i => $row) { + $rows[$i]['pdtoken'] = StoredFile::NormalizeGunid($row['pdtoken']); + $rows[$i]['gunid'] = StoredFile::NormalizeGunid($row['gunid']); + } + return $rows; } - foreach ($rows as $i => $row) { - $rows[$i]['pdtoken'] = StoredFile::NormalizeGunid($row['pdtoken']); - $rows[$i]['gunid'] = StoredFile::NormalizeGunid($row['gunid']); - } - return $rows; - } - /** - * Check remote state of uploaded file - * - * @param string $pdtoken - * put/download token (from network hub) - * @return array - * hash: chsum, size, url - */ - function uploadCheck($pdtoken) - { - $ret = $this->xmlrpcCall('archive.uploadCheck', + /** + * Check remote state of uploaded file + * + * @param string $pdtoken + * put/download token (from network hub) + * @return array + * hash: chsum, size, url + */ + function uploadCheck($pdtoken) + { + $ret = $this->xmlrpcCall('archive.uploadCheck', array('token'=>$pdtoken)); - return $ret; - } + return $ret; + } - /** - * Ping to remote Campcaster server - * - * @return string - * network hub response or error object - */ - function ping() - { - $res = $this->xmlrpcCall('ping', + /** + * Ping to remote Campcaster server + * + * @return string + * network hub response or error object + */ + function ping() + { + $res = $this->xmlrpcCall('ping', array('par'=>'ping_'.date('H:i:s'))); - return $res; - } + return $res; + } - /** - * XMLRPC call to network hub. - * - * @param string $method - * method name - * @param array $pars - * call parameters - * @return mixed - * response - */ - function xmlrpcCall($method, $pars=array()) - { - global $CC_CONFIG; - $xrp = XML_RPC_encode($pars); + /** + * XMLRPC call to network hub. + * + * @param string $method + * method name + * @param array $pars + * call parameters + * @return mixed + * response + */ + function xmlrpcCall($method, $pars=array()) + { + global $CC_CONFIG; + $xrp = XML_RPC_encode($pars); - $pr = new Prefs($this->gb); - $group = $CC_CONFIG["StationPrefsGr"]; - $key = 'archiveServerLocation'; - $archiveUrl = $pr->loadGroupPref($group, $key, false); + $pr = new Prefs($this->gb); + $group = $CC_CONFIG["StationPrefsGr"]; + $key = 'archiveServerLocation'; + $archiveUrl = $pr->loadGroupPref($group, $key, false); - if ($archiveUrl) { - $archiveUrlInfo = parse_url($archiveUrl); - if ($archiveUrlInfo['port']) { - $port = $archiveUrlInfo['port']; + if ($archiveUrl) { + $archiveUrlInfo = parse_url($archiveUrl); + if ($archiveUrlInfo['port']) { + $port = $archiveUrlInfo['port']; + } + else { + $port = 80; + } + + $c = new XML_RPC_Client($archiveUrlInfo['path'], $archiveUrlInfo['host'], $port); } else { - $port = 80; - } - - $c = new XML_RPC_Client($archiveUrlInfo['path'], $archiveUrlInfo['host'], $port); - } - else { - $c = new XML_RPC_Client( + $c = new XML_RPC_Client( $CC_CONFIG['archiveUrlPath']."/".$CC_CONFIG['archiveXMLRPC'], $CC_CONFIG['archiveUrlHost'], $CC_CONFIG['archiveUrlPort'] - ); - } + ); + } - $f = new XML_RPC_Message($method, array($xrp)); - $r = $c->send($f); - if (!$r) { - return PEAR::raiseError("XML-RPC request failed", TRERR_XR_FAIL); - } elseif ($r->faultCode() > 0) { - return PEAR::raiseError($r->faultString(), $r->faultCode()); - // return PEAR::raiseError($r->faultString(). - // " (code ".$r->faultCode().")", TRERR_XR_FAIL); - } else { - $v = $r->value(); - return XML_RPC_decode($v); - } - } - - - /** - * Checksum of local file - * - * @param string $fpath - * local filepath - * @return string - * checksum - */ - function _chsum($fpath) - { - return md5_file($fpath); - } - - - /** - * Check exception and eventually mark transport as failed - * - * @param mixed $res - * result object to be checked - * @param unknown $trec - * transport record object - * @return unknown - */ - function _failFatal($res, $trec) - { - if (PEAR::isError($res)) { - switch ($res->getCode()) { - // non fatal: - case TRERR_XR_FAIL: - break; - // fatal: - default: - $trec->fail('', $res); + $f = new XML_RPC_Message($method, array($xrp)); + $r = $c->send($f); + if (!$r) { + return PEAR::raiseError("XML-RPC request failed", TRERR_XR_FAIL); + } elseif ($r->faultCode() > 0) { + return PEAR::raiseError($r->faultString(), $r->faultCode()); + // return PEAR::raiseError($r->faultString(). + // " (code ".$r->faultCode().")", TRERR_XR_FAIL); + } else { + $v = $r->value(); + return XML_RPC_decode($v); } } - return $res; - } - /** - * Clean up transport jobs - * - * @param string $interval - * psql time interval - older closed jobs will be deleted - * @param boolean $forced - * if true, delete non-closed jobs too - * @return boolean true or error - */ - function _cleanUp($interval='1 minute'/*'1 hour'*/, $forced=FALSE) - { - global $CC_CONFIG, $CC_DBC; - $cond = ($forced ? '' : " AND state='closed' AND lock = 'N'"); - $r = $CC_DBC->query(" + /** + * Checksum of local file + * + * @param string $fpath + * local filepath + * @return string + * checksum + */ + function _chsum($fpath) + { + return md5_file($fpath); + } + + + /** + * Check exception and eventually mark transport as failed + * + * @param mixed $res + * result object to be checked + * @param unknown $trec + * transport record object + * @return unknown + */ + function _failFatal($res, $trec) + { + if (PEAR::isError($res)) { + switch ($res->getCode()) { + // non fatal: + case TRERR_XR_FAIL: + break; + // fatal: + default: + $trec->fail('', $res); + } + } + return $res; + } + + + /** + * Clean up transport jobs + * + * @param string $interval + * psql time interval - older closed jobs will be deleted + * @param boolean $forced + * if true, delete non-closed jobs too + * @return boolean true or error + */ + function _cleanUp($interval='1 minute'/*'1 hour'*/, $forced=FALSE) + { + global $CC_CONFIG, $CC_DBC; + $cond = ($forced ? '' : " AND state='closed' AND lock = 'N'"); + $r = $CC_DBC->query(" DELETE FROM ".$CC_CONFIG['transTable']." WHERE ts < now() - interval '$interval'".$cond - ); - if (PEAR::isError($r)) { - return $r; - } - return TRUE; - } - - - /** - * Logging wrapper for PEAR error object - * - * @param string $txt - * log message - * @param PEAR_Error $eo - * @param array $row - * array returned from getRow - * @return mixed - * void or error object - */ - function trLogPear($txt, $eo, $row=NULL) - { - $msg = $txt.$eo->getMessage()." ".$eo->getUserInfo(). - " [".$eo->getCode()."]"; - if (!is_null($row)) { - $trec = TransportRecord::recall($this, $row['trtok']); - if (!PEAR::isError($trec)) { - $trec->setState('failed', array('errmsg'=>$msg)); - } - $msg .= "\n ".serialize($row); - } - $this->trLog($msg); - } - - - /** - * Logging for debug transports - * - * @param string $msg - * log message - * @return mixed - * void or error object - */ - function trLog($msg) - { - global $CC_CONFIG; - $logfile = $CC_CONFIG['transDir']."/activity.log"; - if (FALSE === ($fp = fopen($logfile, "a"))) { - return PEAR::raiseError( - "Transport::trLog: Can't write to log ($logfile)" ); + if (PEAR::isError($r)) { + return $r; + } + return TRUE; } - flock($fp,LOCK_SH); - fputs($fp, "---".date("H:i:s")."---\n $msg\n"); - flock($fp,LOCK_UN); - fclose($fp); - } - /* ====================================================== install methods */ - /** - * Delete all transports - * - * @return mixed - * void or error object - */ - function resetData() - { - global $CC_CONFIG, $CC_DBC; - return $CC_DBC->query("DELETE FROM ".$CC_CONFIG['transTable']); - } + /** + * Logging wrapper for PEAR error object + * + * @param string $txt + * log message + * @param PEAR_Error $eo + * @param array $row + * array returned from getRow + * @return mixed + * void or error object + */ + function trLogPear($txt, $eo, $row=NULL) + { + $msg = $txt.$eo->getMessage()." ".$eo->getUserInfo(). + " [".$eo->getCode()."]"; + if (!is_null($row)) { + $trec = TransportRecord::recall($this, $row['trtok']); + if (!PEAR::isError($trec)) { + $trec->setState('failed', array('errmsg'=>$msg)); + } + $msg .= "\n ".serialize($row); + } + $this->trLog($msg); + } + + + /** + * Logging for debug transports + * + * @param string $msg + * log message + * @return mixed + * void or error object + */ + function trLog($msg) + { + global $CC_CONFIG; + $logfile = $CC_CONFIG['transDir']."/activity.log"; + if (FALSE === ($fp = fopen($logfile, "a"))) { + return PEAR::raiseError( + "Transport::trLog: Can't write to log ($logfile)" + ); + } + flock($fp,LOCK_SH); + fputs($fp, "---".date("H:i:s")."---\n $msg\n"); + flock($fp,LOCK_UN); + fclose($fp); + } + + + /* ====================================================== install methods */ + /** + * Delete all transports + * + * @return mixed + * void or error object + */ + function resetData() + { + global $CC_CONFIG, $CC_DBC; + return $CC_DBC->query("DELETE FROM ".$CC_CONFIG['transTable']); + } } diff --git a/backend/TransportRecord.php b/backend/TransportRecord.php index 9a491e7eb..6c804279c 100644 --- a/backend/TransportRecord.php +++ b/backend/TransportRecord.php @@ -12,9 +12,9 @@ define('TR_LEAVE_CLOSED', TRUE); */ class TransportRecord { - /** - * @var DB - */ + /** + * @var DB + */ //public $dbc; /** @@ -72,12 +72,12 @@ class TransportRecord $trec = new TransportRecord($tr); $trec->trtok = $trtok = $tr->_createTransportToken(); $trec->row = array_merge($defaults, - array('trtype'=>$trtype, 'direction'=>$direction)); + array('trtype'=>$trtype, 'direction'=>$direction)); $trec->recalled = TRUE; if (!isset($defaults['title'])) { $defaults['title'] = $trec->getTitle(); if (PEAR::isError($defaults['title'])) { - return $defaults['title']; + return $defaults['title']; } } $id = $CC_DBC->nextId($CC_CONFIG['transSequence']); @@ -96,7 +96,7 @@ class TransportRecord "; $res = $CC_DBC->query($query); if (PEAR::isError($res)) { - return $res; + return $res; } return $trec; } @@ -126,7 +126,7 @@ class TransportRecord WHERE trtok='$trtok' "); if (PEAR::isError($row)) { - return $row; + return $row; } if (is_null($row)) { return PEAR::raiseError("TransportRecord::recall:". @@ -170,16 +170,16 @@ class TransportRecord UPDATE ".$CC_CONFIG['transTable']." SET $set WHERE trtok='{$this->trtok}'". - (is_null($oldState) ? '' : " AND state='$oldState'"). - (is_null($lock) ? '' : " AND lock = '$slock'") + (is_null($oldState) ? '' : " AND state='$oldState'"). + (is_null($lock) ? '' : " AND lock = '$slock'") ); if (PEAR::isError($r)) { - return $r; + return $r; } // return TRUE; $affRows = $CC_DBC->affectedRows(); if (PEAR::isError($affRows)) { - return $affRows; + return $affRows; } return ($affRows == 1); } @@ -217,7 +217,7 @@ class TransportRecord global $CC_CONFIG, $CC_DBC; $pidsql = (is_null($pid) ? "NULL" : "$pid" ); if ($this->dropped) { - return TRUE; + return TRUE; } $slock = ($lock ? 'Y' : 'N'); $nlock = (!$lock); @@ -228,11 +228,11 @@ class TransportRecord WHERE trtok='{$this->trtok}' AND lock = '$snlock'" ); if (PEAR::isError($r)) { - return $r; + return $r; } $affRows = $CC_DBC->affectedRows(); if (PEAR::isError($affRows)) { - return $affRows; + return $affRows; } if ($affRows === 0) { $ltxt = ($lock ? 'lock' : 'unlock' ); @@ -303,7 +303,7 @@ class TransportRecord } $r = $this->setState('failed', array('errmsg'=>$msg)); if (PEAR::isError($r)) { - return $r; + return $r; } return TRUE; } @@ -326,7 +326,7 @@ class TransportRecord if (TR_LEAVE_CLOSED) { $r = $this->setState('closed'); if (PEAR::isError($r)) { - return $r; + return $r; } } else { $r = $CC_DBC->query(" @@ -334,7 +334,7 @@ class TransportRecord WHERE trtok='{$this->trtok}' "); if (PEAR::isError($r)) { - return $r; + return $r; } $this->recalled = FALSE; $this->dropped = TRUE; @@ -383,7 +383,7 @@ class TransportRecord $defStr = 'unknown'; $trtype = $this->getTransportType(); //contains recall check if (PEAR::isError($trtype)) { - return $trtype; + return $trtype; } switch ($trtype) { case "audioclip": @@ -396,9 +396,9 @@ class TransportRecord } if (PEAR::isError($title)) { if ($title->getCode() == GBERR_FOBJNEX) { - $title = $defStr; + $title = $defStr; } else { - return $title; + return $title; } } break; @@ -407,10 +407,10 @@ class TransportRecord break; case "file": $title = ( isset($this->row['localfile']) ? - basename($this->row['localfile']) : 'regular file'); + basename($this->row['localfile']) : 'regular file'); break; default: - $title = $defStr; + $title = $defStr; } return $title; } diff --git a/backend/Validator.php b/backend/Validator.php index a53b9fdf4..d730aee10 100644 --- a/backend/Validator.php +++ b/backend/Validator.php @@ -67,12 +67,12 @@ class Validator { 'webstream' => "webstreamFormat", ); if (!isset($formats[$format])) { - return $this->_err(VAL_FORMAT); + return $this->_err(VAL_FORMAT); } $formatName = $formats[$format]; $formatFile = dirname(__FILE__)."/$formatName.php"; if (!file_exists($formatFile)) { - return $this->_err(VAL_FORMAT); + return $this->_err(VAL_FORMAT); } require($formatFile); $this->formTree = $$formatName; @@ -151,15 +151,15 @@ class Validator { $dname = (($node->ns? $node->ns.":" : '').$node->name); $formTree =& $this->formTree; if (DEBUG) { - echo"\nVAL::validateNode: 1 $dname/$fname\n"; + echo"\nVAL::validateNode: 1 $dname/$fname\n"; } // check root node name: if ($dname != $fname) { - return $this->_err(VAL_ROOT, $fname); + return $this->_err(VAL_ROOT, $fname); } // check if this element is defined in format: if (!isset($formTree[$fname])) { - return $this->_err(VAL_NOTDEF, $fname); + return $this->_err(VAL_NOTDEF, $fname); } // check element content if (isset($formTree[$fname]['regexp'])) { @@ -171,12 +171,12 @@ class Validator { // validate attributes: $ra = $this->validateAttributes($node, $fname); if (PEAR::isError($ra)) { - return $ra; + return $ra; } // validate children: $r = $this->validateChildren($node, $fname); if (PEAR::isError($r)) { - return $r; + return $r; } return TRUE; } @@ -251,7 +251,7 @@ class Validator { // call children recursive: $r = $this->validateNode($node->children[$i], $chname); if (PEAR::isError($r)) { - return $r; + return $r; } $childs[$chname] = TRUE; } @@ -269,13 +269,13 @@ class Validator { foreach ($fchilds['oneof'] as $i => $ch) { if (isset($childs[$ch])) { if ($one) { - return $this->_err(VAL_UNEXPONEOF, "$ch in $fname"); + return $this->_err(VAL_UNEXPONEOF, "$ch in $fname"); } $one = TRUE; } } if (!$one) { - return $this->_err(VAL_NOONEOF); + return $this->_err(VAL_NOONEOF); } } } @@ -340,9 +340,9 @@ class Validator { { $formTree =& $this->formTree; $listed = ( - isset($formTree[$fname][$nType][$reqType]) ? - array_search($chname, $formTree[$fname][$nType][$reqType]) : - FALSE + isset($formTree[$fname][$nType][$reqType]) ? + array_search($chname, $formTree[$fname][$nType][$reqType]) : + FALSE ); return $listed; } @@ -360,22 +360,22 @@ class Validator { function _err($errno, $par='') { $msg = array( - VAL_ROOT => 'Wrong root element', - VAL_NOREQE => 'Required element missing', - VAL_NOONEOF => 'One-of element missing', - VAL_UNKNOWNE => 'Unknown element', - VAL_UNKNOWNA => 'Unknown attribute', - VAL_NOTDEF => 'Not defined', - VAL_UNEXPONEOF => 'Unexpected second object from one-of set', - VAL_FORMAT => 'Unknown format', - VAL_CONTENT => 'Invalid content', - VAL_NOREQA => 'Required attribute missing', - VAL_ATTRIB => 'Invalid attribute format', - VAL_PREDXML => 'Invalid predicate type', + VAL_ROOT => 'Wrong root element', + VAL_NOREQE => 'Required element missing', + VAL_NOONEOF => 'One-of element missing', + VAL_UNKNOWNE => 'Unknown element', + VAL_UNKNOWNA => 'Unknown attribute', + VAL_NOTDEF => 'Not defined', + VAL_UNEXPONEOF => 'Unexpected second object from one-of set', + VAL_FORMAT => 'Unknown format', + VAL_CONTENT => 'Invalid content', + VAL_NOREQA => 'Required attribute missing', + VAL_ATTRIB => 'Invalid attribute format', + VAL_PREDXML => 'Invalid predicate type', ); return PEAR::raiseError( "Validator: {$msg[$errno]} #$errno ($par, gunid={$this->gunid})", - $errno + $errno ); } diff --git a/backend/XmlParser.php b/backend/XmlParser.php index 89d59e123..7d440460b 100644 --- a/backend/XmlParser.php +++ b/backend/XmlParser.php @@ -164,12 +164,12 @@ class XmlParser { $res = xml_parse($xml_parser, $data, TRUE); if (!$res) { $this->err = array(TRUE, - sprintf("XML error: %s at line %d\n", - xml_error_string(xml_get_error_code($xml_parser)), - xml_get_current_line_number($xml_parser) - ) + sprintf("XML error: %s at line %d\n", + xml_error_string(xml_get_error_code($xml_parser)), + xml_get_current_line_number($xml_parser) + ) ); -// var_dump($data); + // var_dump($data); } xml_parser_free($xml_parser); } @@ -188,31 +188,31 @@ class XmlParser { function &parse($data='', $loc='file') { switch ($loc) { - case "file": - if (!is_file($data)) { - return PEAR::raiseError( + case "file": + if (!is_file($data)) { + return PEAR::raiseError( "XmlParser::parse: file not found ($data)" - ); - } - if (!is_readable($data)) { - return PEAR::raiseError( + ); + } + if (!is_readable($data)) { + return PEAR::raiseError( "XmlParser::parse: can't read file ($data)" - ); - } - $data = file_get_contents($data); - case "string": - $parser = new XmlParser($data); - if ($parser->isError()) { - return PEAR::raiseError( + ); + } + $data = file_get_contents($data); + case "string": + $parser = new XmlParser($data); + if ($parser->isError()) { + return PEAR::raiseError( "XmlParser::parse: ".$parser->getError() - ); - } - $tree = $parser->getTree(); - break; - default: - return PEAR::raiseError( + ); + } + $tree = $parser->getTree(); + break; + default: + return PEAR::raiseError( "XmlParser::parse: unsupported source location ($loc)" - ); + ); } return $tree; } @@ -237,7 +237,7 @@ class XmlParser { $atnm = $a['localPart']; unset($attrs[$atn]); if ($atns == 'xmlns') { - $nSpaces[$atnm] = $atv; + $nSpaces[$atnm] = $atv; } else if ($atns == NULL && $atnm == 'xmlns') { $nSpaces[''] = $atv; } else { @@ -280,7 +280,7 @@ class XmlParser { function characterData($parser, $data) { $cnt = count($this->stack); if (trim($data)!='') { - $this->stack[$cnt-1]->content .= $data; + $this->stack[$cnt-1]->content .= $data; } } @@ -299,7 +299,7 @@ class XmlParser { //if(substr($data, 0, 1) == "&" && substr($data, -1, 1) == ";"){ // $this->stack[$cnt-1]->content .= trim($data); //}else{ - $this->stack[$cnt-1]->content .= "*** $data ***"; + $this->stack[$cnt-1]->content .= "*** $data ***"; //} } @@ -376,7 +376,7 @@ class XmlParser { } $res .= XML_Util::replaceEntities("{$el->content}"); if ($haveCh) { - $res .= "\n{$ind}"; + $res .= "\n{$ind}"; } $res .= ""; return $res; diff --git a/backend/propel-db/build/classes/campcaster/CcPlaylistcontents.php b/backend/propel-db/build/classes/campcaster/CcPlaylistcontents.php index 53b54fde1..9a7c3764a 100644 --- a/backend/propel-db/build/classes/campcaster/CcPlaylistcontents.php +++ b/backend/propel-db/build/classes/campcaster/CcPlaylistcontents.php @@ -5,7 +5,7 @@ require_once('Common.php'); /** * Skeleton subclass for representing a row from the 'cc_playlistcontents' table. * - * + * * * You should add additional methods to this class to meet the * application requirements. This class will only be generated as @@ -15,55 +15,55 @@ require_once('Common.php'); */ class CcPlaylistcontents extends BaseCcPlaylistcontents { - public function getDbFadein() - { - return $this->fadein; - } - - public function setDbFadein($time) + public function getDbFadein() { - $this->fadein = $time; - //$this->modifiedColumns[] = CcPlaylistcontentsPeer::FADEIN; + return $this->fadein; + } + + public function setDbFadein($time) + { + $this->fadein = $time; + //$this->modifiedColumns[] = CcPlaylistcontentsPeer::FADEIN; return Common::setTimeInSub($this, 'FADEIN', $time); } - public function getDbFadeout() + public function getDbFadeout() { return $this->fadeout; } - public function setDbFadeout($time) + public function setDbFadeout($time) { - $this->fadeout = $time; - //$this->modifiedColumns[] = CcPlaylistcontentsPeer::FADEOUT; + $this->fadeout = $time; + //$this->modifiedColumns[] = CcPlaylistcontentsPeer::FADEOUT; return Common::setTimeInSub($this, 'FADEOUT', $time); } - public function getDbCuein() + public function getDbCuein() { return $this->cuein; } - public function setDbCuein($time) + public function setDbCuein($time) { - $this->cuein = $time; - //$this->modifiedColumns[] = CcPlaylistcontentsPeer::CUEIN; + $this->cuein = $time; + //$this->modifiedColumns[] = CcPlaylistcontentsPeer::CUEIN; return Common::setTimeInSub($this, 'CUEIN', $time); } - public function getDbCueout() + public function getDbCueout() { return $this->cueout; } public function setDbCueout($time) { - $this->cueout = $time; - //$this->modifiedColumns[] = CcPlaylistcontentsPeer::CUEOUT; + $this->cueout = $time; + //$this->modifiedColumns[] = CcPlaylistcontentsPeer::CUEOUT; return Common::setTimeInSub($this, 'CUEOUT', $time); } - public function getDbCliplength() + public function getDbCliplength() { return $this->cliplength; } @@ -71,11 +71,8 @@ class CcPlaylistcontents extends BaseCcPlaylistcontents { public function setDbCliplength($time) { $this->cliplength = $time; - //$this->modifiedColumns[] = CcPlaylistcontentsPeer::CLIPLENGTH; + //$this->modifiedColumns[] = CcPlaylistcontentsPeer::CLIPLENGTH; return Common::setTimeInSub($this, 'CLIPLENGTH', $time); } - - - } // CcPlaylistcontents diff --git a/backend/propel-db/build/classes/campcaster/Common.php b/backend/propel-db/build/classes/campcaster/Common.php index 18b93ffcd..960bff34a 100644 --- a/backend/propel-db/build/classes/campcaster/Common.php +++ b/backend/propel-db/build/classes/campcaster/Common.php @@ -1,19 +1,19 @@ prepare($sql); - $stmt->bindValue(':f1', $time); - $stmt->bindValue(':p1', $row->getDbId()); - $stmt->execute(); - } + public static function setTimeInSub($row, $col, $time) + { + $class = get_class($row).'Peer'; + + $con = Propel::getConnection($class::DATABASE_NAME); + + $sql = 'UPDATE '.$class::TABLE_NAME + . ' SET '.$col.' = :f1' + . ' WHERE ' .$class::ID. ' = :p1'; + $stmt = $con->prepare($sql); + $stmt->bindValue(':f1', $time); + $stmt->bindValue(':p1', $row->getDbId()); + $stmt->execute(); + } } diff --git a/backend/xmlrpc/xrLocStor.php b/backend/xmlrpc/xrLocStor.php index fb9acf702..5408a389e 100644 --- a/backend/xmlrpc/xrLocStor.php +++ b/backend/xmlrpc/xrLocStor.php @@ -40,7 +40,7 @@ function errHndl($errno, $errmsg, $filename, $linenum, $vars) break; default: $xr = new XML_RPC_Response(0, 805, - htmlspecialchars("ERROR:xrLocStor: $errno $errmsg ($filename:$linenum)")); + htmlspecialchars("ERROR:xrLocStor: $errno $errmsg ($filename:$linenum)")); header("Content-type: text/xml"); echo $xr->serialize(); exit($errno); @@ -159,10 +159,10 @@ $defs = array(); foreach ($methods as $method => $description) { $defs["locstor.$method"] = array( "function" => array(&$locStor, "xr_$method"), - // NOTE: the way this signature is set up, every function must take at least one parameter! + // NOTE: the way this signature is set up, every function must take at least one parameter! "signature" => array( - array($GLOBALS['XML_RPC_Struct'], $GLOBALS['XML_RPC_Struct']) - ), + array($GLOBALS['XML_RPC_Struct'], $GLOBALS['XML_RPC_Struct']) + ), "docstring" => $description ); } diff --git a/htmlUI/Input.php b/htmlUI/Input.php index a1b3ceab7..c80934b07 100644 --- a/htmlUI/Input.php +++ b/htmlUI/Input.php @@ -14,71 +14,71 @@ $g_inputErrors = array(); * @package Campsite */ class Input { - /** - * Please see: {@link http://ca.php.net/manual/en/function.get-magic-quotes-gpc.php - * this PHP.net page specifically the user note by php at kaiundina dot de}, - * for why this is so complicated. - * - * @param array $p_array - * @return array - */ - function CleanMagicQuotes($p_array) - { - $gpcList = array(); + /** + * Please see: {@link http://ca.php.net/manual/en/function.get-magic-quotes-gpc.php + * this PHP.net page specifically the user note by php at kaiundina dot de}, + * for why this is so complicated. + * + * @param array $p_array + * @return array + */ + function CleanMagicQuotes($p_array) + { + $gpcList = array(); - foreach ($p_array as $key => $value) { - $decodedKey = stripslashes($key); - if (is_array($value)) { - $decodedValue = Input::CleanMagicQuotes($value); - } else { - $decodedValue = stripslashes($value); - } - $gpcList[$decodedKey] = $decodedValue; - } - return $gpcList; - } // fn CleanMagicQuotes + foreach ($p_array as $key => $value) { + $decodedKey = stripslashes($key); + if (is_array($value)) { + $decodedValue = Input::CleanMagicQuotes($value); + } else { + $decodedValue = stripslashes($value); + } + $gpcList[$decodedKey] = $decodedValue; + } + return $gpcList; + } // fn CleanMagicQuotes - /** - * Get an input value from the $_REQUEST array and check its type. - * The default value is returned if the value is not defined in the - * $_REQUEST array, or if the value does not match the required type. - * - * The type 'checkbox' is special - you cannot specify a default - * value for this. The return value will be TRUE or FALSE, but - * you can change this by specifying 'numeric' as the 3rd parameter - * in which case it will return '1' or '0'. - * - * Use Input::IsValid() to check if any errors were generated. - * - * @param string $p_varName - * The index into the $_REQUEST array. - * - * @param string $p_type - * The type of data expected; can be: - * "int" - * "string" - * "array" - * "checkbox" - * "boolean" - * - * Default is 'string'. - * - * @param mixed $p_defaultValue - * The default value to return if the value is not defined in - * the $_REQUEST array, or if the value does not match - * the required type. - * - * @param boolean $p_errorsOk - * Set to true to ignore any errors for this variable (i.e. - * Input::IsValid() will still return true even if there - * are errors for this varaible). - * - * @return mixed - */ - function Get($p_varName, $p_type = 'string', $p_defaultValue = null, $p_errorsOk = false) - { - global $g_inputErrors; + /** + * Get an input value from the $_REQUEST array and check its type. + * The default value is returned if the value is not defined in the + * $_REQUEST array, or if the value does not match the required type. + * + * The type 'checkbox' is special - you cannot specify a default + * value for this. The return value will be TRUE or FALSE, but + * you can change this by specifying 'numeric' as the 3rd parameter + * in which case it will return '1' or '0'. + * + * Use Input::IsValid() to check if any errors were generated. + * + * @param string $p_varName + * The index into the $_REQUEST array. + * + * @param string $p_type + * The type of data expected; can be: + * "int" + * "string" + * "array" + * "checkbox" + * "boolean" + * + * Default is 'string'. + * + * @param mixed $p_defaultValue + * The default value to return if the value is not defined in + * the $_REQUEST array, or if the value does not match + * the required type. + * + * @param boolean $p_errorsOk + * Set to true to ignore any errors for this variable (i.e. + * Input::IsValid() will still return true even if there + * are errors for this varaible). + * + * @return mixed + */ + function Get($p_varName, $p_type = 'string', $p_defaultValue = null, $p_errorsOk = false) + { + global $g_inputErrors; $p_type = strtolower($p_type); if ($p_type == 'checkbox') { @@ -88,99 +88,99 @@ class Input { return isset($_REQUEST[$p_varName]) ? '1' : '0'; } } - if (!isset($_REQUEST[$p_varName])) { - if (!$p_errorsOk) { - $g_inputErrors[$p_varName] = 'not set'; - } - return $p_defaultValue; - } - // Clean the slashes - if (get_magic_quotes_gpc()) { - if (is_array($_REQUEST[$p_varName])) { - $_REQUEST[$p_varName] = Input::CleanMagicQuotes($_REQUEST[$p_varName]); - } else { - $_REQUEST[$p_varName] = stripslashes($_REQUEST[$p_varName]); - } - } - switch ($p_type) { - case 'boolean': - $value = strtolower($_REQUEST[$p_varName]); - if ( ($value == "true") || (is_numeric($value) && ($value > 0)) ) { - return true; - } else { - return false; - } - break; - case 'int': - if (!is_numeric($_REQUEST[$p_varName])) { - if (!$p_errorsOk) { - $g_inputErrors[$p_varName] = 'Incorrect type. Expected type '.$p_type - .', but received type '.gettype($_REQUEST[$p_varName]).'.' - .' Value is "'.$_REQUEST[$p_varName].'".'; - } - return $p_defaultValue; - } - break; - case 'string': - if (!is_string($_REQUEST[$p_varName])) { - if (!$p_errorsOk) { - $g_inputErrors[$p_varName] = 'Incorrect type. Expected type '.$p_type - .', but received type '.gettype($_REQUEST[$p_varName]).'.' - .' Value is "'.$_REQUEST[$p_varName].'".'; - } - return $p_defaultValue; - } - break; - case 'array': - if (!is_array($_REQUEST[$p_varName])) { - // Create an array if it isnt one already. - // Arrays are used with checkboxes and radio buttons. - // The problem with them is that if there is only one - // checkbox, the given value will not be an array. So - // we make it easy for the programmer by always returning - // an array. - $newArray = array(); - $newArray[] = $_REQUEST[$p_varName]; - return $newArray; -// if (!$p_errorsOk) { -// $g_inputErrors[$p_varName] = 'Incorrect type. Expected type '.$p_type -// .', but received type '.gettype($_REQUEST[$p_varName]).'.' -// .' Value is "'.$_REQUEST[$p_varName].'".'; -// } -// return $p_defaultValue; - } - } - return $_REQUEST[$p_varName]; - } // fn get + if (!isset($_REQUEST[$p_varName])) { + if (!$p_errorsOk) { + $g_inputErrors[$p_varName] = 'not set'; + } + return $p_defaultValue; + } + // Clean the slashes + if (get_magic_quotes_gpc()) { + if (is_array($_REQUEST[$p_varName])) { + $_REQUEST[$p_varName] = Input::CleanMagicQuotes($_REQUEST[$p_varName]); + } else { + $_REQUEST[$p_varName] = stripslashes($_REQUEST[$p_varName]); + } + } + switch ($p_type) { + case 'boolean': + $value = strtolower($_REQUEST[$p_varName]); + if ( ($value == "true") || (is_numeric($value) && ($value > 0)) ) { + return true; + } else { + return false; + } + break; + case 'int': + if (!is_numeric($_REQUEST[$p_varName])) { + if (!$p_errorsOk) { + $g_inputErrors[$p_varName] = 'Incorrect type. Expected type '.$p_type + .', but received type '.gettype($_REQUEST[$p_varName]).'.' + .' Value is "'.$_REQUEST[$p_varName].'".'; + } + return $p_defaultValue; + } + break; + case 'string': + if (!is_string($_REQUEST[$p_varName])) { + if (!$p_errorsOk) { + $g_inputErrors[$p_varName] = 'Incorrect type. Expected type '.$p_type + .', but received type '.gettype($_REQUEST[$p_varName]).'.' + .' Value is "'.$_REQUEST[$p_varName].'".'; + } + return $p_defaultValue; + } + break; + case 'array': + if (!is_array($_REQUEST[$p_varName])) { + // Create an array if it isnt one already. + // Arrays are used with checkboxes and radio buttons. + // The problem with them is that if there is only one + // checkbox, the given value will not be an array. So + // we make it easy for the programmer by always returning + // an array. + $newArray = array(); + $newArray[] = $_REQUEST[$p_varName]; + return $newArray; + // if (!$p_errorsOk) { + // $g_inputErrors[$p_varName] = 'Incorrect type. Expected type '.$p_type + // .', but received type '.gettype($_REQUEST[$p_varName]).'.' + // .' Value is "'.$_REQUEST[$p_varName].'".'; + // } + // return $p_defaultValue; + } + } + return $_REQUEST[$p_varName]; + } // fn get - /** - * Return FALSE if any calls to Input::Get() resulted in an error. - * @return boolean - */ - function IsValid() - { - global $g_inputErrors; - if (count($g_inputErrors) > 0) { - return false; - } else { - return true; - } - } // fn isValid + /** + * Return FALSE if any calls to Input::Get() resulted in an error. + * @return boolean + */ + function IsValid() + { + global $g_inputErrors; + if (count($g_inputErrors) > 0) { + return false; + } else { + return true; + } + } // fn isValid - /** - * Return a default error string. - * @return string - */ - function GetErrorString() - { - global $g_inputErrors; - ob_start(); - print_r($g_inputErrors); - $str = ob_get_clean(); - return $str; - } // fn GetErrorString + /** + * Return a default error string. + * @return string + */ + function GetErrorString() + { + global $g_inputErrors; + ob_start(); + print_r($g_inputErrors); + $str = ob_get_clean(); + return $str; + } // fn GetErrorString } // class Input diff --git a/htmlUI/twitter.class.php b/htmlUI/twitter.class.php index 092c57967..b4d9588a0 100644 --- a/htmlUI/twitter.class.php +++ b/htmlUI/twitter.class.php @@ -47,7 +47,7 @@ class twitter{ var $username=''; var $password=''; var $user_agent=''; - + /////////////// // // I don't know if these headers have become standards yet @@ -59,16 +59,16 @@ class twitter{ var $headers=array('X-Twitter-Client: ', 'X-Twitter-Client-Version: ', 'X-Twitter-Client-URL: '); - + var $responseInfo=array(); - - + + function twitter(){} - - - - - + + + + + ///////////////////////////////////////// // // Twitter API calls @@ -91,9 +91,9 @@ class twitter{ // // ///////////////////////////////////////// - - - // Updates the authenticating user's status. + + + // Updates the authenticating user's status. // Requires the status parameter specified below. // // status. (string) Required. The text of your status update. Must not be @@ -105,7 +105,7 @@ class twitter{ $postargs = 'status='.urlencode($status); return $this->process($request,$postargs); } - + // Returns the 20 most recent statuses from non-protected users who have // set a custom user icon. Does not require authentication. // @@ -114,12 +114,13 @@ class twitter{ // function publicTimeline($sinceid=false){ $qs=''; - if($sinceid!==false) + if($sinceid!==false) { $qs='?since_id='.intval($sinceid); + } $request = 'http://twitter.com/statuses/public_timeline.xml'.$qs; return $this->process($request); } - + // Returns the 20 most recent statuses posted in the last 24 hours from the // authenticating user and that user's friends. It's also possible to request // another user's friends_timeline via the id parameter below. @@ -128,21 +129,22 @@ class twitter{ // to return the friends_timeline. (set to false if you // want to use authenticated user). // since. (HTTP-formatted date) Optional. Narrows the returned results to just those - // statuses created after the specified date. + // statuses created after the specified date. // function friendsTimeline($id=false,$since=false){ $qs=''; - if($since!==false) + if($since!==false) { $qs='?since='.urlencode($since); - - if($id===false) + } + + if($id===false) { $request = 'http://twitter.com/statuses/friends_timeline.xml'.$qs; - else + } else { $request = 'http://twitter.com/statuses/friends_timeline/'.urlencode($id).'.xml'.$qs; - + } return $this->process($request); } - + // Returns the 20 most recent statuses posted in the last 24 hours from the // authenticating user. It's also possible to request another user's timeline // via the id parameter below. @@ -157,16 +159,17 @@ class twitter{ function userTimeline($id=false,$count=20,$since=false){ $qs='?count='.intval($count); if($since!==false) - $qs .= '&since='.urlencode($since); - - if($id===false) + $qs .= '&since='.urlencode($since); + + if($id===false) { $request = 'http://twitter.com/statuses/user_timeline.xml'.$qs; - else + } else { $request = 'http://twitter.com/statuses/user_timeline/'.urlencode($id).'.xml'.$qs; - + } + return $this->process($request); } - + // Returns a single status, specified by the id parameter below. The status's author // will be returned inline. // @@ -184,25 +187,25 @@ class twitter{ // function friends($id=false){ if($id===false) - $request = 'http://twitter.com/statuses/friends.xml'; + $request = 'http://twitter.com/statuses/friends.xml'; else - $request = 'http://twitter.com/statuses/friends/'.urlencode($id).'.xml'; + $request = 'http://twitter.com/statuses/friends/'.urlencode($id).'.xml'; return $this->process($request); } - + // Returns the authenticating user's followers, each with current status inline. // function followers(){ $request = 'http://twitter.com/statuses/followers.xml'; return $this->process($request); } - + // Returns a list of the users currently featured on the site with their current statuses inline. function featured(){ $request = 'http://twitter.com/statuses/featured.xml'; return $this->process($request); } - + // Returns extended information of a given user, specified by ID or screen name as per the required // id parameter below. This information includes design settings, so third party developers can theme // their widgets according to a given user's preferences. @@ -213,52 +216,54 @@ class twitter{ $request = 'http://twitter.com/users/show/'.urlencode($id).'.xml'; return $this->process($request); } - + // Returns a list of the direct messages sent to the authenticating user. // // since. (HTTP-formatted date) Optional. Narrows the resulting list of direct messages to just those - // sent after the specified date. + // sent after the specified date. // function directMessages($since=false){ $qs=''; - if($since!==false) + if($since!==false) { $qs='?since='.urlencode($since); + } $request = 'http://twitter.com/direct_messages.xml'.$qs; return $this->process($request); } - + // Sends a new direct message to the specified user from the authenticating user. Requires both the user // and text parameters below. // // user. (string OR int) Required. The ID or screen name of the recipient user. // text. (string) Required. The text of your direct message. Be sure to URL encode as necessary, and keep - // it under 140 characters. + // it under 140 characters. // function sendDirectMessage($user,$text){ $request = 'http://twitter.com/direct_messages/new.xml'; $postargs = 'user='.urlencode($user).'&text='.urlencode($text); return $this->process($request,$postargs); } - - - - - + + + + + // internal function where all the juicy curl fun takes place // this should not be called by anything external unless you are // doing something else completely then knock youself out. function process($url,$postargs=false){ - + $ch = curl_init($url); if($postargs !== false){ curl_setopt ($ch, CURLOPT_POST, true); curl_setopt ($ch, CURLOPT_POSTFIELDS, $postargs); } - - if($this->username !== false && $this->password !== false) + + if($this->username !== false && $this->password !== false) { curl_setopt($ch, CURLOPT_USERPWD, $this->username.':'.$this->password); - + } + curl_setopt($ch, CURLOPT_VERBOSE, 0); curl_setopt($ch, CURLOPT_NOBODY, 0); curl_setopt($ch, CURLOPT_HEADER, 0); @@ -268,17 +273,17 @@ class twitter{ curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers); $response = curl_exec($ch); - + $this->responseInfo=curl_getinfo($ch); curl_close($ch); - - + + if(intval($this->responseInfo['http_code'])==200){ if(class_exists('SimpleXMLElement')){ $xml = new SimpleXMLElement($response); return $xml; }else{ - return $response; + return $response; } }else{ return false; diff --git a/htmlUI/ui_base.inc.php b/htmlUI/ui_base.inc.php index b3335b484..eb8391f94 100644 --- a/htmlUI/ui_base.inc.php +++ b/htmlUI/ui_base.inc.php @@ -80,18 +80,18 @@ function _getDArr($format) { #$arr[''] = '00'; switch($format) { - case 'h': - for($n=0; $n<=23; $n++) { - $arr[sprintf('%02d', $n)] = sprintf('%02d', $n); - } - break; + case 'h': + for($n=0; $n<=23; $n++) { + $arr[sprintf('%02d', $n)] = sprintf('%02d', $n); + } + break; - case 'm': - case 's': - for($n=0; $n<=59; $n++) { - $arr[sprintf('%02d', $n)] = sprintf('%02d', $n); - } - break; + case 'm': + case 's': + for($n=0; $n<=59; $n++) { + $arr[sprintf('%02d', $n)] = sprintf('%02d', $n); + } + break; } return $arr; @@ -238,9 +238,9 @@ class uiBase 'EXCHANGE' => array('class' => 'uiexchange', 'file' => 'ui_exchange.class.php'), 'TRANSFERS' => array('class' => 'uitransfers', 'file' => 'ui_transfers.class.php'), 'CALENDAR' => array('class' => 'uicalendar', 'file' => 'ui_calendar.class.php'), - array('class' => 'jscom', 'file' => 'ui_jscom.php'), + array('class' => 'jscom', 'file' => 'ui_jscom.php'), 'TWITTER' => array('class' => 'uitwitter', 'file' => 'ui_twitter.class.php'), - array('class' => 'twitter', 'file' => 'twitter.class.php') + array('class' => 'twitter', 'file' => 'twitter.class.php') ); @@ -253,8 +253,7 @@ class uiBase global $CC_DBC, $CC_CONFIG; $this->gb = new GreenBox(); $CC_CONFIG['accessRawAudioUrl'] = $CC_CONFIG['storageUrlPath'].'/xmlrpc/simpleGet.php'; - $this->sessid = isset($_REQUEST[$CC_CONFIG['authCookieName']]) ? - $_REQUEST[$CC_CONFIG['authCookieName']] : null; + $this->sessid = isset($_REQUEST[$CC_CONFIG['authCookieName']]) ? $_REQUEST[$CC_CONFIG['authCookieName']] : null; $this->userid = GreenBox::GetSessUserId($this->sessid); $this->login = Alib::GetSessLogin($this->sessid); if (PEAR::isError($this->login)) { @@ -269,8 +268,8 @@ class uiBase $this->id = $this->gb->storId; } if (!is_null($this->id)) { - $f = StoredFile::Recall($this->id); - $this->type = $f->getType(); + $f = StoredFile::Recall($this->id); + $this->type = $f->getType(); } } @@ -314,10 +313,10 @@ class uiBase { global $CC_CONFIG; if (!is_array($this->STATIONPREFS) || ($reload === TRUE) ) { - $this->STATIONPREFS = array(); + $this->STATIONPREFS = array(); foreach ($mask as $key => $val) { if (isset($val['isPref']) && $val['isPref']) { - $setting = $this->gb->loadGroupPref($CC_CONFIG['StationPrefsGr'], $val['element']); + $setting = $this->gb->loadGroupPref($CC_CONFIG['StationPrefsGr'], $val['element']); if (is_string($setting)) { $this->STATIONPREFS[$val['element']] = $setting; } elseif ($val['required']) { @@ -399,9 +398,9 @@ class uiBase } $elem[$v['element']] =& $form->createElement($type, - $v['element'], - $label, - $attrs); + $v['element'], + $label, + $attrs); if (!$groupit) { $form->addElement($elem[$v['element']]); } @@ -458,21 +457,21 @@ class uiBase * @param array $input * array of form-elements */ -// function _dateArr2Str(&$input) -// { -// foreach ($input as $k => $v){ -// if (is_array($v)) { -// if ( ( isset($v['d']) ) && ( isset($v['M']) || isset($v['m']) ) && ( isset($v['Y']) || isset($v['y']) ) ) { -// $input[$k] = $v['Y'].$v['y'].'-'.sprintf('%02d', $v['M'].$v['m']).'-'.sprintf('%02d', $v['d']); -// } -// if ( ( isset($v['H']) ) || isset($v['h'] ) && ( isset($v['i']) ) && ( isset($v['s']) ) ) { -// $input[$k] = sprintf('%02d', $v['H'].$v['h']).':'.sprintf('%02d', $v['i']).':'.sprintf('%02d', $v['s']); -// } -// } -// } -// -// return $input; -// } // fn _dateArr2Str + // function _dateArr2Str(&$input) + // { + // foreach ($input as $k => $v){ + // if (is_array($v)) { + // if ( ( isset($v['d']) ) && ( isset($v['M']) || isset($v['m']) ) && ( isset($v['Y']) || isset($v['y']) ) ) { + // $input[$k] = $v['Y'].$v['y'].'-'.sprintf('%02d', $v['M'].$v['m']).'-'.sprintf('%02d', $v['d']); + // } + // if ( ( isset($v['H']) ) || isset($v['h'] ) && ( isset($v['i']) ) && ( isset($v['s']) ) ) { + // $input[$k] = sprintf('%02d', $v['H'].$v['h']).':'.sprintf('%02d', $v['i']).':'.sprintf('%02d', $v['s']); + // } + // } + // } + // + // return $input; + // } // fn _dateArr2Str /** @@ -482,35 +481,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 "
    ".var_export($ia, TRUE)."
    "; -// } -// return FALSE; -// } + // 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']; + // } /** @@ -535,8 +534,8 @@ class uiBase 'creator' => $this->gb->getPLMetadataValue($id, UI_MDATA_KEY_CREATOR), 'duration' => $this->gb->getPLMetadataValue($id, UI_MDATA_KEY_DURATION), 'type' => 'playlist', - ); - return ($data); + ); + return ($data); } public function getMetaInfo($id) @@ -552,8 +551,8 @@ class uiBase '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); + ); + return ($data); } @@ -594,5 +593,5 @@ class uiBase return $str; } -} // class uiBase -?> \ No newline at end of file + } // class uiBase + ?> \ No newline at end of file diff --git a/htmlUI/ui_browse.class.php b/htmlUI/ui_browse.class.php index baed19624..7759e8dae 100644 --- a/htmlUI/ui_browse.class.php +++ b/htmlUI/ui_browse.class.php @@ -102,7 +102,7 @@ class uiBrowse $this->setCategory(array('col' => $col, 'category' => $this->col[$col]['category'])); $this->setValue( - array('col' => $col, + array('col' => $col, 'category' => $this->col[$col]['category'], 'value' => $this->col[$col]['value'])); } @@ -118,7 +118,7 @@ class uiBrowse */ public function getCriteria() { - return $this->criteria; + return $this->criteria; } // fn getCriteria @@ -152,8 +152,8 @@ class uiBrowse 'category' => uiBase::formElementEncode($this->col[$n]['category']))); $mask2['browse_columns']['value']['options'] = $this->options($this->col[$n]['values']['results']); - $mask2['browse_columns']['category']['attributes']['id'] = "category_" . $n; - $mask2['browse_columns']['value']['attributes']['id'] = "category_value_" . $n; + $mask2['browse_columns']['category']['attributes']['id'] = "category_" . $n; + $mask2['browse_columns']['value']['attributes']['id'] = "category_value_" . $n; $mask2['browse_columns']['value']['default'] = $this->col[$n]['form_value']; uiBase::parseArrayToForm($form, $mask2['browse_columns']); @@ -214,7 +214,7 @@ class uiBrowse // reload the values. for ($i = $columnNumber; $i <= 3; $i++) { $browseValues = $this->Base->gb->browseCategory( - $this->col[$i]["category"], $tmpCriteria, $this->Base->sessid); + $this->col[$i]["category"], $tmpCriteria, $this->Base->sessid); if (!PEAR::isError($browseValues)) { $this->col[$i]['values'] = $browseValues; } @@ -222,7 +222,7 @@ class uiBrowse } if($redirect) { - $this->Base->redirUrl = UI_BROWSER.'?act='.$this->prefix; + $this->Base->redirUrl = UI_BROWSER.'?act='.$this->prefix; } } // fn setCategory @@ -249,10 +249,10 @@ class uiBrowse if ($value == '%%all%%') { unset($this->col[$columnNumber]['criteria']['conditions']); } else { - $conditions = array('cat' => uiBase::formElementDecode($category), + $conditions = array('cat' => uiBase::formElementDecode($category), 'op' => '=', 'val' => $value); - $this->col[$columnNumber]['criteria']['conditions'] = $conditions; + $this->col[$columnNumber]['criteria']['conditions'] = $conditions; } // Clear all columns above this one of selected values. @@ -273,64 +273,64 @@ class uiBrowse for ($tmpColNum = $columnNumber + 1; $tmpColNum <= 3; $tmpColNum++) { $tmpCategory = $this->col[$tmpColNum]['category']; $browseValues = $this->Base->gb->browseCategory( - $tmpCategory, $tmpCriteria, $this->Base->sessid); + $tmpCategory, $tmpCriteria, $this->Base->sessid); if (!PEAR::isError($browseValues)) { $this->col[$tmpColNum]['values'] = $browseValues; } } if($redirect) { - $this->Base->redirUrl = UI_BROWSER.'?act='.$this->prefix; + $this->Base->redirUrl = UI_BROWSER.'?act='.$this->prefix; } } // fn setValue public function refresh($p_param){ - $category_1 = array( + $category_1 = array( 'col' => 1, 'category' => $p_param['cat1'] - ); + ); - $value_1 = array( + $value_1 = array( 'col' => 1, 'category' => $p_param['cat1'], 'value' => array( - 0 => $p_param['val1'] - ) - ); + 0 => $p_param['val1'] + ) + ); - $category_2 = array( + $category_2 = array( 'col' => 2, 'category' => $p_param['cat2'] - ); + ); - $value_2 = array( + $value_2 = array( 'col' => 2, 'category' => $p_param['cat2'], 'value' => array( - 0 => $p_param['val2'] - ) - ); + 0 => $p_param['val2'] + ) + ); - $category_3 = array( + $category_3 = array( 'col' => 3, 'category' => $p_param['cat3'] - ); + ); - $value_3 = array( + $value_3 = array( 'col' => 3, 'category' => $p_param['cat3'], 'value' => array( - 0 => $p_param['val3'] - ) - ); + 0 => $p_param['val3'] + ) + ); - $this->setCategory($category_1, false); - $this->setCategory($category_2, false); - $this->setCategory($category_3, false); + $this->setCategory($category_1, false); + $this->setCategory($category_2, false); + $this->setCategory($category_3, false); - $this->setValue($value_1, false); - $this->setValue($value_2, false); - $this->setValue($value_3, true); + $this->setValue($value_1, false); + $this->setValue($value_2, false); + $this->setValue($value_3, true); } /** @@ -414,10 +414,10 @@ class uiBrowse } if (!isset($this->results['pagination'][1])) { - $this->results['pagination'][1] = '|<<'; + $this->results['pagination'][1] = '|<<'; } if (!isset($this->results['pagination'][$maxp])) { - $this->results['pagination'][$maxp] = '>>|'; + $this->results['pagination'][$maxp] = '>>|'; } $this->results['next'] = ($results['cnt'] > ($this->criteria['offset'] + $this->criteria['limit'])) ? TRUE : FALSE; $this->results['prev'] = ($this->criteria['offset'] > 0) ? TRUE : FALSE; @@ -490,9 +490,9 @@ class uiBrowse for ($n = 1; $n <= 3; $n++) { $browseValues = $this->Base->gb->browseCategory( - $this->col[$n]['category'], - $tmpCriteria, - $this->Base->sessid); + $this->col[$n]['category'], + $tmpCriteria, + $this->Base->sessid); if (!PEAR::isError($browseValues)) { $this->col[$n]['values'] = $browseValues; } diff --git a/htmlUI/ui_handler.class.php b/htmlUI/ui_handler.class.php index 0a82c40e5..1ba4093d8 100644 --- a/htmlUI/ui_handler.class.php +++ b/htmlUI/ui_handler.class.php @@ -10,10 +10,10 @@ define('ACTION_BASE', '/actions' ) ; * @copyright 2010 Sourcefabric O.P.S. */ class uiHandler extends uiBase { - /** - * @var string - */ - public $redirUrl; + /** + * @var string + */ + public $redirUrl; /** * Initialize a new Browser Class @@ -28,12 +28,12 @@ class uiHandler extends uiBase { // --- authentication --- /** - * Login to the storageServer. - * It set sessid to the cookie with name defined in ../conf.php - * - * @param array $formdata - * The REQUEST array. - */ + * Login to the storageServer. + * It set sessid to the cookie with name defined in ../conf.php + * + * @param array $formdata + * The REQUEST array. + */ function login($formdata, $mask) { global $CC_CONFIG; @@ -65,7 +65,7 @@ class uiHandler extends uiBase { $this->langid = $formdata['langid']; $this->redirUrl = UI_BROWSER.'?popup[]=_2SCHEDULER&popup[]=_close'; return TRUE; - } // fn login + } // fn login /** @@ -84,164 +84,164 @@ class uiHandler extends uiBase { session_destroy(); if ($trigger_login) { - $this->redirUrl = UI_BROWSER.'?popup[]=_clear_parent&popup[]=login'; + $this->redirUrl = UI_BROWSER.'?popup[]=_clear_parent&popup[]=login'; } else { - $this->redirUrl = UI_BROWSER.'?popup[]=_clear_parent&popup[]=_close'; + $this->redirUrl = UI_BROWSER.'?popup[]=_clear_parent&popup[]=_close'; } } // fn logout // --- files --- - function processFile($audio_file, $caller){ + function processFile($audio_file, $caller){ - global $CC_CONFIG; + global $CC_CONFIG; - if ($this->testForAudioType($audio_file) === FALSE) { - die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "uses an unsupported file type."}}'); - } + if ($this->testForAudioType($audio_file) === FALSE) { + die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "uses an unsupported file type."}}'); + } - $md5 = md5_file($audio_file); - $duplicate = StoredFile::RecallByMd5($md5); - if ($duplicate) { - if (PEAR::isError($duplicate)) { - die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": ' . $duplicate->getMessage() .'}}'); - } - else { - $duplicateName = $this->gb->getMetadataValue($duplicate->getId(), UI_MDATA_KEY_TITLE, $this->sessid); - die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "An identical audioclip named ' . $duplicateName . ' already exists in the storage server."}}'); - } - } + $md5 = md5_file($audio_file); + $duplicate = StoredFile::RecallByMd5($md5); + if ($duplicate) { + if (PEAR::isError($duplicate)) { + die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": ' . $duplicate->getMessage() .'}}'); + } + else { + $duplicateName = $this->gb->getMetadataValue($duplicate->getId(), UI_MDATA_KEY_TITLE, $this->sessid); + die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "An identical audioclip named ' . $duplicateName . ' already exists in the storage server."}}'); + } + } - $metadata = camp_get_audio_metadata($audio_file); + $metadata = camp_get_audio_metadata($audio_file); - if (PEAR::isError($metadata)) { - die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": ' + $metadata->getMessage() + '}}'); - } + if (PEAR::isError($metadata)) { + die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": ' + $metadata->getMessage() + '}}'); + } - // #2196 no id tag -> use the original filename - if (basename($audio_file) == $metadata['dc:title']) { - $metadata['dc:title'] = basename($audio_file); - $metadata['ls:filename'] = basename($audio_file); - } + // #2196 no id tag -> use the original filename + if (basename($audio_file) == $metadata['dc:title']) { + $metadata['dc:title'] = basename($audio_file); + $metadata['ls:filename'] = basename($audio_file); + } - // setMetadataBatch doesnt like these values - unset($metadata['audio']); - unset($metadata['playtime_seconds']); + // setMetadataBatch doesnt like these values + unset($metadata['audio']); + unset($metadata['playtime_seconds']); - $values = array( + $values = array( "filename" => basename($audio_file), "filepath" => $audio_file, "filetype" => "audioclip", "mime" => $metadata["dc:format"], "md5" => $md5 - ); - $storedFile = $this->gb->putFile($values, $this->sessid); + ); + $storedFile = $this->gb->putFile($values, $this->sessid); - if (PEAR::isError($storedFile)) { - die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": ' + $storedFile->getMessage() + '}}'); - } + if (PEAR::isError($storedFile)) { + die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": ' + $storedFile->getMessage() + '}}'); + } - $result = $storedFile->setMetadataBatch($metadata); + $result = $storedFile->setMetadataBatch($metadata); - return $storedFile->getId(); - } + return $storedFile->getId(); + } - function pluploadFile($data) - { - header('Content-type: text/plain; charset=UTF-8'); - header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); - header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); - header("Cache-Control: no-store, no-cache, must-revalidate"); - header("Cache-Control: post-check=0, pre-check=0", false); - header("Pragma: no-cache"); + function pluploadFile($data) + { + header('Content-type: text/plain; charset=UTF-8'); + header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); + header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); + header("Cache-Control: no-store, no-cache, must-revalidate"); + header("Cache-Control: post-check=0, pre-check=0", false); + header("Pragma: no-cache"); - // Settings - $targetDir = ini_get("upload_tmp_dir") . DIRECTORY_SEPARATOR . "plupload"; - $cleanupTargetDir = false; // Remove old files - $maxFileAge = 60 * 60; // Temp file age in seconds + // Settings + $targetDir = ini_get("upload_tmp_dir") . DIRECTORY_SEPARATOR . "plupload"; + $cleanupTargetDir = false; // Remove old files + $maxFileAge = 60 * 60; // Temp file age in seconds - // 5 minutes execution time - @set_time_limit(5 * 60); + // 5 minutes execution time + @set_time_limit(5 * 60); - // Get parameters - $chunk = isset($_REQUEST["chunk"]) ? $_REQUEST["chunk"] : 0; - $chunks = isset($_REQUEST["chunks"]) ? $_REQUEST["chunks"] : 0; - $fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : ''; + // Get parameters + $chunk = isset($_REQUEST["chunk"]) ? $_REQUEST["chunk"] : 0; + $chunks = isset($_REQUEST["chunks"]) ? $_REQUEST["chunks"] : 0; + $fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : ''; - // Clean the fileName for security reasons - //$fileName = preg_replace('/[^\w\._]+/', '', $fileName); + // Clean the fileName for security reasons + //$fileName = preg_replace('/[^\w\._]+/', '', $fileName); - // Create target dir - if (!file_exists($targetDir)) { - @mkdir($targetDir); - } + // Create target dir + if (!file_exists($targetDir)) { + @mkdir($targetDir); + } - // Remove old temp files - if (is_dir($targetDir) && ($dir = opendir($targetDir))) { - while (($file = readdir($dir)) !== false) { - $filePath = $targetDir . DIRECTORY_SEPARATOR . $file; + // Remove old temp files + if (is_dir($targetDir) && ($dir = opendir($targetDir))) { + while (($file = readdir($dir)) !== false) { + $filePath = $targetDir . DIRECTORY_SEPARATOR . $file; - // Remove temp files if they are older than the max age - if (preg_match('/\\.tmp$/', $file) && (filemtime($filePath) < time() - $maxFileAge)) - @unlink($filePath); - } + // Remove temp files if they are older than the max age + if (preg_match('/\\.tmp$/', $file) && (filemtime($filePath) < time() - $maxFileAge)) + @unlink($filePath); + } - closedir($dir); - } - else { - die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}'); - } + closedir($dir); + } + else { + die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}'); + } - // Look for the content type header - if (isset($_SERVER["HTTP_CONTENT_TYPE"])) - $contentType = $_SERVER["HTTP_CONTENT_TYPE"]; + // Look for the content type header + if (isset($_SERVER["HTTP_CONTENT_TYPE"])) + $contentType = $_SERVER["HTTP_CONTENT_TYPE"]; - if (isset($_SERVER["CONTENT_TYPE"])) - $contentType = $_SERVER["CONTENT_TYPE"]; + if (isset($_SERVER["CONTENT_TYPE"])) + $contentType = $_SERVER["CONTENT_TYPE"]; - if (strpos($contentType, "multipart") !== false) { - if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) { - // Open temp file - $out = fopen($targetDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab"); - if ($out) { - // Read binary input stream and append it to temp file - $in = fopen($_FILES['file']['tmp_name'], "rb"); + if (strpos($contentType, "multipart") !== false) { + if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) { + // Open temp file + $out = fopen($targetDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab"); + if ($out) { + // Read binary input stream and append it to temp file + $in = fopen($_FILES['file']['tmp_name'], "rb"); - if ($in) { - while ($buff = fread($in, 4096)) - fwrite($out, $buff); - } else - die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}'); + if ($in) { + while ($buff = fread($in, 4096)) + fwrite($out, $buff); + } else + die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}'); - fclose($out); - unlink($_FILES['file']['tmp_name']); - } else - die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}'); - } else - die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}'); - } else { - // Open temp file - $out = fopen($targetDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab"); - if ($out) { - // Read binary input stream and append it to temp file - $in = fopen("php://input", "rb"); + fclose($out); + unlink($_FILES['file']['tmp_name']); + } else + die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}'); + } else + die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}'); + } else { + // Open temp file + $out = fopen($targetDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab"); + if ($out) { + // Read binary input stream and append it to temp file + $in = fopen("php://input", "rb"); - if ($in) { - while ($buff = fread($in, 4096)) - fwrite($out, $buff); - } else - die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}'); + if ($in) { + while ($buff = fread($in, 4096)) + fwrite($out, $buff); + } else + die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}'); - fclose($out); - return $this->processFile($targetDir . DIRECTORY_SEPARATOR . $fileName); + fclose($out); + return $this->processFile($targetDir . DIRECTORY_SEPARATOR . $fileName); - } else - die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}'); - } + } else + die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}'); + } - // Return JSON-RPC response - die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}'); - } + // Return JSON-RPC response + die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}'); + } /** * Provides file upload and store it to the storage @@ -254,7 +254,7 @@ class uiHandler extends uiBase { global $CC_CONFIG; if ($this->testForAudioType($formdata['mediafile']['name']) === FALSE) { if (UI_ERROR) { - $this->_retMsg('"$1" uses an unsupported file type.', $formdata['mediafile']['name']); + $this->_retMsg('"$1" uses an unsupported file type.', $formdata['mediafile']['name']); } $this->redirUrl = UI_BROWSER."?act=addFileData&folderId=".$formdata['folderId']; return FALSE; @@ -347,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']); -//// } -//// 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); -// } -// } -// } -// } + // 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']); + //// } + //// 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); + // } + // } + // } + // } /** @@ -461,15 +461,15 @@ class uiHandler extends uiBase { foreach ($mask['pages'] as $key => $val) { foreach ($mask['pages'][$key] as $k => $v) { - $element = uiBase::formElementEncode($v['element']); + $element = uiBase::formElementEncode($v['element']); if ($formdata[$key.'___'.$element]) - $mData[uiBase::formElementDecode($v['element'])] = $formdata[$key.'___'.$element]; + $mData[uiBase::formElementDecode($v['element'])] = $formdata[$key.'___'.$element]; } } $_SESSION["debug"] = $mData; if (!count($mData)) { - return; + return; } foreach ($mData as $key => $val) { @@ -491,15 +491,15 @@ class uiHandler extends uiBase { * @param int $id * destination folder id */ -// function rename($newname, $id) -// { -// $r = $this->gb->renameFile($id, $newname, $this->sessid); -// if (PEAR::isError($r)) { -// $this->_retMsg($r->getMessage()); -// } -// //$this->redirUrl = UI_BROWSER."?act=fileList&id=".$this->pid; -// $this->redirUrl = UI_BROWSER."?act=fileList&id=".$this->pid; -// } // fn rename + // function rename($newname, $id) + // { + // $r = $this->gb->renameFile($id, $newname, $this->sessid); + // if (PEAR::isError($r)) { + // $this->_retMsg($r->getMessage()); + // } + // //$this->redirUrl = UI_BROWSER."?act=fileList&id=".$this->pid; + // $this->redirUrl = UI_BROWSER."?act=fileList&id=".$this->pid; + // } // fn rename /** @@ -517,19 +517,19 @@ class uiHandler extends uiBase { $this->redirUrl = UI_BROWSER."?popup[]=_reload_parent&popup[]=_close"; if (is_array($id)) { - $ids = $id; + $ids = $id; } else { - $ids[] = $id; + $ids[] = $id; } foreach ($ids as $id) { - $media = StoredFile::Recall($id); - $r = $media->delete(); + $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; @@ -548,9 +548,9 @@ class uiHandler extends uiBase { { $r = $this->gb->access($id, $this->sessid); if (PEAR::isError($r)) { - $this->_retMsg($r->getMessage()); + $this->_retMsg($r->getMessage()); } else { - echo $r; + echo $r; } } // fn getFile @@ -571,24 +571,24 @@ class uiHandler extends uiBase { // --- perms --- /** - * Add new permission record - * - * @param int $subj - * local user/group id - * @param string $permAction - * type of action from set predefined in conf.php - * @param int $id - * local id of file/object - * @param char $allowDeny - * 'A' or 'D' - * @return boolean - */ + * Add new permission record + * + * @param int $subj + * local user/group id + * @param string $permAction + * type of action from set predefined in conf.php + * @param int $id + * local id of file/object + * @param char $allowDeny + * 'A' or 'D' + * @return boolean + */ function addPerm($subj, $permAction, $id, $allowDeny) { if (PEAR::isError( - $this->gb->addPerm( - $subj, $permAction, $id, $allowDeny, $this->sessid - ) + $this->gb->addPerm( + $subj, $permAction, $id, $allowDeny, $this->sessid + ) )) { $this->_retMsg('Access denied.'); return FALSE; @@ -665,14 +665,14 @@ class uiHandler extends uiBase { } } /* - foreach($mask as $k) { - if ($k['type']=='file' && $k['required']==TRUE) { - if ($_FILES[$k['element']]['error']) { - $_SESSION['retransferFormData'] = array_merge($_REQUEST, $_FILES); - return FALSE; - } - } - } */ + foreach($mask as $k) { + if ($k['type']=='file' && $k['required']==TRUE) { + if ($_FILES[$k['element']]['error']) { + $_SESSION['retransferFormData'] = array_merge($_REQUEST, $_FILES); + return FALSE; + } + } + } */ return TRUE; } // fn _validateForm @@ -694,17 +694,17 @@ class uiHandler extends uiBase { foreach ($mask as $key => $val) { if (isset($val['isPref']) && $val['isPref']) { if (!empty($formdata[$val['element']])) { - $result = $this->gb->saveGroupPref($this->sessid, $CC_CONFIG['StationPrefsGr'], $val['element'], $formdata[$val['element']]); + $result = $this->gb->saveGroupPref($this->sessid, $CC_CONFIG['StationPrefsGr'], $val['element'], $formdata[$val['element']]); if (PEAR::isError($result)) - $this->_retMsg('Error while saving settings.'); + $this->_retMsg('Error while saving settings.'); } else { $this->gb->delGroupPref($this->sessid, $CC_CONFIG['StationPrefsGr'], $val['element']); } } if (isset($val['type']) - && ($val['type'] == 'file') - && ($val['element'] == "stationlogo") - && !empty($formdata[$val['element']]['name'])) { + && ($val['type'] == 'file') + && ($val['element'] == "stationlogo") + && !empty($formdata[$val['element']]['name'])) { $stationLogoPath = $this->gb->loadGroupPref($CC_CONFIG['StationPrefsGr'], 'stationLogoPath'); $filePath = $formdata[$val['element']]['tmp_name']; if (function_exists("getimagesize")) { @@ -731,7 +731,7 @@ class uiHandler extends uiBase { } return TRUE; - } // fn changeStationPrefs + } -} // class uiHandler +} ?> \ No newline at end of file diff --git a/htmlUI/ui_handler.php b/htmlUI/ui_handler.php index 247a530d8..5d98d115f 100644 --- a/htmlUI/ui_handler.php +++ b/htmlUI/ui_handler.php @@ -14,526 +14,526 @@ if (get_magic_quotes_gpc()) { switch ($_REQUEST['act']) { case "login": - if ($uiHandler->login($_REQUEST, $ui_fmask["login"]) === TRUE) { - $uiHandler->loadStationPrefs($ui_fmask['stationPrefs'], TRUE); - # $uiHandler->PLAYLIST->reportLookedPL(); - $uiHandler->PLAYLIST->loadLookedFromPref(); - } - include(dirname(__FILE__).'/templates/loader/index.tpl'); - include(dirname(__FILE__).'/templates/popup/_reload_parent.tpl'); - include(dirname(__FILE__).'/templates/popup/_close.tpl'); - exit; + if ($uiHandler->login($_REQUEST, $ui_fmask["login"]) === TRUE) { + $uiHandler->loadStationPrefs($ui_fmask['stationPrefs'], TRUE); + # $uiHandler->PLAYLIST->reportLookedPL(); + $uiHandler->PLAYLIST->loadLookedFromPref(); + } + include(dirname(__FILE__).'/templates/loader/index.tpl'); + include(dirname(__FILE__).'/templates/popup/_reload_parent.tpl'); + include(dirname(__FILE__).'/templates/popup/_close.tpl'); + exit; case "logout": - $uiHandler->SCRATCHPAD->save(); - $uiHandler->PLAYLIST->release(); - $uiHandler->logout(); - break; + $uiHandler->SCRATCHPAD->save(); + $uiHandler->PLAYLIST->release(); + $uiHandler->logout(); + break; case "signover": - $uiHandler->SCRATCHPAD->save(); - $uiHandler->PLAYLIST->release(); - $uiHandler->logout(TRUE); - break; + $uiHandler->SCRATCHPAD->save(); + $uiHandler->PLAYLIST->release(); + $uiHandler->logout(TRUE); + break; case "plupload": - $ui_tmpid = $uiHandler->pluploadFile($_REQUEST); - if($ui_tmpid) { - $uiHandler->SCRATCHPAD->addItem($ui_tmpid); - } - ob_end_clean(); + $ui_tmpid = $uiHandler->pluploadFile($_REQUEST); + if($ui_tmpid) { + $uiHandler->SCRATCHPAD->addItem($ui_tmpid); + } + ob_end_clean(); - die('{"jsonrpc" : "2.0", "error" : {}}'); + die('{"jsonrpc" : "2.0", "error" : {}}'); - // file/webstream handling + // file/webstream handling case "addFileData": - if (($ui_tmpid = $uiHandler->uploadFile(array_merge($_REQUEST, $_FILES), $ui_fmask["file"])) !== FALSE) { - $uiHandler->SCRATCHPAD->addItem($ui_tmpid); - } - break; + if (($ui_tmpid = $uiHandler->uploadFile(array_merge($_REQUEST, $_FILES), $ui_fmask["file"])) !== FALSE) { + $uiHandler->SCRATCHPAD->addItem($ui_tmpid); + } + break; case "addWebstreamData": - $ui_tmpid = $uiHandler->addWebstream($_REQUEST, $ui_fmask['webstream']); - $uiHandler->SCRATCHPAD->addItem($ui_tmpid); - break; + $ui_tmpid = $uiHandler->addWebstream($_REQUEST, $ui_fmask['webstream']); + $uiHandler->SCRATCHPAD->addItem($ui_tmpid); + break; case "addWebstreamMData": case "editWebstreamData": - $uiHandler->editWebstream($_REQUEST, $ui_fmask['webstream']); - $uiHandler->SCRATCHPAD->reloadMetadata(); - break; + $uiHandler->editWebstream($_REQUEST, $ui_fmask['webstream']); + $uiHandler->SCRATCHPAD->reloadMetadata(); + break; case "editMetaData": - $uiHandler->editMetaData($_REQUEST); - $uiHandler->SCRATCHPAD->reloadMetadata(); - break; + $uiHandler->editMetaData($_REQUEST); + $uiHandler->SCRATCHPAD->reloadMetadata(); + break; case "rename": - $uiHandler->rename($_REQUEST["newname"], $uiHandler->id); - break; + $uiHandler->rename($_REQUEST["newname"], $uiHandler->id); + break; case "delete": - if ($uiHandler->delete($_REQUEST['id'], $_REQUEST['delOverride'])) { - if ($uiHandler->type != 'Folder') { - $uiHandler->SCRATCHPAD->removeItems($_REQUEST['id']); - } - } - break; + if ($uiHandler->delete($_REQUEST['id'], $_REQUEST['delOverride'])) { + if ($uiHandler->type != 'Folder') { + $uiHandler->SCRATCHPAD->removeItems($_REQUEST['id']); + } + } + break; case "addPerm": - $uiHandler->addPerm($_REQUEST["subj"], $_REQUEST["permAction"], $uiHandler->id, $_REQUEST["allowDeny"]); - break; + $uiHandler->addPerm($_REQUEST["subj"], $_REQUEST["permAction"], $uiHandler->id, $_REQUEST["allowDeny"]); + break; case "removePerm": - $uiHandler->removePerm($_REQUEST["permid"], $_REQUEST["oid"]); - break; + $uiHandler->removePerm($_REQUEST["permid"], $_REQUEST["oid"]); + break; case "SUBJECTS.addSubj": - $uiHandler->SUBJECTS->addSubj($_REQUEST); - break; + $uiHandler->SUBJECTS->addSubj($_REQUEST); + break; case "SUBJECTS.removeSubj": - $uiHandler->SUBJECTS->removeSubj($_REQUEST); - break; + $uiHandler->SUBJECTS->removeSubj($_REQUEST); + break; case "SUBJECTS.addSubj2Gr": - $uiHandler->SUBJECTS->addSubj2Gr($_REQUEST); - break; + $uiHandler->SUBJECTS->addSubj2Gr($_REQUEST); + break; case "SUBJECTS.removeSubjFromGr": - $uiHandler->SUBJECTS->removeSubjFromGr($_REQUEST); - break; + $uiHandler->SUBJECTS->removeSubjFromGr($_REQUEST); + break; case "SUBJECTS.chgPasswd": - $uiHandler->SUBJECTS->chgPasswd($_REQUEST); - break; + $uiHandler->SUBJECTS->chgPasswd($_REQUEST); + break; case "changeStationPrefs": - $uiHandler->changeStationPrefs(array_merge($_REQUEST, $_FILES), $ui_fmask["stationPrefs"]); - $uiHandler->redirUrl = UI_BROWSER."?act=changeStationPrefs"; - break; + $uiHandler->changeStationPrefs(array_merge($_REQUEST, $_FILES), $ui_fmask["stationPrefs"]); + $uiHandler->redirUrl = UI_BROWSER."?act=changeStationPrefs"; + break; case "SP.addItem": - $uiHandler->SCRATCHPAD->addItem($_REQUEST['id'], $_REQUEST['type']); - $uiHandler->SCRATCHPAD->setReload(); - break; + $uiHandler->SCRATCHPAD->addItem($_REQUEST['id'], $_REQUEST['type']); + $uiHandler->SCRATCHPAD->setReload(); + break; case "SP.removeItem": - $uiHandler->SCRATCHPAD->removeItems($_REQUEST['id']); - $uiHandler->SCRATCHPAD->setReload(); - break; + $uiHandler->SCRATCHPAD->removeItems($_REQUEST['id']); + $uiHandler->SCRATCHPAD->setReload(); + break; case "SP.reorder": - $uiHandler->SCRATCHPAD->reorder($_REQUEST['by']); - $uiHandler->SCRATCHPAD->setReload(); - break; + $uiHandler->SCRATCHPAD->reorder($_REQUEST['by']); + $uiHandler->SCRATCHPAD->setReload(); + break; case "SEARCH.newSearch": - $uiHandler->SEARCH->newSearch($_REQUEST); + $uiHandler->SEARCH->newSearch($_REQUEST); $NO_REDIRECT = true; - $_REQUEST["act"] = "SEARCH"; - include("ui_browser.php"); - break; + $_REQUEST["act"] = "SEARCH"; + include("ui_browser.php"); + break; case "SEARCH.simpleSearch": - $uiHandler->SEARCH->simpleSearch($_REQUEST); - $NO_REDIRECT = true; - $_REQUEST["act"] = "SEARCH"; - include("ui_browser.php"); - break; + $uiHandler->SEARCH->simpleSearch($_REQUEST); + $NO_REDIRECT = true; + $_REQUEST["act"] = "SEARCH"; + include("ui_browser.php"); + break; case "SEARCH.reorder": - $uiHandler->SEARCH->reorder($_REQUEST['by']); - $NO_REDIRECT = true; - $_REQUEST["act"] = "SEARCH"; - include("ui_browser.php"); - break; + $uiHandler->SEARCH->reorder($_REQUEST['by']); + $NO_REDIRECT = true; + $_REQUEST["act"] = "SEARCH"; + include("ui_browser.php"); + break; case "SEARCH.clear": - $uiHandler->SEARCH->clear(); - $NO_REDIRECT = true; - $_REQUEST["act"] = "SEARCH"; - include("ui_browser.php"); - break; + $uiHandler->SEARCH->clear(); + $NO_REDIRECT = true; + $_REQUEST["act"] = "SEARCH"; + include("ui_browser.php"); + break; case "SEARCH.setOffset": - $uiHandler->SEARCH->setOffset($_REQUEST['page']); - $NO_REDIRECT = true; - $_REQUEST["act"] = "SEARCH"; - include("ui_browser.php"); - break; + $uiHandler->SEARCH->setOffset($_REQUEST['page']); + $NO_REDIRECT = true; + $_REQUEST["act"] = "SEARCH"; + include("ui_browser.php"); + break; - case "BROWSE.refresh": - $uiHandler->BROWSE->refresh($_REQUEST); - $NO_REDIRECT = true; - $_REQUEST["act"] = "BROWSE"; - include("ui_browser.php"); - break; + case "BROWSE.refresh": + $uiHandler->BROWSE->refresh($_REQUEST); + $NO_REDIRECT = true; + $_REQUEST["act"] = "BROWSE"; + include("ui_browser.php"); + break; case "BROWSE.setCategory": - $uiHandler->BROWSE->setCategory($_REQUEST); - $NO_REDIRECT = true; - $_REQUEST["act"] = "BROWSE"; - include("ui_browser.php"); - break; + $uiHandler->BROWSE->setCategory($_REQUEST); + $NO_REDIRECT = true; + $_REQUEST["act"] = "BROWSE"; + include("ui_browser.php"); + break; case "BROWSE.setValue": - $uiHandler->BROWSE->setValue($_REQUEST); - $NO_REDIRECT = true; - $_REQUEST["act"] = "BROWSE"; - include("ui_browser.php"); - break; + $uiHandler->BROWSE->setValue($_REQUEST); + $NO_REDIRECT = true; + $_REQUEST["act"] = "BROWSE"; + include("ui_browser.php"); + break; case "BROWSE.reorder": - $uiHandler->BROWSE->reorder($_REQUEST['by']); - $NO_REDIRECT = true; - $_REQUEST["act"] = "BROWSE"; - include("ui_browser.php"); - break; + $uiHandler->BROWSE->reorder($_REQUEST['by']); + $NO_REDIRECT = true; + $_REQUEST["act"] = "BROWSE"; + include("ui_browser.php"); + break; case "BROWSE.setDefaults": - $uiHandler->BROWSE->setDefaults(TRUE); - $NO_REDIRECT = true; - $_REQUEST["act"] = "BROWSE"; - include("ui_browser.php"); - break; + $uiHandler->BROWSE->setDefaults(TRUE); + $NO_REDIRECT = true; + $_REQUEST["act"] = "BROWSE"; + include("ui_browser.php"); + break; case "BROWSE.setOffset": - $uiHandler->BROWSE->setOffset($_REQUEST['page']); - $NO_REDIRECT = true; - $_REQUEST["act"] = "BROWSE"; - include("ui_browser.php"); - break; + $uiHandler->BROWSE->setOffset($_REQUEST['page']); + $NO_REDIRECT = true; + $_REQUEST["act"] = "BROWSE"; + include("ui_browser.php"); + break; case "BROWSE.setLimit": - $uiHandler->BROWSE->setLimit($_REQUEST['limit']); - $NO_REDIRECT = true; - $_REQUEST["act"] = "BROWSE"; - include("ui_browser.php"); - break; + $uiHandler->BROWSE->setLimit($_REQUEST['limit']); + $NO_REDIRECT = true; + $_REQUEST["act"] = "BROWSE"; + include("ui_browser.php"); + break; case "BROWSE.setFiletype": - $uiHandler->BROWSE->setFiletype($_REQUEST['filetype']); - $NO_REDIRECT = true; - $_REQUEST["act"] = "BROWSE"; - include("ui_browser.php"); - break; + $uiHandler->BROWSE->setFiletype($_REQUEST['filetype']); + $NO_REDIRECT = true; + $_REQUEST["act"] = "BROWSE"; + include("ui_browser.php"); + break; case "HUBBROWSE.setCategory": - $uiHandler->HUBBROWSE->setCategory($_REQUEST); - break; + $uiHandler->HUBBROWSE->setCategory($_REQUEST); + break; case "HUBBROWSE.setValue": - $uiHandler->HUBBROWSE->setValue($_REQUEST); - break; + $uiHandler->HUBBROWSE->setValue($_REQUEST); + break; case "HUBBROWSE.reorder": - $uiHandler->HUBBROWSE->reorder($_REQUEST['by']); - break; + $uiHandler->HUBBROWSE->reorder($_REQUEST['by']); + break; case "HUBBROWSE.setDefaults": - $uiHandler->HUBBROWSE->setDefaults(TRUE); - break; + $uiHandler->HUBBROWSE->setDefaults(TRUE); + break; case "HUBBROWSE.setOffset": - $uiHandler->HUBBROWSE->setOffset($_REQUEST['page']); - break; + $uiHandler->HUBBROWSE->setOffset($_REQUEST['page']); + break; case "HUBBROWSE.setLimit": - $uiHandler->HUBBROWSE->setLimit($_REQUEST['limit']); - break; + $uiHandler->HUBBROWSE->setLimit($_REQUEST['limit']); + break; case "HUBBROWSE.setFiletype": - $uiHandler->HUBBROWSE->setFiletype($_REQUEST['filetype']); - break; + $uiHandler->HUBBROWSE->setFiletype($_REQUEST['filetype']); + break; case "HUBSEARCH.newSearch": - $uiHandler->HUBSEARCH->newSearch($_REQUEST); - break; + $uiHandler->HUBSEARCH->newSearch($_REQUEST); + break; case "HUBSEARCH.reorder": - $uiHandler->HUBSEARCH->reorder($_REQUEST['by']); - break; + $uiHandler->HUBSEARCH->reorder($_REQUEST['by']); + break; case "HUBSEARCH.clear": - $uiHandler->HUBSEARCH->clear(); - break; + $uiHandler->HUBSEARCH->clear(); + break; case "HUBSEARCH.setOffset": - $uiHandler->HUBSEARCH->setOffset($_REQUEST['page']); - $NO_REDIRECT = true; - $_REQUEST["act"] = "HUBSEARCH"; - include("ui_browser.php"); - break; + $uiHandler->HUBSEARCH->setOffset($_REQUEST['page']); + $NO_REDIRECT = true; + $_REQUEST["act"] = "HUBSEARCH"; + include("ui_browser.php"); + break; case "TRANSFERS.reorder": - $uiHandler->TRANSFERS->reorder($_REQUEST['by']); - break; + $uiHandler->TRANSFERS->reorder($_REQUEST['by']); + break; case "TRANSFERS.setOffset": - $uiHandler->TRANSFERS->setOffset($_REQUEST['page']); - break; + $uiHandler->TRANSFERS->setOffset($_REQUEST['page']); + break; case "TR.pause": case "TR.resume": case "TR.cancel": - $ids = ''; - if (is_array($_REQUEST['id'])) { - foreach ($_REQUEST['id'] as $id) { - $ids .= '&id[]='.$id; - } - } else { - $ids = '&id='.$_REQUEST['id']; - } - //echo '_REQUEST:'; print_r($_REQUEST); echo "\n"; - $uiHandler->redirUrl = UI_BROWSER."?popup[]={$_REQUEST['act']}{$ids}"; - break; + $ids = ''; + if (is_array($_REQUEST['id'])) { + foreach ($_REQUEST['id'] as $id) { + $ids .= '&id[]='.$id; + } + } else { + $ids = '&id='.$_REQUEST['id']; + } + //echo '_REQUEST:'; print_r($_REQUEST); echo "\n"; + $uiHandler->redirUrl = UI_BROWSER."?popup[]={$_REQUEST['act']}{$ids}"; + break; case "TR.cancelConfirm": - //echo '_REQUEST:'; print_r($_REQUEST); echo "\n"; - $uiHandler->TRANSFERS->doTransportAction($_REQUEST['id'],'cancel'); - $uiHandler->redirUrl = UI_BROWSER.'?popup[]=_reload_parent&popup[]=_close'; - break; + //echo '_REQUEST:'; print_r($_REQUEST); echo "\n"; + $uiHandler->TRANSFERS->doTransportAction($_REQUEST['id'],'cancel'); + $uiHandler->redirUrl = UI_BROWSER.'?popup[]=_reload_parent&popup[]=_close'; + break; case "PL.activate": - if ($uiHandler->PLAYLIST->activate($_REQUEST['id']) === TRUE) { - $uiHandler->SCRATCHPAD->addItem($_REQUEST['id'], 'playlist'); - } - $uiHandler->PLAYLIST->setReload(); - break; - - case "PL.create": - //$ids = (isset($_REQUEST['id']) ? $_REQUEST['id'] : null); - if (($ui_tmpid = $uiHandler->PLAYLIST->create()) !== FALSE) { - if ($ids) { - //$uiHandler->SCRATCHPAD->addItem($ids); - } - $uiHandler->SCRATCHPAD->addItem($ui_tmpid, 'playlist'); - } - $uiHandler->PLAYLIST->setRedirect('_2PL.editMetaData'); - break; - - case "PL.addItem": - if (isset($_REQUEST['id'])) { - if ($uiHandler->PLAYLIST->addItem($_REQUEST['id']) === TRUE) { - $uiHandler->SCRATCHPAD->addItem($_REQUEST['id']); - } + if ($uiHandler->PLAYLIST->activate($_REQUEST['id']) === TRUE) { + $uiHandler->SCRATCHPAD->addItem($_REQUEST['id'], 'playlist'); } $uiHandler->PLAYLIST->setReload(); break; - + + case "PL.create": + //$ids = (isset($_REQUEST['id']) ? $_REQUEST['id'] : null); + if (($ui_tmpid = $uiHandler->PLAYLIST->create()) !== FALSE) { + if ($ids) { + //$uiHandler->SCRATCHPAD->addItem($ids); + } + $uiHandler->SCRATCHPAD->addItem($ui_tmpid, 'playlist'); + } + $uiHandler->PLAYLIST->setRedirect('_2PL.editMetaData'); + break; + + case "PL.addItem": + if (isset($_REQUEST['id'])) { + if ($uiHandler->PLAYLIST->addItem($_REQUEST['id']) === TRUE) { + $uiHandler->SCRATCHPAD->addItem($_REQUEST['id']); + } + } + $uiHandler->PLAYLIST->setReload(); + break; + case "SPL.addItem": if (isset($_REQUEST['id'])) { - if ($uiHandler->PLAYLIST->addItem($_REQUEST['id']) === TRUE) { - $uiHandler->SCRATCHPAD->addItem($_REQUEST['id']); - } + if ($uiHandler->PLAYLIST->addItem($_REQUEST['id']) === TRUE) { + $uiHandler->SCRATCHPAD->addItem($_REQUEST['id']); + } } die('{"jsonrpc" : "2.0"}'); - - case "PL.setClipLength": - $uiHandler->PLAYLIST->setClipLength($_REQUEST['pos'], $_REQUEST['cueIn'], $_REQUEST['cueOut']); - break; - case "PL.setFadeLength": - $uiHandler->PLAYLIST->setFadeLength($_REQUEST['pos'], $_REQUEST['fadeIn'], $_REQUEST['fadeOut']); - break; + case "PL.setClipLength": + $uiHandler->PLAYLIST->setClipLength($_REQUEST['pos'], $_REQUEST['cueIn'], $_REQUEST['cueOut']); + break; + + case "PL.setFadeLength": + $uiHandler->PLAYLIST->setFadeLength($_REQUEST['pos'], $_REQUEST['fadeIn'], $_REQUEST['fadeOut']); + break; case "PL.removeItem": - $uiHandler->PLAYLIST->removeItem($_REQUEST['id']); - $uiHandler->PLAYLIST->setReload(); - break; - + $uiHandler->PLAYLIST->removeItem($_REQUEST['id']); + $uiHandler->PLAYLIST->setReload(); + break; + case "PL.release": - $uiHandler->PLAYLIST->release(); - $uiHandler->PLAYLIST->setReload(); - break; + $uiHandler->PLAYLIST->release(); + $uiHandler->PLAYLIST->setReload(); + break; case "PL.save": - if (($ui_tmpid = $uiHandler->PLAYLIST->save()) !== FALSE) { - $uiHandler->SCRATCHPAD->addItem($ui_tmpid); - } - $uiHandler->PLAYLIST->setReload(); - break; + if (($ui_tmpid = $uiHandler->PLAYLIST->save()) !== FALSE) { + $uiHandler->SCRATCHPAD->addItem($ui_tmpid); + } + $uiHandler->PLAYLIST->setReload(); + break; case "PL.revert": - if (($ui_tmpid = $uiHandler->PLAYLIST->revert()) !== FALSE) { - $uiHandler->SCRATCHPAD->addItem($ui_tmpid); - } - $uiHandler->PLAYLIST->setReload(); - break; + if (($ui_tmpid = $uiHandler->PLAYLIST->revert()) !== FALSE) { + $uiHandler->SCRATCHPAD->addItem($ui_tmpid); + } + $uiHandler->PLAYLIST->setReload(); + break; case "PL.revertANDclose": - $uiHandler->PLAYLIST->revert(); - $uiHandler->PLAYLIST->release(); - $uiHandler->PLAYLIST->setReload(); - break; + $uiHandler->PLAYLIST->revert(); + $uiHandler->PLAYLIST->release(); + $uiHandler->PLAYLIST->setReload(); + break; case"PL.unlook": - $uiHandler->PLAYLIST->loadLookedFromPref(); - $uiHandler->PLAYLIST->setReload(); - break; + $uiHandler->PLAYLIST->loadLookedFromPref(); + $uiHandler->PLAYLIST->setReload(); + break; case "PL.changeTransition": - $uiHandler->PLAYLIST->changeTransition($_REQUEST['id'], $_REQUEST['type'], $_REQUEST['duration']); - $uiHandler->PLAYLIST->setReload(); - break; + $uiHandler->PLAYLIST->changeTransition($_REQUEST['id'], $_REQUEST['type'], $_REQUEST['duration']); + $uiHandler->PLAYLIST->setReload(); + break; case "PL.moveItem": - $uiHandler->PLAYLIST->moveItem($_REQUEST['oldPos'], $_REQUEST['newPos']); - break; + $uiHandler->PLAYLIST->moveItem($_REQUEST['oldPos'], $_REQUEST['newPos']); + break; case "PL.reorder": - $uiHandler->PLAYLIST->reorder($_REQUEST['pl_items']); - $uiHandler->PLAYLIST->setReturn(); - break; + $uiHandler->PLAYLIST->reorder($_REQUEST['pl_items']); + $uiHandler->PLAYLIST->setReturn(); + break; case "PL.reArrange": - $uiHandler->PLAYLIST->reorder($_REQUEST['pl_items']); - $uiHandler->PLAYLIST->setReload(); - break; + $uiHandler->PLAYLIST->reorder($_REQUEST['pl_items']); + $uiHandler->PLAYLIST->setReload(); + break; case "PL.editMetaData": - $uiHandler->PLAYLIST->editMetaData($_REQUEST); - //$uiHandler->SCRATCHPAD->addItem($_REQUEST['id']); - break; + $uiHandler->PLAYLIST->editMetaData($_REQUEST); + //$uiHandler->SCRATCHPAD->addItem($_REQUEST['id']); + break; case "PL.deleteActive": - if (($ui_tmpid = $uiHandler->PLAYLIST->deleteActive()) !== FALSE) { - $uiHandler->SCRATCHPAD->removeItems($ui_tmpid); - } - $uiHandler->PLAYLIST->setReload(); - break; - - case "PL.delete": - if (($ui_tmpid = $uiHandler->PLAYLIST->delete($_REQUEST['id'])) !== FALSE) { - $uiHandler->SCRATCHPAD->removeItems($ui_tmpid); - } - $uiHandler->PLAYLIST->setReload(); - break; + if (($ui_tmpid = $uiHandler->PLAYLIST->deleteActive()) !== FALSE) { + $uiHandler->SCRATCHPAD->removeItems($ui_tmpid); + } + $uiHandler->PLAYLIST->setReload(); + break; + + case "PL.delete": + if (($ui_tmpid = $uiHandler->PLAYLIST->delete($_REQUEST['id'])) !== FALSE) { + $uiHandler->SCRATCHPAD->removeItems($ui_tmpid); + } + $uiHandler->PLAYLIST->setReload(); + break; case "PL.export": - $uiHandler->redirUrl = UI_BROWSER."?popup[]=PL.redirect2DownloadExportedFile&id={$_REQUEST['id']}&playlisttype={$_REQUEST['playlisttype']}&exporttype={$_REQUEST['exporttype']}"; - break; + $uiHandler->redirUrl = UI_BROWSER."?popup[]=PL.redirect2DownloadExportedFile&id={$_REQUEST['id']}&playlisttype={$_REQUEST['playlisttype']}&exporttype={$_REQUEST['exporttype']}"; + break; case "PL.import": - //echo '_FILES:'; print_r($_FILES); - $importedPlaylist = $uiHandler->gb->importPlaylistOpen($uiHandler->sessid); - //echo 'importPlaylistOpen:'; print_r($importedPlaylist); - copy($_FILES['playlist']['tmp_name'],$importedPlaylist['fname']); - $uiHandler->gb->importPlaylistClose($importedPlaylist['token']); - $uiHandler->redirUrl = UI_BROWSER."?act=PL.import"; - break; + //echo '_FILES:'; print_r($_FILES); + $importedPlaylist = $uiHandler->gb->importPlaylistOpen($uiHandler->sessid); + //echo 'importPlaylistOpen:'; print_r($importedPlaylist); + copy($_FILES['playlist']['tmp_name'],$importedPlaylist['fname']); + $uiHandler->gb->importPlaylistClose($importedPlaylist['token']); + $uiHandler->redirUrl = UI_BROWSER."?act=PL.import"; + break; case "SCHEDULER.set": - $uiHandler->SCHEDULER->set($_REQUEST); - //$uiHandler->SCHEDULER->setReload(); - $NO_REDIRECT = true; - $_REQUEST["act"] = "SCHEDULER"; - include("ui_browser.php"); - break; + $uiHandler->SCHEDULER->set($_REQUEST); + //$uiHandler->SCHEDULER->setReload(); + $NO_REDIRECT = true; + $_REQUEST["act"] = "SCHEDULER"; + include("ui_browser.php"); + break; case "SCHEDULER.setScheduleAtTime": - $uiHandler->SCHEDULER->setScheduleAtTime($_REQUEST); - $uiHandler->SCHEDULER->setClose(); - break; + $uiHandler->SCHEDULER->setScheduleAtTime($_REQUEST); + $uiHandler->SCHEDULER->setClose(); + break; case "SCHEDULER.addItem": - $groupId = $uiHandler->SCHEDULER->addItem($_REQUEST); - if (PEAR::isError($groupId) && $groupId->getCode() == 555) { - $Smarty->assign("USER_ERROR", "Scheduling conflict."); - } + $groupId = $uiHandler->SCHEDULER->addItem($_REQUEST); + if (PEAR::isError($groupId) && $groupId->getCode() == 555) { + $Smarty->assign("USER_ERROR", "Scheduling conflict."); + } - $NO_REDIRECT = true; - $_REQUEST["act"] = "SCHEDULER"; - include("ui_browser.php"); - break; + $NO_REDIRECT = true; + $_REQUEST["act"] = "SCHEDULER"; + include("ui_browser.php"); + break; case "SCHEDULER.removeItem": - $uiHandler->SCHEDULER->removeFromScheduleMethod($_REQUEST['scheduleId']); - $uiHandler->SCHEDULER->setReload(); - break; + $uiHandler->SCHEDULER->removeFromScheduleMethod($_REQUEST['scheduleId']); + $uiHandler->SCHEDULER->setReload(); + break; case "SCHEDULER.startDaemon": - $uiHandler->SCHEDULER->startDaemon(TRUE); - $uiHandler->SCHEDULER->setReload(); - break; + $uiHandler->SCHEDULER->startDaemon(TRUE); + $uiHandler->SCHEDULER->setReload(); + break; case "SCHEDULER.stopDaemon": - $uiHandler->SCHEDULER->stopDaemon(TRUE); - $uiHandler->SCHEDULER->setReload(); - break; + $uiHandler->SCHEDULER->stopDaemon(TRUE); + $uiHandler->SCHEDULER->setReload(); + break; case 'SCHEDULER.scheduleExportOpen': // Make sure days are always 2 digits. - $_REQUEST['fromDay'] = (strlen($_REQUEST['fromDay'])>1)?$_REQUEST['fromDay']:'0'.$_REQUEST['fromDay']; - $_REQUEST['toDay'] = (strlen($_REQUEST['toDay'])>1)?$_REQUEST['toDay']:'0'.$_REQUEST['toDay']; + $_REQUEST['fromDay'] = (strlen($_REQUEST['fromDay'])>1)?$_REQUEST['fromDay']:'0'.$_REQUEST['fromDay']; + $_REQUEST['toDay'] = (strlen($_REQUEST['toDay'])>1)?$_REQUEST['toDay']:'0'.$_REQUEST['toDay']; - $fromTime = $_REQUEST['fromYear'].'-'.$_REQUEST['fromMonth'].'-'.$_REQUEST['fromDay'].' ' - .$_REQUEST['fromHour'].':'.$_REQUEST['fromMinute'].':00'; - $toTime = $_REQUEST['toYear'].'-'.$_REQUEST['toMonth'].'-'.$_REQUEST['toDay'].' ' - .$_REQUEST['toHour'].':'.$_REQUEST['toMinute'].':00'; - //echo '';echo "fromTime:$fromTime | toTime:$toTime";echo''."\n"; - $uiHandler->SCHEDULER->scheduleExportOpen($fromTime, $toTime); - $uiHandler->redirUrl = UI_BROWSER.'?act=SCHEDULER'; - break; + $fromTime = $_REQUEST['fromYear'].'-'.$_REQUEST['fromMonth'].'-'.$_REQUEST['fromDay'].' ' + .$_REQUEST['fromHour'].':'.$_REQUEST['fromMinute'].':00'; + $toTime = $_REQUEST['toYear'].'-'.$_REQUEST['toMonth'].'-'.$_REQUEST['toDay'].' ' + .$_REQUEST['toHour'].':'.$_REQUEST['toMinute'].':00'; + //echo '';echo "fromTime:$fromTime | toTime:$toTime";echo''."\n"; + $uiHandler->SCHEDULER->scheduleExportOpen($fromTime, $toTime); + $uiHandler->redirUrl = UI_BROWSER.'?act=SCHEDULER'; + break; case 'SCHEDULER.setImportFile': - $uiHandler->SCHEDULER->scheduleImportOpen($_REQUEST['target']); - $uiHandler->redirUrl = UI_BROWSER.'?act=SCHEDULER'; - break; + $uiHandler->SCHEDULER->scheduleImportOpen($_REQUEST['target']); + $uiHandler->redirUrl = UI_BROWSER.'?act=SCHEDULER'; + break; case 'BACKUP.createBackupOpen': - $uiHandler->EXCHANGE->createBackupOpen(); - $uiHandler->redirUrl = UI_BROWSER.'?act=BACKUP'; - break; + $uiHandler->EXCHANGE->createBackupOpen(); + $uiHandler->redirUrl = UI_BROWSER.'?act=BACKUP'; + break; case 'BACKUP.copy2target': - $uiHandler->EXCHANGE->copy2target($_REQUEST['target']); - $uiHandler->redirUrl = UI_BROWSER.'?act=BACKUP'; - break; + $uiHandler->EXCHANGE->copy2target($_REQUEST['target']); + $uiHandler->redirUrl = UI_BROWSER.'?act=BACKUP'; + break; case 'BACKUP.createBackupClose': - $uiHandler->EXCHANGE->createBackupClose(); - $uiHandler->redirUrl = UI_BROWSER.'?act=BACKUP'; - break; + $uiHandler->EXCHANGE->createBackupClose(); + $uiHandler->redirUrl = UI_BROWSER.'?act=BACKUP'; + break; case 'RESTORE.setBackupFileToRestore': - $uiHandler->EXCHANGE->backupRestoreOpen($_REQUEST['target']); - $uiHandler->redirUrl = UI_BROWSER.'?act=RESTORE'; - break; + $uiHandler->EXCHANGE->backupRestoreOpen($_REQUEST['target']); + $uiHandler->redirUrl = UI_BROWSER.'?act=RESTORE'; + break; case 'RESTORE.backupRestoreClose': - $uiHandler->EXCHANGE->backupRestoreClose(); - $uiHandler->redirUrl = UI_BROWSER.'?act=RESTORE'; - break; + $uiHandler->EXCHANGE->backupRestoreClose(); + $uiHandler->redirUrl = UI_BROWSER.'?act=RESTORE'; + break; case 'SESSION.CLEAR': - $_SESSION = array(); - die(); - break; + $_SESSION = array(); + die(); + break; - case 'twitter.saveSettings': + case 'twitter.saveSettings': $uiHandler->TWITTER->saveSettings(); $uiHandler->redirUrl = UI_BROWSER.'?act=twitter.settings'; - break; + break; case NULL: - if ($uiHandler->userid) { - $uiHandler->_retMsg('The uploaded file is bigger than allowed in system settings. See "Help", chapter "Troubleshooting" for more information.'); - } - $uiHandler->redirUrl = UI_BROWSER; - if ($_REQUEST['is_popup']) { - $uiHandler->redirUrl = UI_BROWSER.'?popup[]=_reload_parent&popup[]=_close'; - } - break; + if ($uiHandler->userid) { + $uiHandler->_retMsg('The uploaded file is bigger than allowed in system settings. See "Help", chapter "Troubleshooting" for more information.'); + } + $uiHandler->redirUrl = UI_BROWSER; + if ($_REQUEST['is_popup']) { + $uiHandler->redirUrl = UI_BROWSER.'?popup[]=_reload_parent&popup[]=_close'; + } + break; default: - $uiHandler->_retMsg(tra('Unknown method: $1', $_REQUEST['act'])); - $uiHandler->redirUrl = UI_BROWSER; - if ($_REQUEST['is_popup']) { - $uiHandler->redirUrl = UI_BROWSER.'?popup[]=_reload_parent&popup[]=_close'; - } - //break; + $uiHandler->_retMsg(tra('Unknown method: $1', $_REQUEST['act'])); + $uiHandler->redirUrl = UI_BROWSER; + if ($_REQUEST['is_popup']) { + $uiHandler->redirUrl = UI_BROWSER.'?popup[]=_reload_parent&popup[]=_close'; + } + //break; } @@ -544,9 +544,9 @@ if ($uiHandler->alertMsg) { ob_end_flush(); if (!isset($NO_REDIRECT)) { if (isset($_REQUEST['target'])) { - header('Location: ui_browser.php?act='.$_REQUEST['target']); + header('Location: ui_browser.php?act='.$_REQUEST['target']); } else { - header("Location: ".$uiHandler->redirUrl); + header("Location: ".$uiHandler->redirUrl); } } exit; diff --git a/htmlUI/ui_playlist.class.php b/htmlUI/ui_playlist.class.php index 7be533bbe..9e47d2270 100644 --- a/htmlUI/ui_playlist.class.php +++ b/htmlUI/ui_playlist.class.php @@ -8,15 +8,15 @@ require_once(dirname(__FILE__)."/../backend/Playlist.php"); */ class uiPlaylist { - public $activeId; - public $title; - public $duration; + public $activeId; + public $title; + public $duration; - private $Base; - private $reloadUrl; - private $redirectUrl; - private $returnUrl; - private $flat; + private $Base; + private $reloadUrl; + private $redirectUrl; + private $returnUrl; + private $flat; public function __construct($uiBase) { @@ -32,11 +32,11 @@ class uiPlaylist public function setReload($url=NULL) { - if($url) - $this->Base->redirUrl = $url; - else + if($url) { + $this->Base->redirUrl = $url; + } else { $this->Base->redirUrl = $this->reloadUrl; - + } } // fn setReload @@ -94,15 +94,15 @@ class uiPlaylist $userid = $this->Base->gb->playlistIsAvailable($plid, $this->Base->sessid); if ($userid !== TRUE) { - if (UI_WARNING) { - $this->Base->_retMsg('Playlist has been locked by "$1".', Subjects::GetSubjName($userid)); - } + if (UI_WARNING) { + $this->Base->_retMsg('Playlist has been locked by "$1".', Subjects::GetSubjName($userid)); + } return FALSE; } $res = $this->Base->gb->lockPlaylistForEdit($plid, $this->Base->sessid); if (PEAR::isError($res) || $res === FALSE) { if (UI_VERBOSE === TRUE) { - print_r($res); + print_r($res); } $this->Base->_retMsg('Unable to open playlist "$1".', $this->Base->getMetadataValue($plid, UI_MDATA_KEY_TITLE)); return FALSE; @@ -112,7 +112,7 @@ class uiPlaylist $this->activeId = $plid; if ($msg && UI_VERBOSE) { - $this->Base->_retMsg('Playlist "$1" opened.', $this->Base->getMetadataValue($plid, UI_MDATA_KEY_TITLE)); + $this->Base->_retMsg('Playlist "$1" opened.', $this->Base->getMetadataValue($plid, UI_MDATA_KEY_TITLE)); } return TRUE; @@ -125,17 +125,17 @@ class uiPlaylist // delete PL from session if (!$this->activeId) { if (UI_WARNING) { - $this->Base->_retMsg('There is no playlist available to unlock.'); + $this->Base->_retMsg('There is no playlist available to unlock.'); } return FALSE; } $res = $this->Base->gb->releaseLockedPlaylist($this->activeId, $this->Base->sessid); if (PEAR::isError($res) || $res === FALSE) { if (UI_VERBOSE === TRUE) { - print_r($res); + print_r($res); } if (UI_WARNING) { - $this->Base->_retMsg('Unable to release playlist.'); + $this->Base->_retMsg('Unable to release playlist.'); } return FALSE; } @@ -150,7 +150,7 @@ class uiPlaylist { if (is_string($this->Base->gb->loadPref($this->Base->sessid, UI_PL_ACCESSTOKEN_KEY))) { if ($setMsg == TRUE) { - $this->Base->_retMsg('Found locked playlist.'); + $this->Base->_retMsg('Found locked playlist.'); } return TRUE; } @@ -194,15 +194,15 @@ class uiPlaylist $cueIn = NULL; /* - gstreamer bug: - Warning: The clipEnd can't be bigger than ninety nine percent (99%) of the clipLength, - this means also if no clipEnd is defined it should be 00:00:00.000000 and not the clipLength. - $clipend = '00:00:00.000000'; - */ + gstreamer bug: + Warning: The clipEnd can't be bigger than ninety nine percent (99%) of the clipLength, + this means also if no clipEnd is defined it should be 00:00:00.000000 and not the clipLength. + $clipend = '00:00:00.000000'; + */ if (!$elemIds) { if (UI_WARNING) { - $this->Base->_retMsg('No item(s) selected.'); + $this->Base->_retMsg('No item(s) selected.'); } return FALSE; } @@ -217,7 +217,7 @@ class uiPlaylist $r = $this->Base->gb->addAudioClipToPlaylist($this->activeId, $elemId, $pos, $fadeIn, $fadeOut, $cliplength, $cueIn, $cueOut); if (PEAR::isError($r)) { if (UI_VERBOSE === TRUE) { - print_r($r); + print_r($r); } $this->Base->_retMsg('Error while trying to add item to playlist.'); return FALSE; @@ -234,12 +234,12 @@ class uiPlaylist { if (!$positions) { if (UI_WARNING) { - $this->Base->_retMsg('No item(s) selected.'); + $this->Base->_retMsg('No item(s) selected.'); } return FALSE; } if (!is_array($positions)) - $positions = array($positions); + $positions = array($positions); //so the automatic updating of playlist positioning doesn't affect removal. sort($positions); @@ -312,7 +312,7 @@ class uiPlaylist $response["newPos"] = $newPos; } else{ - $response["error"] = FALSE; + $response["error"] = FALSE; } die(json_encode($response)); @@ -364,7 +364,7 @@ class uiPlaylist $form->setConstants(array('act' => 'PL.editMetaData', 'id' => $id, 'curr_langid' => $langid - ) + ) ); $renderer = new HTML_QuickForm_Renderer_Array(true, true); $form->accept($renderer); @@ -402,20 +402,20 @@ class uiPlaylist } if (!count($mData)) { - return; + return; } foreach ($mData as $key => $val) { $r = $this->Base->gb->setPLMetadataValue($id, $key, $val, $curr_langid); if (PEAR::isError($r)) { if (UI_VERBOSE === TRUE) { - print_r($r); + print_r($r); } $this->Base->_retMsg('Unable to set "$1" to value "$2".', $key, $val); } } if (UI_VERBOSE) { - $this->Base->_retMsg('Metadata saved.'); + $this->Base->_retMsg('Metadata saved.'); } $this->Base->SCRATCHPAD->reloadMetadata(); @@ -459,7 +459,7 @@ class uiPlaylist function isUsedBy($id) { if (($userid = $this->Base->gb->playlistIsAvailable($id, $this->Base->sessid)) !== TRUE) { - return Subjects::GetSubjName($userid); + return Subjects::GetSubjName($userid); } return FALSE; } // fn isUsedBy diff --git a/htmlUI/ui_scratchpad.class.php b/htmlUI/ui_scratchpad.class.php index 23e261393..4593c6178 100644 --- a/htmlUI/ui_scratchpad.class.php +++ b/htmlUI/ui_scratchpad.class.php @@ -1,36 +1,32 @@ 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); @@ -91,8 +87,8 @@ class uiScratchPad else { $gunid = $savedId; if (preg_match('/[0-9]{1,20}/', $gunid)) { - $f = StoredFile::RecallByGunid($gunid); - //$id = BasicStor::IdFromGunid($this->Base->toHex($gunid)); + $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; @@ -134,13 +130,13 @@ class uiScratchPad { if (!$this->Base->STATIONPREFS[UI_SCRATCHPAD_MAXLENGTH_KEY]) { if (UI_WARNING) { - $this->Base->_retMsg('The scratchpad length is not set in system preferences, so it cannot be used.'); + $this->Base->_retMsg('The scratchpad length is not set in system preferences, so it cannot be used.'); } return false; } if (!$ids) { if (UI_WARNING) { - $this->Base->_retMsg('No item(s) selected.'); + $this->Base->_retMsg('No item(s) selected.'); } return FALSE; } @@ -150,16 +146,17 @@ class uiScratchPad $scratchpad = $this->get(); foreach ($ids as $id) { - if($type === 'playlist') + if($type === 'playlist') { $item = $this->Base->getPLMetaInfo($id); - else + } else { $item = $this->Base->getMetaInfo($id); + } foreach ($scratchpad as $key => $val) { if ($val['id'] == $item['id']) { unset($scratchpad[$key]); if (UI_VERBOSE) { - $this->Base->_retMsg('Entry $1 is already on the scratchpad. It has been moved to the top of the list.', $item['title'], $val['added']); + $this->Base->_retMsg('Entry $1 is already on the scratchpad. It has been moved to the top of the list.', $item['title'], $val['added']); } } else { #$this->Base->incAccessCounter($id); @@ -170,11 +167,11 @@ class uiScratchPad $maxScratchpadLength = $this->Base->STATIONPREFS[UI_SCRATCHPAD_MAXLENGTH_KEY]; for ($n = 0; $n < $maxScratchpadLength; $n++) { - if (!isset($scratchpad[$n])) { - break; - } + if (!isset($scratchpad[$n])) { + break; + } if (is_array($scratchpad[$n])) { - $this->items[$n] = $scratchpad[$n]; + $this->items[$n] = $scratchpad[$n]; } } ksort($this->items); @@ -192,7 +189,7 @@ class uiScratchPad { if (!$ids) { if (UI_WARNING) { - $this->Base->_retMsg('No item(s) selected.'); + $this->Base->_retMsg('No item(s) selected.'); } return FALSE; } @@ -232,17 +229,17 @@ class uiScratchPad $curr = $this->order[$by]; $this->order = array(); if (is_null($curr) || $curr=='DESC') { - $this->order[$by] = 'ASC'; + $this->order[$by] = 'ASC'; } else { - $this->order[$by] = 'DESC'; + $this->order[$by] = 'DESC'; } switch ($this->order[$by]) { case "ASC": - asort($s); - break; + asort($s); + break; case "DESC": - arsort($s); - break; + arsort($s); + break; } foreach ($s as $key=>$val) { $res[] = $this->items[$key]; @@ -259,10 +256,11 @@ class uiScratchPad public function reloadMetadata() { foreach ($this->items as $key => $val) { - if($val['type'] === 'playlist') + if ($val['type'] === 'playlist') { $this->items[$key] = $this->Base->getPLMetaInfo($val['id']); - else + } else { $this->items[$key] = $this->Base->getMetaInfo($val['id']); + } } } @@ -277,4 +275,4 @@ class uiScratchPad } } // class uiScratchPad -?> +?> \ No newline at end of file diff --git a/htmlUI/ui_subjects.class.php b/htmlUI/ui_subjects.class.php index 1bcdd2dce..8f1a0b1eb 100644 --- a/htmlUI/ui_subjects.class.php +++ b/htmlUI/ui_subjects.class.php @@ -6,10 +6,10 @@ */ class uiSubjects { - public $Base; - private $reloadUrl; - private $suRedirUrl; - private $redirUrl; + public $Base; + private $reloadUrl; + private $suRedirUrl; + private $redirUrl; public function __construct(&$uiBase) { @@ -22,19 +22,19 @@ class uiSubjects public function setReload() { - $this->Base->redirUrl = $this->reloadUrl; + $this->Base->redirUrl = $this->reloadUrl; } public function setSuRedir() { - $this->Base->redirUrl = $this->suRedirUrl; + $this->Base->redirUrl = $this->suRedirUrl; } public function setRedir() { - $this->Base->redirUrl = $this->redirUrl; + $this->Base->redirUrl = $this->redirUrl; } @@ -62,15 +62,15 @@ class uiSubjects } - /** - * Create a new user or group (empty password => create group). - * - * @param array $request - * Must have keys -> value: - * login - string - * passwd - string - * @return string - */ + /** + * Create a new user or group (empty password => create group). + * + * @param array $request + * Must have keys -> value: + * login - string + * passwd - string + * @return string + */ public function addSubj($request) { include(dirname(__FILE__). '/formmask/subjects.inc.php'); diff --git a/install/install.php b/install/install.php index 45780c181..fe45e0b0b 100644 --- a/install/install.php +++ b/install/install.php @@ -32,22 +32,22 @@ echo " *** Database Installation ***\n"; // Create the database user $command = "sudo -u postgres psql postgres --command \"CREATE USER {$CC_CONFIG['dsn']['username']} " - ." ENCRYPTED PASSWORD '{$CC_CONFIG['dsn']['password']}' LOGIN CREATEDB NOCREATEUSER;\" 2>/dev/null"; +." ENCRYPTED PASSWORD '{$CC_CONFIG['dsn']['password']}' LOGIN CREATEDB NOCREATEUSER;\" 2>/dev/null"; //echo $command."\n"; @exec($command, $output, $results); if ($results == 0) { - echo " * User {$CC_CONFIG['dsn']['username']} created.\n"; + echo " * User {$CC_CONFIG['dsn']['username']} created.\n"; } else { - echo " * User {$CC_CONFIG['dsn']['username']} already exists.\n"; + echo " * User {$CC_CONFIG['dsn']['username']} already exists.\n"; } $command = "sudo -u postgres createdb {$CC_CONFIG['dsn']['database']} --owner {$CC_CONFIG['dsn']['username']} 2> /dev/null"; //echo $command."\n"; @exec($command, $output, $results); if ($results == 0) { - echo " * Database '{$CC_CONFIG['dsn']['database']}' created.\n"; + echo " * Database '{$CC_CONFIG['dsn']['database']}' created.\n"; } else { - echo " * Database '{$CC_CONFIG['dsn']['database']}' already exists.\n"; + echo " * Database '{$CC_CONFIG['dsn']['database']}' already exists.\n"; } // Connect to DB @@ -56,11 +56,11 @@ campcaster_db_connect(true); // Install postgres scripting language $langIsInstalled = $CC_DBC->GetOne('SELECT COUNT(*) FROM pg_language WHERE lanname = \'plpgsql\''); if ($langIsInstalled == '0') { - echo " * Installing Postgres scripting language...\n"; - $sql = "CREATE LANGUAGE 'plpgsql'"; - camp_install_query($sql, false); + echo " * Installing Postgres scripting language...\n"; + $sql = "CREATE LANGUAGE 'plpgsql'"; + camp_install_query($sql, false); } else { - echo " * Postgres scripting language already installed\n"; + echo " * Postgres scripting language already installed\n"; } //------------------------------------------------------------------------------ @@ -249,9 +249,9 @@ if (!camp_db_table_exists($CC_CONFIG['filesTable'])) { camp_install_query($sql, false); -// $sql = "CREATE UNIQUE INDEX ".$CC_CONFIG['filesTable']."_id_idx -// ON ".$CC_CONFIG['filesTable']." (id)"; -// camp_install_query($sql, false); + // $sql = "CREATE UNIQUE INDEX ".$CC_CONFIG['filesTable']."_id_idx + // ON ".$CC_CONFIG['filesTable']." (id)"; + // camp_install_query($sql, false); $sql = "CREATE UNIQUE INDEX ".$CC_CONFIG['filesTable']."_gunid_idx ON ".$CC_CONFIG['filesTable']." (gunid)"; @@ -457,19 +457,19 @@ if (!camp_db_table_exists($CC_CONFIG['transTable'])) { if (!camp_db_table_exists($CC_CONFIG['scheduleTable'])) { echo " * Creating database table ".$CC_CONFIG['scheduleTable']."..."; $sql = "CREATE TABLE ".$CC_CONFIG['scheduleTable']."(" - ." id bigint NOT NULL," - ." playlist_id integer NOT NULL," - ." starts timestamp without time zone NOT NULL," - ." ends timestamp without time zone NOT NULL," - ." group_id integer," - ." file_id integer," - ." clip_length time without time zone DEFAULT '00:00:00'::time without time zone," - ." fade_in time without time zone DEFAULT '00:00:00'::time without time zone," - ." fade_out time without time zone DEFAULT '00:00:00'::time without time zone," - ." cue_in time without time zone DEFAULT '00:00:00'::time without time zone," - ." cue_out time without time zone DEFAULT '00:00:00'::time without time zone," - ." CONSTRAINT cc_schedule_pkey PRIMARY KEY (id)," - ." CONSTRAINT unique_id UNIQUE (id))"; + ." id bigint NOT NULL," + ." playlist_id integer NOT NULL," + ." starts timestamp without time zone NOT NULL," + ." ends timestamp without time zone NOT NULL," + ." group_id integer," + ." file_id integer," + ." clip_length time without time zone DEFAULT '00:00:00'::time without time zone," + ." fade_in time without time zone DEFAULT '00:00:00'::time without time zone," + ." fade_out time without time zone DEFAULT '00:00:00'::time without time zone," + ." cue_in time without time zone DEFAULT '00:00:00'::time without time zone," + ." cue_out time without time zone DEFAULT '00:00:00'::time without time zone," + ." CONSTRAINT cc_schedule_pkey PRIMARY KEY (id)," + ." CONSTRAINT unique_id UNIQUE (id))"; camp_install_query($sql); } else { @@ -477,11 +477,11 @@ if (!camp_db_table_exists($CC_CONFIG['scheduleTable'])) { } if (!camp_db_sequence_exists("schedule_group_id_seq")) { - echo " * Creating sequence 'schedule_group_id_seq'..."; - $sql = "CREATE SEQUENCE schedule_group_id_seq"; - camp_install_query($sql); + echo " * Creating sequence 'schedule_group_id_seq'..."; + $sql = "CREATE SEQUENCE schedule_group_id_seq"; + camp_install_query($sql); } else { - echo " * Skipping: sequence already exists 'schedule_group_id_seq'.\n"; + echo " * Skipping: sequence already exists 'schedule_group_id_seq'.\n"; } if (!camp_db_table_exists($CC_CONFIG['backupTable'])) { @@ -524,8 +524,8 @@ if (!camp_db_table_exists($CC_CONFIG['prefTable'])) { echo " * Inserting starting data into table ".$CC_CONFIG['prefTable']."..."; $stPrefGr = Subjects::GetSubjId($CC_CONFIG['StationPrefsGr']); Prefs::Insert($CC_CONFIG["systemPrefId"], 'stationName', "Radio Station 1"); -// $genres = file_get_contents( dirname(__FILE__).'/../genres.xml'); -// Prefs::Insert($CC_CONFIG["systemPrefId"], 'genres', $genres); + // $genres = file_get_contents( dirname(__FILE__).'/../genres.xml'); + // Prefs::Insert($CC_CONFIG["systemPrefId"], 'genres', $genres); echo "done.\n"; } else { echo " * Skipping: database table already exists: ".$CC_CONFIG['prefTable']."\n"; diff --git a/install/installInit.php b/install/installInit.php index 5869a831f..20d7d54b2 100644 --- a/install/installInit.php +++ b/install/installInit.php @@ -73,14 +73,14 @@ function install_setDirPermissions($filePath) { $fileGroup = filegroup($CC_CONFIG["smartyTemplateCompiled"]); $groupOwner = (function_exists('posix_getgrgid'))?@posix_getgrgid($fileGroup):''; if (!empty($groupOwner) && ($groupOwner["name"] != $CC_CONFIG["webServerUser"])) { - echo " * Error: Your directory permissions for {$filePath} are not set correctly.
    \n"; - echo " * The group perms need to be set to the web server user, in this case '{$CC_CONFIG['webServerUser']}'.
    \n"; - echo " * Currently the group is set to be '{$groupOwner['name']}'.
    \n"; - exit(1); + echo " * Error: Your directory permissions for {$filePath} are not set correctly.
    \n"; + echo " * The group perms need to be set to the web server user, in this case '{$CC_CONFIG['webServerUser']}'.
    \n"; + echo " * Currently the group is set to be '{$groupOwner['name']}'.
    \n"; + exit(1); } if (!($fileperms & 0x0400)) { - echo " * Error: Sticky bit not set for {$filePath}.
    \n"; - exit(1); + echo " * Error: Sticky bit not set for {$filePath}.
    \n"; + exit(1); } } diff --git a/utils/CleanStor.php b/utils/CleanStor.php index 7099944a8..ac9359aee 100644 --- a/utils/CleanStor.php +++ b/utils/CleanStor.php @@ -16,9 +16,9 @@ require_once('../backend/StoredFile.php'); function printUsage() { - global $CC_CONFIG; + global $CC_CONFIG; - echo "Usage:\n"; + echo "Usage:\n"; echo " ./CleanStor [OPTION] \n"; echo "\n"; echo "Options:\n"; @@ -31,33 +31,33 @@ function printUsage() { } function camp_clean_files($p_path) { - if (!empty($p_path) && (strlen($p_path) > 4)) { + if (!empty($p_path) && (strlen($p_path) > 4)) { list($dirList,$fileList) = File_Find::maptree($p_path); $array_mus; foreach ($fileList as $filepath) { - if (@substr($filepath, strlen($filepath) - 3) != "xml") { - $array_mus[] = $filepath; - } + if (@substr($filepath, strlen($filepath) - 3) != "xml") { + $array_mus[] = $filepath; + } } foreach ($array_mus as $audio_file) { - if (@is_link($audio_file) && !@stat($audio_file)) { + if (@is_link($audio_file) && !@stat($audio_file)) { - //filesystem clean up. - @unlink($audio_file); - echo "unlinked $audio_file\n"; - @unlink($audio_file . ".xml"); - echo "unlinked " . $audio_file . ".xml\n"; - @rmdir(@dirname($audio_file)); - echo "removed dir " . @dirname($audio_file) . "\n"; + //filesystem clean up. + @unlink($audio_file); + echo "unlinked $audio_file\n"; + @unlink($audio_file . ".xml"); + echo "unlinked " . $audio_file . ".xml\n"; + @rmdir(@dirname($audio_file)); + echo "removed dir " . @dirname($audio_file) . "\n"; - //database clean up. - $stored_audio_file = StoredFile::RecallByGunid(@basename($audio_file)); - $stored_audio_file->delete(); - } + //database clean up. + $stored_audio_file = StoredFile::RecallByGunid(@basename($audio_file)); + $stored_audio_file->delete(); + } } } @@ -69,8 +69,8 @@ function camp_remove_files($p_path) { list($dirList,$fileList) = File_Find::maptree($p_path); foreach ($fileList as $filepath) { - echo " * Removing $filepath\n"; - @unlink($filepath); + echo " * Removing $filepath\n"; + @unlink($filepath); echo "done.\n"; } foreach ($dirList as $dirpath) { @@ -82,18 +82,18 @@ function camp_remove_files($p_path) { } function camp_empty_db($db) { - global $CC_CONFIG; + global $CC_CONFIG; - if (!PEAR::isError($db)) { - if (camp_db_table_exists($CC_CONFIG['filesTable'])) { - echo " * Deleting from database table ".$CC_CONFIG['filesTable']."\n"; - $sql = "DELETE FROM ".$CC_CONFIG['filesTable']; - camp_install_query($sql, false); - } - else { - echo " * Skipping: database table ".$CC_CONFIG['filesTable']."\n"; - } - } + if (!PEAR::isError($db)) { + if (camp_db_table_exists($CC_CONFIG['filesTable'])) { + echo " * Deleting from database table ".$CC_CONFIG['filesTable']."\n"; + $sql = "DELETE FROM ".$CC_CONFIG['filesTable']; + camp_install_query($sql, false); + } + else { + echo " * Skipping: database table ".$CC_CONFIG['filesTable']."\n"; + } + } } @@ -104,17 +104,17 @@ $CC_DBC->setFetchMode(DB_FETCHMODE_ASSOC); switch($argv[1]){ - case '-e': - case '--empty': - camp_empty_db($CC_DBC); - camp_remove_files($CC_CONFIG['storageDir']); - break; - case '-c': - case '--clean': - camp_clean_files($CC_CONFIG['storageDir']); - break; - default: - printUsage(); + case '-e': + case '--empty': + camp_empty_db($CC_DBC); + camp_remove_files($CC_CONFIG['storageDir']); + break; + case '-c': + case '--clean': + camp_clean_files($CC_CONFIG['storageDir']); + break; + default: + printUsage(); } diff --git a/utils/campcaster-backup.php b/utils/campcaster-backup.php index 9443f60c5..596d156b3 100644 --- a/utils/campcaster-backup.php +++ b/utils/campcaster-backup.php @@ -20,18 +20,18 @@ $stid = $bs->storId; function admDumpFolder(&$bs, $fid, $ind='') { - // NOTE: need to fix this, removed due to tree removal -// $name = M2tree::GetObjName($fid); -// if (PEAR::isError($name)) { -// echo $name->getMessage(); -// exit; -// } + // NOTE: need to fix this, removed due to tree removal + // $name = M2tree::GetObjName($fid); + // if (PEAR::isError($name)) { + // echo $name->getMessage(); + // exit; + // } $media = StoredFile::Recall($fid); $type = $media->getType(); $gunid = $media->getGunid(); $pars = array(); if ($gunid) { - $pars['id']="$gunid"; + $pars['id']="$gunid"; } $pars['name'] = "$name"; switch ($type) { @@ -65,13 +65,13 @@ function admDumpGroup(&$bs, $gid, $ind='') { $name = Subjects::GetSubjName($gid); if (PEAR::isError($name)) { - echo $name->getMessage(); - exit; + echo $name->getMessage(); + exit; } $isGr = Subjects::IsGroup($gid); if (PEAR::isError($isGr)) { - echo $isGr->getMessage(); - exit; + echo $isGr->getMessage(); + exit; } $pars = array('name'=>"$name"); $pars['id'] = $gid; @@ -84,8 +84,8 @@ function admDumpGroup(&$bs, $gid, $ind='') } $garr = Subjects::ListGroup($gid); if (PEAR::isError($garr)) { - echo $garr->getMessage(); - exit; + echo $garr->getMessage(); + exit; } $res = ''; foreach ($garr as $i => $member) { @@ -99,98 +99,98 @@ function admDumpGroup(&$bs, $gid, $ind='') ); $prefs = admDumpPrefs($bs, $gid); if (!is_null($prefs)) { - $res .= $prefs; + $res .= $prefs; } if ($res) { - $tagarr['content'] = $res; + $tagarr['content'] = $res; } return XML_Util::createTagFromArray($tagarr, $res === ''); -// if (!$res) { -// } else { -// return XML_Util::createTagFromArray(array( -// 'namespace' => NSPACE, -// 'localPart' => 'group', -// 'attributes'=> $pars, -// 'content' => $res, -// ), FALSE); -// } + // if (!$res) { + // } else { + // return XML_Util::createTagFromArray(array( + // 'namespace' => NSPACE, + // 'localPart' => 'group', + // 'attributes'=> $pars, + // 'content' => $res, + // ), FALSE); + // } -} -function admDumpSubjects(&$bs, $ind='') -{ - $res =''; - $subjs = Subjects::GetSubjects('id, login, pass, type'); - foreach ($subjs as $i => $member) { - switch ($member['type']) { - case "U": - $prefs = admDumpPrefs($bs, $member['id']); - $pars = array('login'=>"{$member['login']}", 'pass'=>"{$member['pass']}"); - $pars['id'] = $member['id']; - $tagarr = array( + } + function admDumpSubjects(&$bs, $ind='') + { + $res =''; + $subjs = Subjects::GetSubjects('id, login, pass, type'); + foreach ($subjs as $i => $member) { + switch ($member['type']) { + case "U": + $prefs = admDumpPrefs($bs, $member['id']); + $pars = array('login'=>"{$member['login']}", 'pass'=>"{$member['pass']}"); + $pars['id'] = $member['id']; + $tagarr = array( 'namespace' => NSPACE, 'localPart' => 'user', 'attributes'=> $pars, - ); - if (!is_null($prefs)) { - $tagarr['content'] = $prefs; - } - $res .= XML_Util::createTagFromArray($tagarr , FALSE); - break; - case "G": - $res .= admDumpGroup($bs, $member['id'], "$ind "); - break; + ); + if (!is_null($prefs)) { + $tagarr['content'] = $prefs; + } + $res .= XML_Util::createTagFromArray($tagarr , FALSE); + break; + case "G": + $res .= admDumpGroup($bs, $member['id'], "$ind "); + break; + } } - } -# return "$ind\n$res$ind\n"; - return XML_Util::createTagFromArray(array( + # return "$ind\n$res$ind\n"; + return XML_Util::createTagFromArray(array( 'namespace' => NSPACE, 'localPart' => 'subjects', 'content'=> $res, - ), FALSE); -} + ), FALSE); + } -function admDumpPrefs(&$bs, $subjid) -{ - $res =''; - $pr = new Prefs($bs); - $prefkeys = $pr->readKeys($subjid); -# var_dump($subjid); var_dump($prefkeys); #exit; - foreach ($prefkeys as $i => $prefk) { - $keystr = $prefk['keystr']; - $prefval = $pr->readVal($subjid, $keystr); - $pars = array('name'=>"$keystr", 'val'=>"$prefval"); - $res .= XML_Util::createTagFromArray(array( + function admDumpPrefs(&$bs, $subjid) + { + $res =''; + $pr = new Prefs($bs); + $prefkeys = $pr->readKeys($subjid); + # var_dump($subjid); var_dump($prefkeys); #exit; + foreach ($prefkeys as $i => $prefk) { + $keystr = $prefk['keystr']; + $prefval = $pr->readVal($subjid, $keystr); + $pars = array('name'=>"$keystr", 'val'=>"$prefval"); + $res .= XML_Util::createTagFromArray(array( 'namespace' => NSPACE, 'localPart' => 'pref', 'attributes'=> $pars, - )); - } - if (!$res) { - return NULL; - } - return XML_Util::createTagFromArray(array( + )); + } + if (!$res) { + return NULL; + } + return XML_Util::createTagFromArray(array( 'namespace' => NSPACE, 'localPart' => 'preferences', 'content'=> $res, - ), FALSE); -} + ), FALSE); + } -$subjects = admDumpSubjects($bs, ' '); -$tree = admDumpFolder($bs, $stid, ' '); + $subjects = admDumpSubjects($bs, ' '); + $tree = admDumpFolder($bs, $stid, ' '); -$res = XML_Util::getXMLDeclaration("1.0", "UTF-8")."\n"; -$node = XML_Util::createTagFromArray(array( + $res = XML_Util::getXMLDeclaration("1.0", "UTF-8")."\n"; + $node = XML_Util::createTagFromArray(array( 'namespace' => NSPACE, 'localPart' => 'storageServer', 'content' => "$subjects$tree", -), FALSE); -$res .= $node; + ), FALSE); + $res .= $node; -$fmt = new XML_Beautifier(); -$res = $fmt->formatString($res); + $fmt = new XML_Beautifier(); + $res = $fmt->formatString($res); -#var_export($res); -#var_dump($res); -echo "$res"; + #var_export($res); + #var_dump($res); + echo "$res"; -?> \ No newline at end of file + ?> \ No newline at end of file diff --git a/utils/campcaster-import.php b/utils/campcaster-import.php index 05459acb1..77f2223b0 100644 --- a/utils/campcaster-import.php +++ b/utils/campcaster-import.php @@ -26,7 +26,7 @@ function camp_import_error_handler() function printUsage() { - global $CC_CONFIG; + global $CC_CONFIG; echo "There are two ways to import audio files into Campcaster: linking\n"; echo "or copying.\n"; echo "\n"; @@ -71,11 +71,11 @@ function import_err($p_pearErrorObj, $txt='') { global $g_errors; if (PEAR::isError($p_pearErrorObj)) { - $msg = $p_pearErrorObj->getMessage()." ".$p_pearErrorObj->getUserInfo(); + $msg = $p_pearErrorObj->getMessage()." ".$p_pearErrorObj->getUserInfo(); } echo "\nERROR: $msg\n"; if (!empty($txt)) { - echo "ERROR: $txt\n"; + echo "ERROR: $txt\n"; } $g_errors++; } @@ -174,20 +174,20 @@ function camp_import_audio_file($p_filepath, $p_importMode = null, $p_testOnly = global $g_errors; $g_errors++; echo "ERROR: $p_filepath\n" - ." When importing with the '--link' option, files must be set\n" - ." world-readable. The file permissions for the file cannot be\n" - ." changed. Check that you are not trying to import from a FAT32\n" - ." drive. Otherwise, this problem might be fixed by running this \n" - ." script with 'sudo'.\n"; + ." When importing with the '--link' option, files must be set\n" + ." world-readable. The file permissions for the file cannot be\n" + ." changed. Check that you are not trying to import from a FAT32\n" + ." drive. Otherwise, this problem might be fixed by running this \n" + ." script with 'sudo'.\n"; return; } } } -// $timeBegin = microtime(true); + // $timeBegin = microtime(true); $md5sum = md5_file($p_filepath); -// $timeEnd = microtime(true); -// echo " * MD5 time: ".($timeEnd-$timeBegin)."\n"; + // $timeEnd = microtime(true); + // echo " * MD5 time: ".($timeEnd-$timeBegin)."\n"; // Look up md5sum in database $duplicate = StoredFile::RecallByMd5($md5sum); @@ -211,9 +211,9 @@ function camp_import_audio_file($p_filepath, $p_importMode = null, $p_testOnly = ); $storedFile = StoredFile::Insert($values, $doCopyFiles); if (PEAR::isError($storedFile)) { - import_err($storedFile, "Error in StoredFile::Insert()"); - echo var_export($metadata)."\n"; - return; + import_err($storedFile, "Error in StoredFile::Insert()"); + echo var_export($metadata)."\n"; + return; } } else { echo "==========================================================================\n"; @@ -250,8 +250,8 @@ if ($DEBUG_IMPORT) { PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, "camp_import_error_handler"); $CC_DBC = DB::connect($dsn, TRUE); if (PEAR::isError($CC_DBC)) { - echo "ERROR: ".$CC_DBC->getMessage()." ".$CC_DBC->getUserInfo()."\n"; - exit(1); + echo "ERROR: ".$CC_DBC->getMessage()." ".$CC_DBC->getUserInfo()."\n"; + exit(1); } $CC_DBC->setFetchMode(DB_FETCHMODE_ASSOC); @@ -308,8 +308,8 @@ if (is_null($importMode)) { global $CC_CONFIG; if (!is_writable($CC_CONFIG["storageDir"])) { - echo "ERROR: You do not have write permissions to the directory you are trying to import to:\n " . $CC_CONFIG["storageDir"] . "\n\n"; - exit; + echo "ERROR: You do not have write permissions to the directory you are trying to import to:\n " . $CC_CONFIG["storageDir"] . "\n\n"; + exit; } global $g_fileCount; @@ -335,9 +335,9 @@ if (is_array($files)) { $end = intval(date('U')); $time = $end - $start; if ($time > 0) { - $speed = round(($g_fileCount+$g_duplicates)/$time, 1); + $speed = round(($g_fileCount+$g_duplicates)/$time, 1); } else { - $speed = ($g_fileCount+$g_duplicates); + $speed = ($g_fileCount+$g_duplicates); } echo "==========================================================================\n";