Fixed whitespace to standard coding conventions.

This commit is contained in:
paul.baranowski 2010-11-18 14:39:03 -05:00
parent 52fe579ce4
commit 8014f94c58
35 changed files with 6072 additions and 6070 deletions

View File

@ -6,17 +6,17 @@ require_once('../backend/Schedule.php');
$api_key = $_GET['api_key']; $api_key = $_GET['api_key'];
if(!in_array($api_key, $CC_CONFIG["apiKey"])) if(!in_array($api_key, $CC_CONFIG["apiKey"]))
{ {
header('HTTP/1.0 401 Unauthorized'); header('HTTP/1.0 401 Unauthorized');
print 'You are not allowed to access this resource.'; print 'You are not allowed to access this resource.';
exit; exit;
} }
PEAR::setErrorHandling(PEAR_ERROR_RETURN); PEAR::setErrorHandling(PEAR_ERROR_RETURN);
$CC_DBC = DB::connect($CC_CONFIG['dsn'], TRUE); $CC_DBC = DB::connect($CC_CONFIG['dsn'], TRUE);
if (PEAR::isError($CC_DBC)) { if (PEAR::isError($CC_DBC)) {
echo "ERROR: ".$CC_DBC->getMessage()." ".$CC_DBC->getUserInfo()."\n"; echo "ERROR: ".$CC_DBC->getMessage()." ".$CC_DBC->getUserInfo()."\n";
exit(1); exit(1);
} }
$CC_DBC->setFetchMode(DB_FETCHMODE_ASSOC); $CC_DBC->setFetchMode(DB_FETCHMODE_ASSOC);
$from = $_GET["from"]; $from = $_GET["from"];

View File

@ -26,22 +26,22 @@ class AccessRecur {
$ppa = new AccessRecur($ls, $sessid); $ppa = new AccessRecur($ls, $sessid);
$r = $ls->accessPlaylist($sessid, $plid, FALSE, $parent); $r = $ls->accessPlaylist($sessid, $plid, FALSE, $parent);
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
} }
$plRes = $r; $plRes = $r;
$r = StoredFile::RecallByGunid($plid); $r = StoredFile::RecallByGunid($plid);
if (is_null($r) || PEAR::isError($r)) { if (is_null($r) || PEAR::isError($r)) {
return $r; return $r;
} }
$ac = $r; $ac = $r;
$r = $ac->md->genPhpArray(); $r = $ac->md->genPhpArray();
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
} }
$pla = $r; $pla = $r;
$r = $ppa->processPlaylist($pla, $plRes['token']); $r = $ppa->processPlaylist($pla, $plRes['token']);
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
} }
$plRes['content'] = $r; $plRes['content'] = $r;
return $plRes; return $plRes;
@ -58,14 +58,14 @@ class AccessRecur {
WHERE parent=x'{$token}'::bigint WHERE parent=x'{$token}'::bigint
"); ");
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
} }
$arr = $r; $arr = $r;
foreach ($arr as $i => $item) { foreach ($arr as $i => $item) {
extract($item); // token2, gunid extract($item); // token2, gunid
$r = BasicStor::GetType($gunid); $r = BasicStor::GetType($gunid);
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
} }
$ftype = $r; $ftype = $r;
# echo "$ftype/$token2\n"; # echo "$ftype/$token2\n";
@ -73,23 +73,23 @@ class AccessRecur {
case "audioclip": case "audioclip":
$r = $ppa->ls->releaseRawAudioData($ppa->sessid, $token2); $r = $ppa->ls->releaseRawAudioData($ppa->sessid, $token2);
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
} }
# var_dump($r); # var_dump($r);
break; break;
case "playlist": case "playlist":
$r = $ppa->releasePlaylist($ppa->ls, $ppa->sessid, $token2); $r = $ppa->releasePlaylist($ppa->ls, $ppa->sessid, $token2);
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
} }
# var_dump($r); # var_dump($r);
break; break;
default: default:
} }
} }
$r = $ppa->ls->releasePlaylist($ppa->sessid, $token, FALSE); $r = $ppa->ls->releasePlaylist($ppa->sessid, $token, FALSE);
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
} }
return $r; return $r;
} }
@ -103,11 +103,11 @@ class AccessRecur {
case "playlistElement": case "playlistElement":
$r = $this->processPlaylistElement($ple, $parent); $r = $this->processPlaylistElement($ple, $parent);
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
} }
// $res = array_merge($res, $r); // $res = array_merge($res, $r);
$res[] = $r; $res[] = $r;
break; break;
default: default:
} }
} }
@ -119,7 +119,7 @@ class AccessRecur {
{ {
$r = $this->ls->accessRawAudioData($this->sessid, $gunid, $parent); $r = $this->ls->accessRawAudioData($this->sessid, $gunid, $parent);
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
} }
return $r; return $r;
} }
@ -132,48 +132,48 @@ class AccessRecur {
case "audioClip": case "audioClip":
$r = $this->processAudioClip($ac['attrs']['id'], $parent); $r = $this->processAudioClip($ac['attrs']['id'], $parent);
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
} }
return $r; return $r;
case "playlist": case "playlist":
// if(empty($ac['children'])){ // if(empty($ac['children'])){
$r = $this->accessPlaylist($this->ls, $this->sessid, $r = $this->accessPlaylist($this->ls, $this->sessid,
$ac['attrs']['id'], $parent); $ac['attrs']['id'], $parent);
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
if ($r->getCode() != GBERR_NOTF) { if ($r->getCode() != GBERR_NOTF) {
return $r; return $r;
} else { } else {
$r = $this->processPlaylist($ac, $parent); $r = $this->processPlaylist($ac, $parent);
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
} }
$r = array( $r = array(
'content' => $r, 'content' => $r,
'url' => NULL, 'url' => NULL,
'token' => NULL, 'token' => NULL,
'chsum' => NULL, 'chsum' => NULL,
'size' => NULL, 'size' => NULL,
'warning' => 'inline playlist?', '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;
} }
*/ return $r;
break; /*
}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: default:
} }
} }

View File

@ -38,7 +38,7 @@ class Alib {
} }
$userid = Subjects::GetSubjId($login); $userid = Subjects::GetSubjId($login);
$sql = "INSERT INTO ".$CC_CONFIG['sessTable']." (sessid, userid, login, ts)" $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); $r = $CC_DBC->query($sql);
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
@ -60,12 +60,12 @@ class Alib {
$ct = Alib::CheckAuthToken($sessid); $ct = Alib::CheckAuthToken($sessid);
if ($ct === FALSE) { if ($ct === FALSE) {
return PEAR::raiseError("Alib::logout: not logged ($sessid)", return PEAR::raiseError("Alib::logout: not logged ($sessid)",
ALIBERR_NOTLOGGED, PEAR_ERROR_RETURN); ALIBERR_NOTLOGGED, PEAR_ERROR_RETURN);
} elseif (PEAR::isError($ct)) { } elseif (PEAR::isError($ct)) {
return $ct; return $ct;
} else { } else {
$sql = "DELETE FROM ".$CC_CONFIG['sessTable'] $sql = "DELETE FROM ".$CC_CONFIG['sessTable']
." WHERE sessid='$sessid'"; ." WHERE sessid='$sessid'";
$r = $CC_DBC->query($sql); $r = $CC_DBC->query($sql);
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
@ -85,7 +85,7 @@ class Alib {
{ {
global $CC_CONFIG, $CC_DBC; global $CC_CONFIG, $CC_DBC;
$sql = "SELECT count(*) as cnt FROM ".$CC_CONFIG['sessTable'] $sql = "SELECT count(*) as cnt FROM ".$CC_CONFIG['sessTable']
." WHERE sessid='$sessid'"; ." WHERE sessid='$sessid'";
$c = $CC_DBC->getOne($sql); $c = $CC_DBC->getOne($sql);
return ($c == 1 ? TRUE : (PEAR::isError($c) ? $c : FALSE )); return ($c == 1 ? TRUE : (PEAR::isError($c) ? $c : FALSE ));
} //fn checkAuthToken } //fn checkAuthToken
@ -97,18 +97,18 @@ class Alib {
* @param string $sessid * @param string $sessid
* @return TRUE|PEAR_Error * @return TRUE|PEAR_Error
*/ */
// public function setAuthToken($sessid) // public function setAuthToken($sessid)
// { // {
// $r = $this->checkAuthToken($sessid); // $r = $this->checkAuthToken($sessid);
// if (PEAR::isError($r)) { // if (PEAR::isError($r)) {
// return $r; // return $r;
// } // }
// if (!$r) { // if (!$r) {
// return PEAR::raiseError("ALib::setAuthToken: invalid token ($sessid)"); // return PEAR::raiseError("ALib::setAuthToken: invalid token ($sessid)");
// } // }
// //$this->sessid = $sessid; // //$this->sessid = $sessid;
// return TRUE; // return TRUE;
// } // fn setAuthToken // } // fn setAuthToken
/* -------------------------------------------------------- authorization */ /* -------------------------------------------------------- authorization */
@ -130,7 +130,7 @@ class Alib {
global $CC_CONFIG, $CC_DBC; global $CC_CONFIG, $CC_DBC;
$permid = $CC_DBC->nextId($CC_CONFIG['permSequence']); $permid = $CC_DBC->nextId($CC_CONFIG['permSequence']);
$sql = "INSERT INTO ".$CC_CONFIG['permTable']." (permid, subj, action, obj, type)" $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); $r = $CC_DBC->query($sql);
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return($r); return($r);
@ -213,85 +213,85 @@ class Alib {
*/ */
public static function CheckPerm($sid, $action, $oid=NULL) public static function CheckPerm($sid, $action, $oid=NULL)
{ {
return TRUE; return TRUE;
// global $CC_DBC; // global $CC_DBC;
// global $CC_CONFIG; // global $CC_CONFIG;
// if (!is_numeric($sid)) { // if (!is_numeric($sid)) {
// return FALSE; // return FALSE;
// } // }
//// if (is_null($oid) or $oid=='') { //// if (is_null($oid) or $oid=='') {
//// $oid = M2tree::GetRootNode(); //// $oid = M2tree::GetRootNode();
//// } //// }
//// if (PEAR::isError($oid)) { //// if (PEAR::isError($oid)) {
//// return $oid; //// return $oid;
//// } //// }
// if (!is_numeric($oid)) { // if (!is_numeric($oid)) {
// return FALSE; // return FALSE;
// } // }
// // query construction // // query construction
// // shortcuts: // // shortcuts:
// // p: permTable, // // p: permTable,
// // s: subjTable, m smembTable, // // s: subjTable, m smembTable,
// // t: treeTable ts: structTable, // // t: treeTable ts: structTable,
// // c: classTable, cm: cmembTable // // c: classTable, cm: cmembTable
// // main query elements: // // main query elements:
// $q_flds = "m.level , p.subj, s.login, action, p.type, p.obj"; // $q_flds = "m.level , p.subj, s.login, action, p.type, p.obj";
// $q_from = $CC_CONFIG['permTable']." p "; // $q_from = $CC_CONFIG['permTable']." p ";
// // joins for solving users/groups: // // joins for solving users/groups:
// $q_join = "LEFT JOIN ".$CC_CONFIG['subjTable']." s ON s.id=p.subj "; // $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_join .= "LEFT JOIN ".$CC_CONFIG['smembTable']." m ON m.gid=p.subj ";
// $q_cond = "p.action in('_all', '$action') AND // $q_cond = "p.action in('_all', '$action') AND
// (s.id=$sid OR m.uid=$sid) "; // (s.id=$sid OR m.uid=$sid) ";
// // coalesce -1 for higher priority of nongroup rows: // // coalesce -1 for higher priority of nongroup rows:
// // action DESC order for lower priority of '_all': // // action DESC order for lower priority of '_all':
// $q_ordb = "ORDER BY coalesce(m.level,-1), action DESC, p.type DESC"; // $q_ordb = "ORDER BY coalesce(m.level,-1), action DESC, p.type DESC";
// $q_flds0 = $q_flds; // $q_flds0 = $q_flds;
// $q_from0 = $q_from; // $q_from0 = $q_from;
// $q_join0 = $q_join; // $q_join0 = $q_join;
// $q_cond0 = $q_cond; // $q_cond0 = $q_cond;
// $q_ordb0 = $q_ordb; // $q_ordb0 = $q_ordb;
// // joins for solving object tree: // // joins for solving object tree:
// $q_flds .= ", t.name, ts.level as tlevel"; // $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['treeTable']." t ON t.id=p.obj ";
// //$q_join .= "LEFT JOIN ".$CC_CONFIG['structTable']." ts ON ts.parid=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)"; // //$q_cond .= " AND (t.id=$oid OR ts.objid=$oid)";
// // action DESC order is hack for lower priority of '_all': // // 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"; // $q_ordb = "ORDER BY coalesce(ts.level,0), m.level, action DESC, p.type DESC";
// // query by tree: // // query by tree:
// $query1 = "SELECT $q_flds FROM $q_from $q_join WHERE $q_cond $q_ordb"; // $query1 = "SELECT $q_flds FROM $q_from $q_join WHERE $q_cond $q_ordb";
// $r1 = $CC_DBC->getAll($query1); // $r1 = $CC_DBC->getAll($query1);
// if (PEAR::isError($r1)) { // if (PEAR::isError($r1)) {
// return($r1); // return($r1);
// } // }
// // if there is row with type='A' on the top => permit // // if there is row with type='A' on the top => permit
// //$AllowedByTree = // //$AllowedByTree =
// // (is_array($r1) && count($r1)>0 && $r1[0]['type']=='A'); // // (is_array($r1) && count($r1)>0 && $r1[0]['type']=='A');
// //$DeniedByTree = // //$DeniedByTree =
// // (is_array($r1) && count($r1)>0 && $r1[0]['type']=='D'); // // (is_array($r1) && count($r1)>0 && $r1[0]['type']=='D');
// //
// if (!USE_ALIB_CLASSES) { // if (!USE_ALIB_CLASSES) {
// return $AllowedbyTree; // return $AllowedbyTree;
// } // }
// //
// // joins for solving object classes: // // joins for solving object classes:
// $q_flds = $q_flds0.", c.cname "; // $q_flds = $q_flds0.", c.cname ";
// $q_join = $q_join0."LEFT JOIN ".$CC_CONFIG['classTable']." c ON c.id=p.obj "; // $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_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_cond = $q_cond0." AND (c.id=$oid OR cm.objid=$oid)";
// $q_ordb = $q_ordb0; // $q_ordb = $q_ordb0;
// // query by class: // // query by class:
// $query2 = "SELECT $q_flds FROM $q_from $q_join WHERE $q_cond $q_ordb"; // $query2 = "SELECT $q_flds FROM $q_from $q_join WHERE $q_cond $q_ordb";
// $r2 = $CC_DBC->getAll($query2); // $r2 = $CC_DBC->getAll($query2);
// if (PEAR::isError($r2)) { // if (PEAR::isError($r2)) {
// return $r2; // return $r2;
// } // }
// $AllowedByClass = // $AllowedByClass =
// (is_array($r2) && count($r2)>0 && $r2[0]['type']=='A'); // (is_array($r2) && count($r2)>0 && $r2[0]['type']=='A');
// // not used now: // // not used now:
// // $DeniedByClass = // // $DeniedByClass =
// // (is_array($r2) && count($r2)>0 && $r2[0]['type']=='D'); // // (is_array($r2) && count($r2)>0 && $r2[0]['type']=='D');
// $res = ($AllowedByTree || (!$DeniedByTree && $AllowedByClass)); // $res = ($AllowedByTree || (!$DeniedByTree && $AllowedByClass));
// return $res; // return $res;
} // fn CheckPerm } // fn CheckPerm
@ -326,7 +326,7 @@ class Alib {
} }
if (is_null($uid)){ if (is_null($uid)){
return $CC_DBC->raiseError("Alib::removeSubj: Subj not found ($login)", 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); $r = Alib::RemovePerm(NULL, $uid);
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
@ -354,7 +354,7 @@ class Alib {
if (is_null($r)){ if (is_null($r)){
return PEAR::raiseError("Alib::GetSessLogin:". return PEAR::raiseError("Alib::GetSessLogin:".
" invalid session id ($sessid)", " invalid session id ($sessid)",
ALIBERR_NOTEXISTS, PEAR_ERROR_RETURN); ALIBERR_NOTEXISTS, PEAR_ERROR_RETURN);
} }
return $r; return $r;
} // fn GetSessLogin } // fn GetSessLogin
@ -377,7 +377,7 @@ class Alib {
if (is_null($r)) { if (is_null($r)) {
return PEAR::raiseError("Alib::getSessUserId:". return PEAR::raiseError("Alib::getSessUserId:".
" invalid session id ($p_sessid)", " invalid session id ($p_sessid)",
ALIBERR_NOTEXISTS, PEAR_ERROR_RETURN); ALIBERR_NOTEXISTS, PEAR_ERROR_RETURN);
} }
return $r; return $r;
} // fn getSessUserId } // fn getSessUserId
@ -394,7 +394,7 @@ class Alib {
{ {
global $CC_CONFIG, $CC_DBC; global $CC_CONFIG, $CC_DBC;
$sql = "SELECT s.login, p.* FROM ".$CC_CONFIG['permTable']." p, ".$CC_CONFIG['subjTable']." s" $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); return $CC_DBC->getAll($sql);
} // fn GetObjPerms } // fn GetObjPerms
@ -409,11 +409,11 @@ class Alib {
{ {
global $CC_CONFIG, $CC_DBC; global $CC_CONFIG, $CC_DBC;
$sql = "SELECT *" $sql = "SELECT *"
." FROM ".$CC_CONFIG['permTable'] ." FROM ".$CC_CONFIG['permTable']
." WHERE p.subj=$sid"; ." WHERE p.subj=$sid";
// $sql = "SELECT t.name, t.type as otype , p.*" // $sql = "SELECT t.name, t.type as otype , p.*"
// ." FROM ".$CC_CONFIG['permTable']." p, ".$CC_CONFIG['treeTable']." t" // ." FROM ".$CC_CONFIG['permTable']." p, ".$CC_CONFIG['treeTable']." t"
// ." WHERE t.id=p.obj AND p.subj=$sid"; // ." WHERE t.id=p.obj AND p.subj=$sid";
$a1 = $CC_DBC->getAll($sql); $a1 = $CC_DBC->getAll($sql);
return $a1; return $a1;
} // fn GetSubjPerms } // fn GetSubjPerms
@ -463,7 +463,7 @@ class Alib {
for ($c = 1; $c > 0; ){ for ($c = 1; $c > 0; ){
$sessid = md5(uniqid(rand())); $sessid = md5(uniqid(rand()));
$sql = "SELECT count(*) FROM ".$CC_CONFIG['sessTable'] $sql = "SELECT count(*) FROM ".$CC_CONFIG['sessTable']
." WHERE sessid='$sessid'"; ." WHERE sessid='$sessid'";
$c = $CC_DBC->getOne($sql); $c = $CC_DBC->getOne($sql);
if (PEAR::isError($c)) { if (PEAR::isError($c)) {
return $c; return $c;
@ -488,19 +488,19 @@ class Alib {
{ {
global $CC_CONFIG, $CC_DBC; global $CC_CONFIG, $CC_DBC;
$sql = "SELECT s.login, p.action, p.type" $sql = "SELECT s.login, p.action, p.type"
." FROM ".$CC_CONFIG['permTable']." p, ".$CC_CONFIG['subjTable']." s" ." FROM ".$CC_CONFIG['permTable']." p, ".$CC_CONFIG['subjTable']." s"
." WHERE s.id=p.subj" ." WHERE s.id=p.subj"
." ORDER BY p.permid"; ." ORDER BY p.permid";
$arr = $CC_DBC->getAll($sql); $arr = $CC_DBC->getAll($sql);
if (PEAR::isError($arr)) { if (PEAR::isError($arr)) {
return $arr; return $arr;
} }
$r = $ind.join(', ', array_map(create_function('$v', $r = $ind.join(', ', array_map(create_function('$v',
'return "{$v[\'login\']}/{$v[\'action\']}/{$v[\'type\']}";' 'return "{$v[\'login\']}/{$v[\'action\']}/{$v[\'type\']}";'
), ),
$arr $arr
))."\n"; ))."\n";
return $r; return $r;
} // fn dumpPerms } // fn dumpPerms
@ -532,16 +532,16 @@ class Alib {
$s =& $tdata['subjects']; $s =& $tdata['subjects'];
$CC_DBC->setErrorHandling(PEAR_ERROR_PRINT); $CC_DBC->setErrorHandling(PEAR_ERROR_PRINT);
$perms = array( $perms = array(
array($s['root'], '_all', $t['root'], 'A'), array($s['root'], '_all', $t['root'], 'A'),
array($s['test1'], '_all', $t['pa'], 'A'), array($s['test1'], '_all', $t['pa'], 'A'),
array($s['test1'], 'read', $t['s2b'], 'D'), array($s['test1'], 'read', $t['s2b'], 'D'),
array($s['test2'], 'addChilds', $t['pa'], 'D'), array($s['test2'], 'addChilds', $t['pa'], 'D'),
array($s['test2'], 'read', $t['i2'], 'A'), array($s['test2'], 'read', $t['i2'], 'A'),
array($s['test2'], 'edit', $t['s1a'], 'A'), array($s['test2'], 'edit', $t['s1a'], 'A'),
array($s['test1'], 'addChilds', $t['s2a'], 'D'), array($s['test1'], 'addChilds', $t['s2a'], 'D'),
array($s['test1'], 'addChilds', $t['s2c'], 'D'), array($s['test1'], 'addChilds', $t['s2c'], 'D'),
array($s['gr2'], 'addChilds', $t['i2'], 'A'), array($s['gr2'], 'addChilds', $t['i2'], 'A'),
array($s['test3'], '_all', $t['t1'], 'D'), array($s['test3'], '_all', $t['t1'], 'D'),
); );
if (USE_ALIB_CLASSES){ if (USE_ALIB_CLASSES){
$perms[] = array($s['test3'], 'read', $c['cl_sa'], 'D'); $perms[] = array($s['test3'], 'read', $c['cl_sa'], 'D');
@ -587,14 +587,14 @@ class Alib {
return $r; return $r;
} }
$test_dump = $r. $test_dump = $r.
(Alib::CheckPerm( (Alib::CheckPerm(
$tdata['subjects']['test1'], 'read', $tdata['subjects']['test1'], 'read',
$tdata['tree']['t1'] $tdata['tree']['t1']
)? 'yes':'no').", ". )? 'yes':'no').", ".
(Alib::CheckPerm( (Alib::CheckPerm(
$tdata['subjects']['test1'], 'addChilds', $tdata['subjects']['test1'], 'addChilds',
$tdata['tree']['i2'] $tdata['tree']['i2']
)? 'yes':'no')."\n" )? 'yes':'no')."\n"
; ;
Alib::RemovePerm($tdata['perms'][1]); Alib::RemovePerm($tdata['perms'][1]);
Alib::RemovePerm($tdata['perms'][3]); Alib::RemovePerm($tdata['perms'][3]);

View File

@ -132,7 +132,7 @@ class Backup
// get ids (and real filenames) which files match with criteria // get ids (and real filenames) which files match with criteria
$srch = $this->gb->localSearch($this->criteria,$this->sessid); $srch = $this->gb->localSearch($this->criteria,$this->sessid);
if (PEAR::isError($srch)) { if (PEAR::isError($srch)) {
return $srch; return $srch;
} }
$this->setIDs($srch); $this->setIDs($srch);
@ -167,7 +167,7 @@ class Backup
return array('token'=>$this->token); return array('token'=>$this->token);
} else { } else {
return false; return false;
} }
} }
@ -229,7 +229,7 @@ class Backup
unlink($this->statusFile); unlink($this->statusFile);
unlink($this->tmpFile); unlink($this->tmpFile);
if (is_file($this->tmpName)) { if (is_file($this->tmpName)) {
unlink($this->tmpName); unlink($this->tmpName);
} }
return !is_file($this->tmpFile); return !is_file($this->tmpFile);
} }
@ -288,42 +288,42 @@ class Backup
*/ */
private function setFilenames() private function setFilenames()
{ {
// if ($this->loglevel=='debug') { // if ($this->loglevel=='debug') {
// $this->addLogItem("-I- ".date("Ymd-H:i:s")." setFilenames\n"); // $this->addLogItem("-I- ".date("Ymd-H:i:s")." setFilenames\n");
// } // }
// if (is_array($this->ids)) { // if (is_array($this->ids)) {
// foreach ($this->ids as $i => $item) { // foreach ($this->ids as $i => $item) {
// $gunid = $item['gunid']; // $gunid = $item['gunid'];
// // get a stored file object of this gunid // // get a stored file object of this gunid
// $sf = StoredFile::RecallByGunid($gunid); // $sf = StoredFile::RecallByGunid($gunid);
// if (is_null($sf) || PEAR::isError($sf)) { // if (is_null($sf) || PEAR::isError($sf)) {
// return $sf; // return $sf;
// } // }
// $lid = BasicStor::IdFromGunid($gunid); // $lid = BasicStor::IdFromGunid($gunid);
// if (($res = BasicStor::Authorize('read', $lid, $this->sessid)) !== TRUE) { // if (($res = BasicStor::Authorize('read', $lid, $this->sessid)) !== TRUE) {
// $this->addLogItem("-E- ".date("Ymd-H:i:s")." setFilenames - authorize gunid:$gunid\n"); // $this->addLogItem("-E- ".date("Ymd-H:i:s")." setFilenames - authorize gunid:$gunid\n");
// return PEAR::raiseError('Backup::setFilenames : Authorize ... error.'); // return PEAR::raiseError('Backup::setFilenames : Authorize ... error.');
// } // }
// // if the file is a playlist then it has only a meta file // // if the file is a playlist then it has only a meta file
// if (strtolower($sf->md->format) != 'playlist') { // if (strtolower($sf->md->format) != 'playlist') {
// $this->filenames[] = array( // $this->filenames[] = array(
// 'filename' => $sf->getRealFileName(), // 'filename' => $sf->getRealFileName(),
// 'format' => $sf->md->format // 'format' => $sf->md->format
// ); // );
// } // }
// $this->filenames[] = array( // $this->filenames[] = array(
// 'filename' => $sf->getRealMetadataFileName(), // 'filename' => $sf->getRealMetadataFileName(),
// 'format' => $sf->md->format // 'format' => $sf->md->format
// ); // );
// if ($this->loglevel=='debug') { // if ($this->loglevel=='debug') {
// $this->addLogItem("-I- ".date("Ymd-H:i:s")." setFilenames - add file: {$sf->md->format}|".$sf->getRealMetadataFileName()."\n"); // $this->addLogItem("-I- ".date("Ymd-H:i:s")." setFilenames - add file: {$sf->md->format}|".$sf->getRealMetadataFileName()."\n");
// } // }
// } // }
// return $this->filenames; // return $this->filenames;
// } else { // } else {
// $this->addLogItem("-E- ".date("Ymd-H:i:s")." setFilenames - The IDs variable isn't array.\n"); // $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.'); // 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"); $this->addLogItem("-I- ".date("Ymd-H:i:s")." doIt\n");
} }
$command = dirname(__FILe__)."/../bin/backup.sh" $command = dirname(__FILe__)."/../bin/backup.sh"
." {$this->tmpDir}" ." {$this->tmpDir}"
." {$this->tmpFile}" ." {$this->tmpFile}"
." {$this->statusFile}" ." {$this->statusFile}"
." >> {$this->logFile} &"; ." >> {$this->logFile} &";
$res = system("$command"); $res = system("$command");
sleep(2); sleep(2);
if ($this->loglevel=='debug') { if ($this->loglevel=='debug') {
@ -438,7 +438,7 @@ class Backup
{ {
$acc = BasicStor::bsAccess($this->tmpFile, BACKUP_EXT, null, ACCESS_TYPE); $acc = BasicStor::bsAccess($this->tmpFile, BACKUP_EXT, null, ACCESS_TYPE);
if (PEAR::isError($acc)) { if (PEAR::isError($acc)) {
return $acc; return $acc;
} }
$this->token = $acc['token']; $this->token = $acc['token'];
} }
@ -484,4 +484,4 @@ class Backup
} }
} // classs Backup } // classs Backup
?> ?>

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -50,7 +50,7 @@ class LocStor extends BasicStor {
* {url:writable URL for HTTP PUT, token:access token} * {url:writable URL for HTTP PUT, token:access token}
*/ */
protected function storeAudioClipOpen($sessid, $gunid, $metadata, protected function storeAudioClipOpen($sessid, $gunid, $metadata,
$fname, $chsum, $ftype='audioclip') $fname, $chsum, $ftype='audioclip')
{ {
// Check the gunid format // Check the gunid format
if (!BasicStor::CheckGunid($gunid)) { if (!BasicStor::CheckGunid($gunid)) {
@ -79,7 +79,7 @@ class LocStor extends BasicStor {
if ($storedFile->isAccessed()) { if ($storedFile->isAccessed()) {
return PEAR::raiseError( return PEAR::raiseError(
'LocStor::storeAudioClipOpen: is accessed' 'LocStor::storeAudioClipOpen: is accessed'
); );
} }
$res = $storedFile->replace($oid, $storedFile->getName(), '', $metadata, 'string'); $res = $storedFile->replace($oid, $storedFile->getName(), '', $metadata, 'string');
if (PEAR::isError($res)) { if (PEAR::isError($res)) {
@ -182,7 +182,7 @@ class LocStor extends BasicStor {
protected function storeWebstream($sessid, $gunid, $metadata, $fname, $url) protected function storeWebstream($sessid, $gunid, $metadata, $fname, $url)
{ {
$a = $this->storeAudioClipOpen( $a = $this->storeAudioClipOpen(
$sessid, $gunid, $metadata, $fname, md5(''), 'webstream'); $sessid, $gunid, $metadata, $fname, md5(''), 'webstream');
if (PEAR::isError($a)) { if (PEAR::isError($a)) {
return $a; return $a;
} }
@ -267,7 +267,7 @@ class LocStor extends BasicStor {
if (is_null($id) || !$ex) { if (is_null($id) || !$ex) {
return PEAR::raiseError( return PEAR::raiseError(
"LocStor::downloadRawAudioDataOpen: gunid not found ($gunid)", "LocStor::downloadRawAudioDataOpen: gunid not found ($gunid)",
GBERR_NOTF GBERR_NOTF
); );
} }
if (($res = BasicStor::Authorize('read', $id, $sessid)) !== TRUE) { if (($res = BasicStor::Authorize('read', $id, $sessid)) !== TRUE) {
@ -304,8 +304,8 @@ class LocStor extends BasicStor {
*/ */
protected function downloadMetadataOpen($sessid, $gunid) protected function downloadMetadataOpen($sessid, $gunid)
{ {
// $res = $this->existsAudioClip($sessid, $gunid); // $res = $this->existsAudioClip($sessid, $gunid);
// if(PEAR::isError($res)) return $res; // if(PEAR::isError($res)) return $res;
$media = StoredFile::RecallByGunid($gunid) $media = StoredFile::RecallByGunid($gunid)
$id = $media->getGunid(); $id = $media->getGunid();
if (is_null($id)) { if (is_null($id)) {
@ -414,7 +414,7 @@ class LocStor extends BasicStor {
* </li> * </li>
* </ul> * </ul>
* @see BasicStor::localSearch * @see BasicStor::localSearch
*/ */
public function searchMetadata($sessid, $criteria) public function searchMetadata($sessid, $criteria)
{ {
if (($res = BasicStor::Authorize('read', $this->storId, $sessid)) !== TRUE) { if (($res = BasicStor::Authorize('read', $this->storId, $sessid)) !== TRUE) {
@ -592,7 +592,7 @@ class LocStor extends BasicStor {
if ($ex) { if ($ex) {
return PEAR::raiseError( return PEAR::raiseError(
'LocStor::createPlaylist: already exists' 'LocStor::createPlaylist: already exists'
); );
} }
$tmpFname = uniqid(''); $tmpFname = uniqid('');
if (($res = BasicStor::Authorize('write', null, $sessid)) !== TRUE) { if (($res = BasicStor::Authorize('write', null, $sessid)) !== TRUE) {
@ -608,7 +608,7 @@ class LocStor extends BasicStor {
$fname = "newFile.xml"; $fname = "newFile.xml";
} }
$storedFile->setName($fname); $storedFile->setName($fname);
$storedFile->setState('ready'); $storedFile->setState('ready');
$storedFile->setMime('application/smil'); $storedFile->setMime('application/smil');
return $storedFile->gunid; return $storedFile->gunid;
} }
@ -634,12 +634,12 @@ class LocStor extends BasicStor {
if (!$ex) { if (!$ex) {
return PEAR::raiseError( return PEAR::raiseError(
'LocStor::editPlaylist: playlist not exists' 'LocStor::editPlaylist: playlist not exists'
); );
} }
if ($this->isEdited($playlistId) !== FALSE) { if ($this->isEdited($playlistId) !== FALSE) {
return PEAR::raiseError( return PEAR::raiseError(
'LocStor::editPlaylist: playlist already edited' 'LocStor::editPlaylist: playlist already edited'
); );
} }
$storedFile =& StoredFile::RecallByGunid($playlistId); $storedFile =& StoredFile::RecallByGunid($playlistId);
if (is_null($storedFile) || PEAR::isError($storedFile)) { if (is_null($storedFile) || PEAR::isError($storedFile)) {
@ -753,7 +753,7 @@ class LocStor extends BasicStor {
} }
return PEAR::raiseError( return PEAR::raiseError(
'LocStor::deletePlaylist: playlist not exists', 'LocStor::deletePlaylist: playlist not exists',
GBERR_FILENEX GBERR_FILENEX
); );
} }
$storedFile =& StoredFile::RecallByGunid($playlistId); $storedFile =& StoredFile::RecallByGunid($playlistId);
@ -791,32 +791,32 @@ class LocStor extends BasicStor {
* } * }
*/ */
public function accessPlaylist($sessid, $playlistId, $recursive=FALSE, $parent='0') public function accessPlaylist($sessid, $playlistId, $recursive=FALSE, $parent='0')
// { // {
// if ($recursive) { // if ($recursive) {
// require_once("AccessRecur.php"); // require_once("AccessRecur.php");
// $r = AccessRecur::accessPlaylist($this, $sessid, $playlistId); // $r = AccessRecur::accessPlaylist($this, $sessid, $playlistId);
// if (PEAR::isError($r)) { // if (PEAR::isError($r)) {
// return $r; // return $r;
// } // }
// return $r; // return $r;
// } // }
// $ex = $this->existsPlaylist($sessid, $playlistId); // $ex = $this->existsPlaylist($sessid, $playlistId);
// if (PEAR::isError($ex)) { // if (PEAR::isError($ex)) {
// return $ex; // return $ex;
// } // }
// if (!$ex) { // if (!$ex) {
// return PEAR::raiseError( // return PEAR::raiseError(
// "LocStor::accessPlaylist: playlist not found ($playlistId)", // "LocStor::accessPlaylist: playlist not found ($playlistId)",
// GBERR_NOTF // GBERR_NOTF
// ); // );
// } // }
// $id = BasicStor::IdFromGunid($playlistId); // $id = BasicStor::IdFromGunid($playlistId);
// if (($res = BasicStor::Authorize('read', $id, $sessid)) !== TRUE) { // if (($res = BasicStor::Authorize('read', $id, $sessid)) !== TRUE) {
// return $res; // return $res;
// } // }
// $res = $this->bsOpenDownload($id, 'metadata', $parent); // $res = $this->bsOpenDownload($id, 'metadata', $parent);
// #unset($res['filename']); // #unset($res['filename']);
// return $res; // return $res;
} }
@ -983,7 +983,7 @@ class LocStor extends BasicStor {
if (!$ex) { if (!$ex) {
return PEAR::raiseError( return PEAR::raiseError(
'LocStor::playlistIsAvailable: playlist not exists' 'LocStor::playlistIsAvailable: playlist not exists'
); );
} }
$ie = $this->isEdited($playlistId); $ie = $this->isEdited($playlistId);
if ($ie === FALSE) { if ($ie === FALSE) {
@ -1159,7 +1159,7 @@ class LocStor extends BasicStor {
if ($token != '123456789abcdeff') { if ($token != '123456789abcdeff') {
return PEAR::raiseError( return PEAR::raiseError(
"LocStor::renderPlaylistToRSSClose: invalid token" "LocStor::renderPlaylistToRSSClose: invalid token"
); );
} }
$fakeFile = $CC_CONFIG['accessDir']."/$token.rss"; $fakeFile = $CC_CONFIG['accessDir']."/$token.rss";
unlink($fakeFile); unlink($fakeFile);
@ -1192,7 +1192,7 @@ class LocStor extends BasicStor {
if ($r === FALSE) { if ($r === FALSE) {
return PEAR::raiseError( return PEAR::raiseError(
"LocStor::createBackupOpen: false returned from Backup" "LocStor::createBackupOpen: false returned from Backup"
); );
} }
return $r; return $r;
} }
@ -1351,12 +1351,12 @@ class LocStor extends BasicStor {
* status: string - working | fault | success * status: string - working | fault | success
*/ */
protected function restoreBackupClose($token) { protected function restoreBackupClose($token) {
require_once('Restore.php'); require_once('Restore.php');
$rs = new Restore($this); $rs = new Restore($this);
if (PEAR::isError($rs)) { if (PEAR::isError($rs)) {
return $rs; return $rs;
} }
return $rs->closeRestore($token); return $rs->closeRestore($token);
} }
@ -1387,11 +1387,11 @@ class LocStor extends BasicStor {
{ {
$owner = Alib::GetSessUserId($sessid); $owner = Alib::GetSessUserId($sessid);
if (PEAR::isError($owner)) { if (PEAR::isError($owner)) {
return $owner; return $owner;
} }
$res = $this->bsOpenPut($chsum, NULL, $owner); $res = $this->bsOpenPut($chsum, NULL, $owner);
if (PEAR::isError($res)) { if (PEAR::isError($res)) {
return $res; return $res;
} }
return array('url'=>$res['url'], 'token'=>$res['token']); return array('url'=>$res['url'], 'token'=>$res['token']);
} }
@ -1412,7 +1412,7 @@ class LocStor extends BasicStor {
{ {
$res = $this->bsClosePut($token); $res = $this->bsClosePut($token);
if (PEAR::isError($res)) { if (PEAR::isError($res)) {
return $res; return $res;
} }
extract($res); // fname, owner extract($res); // fname, owner
switch ($trtype) { switch ($trtype) {
@ -1420,11 +1420,11 @@ class LocStor extends BasicStor {
$mdtoken = $pars['mdpdtoken']; $mdtoken = $pars['mdpdtoken'];
$res = $this->bsClosePut($mdtoken); $res = $this->bsClosePut($mdtoken);
if (PEAR::isError($res)) { if (PEAR::isError($res)) {
return $res; return $res;
} }
$mdfname = $res['fname']; $mdfname = $res['fname'];
if ($gunid == '') { if ($gunid == '') {
$gunid = NULL; $gunid = NULL;
} }
$values = array( $values = array(
"filename" => $pars['name'], "filename" => $pars['name'],
@ -1432,45 +1432,45 @@ class LocStor extends BasicStor {
"metadata" => $mdfname, "metadata" => $mdfname,
"gunid" => $pars['gunid'], "gunid" => $pars['gunid'],
"filetype" => "audioclip" "filetype" => "audioclip"
); );
$storedFile = StoredFile::Insert($values); $storedFile = StoredFile::Insert($values);
if (PEAR::isError($storedFile)) { if (PEAR::isError($storedFile)) {
return $storedFile; return $storedFile;
} }
$res = $storedFile->getId(); $res = $storedFile->getId();
@unlink($fname); @unlink($fname);
@unlink($mdfname); @unlink($mdfname);
break; break;
case "playlist": case "playlist":
if ($gunid == '') { if ($gunid == '') {
$gunid = NULL; $gunid = NULL;
} }
$values = array( $values = array(
"filename" => $pars['name'], "filename" => $pars['name'],
"metadata" => $fname, "metadata" => $fname,
"gunid" => $pars['gunid'], "gunid" => $pars['gunid'],
"filetype" => "playlist" "filetype" => "playlist"
); );
$storedFile = StoredFile::Insert($values); $storedFile = StoredFile::Insert($values);
if (PEAR::isError($storedFile)) { if (PEAR::isError($storedFile)) {
return $storedFile; return $storedFile;
} }
$res = $storedFile->getId(); $res = $storedFile->getId();
@unlink($fname); @unlink($fname);
break; break;
case "playlistPkg": case "playlistPkg":
$chsum = md5_file($fname); $chsum = md5_file($fname);
// importPlaylistOpen: // importPlaylistOpen:
$res = $this->bsOpenPut($chsum, NULL, $owner); $res = $this->bsOpenPut($chsum, NULL, $owner);
if (PEAR::isError($res)) { if (PEAR::isError($res)) {
return $res; return $res;
} }
$dest = $res['fname']; $dest = $res['fname'];
$token = $res['token']; $token = $res['token'];
copy($fname, $dest); copy($fname, $dest);
$r = $this->importPlaylistClose($token); $r = $this->importPlaylistClose($token);
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
} }
@unlink($fname); @unlink($fname);
return $r; return $r;
@ -1481,14 +1481,14 @@ class LocStor extends BasicStor {
@unlink($fname); @unlink($fname);
$results = $this->localSearch($criteria); $results = $this->localSearch($criteria);
if (PEAR::isError($results)) { if (PEAR::isError($results)) {
return $results; return $results;
} }
$realfile = tempnam($this->accessDir, 'searchjob_'); $realfile = tempnam($this->accessDir, 'searchjob_');
@chmod($realfile, 0660); @chmod($realfile, 0660);
$len = file_put_contents($realfile, serialize($results)); $len = file_put_contents($realfile, serialize($results));
$acc = BasicStor::bsAccess($realfile, '', NULL, 'download'); $acc = BasicStor::bsAccess($realfile, '', NULL, 'download');
if (PEAR::isError($acc)) { if (PEAR::isError($acc)) {
return $acc; return $acc;
} }
$url = BasicStor::GetUrlPart()."access/".basename($acc['fname']); $url = BasicStor::GetUrlPart()."access/".basename($acc['fname']);
$chsum = md5_file($realfile); $chsum = md5_file($realfile);
@ -1523,227 +1523,227 @@ class LocStor extends BasicStor {
*/ */
function downloadOpen($sessid, $trtype, $pars=array()) function downloadOpen($sessid, $trtype, $pars=array())
{ {
// global $CC_CONFIG; // global $CC_CONFIG;
// switch ($trtype) { // switch ($trtype) {
// case "unknown": // case "unknown":
// case "audioclip": // case "audioclip":
// case "metadata": // case "metadata":
// case "playlist": // case "playlist":
// case "playlistPkg": // case "playlistPkg":
// if (!isset($pars['gunid'])) { // if (!isset($pars['gunid'])) {
// return PEAR::raiseError("Archive::downloadOpen: gunid not set"); // return PEAR::raiseError("Archive::downloadOpen: gunid not set");
// } // }
// break; // break;
// } // }
// $gunid = $pars['gunid']; // $gunid = $pars['gunid'];
// // resolve trtype by object type: // // resolve trtype by object type:
// if ( ($trtype == 'unknown') || ($trtype == 'playlistPkg') ) { // if ( ($trtype == 'unknown') || ($trtype == 'playlistPkg') ) {
// $media = StoredFile::RecallByGunid($gunid); // $media = StoredFile::RecallByGunid($gunid);
// $trtype2 = $media->getType(); // $trtype2 = $media->getType();
// if (PEAR::isError($trtype2)) { // if (PEAR::isError($trtype2)) {
// return $trtype2; // return $trtype2;
// } // }
// // required with content: // // required with content:
// $trtype = ( ($trtype2 == 'playlist') && ($trtype == 'playlistPkg') ? // $trtype = ( ($trtype2 == 'playlist') && ($trtype == 'playlistPkg') ?
// 'playlistPkg' : $trtype2); // 'playlistPkg' : $trtype2);
// //return PEAR::raiseError("Archive::downloadOpen: TT=$trtype TT2=$trtype2 G=$gunid"); // //return PEAR::raiseError("Archive::downloadOpen: TT=$trtype TT2=$trtype2 G=$gunid");
// } // }
// switch ($trtype) { // switch ($trtype) {
// case "audioclip": // case "audioclip":
// $res = $this->downloadRawAudioDataOpen($sessid, $gunid); // $res = $this->downloadRawAudioDataOpen($sessid, $gunid);
// break; // break;
// case "metadata": // case "metadata":
// $res = $this->downloadMetadataOpen($sessid, $gunid); // $res = $this->downloadMetadataOpen($sessid, $gunid);
// break; // break;
// case "playlist": // case "playlist":
// $res = $this->accessPlaylist($sessid, $gunid); // $res = $this->accessPlaylist($sessid, $gunid);
// break; // break;
// case "playlistPkg": // case "playlistPkg":
// $res = $this->bsExportPlaylistOpen($gunid); // $res = $this->bsExportPlaylistOpen($gunid);
// if (PEAR::isError($res)) { // if (PEAR::isError($res)) {
// return $res; // return $res;
// } // }
// $tmpn = tempnam($CC_CONFIG['transDir'], 'plExport_'); // $tmpn = tempnam($CC_CONFIG['transDir'], 'plExport_');
// $plfpath = "$tmpn.lspl"; // $plfpath = "$tmpn.lspl";
// copy($res['fname'], $plfpath); // copy($res['fname'], $plfpath);
// $res = $this->bsExportPlaylistClose($res['token']); // $res = $this->bsExportPlaylistClose($res['token']);
// if (PEAR::isError($res)) { // if (PEAR::isError($res)) {
// return $res; // return $res;
// } // }
// $fname = "transported_playlist.lspl"; // $fname = "transported_playlist.lspl";
// $id = BasicStor::IdFromGunid($gunid); // $id = BasicStor::IdFromGunid($gunid);
// $acc = BasicStor::bsAccess($plfpath, 'lspl', NULL, 'download'); // $acc = BasicStor::bsAccess($plfpath, 'lspl', NULL, 'download');
// if (PEAR::isError($acc)) { // if (PEAR::isError($acc)) {
// return $acc; // return $acc;
// } // }
// $url = BasicStor::GetUrlPart()."access/".basename($acc['fname']); // $url = BasicStor::GetUrlPart()."access/".basename($acc['fname']);
// $chsum = md5_file($plfpath); // $chsum = md5_file($plfpath);
// $size = filesize($plfpath); // $size = filesize($plfpath);
// $res = array( // $res = array(
// 'url'=>$url, 'token'=>$acc['token'], // 'url'=>$url, 'token'=>$acc['token'],
// 'chsum'=>$chsum, 'size'=>$size, // 'chsum'=>$chsum, 'size'=>$size,
// 'filename'=>$fname // 'filename'=>$fname
// ); // );
// break; // break;
// case "searchjob": // case "searchjob":
// $res = $pars; // $res = $pars;
// break; // break;
// case "file": // case "file":
// $res = array(); // $res = array();
// break; // break;
// default: // default:
// return PEAR::raiseError("Archive::downloadOpen: NotImpl ($trtype)"); // return PEAR::raiseError("Archive::downloadOpen: NotImpl ($trtype)");
// } // }
// if (PEAR::isError($res)) { // if (PEAR::isError($res)) {
// return $res; // return $res;
// } // }
// switch ($trtype) { // switch ($trtype) {
// case "audioclip": // case "audioclip":
// case "metadata": // case "metadata":
// case "playlist": // case "playlist":
// case "playlistPkg": // case "playlistPkg":
// $f = StoredFile::RecallByGunid($gunid); // $f = StoredFile::RecallByGunid($gunid);
// $title = $f->getTitle(); // $title = $f->getTitle();
// break; // break;
// case "searchjob": // case "searchjob":
// $title = 'searchjob'; // $title = 'searchjob';
// break; // break;
// case "file": // case "file":
// $title = 'regular file'; // $title = 'regular file';
// break; // break;
// default: // default:
// } // }
// $res['title'] = $title; // $res['title'] = $title;
// $res['trtype'] = $trtype; // $res['trtype'] = $trtype;
// return $res; // return $res;
} }
/** /**
* Close download transport * Close download transport
* *
* @param string $token * @param string $token
* transport token * transport token
* @param string $trtype * @param string $trtype
* transport type * transport type
* @return array * @return array
* hasharray with: * hasharray with:
* url string: writable URL * url string: writable URL
* token string: PUT token * token string: PUT token
*/ */
function downloadClose($token, $trtype) function downloadClose($token, $trtype)
{ {
switch ($trtype) { switch ($trtype) {
case "audioclip": case "audioclip":
$res = $this->downloadRawAudioDataClose($token); $res = $this->downloadRawAudioDataClose($token);
if (PEAR::isError($res)) { if (PEAR::isError($res)) {
return $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);
} }
} return $res;
return $res; case "metadata":
case "searchjob": $res = $this->downloadMetadataClose($token);
$res = BasicStor::bsRelease($token, 'download'); return $res;
return $res; case "playlist":
case "file": $res = $this->releasePlaylist(NULL/*$sessid*/, $token);
return array(); return $res;
default: case "playlistPkg":
return PEAR::raiseError("Archive::downloadClose: NotImpl ($trtype)"); $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 * Prepare hub initiated transport
* *
* @param string $target * @param string $target
* hostname of transport target * hostname of transport target
* @param string $trtype * @param string $trtype
* transport type * transport type
* @param string $direction * @param string $direction
* 'up' | 'down' * 'up' | 'down'
* @param array $pars * @param array $pars
* transport parameters * transport parameters
* @return mixed * @return mixed
*/ */
function prepareHubInitiatedTransfer( function prepareHubInitiatedTransfer(
$target, $trtype='file', $direction='up',$pars=array()) $target, $trtype='file', $direction='up',$pars=array())
{ {
$tr = new Transport($this); $tr = new Transport($this);
$trec = TransportRecord::create($tr, $trtype, $direction, $trec = TransportRecord::create($tr, $trtype, $direction,
array_merge($pars, array('target'=>$target))); array_merge($pars, array('target'=>$target)));
if (PEAR::isError($trec)) { if (PEAR::isError($trec)) {
return $trec; return $trec;
}
return TRUE;
} }
return TRUE;
}
/** /**
* List hub initiated transports * List hub initiated transports
* *
* @param string $target * @param string $target
* hostname of transport target * hostname of transport target
* @param string $direction * @param string $direction
* 'up' | 'down' * 'up' | 'down'
* @param string $trtok * @param string $trtok
* transport token * transport token
* @return mixed * @return mixed
*/ */
function listHubInitiatedTransfers( function listHubInitiatedTransfers(
$target=NULL, $direction=NULL, $trtok=NULL) $target=NULL, $direction=NULL, $trtok=NULL)
{ {
$tr = new Transport($this); $tr = new Transport($this);
$res = $tr->getTransports($direction, $target, $trtok); $res = $tr->getTransports($direction, $target, $trtok);
return $res; 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;
} }
$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 } // class LocStor
?> ?>

File diff suppressed because it is too large Load Diff

View File

@ -44,19 +44,19 @@ class Prefs {
{ {
$subjid = GreenBox::GetSessUserId($sessid); $subjid = GreenBox::GetSessUserId($sessid);
if (PEAR::isError($subjid)) { if (PEAR::isError($subjid)) {
return $subjid; return $subjid;
} }
if (is_null($subjid)) { if (is_null($subjid)) {
return PEAR::raiseError("Prefs::loadPref: invalid session id", return PEAR::raiseError("Prefs::loadPref: invalid session id",
GBERR_SESS); GBERR_SESS);
} }
$val = $this->readVal($subjid, $key); $val = $this->readVal($subjid, $key);
if (PEAR::isError($val)) { if (PEAR::isError($val)) {
return $val; return $val;
} }
if ($val === FALSE) { if ($val === FALSE) {
return PEAR::raiseError("Prefs::loadPref: invalid preference key", return PEAR::raiseError("Prefs::loadPref: invalid preference key",
GBERR_PREF); GBERR_PREF);
} }
return $val; return $val;
} }
@ -77,20 +77,19 @@ class Prefs {
{ {
$subjid = GreenBox::GetSessUserId($sessid); $subjid = GreenBox::GetSessUserId($sessid);
if (PEAR::isError($subjid)) { if (PEAR::isError($subjid)) {
return $subjid; return $subjid;
} }
if (is_null($subjid)) { if (is_null($subjid)) {
return PEAR::raiseError("Prefs::savePref: invalid session id", return PEAR::raiseError("Prefs::savePref: invalid session id", GBERR_SESS);
GBERR_SESS);
} }
$r = $this->update($subjid, $key, $value); $r = $this->update($subjid, $key, $value);
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
} }
if ($r === FALSE) { if ($r === FALSE) {
$r = $this->insert($subjid, $key, $value); $r = $this->insert($subjid, $key, $value);
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
} }
} }
return TRUE; return TRUE;
@ -110,19 +109,17 @@ class Prefs {
{ {
$subjid = GreenBox::GetSessUserId($sessid); $subjid = GreenBox::GetSessUserId($sessid);
if (PEAR::isError($subjid)) { if (PEAR::isError($subjid)) {
return $subjid; return $subjid;
} }
if (is_null($subjid)) { if (is_null($subjid)) {
return PEAR::raiseError("Prefs::delPref: invalid session id", return PEAR::raiseError("Prefs::delPref: invalid session id", GBERR_SESS);
GBERR_SESS);
} }
$r = $this->delete($subjid, $key); $r = $this->delete($subjid, $key);
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
} }
if ($r === FALSE) { if ($r === FALSE) {
return PEAR::raiseError("Prefs::delPref: invalid preference key", return PEAR::raiseError("Prefs::delPref: invalid preference key", GBERR_PREF);
GBERR_PREF);
} }
return TRUE; return TRUE;
} }
@ -146,7 +143,7 @@ class Prefs {
// if sessid is would be used here fix Transport::cronCallMethod ! // if sessid is would be used here fix Transport::cronCallMethod !
$subjid = Subjects::GetSubjId($group); $subjid = Subjects::GetSubjId($group);
if (PEAR::isError($subjid)) { if (PEAR::isError($subjid)) {
return $subjid; return $subjid;
} }
if (is_null($subjid)) { if (is_null($subjid)) {
return PEAR::raiseError( return PEAR::raiseError(
@ -154,7 +151,7 @@ class Prefs {
} }
$val = $this->readVal($subjid, $key); $val = $this->readVal($subjid, $key);
if (PEAR::isError($val)) { if (PEAR::isError($val)) {
return $val; return $val;
} }
if ($val === FALSE) { if ($val === FALSE) {
if ($returnErrorIfKeyNotExists) { if ($returnErrorIfKeyNotExists) {
@ -185,7 +182,7 @@ class Prefs {
{ {
$uid = GreenBox::GetSessUserId($sessid); $uid = GreenBox::GetSessUserId($sessid);
if (PEAR::isError($uid)) { if (PEAR::isError($uid)) {
return $uid; return $uid;
} }
if (is_null($uid)) { if (is_null($uid)) {
return PEAR::raiseError( return PEAR::raiseError(
@ -193,7 +190,7 @@ class Prefs {
} }
$gid = Subjects::GetSubjId($group); $gid = Subjects::GetSubjId($group);
if (PEAR::isError($gid)) { if (PEAR::isError($gid)) {
return $gid; return $gid;
} }
if (is_null($gid)) { if (is_null($gid)) {
return PEAR::raiseError( return PEAR::raiseError(
@ -201,7 +198,7 @@ class Prefs {
} }
$memb = Subjects::IsMemberOf($uid, $gid); $memb = Subjects::IsMemberOf($uid, $gid);
if (PEAR::isError($memb)) { if (PEAR::isError($memb)) {
return $memb; return $memb;
} }
if (!$memb) { if (!$memb) {
return PEAR::raiseError( return PEAR::raiseError(
@ -209,12 +206,12 @@ class Prefs {
} }
$r = $this->update($gid, $key, $value); $r = $this->update($gid, $key, $value);
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
} }
if ($r === FALSE) { if ($r === FALSE) {
$r = $this->insert($gid, $key, $value); $r = $this->insert($gid, $key, $value);
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
} }
} }
return TRUE; return TRUE;
@ -235,7 +232,7 @@ class Prefs {
{ {
$uid = GreenBox::GetSessUserId($sessid); $uid = GreenBox::GetSessUserId($sessid);
if (PEAR::isError($uid)) { if (PEAR::isError($uid)) {
return $uid; return $uid;
} }
if (is_null($uid)) { if (is_null($uid)) {
return PEAR::raiseError( return PEAR::raiseError(
@ -243,7 +240,7 @@ class Prefs {
} }
$gid = Subjects::GetSubjId($group); $gid = Subjects::GetSubjId($group);
if (PEAR::isError($gid)) { if (PEAR::isError($gid)) {
return $gid; return $gid;
} }
if (is_null($gid)) { if (is_null($gid)) {
return PEAR::raiseError( return PEAR::raiseError(
@ -251,7 +248,7 @@ class Prefs {
} }
$memb = Subjects::IsMemberOf($uid, $gid); $memb = Subjects::IsMemberOf($uid, $gid);
if (PEAR::isError($memb)) { if (PEAR::isError($memb)) {
return $memb; return $memb;
} }
if (!$memb) { if (!$memb) {
return PEAR::raiseError( return PEAR::raiseError(
@ -259,7 +256,7 @@ class Prefs {
} }
$r = $this->delete($gid, $key); $r = $this->delete($gid, $key);
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
} }
if ($r === FALSE) { if ($r === FALSE) {
return PEAR::raiseError( return PEAR::raiseError(
@ -287,7 +284,7 @@ class Prefs {
global $CC_CONFIG, $CC_DBC; global $CC_CONFIG, $CC_DBC;
$id = $CC_DBC->nextId($CC_CONFIG['prefSequence']); $id = $CC_DBC->nextId($CC_CONFIG['prefSequence']);
if (PEAR::isError($id)) { if (PEAR::isError($id)) {
return $id; return $id;
} }
$r = $CC_DBC->query(" $r = $CC_DBC->query("
INSERT INTO ".$CC_CONFIG['prefTable']." INSERT INTO ".$CC_CONFIG['prefTable']."
@ -296,7 +293,7 @@ class Prefs {
($id, $subjid, '$keystr', '$valstr') ($id, $subjid, '$keystr', '$valstr')
"); ");
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
} }
return $id; return $id;
} }
@ -320,10 +317,10 @@ class Prefs {
WHERE subjid=$subjid AND keystr='$keystr' WHERE subjid=$subjid AND keystr='$keystr'
"); ");
if (PEAR::isError($val)) { if (PEAR::isError($val)) {
return $val; return $val;
} }
if (is_null($val)) { if (is_null($val)) {
return FALSE; return FALSE;
} }
return $val; return $val;
} }
@ -345,10 +342,10 @@ class Prefs {
WHERE subjid=$subjid WHERE subjid=$subjid
"); ");
if (PEAR::isError($res)) { if (PEAR::isError($res)) {
return $res; return $res;
} }
if (is_null($res)) { if (is_null($res)) {
return FALSE; return FALSE;
} }
return $res; return $res;
} }
@ -374,10 +371,10 @@ class Prefs {
WHERE subjid=$subjid AND keystr='$keystr' WHERE subjid=$subjid AND keystr='$keystr'
"); ");
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
} }
if ($CC_DBC->affectedRows() < 1) { if ($CC_DBC->affectedRows() < 1) {
return FALSE; return FALSE;
} }
return TRUE; return TRUE;
} }
@ -400,10 +397,10 @@ class Prefs {
WHERE subjid=$subjid AND keystr='$keystr' WHERE subjid=$subjid AND keystr='$keystr'
"); ");
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
} }
if ($CC_DBC->affectedRows() < 1) { if ($CC_DBC->affectedRows() < 1) {
return FALSE; return FALSE;
} }
return TRUE; return TRUE;
} }
@ -422,7 +419,7 @@ class Prefs {
$testVal = 'abcDef 0123 ěščřžýáíé ĚŠČŘŽÝÁÍÉ'; $testVal = 'abcDef 0123 ěščřžýáíé ĚŠČŘŽÝÁÍÉ';
$r = savePref($sessid, $testKey, $testVal); $r = savePref($sessid, $testKey, $testVal);
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
} }
$val = loadPref($sessid, $testKey); $val = loadPref($sessid, $testKey);
if ($val != $testVal) { if ($val != $testVal) {
@ -431,7 +428,7 @@ class Prefs {
} }
$r = savePref($sessid, $testKey, ''); $r = savePref($sessid, $testKey, '');
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
} }
$val = loadPref($sessid, $testKey); $val = loadPref($sessid, $testKey);
if ($val != $testVal) { if ($val != $testVal) {

View File

@ -35,12 +35,12 @@ class Renderer
// recall playlist: // recall playlist:
$pl = StoredFile::RecallByGunid($plid); $pl = StoredFile::RecallByGunid($plid);
if (is_null($pl) || PEAR::isError($pl)) { if (is_null($pl) || PEAR::isError($pl)) {
return $pl; return $pl;
} }
// smil export: // smil export:
$smil = $pl->outputToSmil(); $smil = $pl->outputToSmil();
if (PEAR::isError($smil)) { if (PEAR::isError($smil)) {
return $smil; return $smil;
} }
// temporary file for smil: // temporary file for smil:
$tmpn = tempnam($CC_CONFIG['bufferDir'], 'plRender_'); $tmpn = tempnam($CC_CONFIG['bufferDir'], 'plRender_');
@ -56,7 +56,7 @@ class Renderer
// open access to output file: /*gunid*/ /*parent*/ // open access to output file: /*gunid*/ /*parent*/
$acc = BasicStor::bsAccess($outf, RENDER_EXT, $plid, 'render', 0, $owner); $acc = BasicStor::bsAccess($outf, RENDER_EXT, $plid, 'render', 0, $owner);
if (PEAR::isError($acc)) { if (PEAR::isError($acc)) {
return $acc; return $acc;
} }
extract($acc); extract($acc);
$statf = Renderer::getStatusFile($gb, $token); $statf = Renderer::getStatusFile($gb, $token);
@ -70,7 +70,7 @@ class Renderer
if ($res === FALSE) { if ($res === FALSE) {
return PEAR::raiseError( return PEAR::raiseError(
'Renderer::rnRender2File: Error running renderer' 'Renderer::rnRender2File: Error running renderer'
); );
} }
return array('token'=>$token); return array('token'=>$token);
} }
@ -93,7 +93,7 @@ class Renderer
if (!file_exists($statf)) { if (!file_exists($statf)) {
return PEAR::raiseError( return PEAR::raiseError(
'Renderer::rnRender2FileCheck: Invalid token' 'Renderer::rnRender2FileCheck: Invalid token'
); );
} }
$status = trim(file_get_contents($statf)); $status = trim(file_get_contents($statf));
$url = Renderer::getUrl($gb, $token); $url = Renderer::getUrl($gb, $token);
@ -142,7 +142,7 @@ class Renderer
global $CC_CONFIG; global $CC_CONFIG;
$r = BasicStor::bsRelease($token, 'render'); $r = BasicStor::bsRelease($token, 'render');
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
} }
$realOgg = $r['realFname']; $realOgg = $r['realFname'];
$tmpn = $CC_CONFIG['bufferDir']."/".basename($realOgg, '.'.RENDER_EXT); $tmpn = $CC_CONFIG['bufferDir']."/".basename($realOgg, '.'.RENDER_EXT);
@ -171,7 +171,7 @@ class Renderer
{ {
$r = Renderer::rnRender2FileCheck($gb, $token); $r = Renderer::rnRender2FileCheck($gb, $token);
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
} }
$status = $r['status']; $status = $r['status'];
$res = array('status' => $status, 'gunid'=>'NULL'); $res = array('status' => $status, 'gunid'=>'NULL');
@ -182,7 +182,7 @@ class Renderer
case "success": case "success":
$r = Renderer::rnRender2StorageCore($gb, $token); $r = Renderer::rnRender2StorageCore($gb, $token);
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
} }
$res['gunid'] = $r['gunid']; $res['gunid'] = $r['gunid'];
break; break;
@ -205,36 +205,36 @@ class Renderer
*/ */
function rnRender2StorageCore(&$gb, $token) function rnRender2StorageCore(&$gb, $token)
{ {
// $r = BasicStor::bsRelease($token, 'render'); // $r = BasicStor::bsRelease($token, 'render');
// if (PEAR::isError($r)) { // if (PEAR::isError($r)) {
// return $r; // return $r;
// } // }
// $realOgg = $r['realFname']; // $realOgg = $r['realFname'];
// $owner = $r['owner']; // $owner = $r['owner'];
// $gunid = $r['gunid']; // $gunid = $r['gunid'];
// $fileName = 'rendered_playlist'; // $fileName = 'rendered_playlist';
// $id = BasicStor::IdFromGunid($gunid); // $id = BasicStor::IdFromGunid($gunid);
// if (PEAR::isError($id)) { // if (PEAR::isError($id)) {
// return $id; // return $id;
// } // }
// $mdata = ''; // $mdata = '';
// foreach (array('dc:title', 'dcterms:extent', 'dc:creator', 'dc:description') as $item) { // foreach (array('dc:title', 'dcterms:extent', 'dc:creator', 'dc:description') as $item) {
// $val = $gb->bsGetMetadataValue($id, $item); // $val = $gb->bsGetMetadataValue($id, $item);
// $mdata .= " <$item>$val</$item>\n"; // $mdata .= " <$item>$val</$item>\n";
// } // }
// $mdata = "<audioClip>\n <metadata>\n$mdata </metadata>\n</audioClip>\n"; // $mdata = "<audioClip>\n <metadata>\n$mdata </metadata>\n</audioClip>\n";
// //$mdata = "<audioClip>\n <metadata>\n$mdata<dcterms:extent>0</dcterms:extent>\n</metadata>\n</audioClip>\n"; // //$mdata = "<audioClip>\n <metadata>\n$mdata<dcterms:extent>0</dcterms:extent>\n</metadata>\n</audioClip>\n";
// $values = array( // $values = array(
// "filename" => $fileName, // "filename" => $fileName,
// "filepath" => $realOgg, // "filepath" => $realOgg,
// "metadata" => $mdata, // "metadata" => $mdata,
// "filetype" => "audioclip" // "filetype" => "audioclip"
// ); // );
// $storedFile = $gb->bsPutFile($values); // $storedFile = $gb->bsPutFile($values);
// if (PEAR::isError($storedFile)) { // if (PEAR::isError($storedFile)) {
// return $storedFile; // return $storedFile;
// } // }
// return array('gunid' => $storedFile->getGunid()); // return array('gunid' => $storedFile->getGunid());
} }

View File

@ -61,7 +61,7 @@ class Restore {
$this->token = null; $this->token = null;
$this->logFile = $CC_CONFIG['bufferDir'].'/'.$this->ACCESS_TYPE.'.log'; $this->logFile = $CC_CONFIG['bufferDir'].'/'.$this->ACCESS_TYPE.'.log';
if ($this->loglevel == 'debug') { 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; $r['status'] = $stat;
if ($stat=='fault') { if ($stat=='fault') {
$r['faultString'] = $message; $r['faultString'] = $message;
} else { } else {
$r['faultString'] = ''; $r['faultString'] = '';
} }
return $r; return $r;
} else { } else {
@ -193,8 +193,8 @@ class Restore {
//simple check of archive format //simple check of archive format
if (is_dir($this->tmpDir.'audioClip/') && if (is_dir($this->tmpDir.'audioClip/') &&
is_dir($this->tmpDir.'meta-inf/') && is_dir($this->tmpDir.'meta-inf/') &&
is_dir($this->tmpDir.'playlist/')) { is_dir($this->tmpDir.'playlist/')) {
//search metafiles //search metafiles
$this->metafiles = $this->getMetaFiles(); $this->metafiles = $this->getMetaFiles();
#$this->addLogItem('metafiles:'.print_r($this->metafiles,true)); #$this->addLogItem('metafiles:'.print_r($this->metafiles,true));
@ -205,15 +205,15 @@ class Restore {
$this->addLogItem("-E- ".date("Ymd-H:i:s"). $this->addLogItem("-E- ".date("Ymd-H:i:s").
" startRestore - addFileToStorage \n". " startRestore - addFileToStorage \n".
"(".$put->getMessage()."/".$put->getUserInfo().")\n" "(".$put->getMessage()."/".$put->getUserInfo().")\n"
); );
file_put_contents($this->statusFile, 'fault|'.$put->getMessage()."/".$put->getUserInfo()); file_put_contents($this->statusFile, 'fault|'.$put->getMessage()."/".$put->getUserInfo());
return; return;
} }
} }
} else { } else {
$this->addLogItem("-E- ".date("Ymd-H:i:s")." startRestore - invalid archive format\n"); $this->addLogItem("-E- ".date("Ymd-H:i:s")." startRestore - invalid archive format\n");
file_put_contents($this->statusFile, 'fault|invalid archive format'); file_put_contents($this->statusFile, 'fault|invalid archive format');
return; return;
} }
file_put_contents($this->statusFile, 'success'); file_put_contents($this->statusFile, 'success');
// unlink($backupfile); // unlink($backupfile);
@ -238,13 +238,13 @@ class Restore {
$playlists = scandir($this->tmpDir.'playlist/'); $playlists = scandir($this->tmpDir.'playlist/');
for ($i = 0; $i < count($audioclips); $i++) { for ($i = 0; $i < count($audioclips); $i++) {
if (strpos($audioclips[$i],'xml')!==false) if (strpos($audioclips[$i],'xml')!==false)
$r[] = array('file' => $this->tmpDir.'audioClip/'.$audioclips[$i], $r[] = array('file' => $this->tmpDir.'audioClip/'.$audioclips[$i],
'type' => 'audioClip', 'type' => 'audioClip',
'id' => str_replace('.xml','',$audioclips[$i])); 'id' => str_replace('.xml','',$audioclips[$i]));
} }
for ($i = 0; $i < count($playlists); $i++) { for ($i = 0; $i < count($playlists); $i++) {
if (strpos($playlists[$i],'xml') !== false) if (strpos($playlists[$i],'xml') !== false)
$r[] = array('file' => $this->tmpDir.'playlist/'.$playlists[$i], $r[] = array('file' => $this->tmpDir.'playlist/'.$playlists[$i],
'type' => 'playlist', 'type' => 'playlist',
'id' => str_replace('.xml','',$playlists[$i])); 'id' => str_replace('.xml','',$playlists[$i]));
} }
@ -265,83 +265,83 @@ class Restore {
* @return mixed * @return mixed
* true if success or PEAR_error * true if success or PEAR_error
*/ */
// function addFileToStorage($file,$type,$gunid) // function addFileToStorage($file,$type,$gunid)
// { // {
// if ($this->loglevel=='debug') { // if ($this->loglevel=='debug') {
// $this->addLogItem("-I- ".date("Ymd-H:i:s")." addFileToStorage - file:$file | type:$type | id:$gunid\n"); // $this->addLogItem("-I- ".date("Ymd-H:i:s")." addFileToStorage - file:$file | type:$type | id:$gunid\n");
// } // }
// require_once("XmlParser.php"); // require_once("XmlParser.php");
// $tree = XmlParser::parse($file); // $tree = XmlParser::parse($file);
// $mediaFileLP = str_replace('.xml','',$file); // $mediaFileLP = str_replace('.xml','',$file);
// $mediaFileLP = ($type=='audioClip' && is_file($mediaFileLP))?$mediaFileLP:''; // $mediaFileLP = ($type=='audioClip' && is_file($mediaFileLP))?$mediaFileLP:'';
// $ex = $this->gb->existsFile($this->sessid,$gunid); // $ex = $this->gb->existsFile($this->sessid,$gunid);
// if (PEAR::isError($ex)) { // if (PEAR::isError($ex)) {
// $this->addLogItem("-E- ".date("Ymd-H:i:s"). // $this->addLogItem("-E- ".date("Ymd-H:i:s").
// " addFileToStorage - existsFile($gunid) ". // " addFileToStorage - existsFile($gunid) ".
// "(".$ex->getMessage()."/".$ex->getUserInfo().")\n" // "(".$ex->getMessage()."/".$ex->getUserInfo().")\n"
// ); // );
// } // }
// if (!PEAR::isError($ex) && $ex) { // file is exists in storage server // if (!PEAR::isError($ex) && $ex) { // file is exists in storage server
// //replace it // //replace it
// $id = BasicStor::IdFromGunid($gunid); // $id = BasicStor::IdFromGunid($gunid);
// $replace = $this->gb->replaceFile( // $replace = $this->gb->replaceFile(
// $id, # id int, virt.file's local id // $id, # id int, virt.file's local id
// $mediaFileLP, # mediaFileLP string, local path of media file // $mediaFileLP, # mediaFileLP string, local path of media file
// $file, # mdataFileLP string, local path of metadata file // $file, # mdataFileLP string, local path of metadata file
// $this->sessid); # sessid string, session id // $this->sessid); # sessid string, session id
// if (PEAR::isError($replace)) { // if (PEAR::isError($replace)) {
// $this->addLogItem("-E- ".date("Ymd-H:i:s"). // $this->addLogItem("-E- ".date("Ymd-H:i:s").
// " addFileToStorage - replaceFile Error ". // " addFileToStorage - replaceFile Error ".
// "(".$replace->getMessage()."/".$replace->getUserInfo().")\n" // "(".$replace->getMessage()."/".$replace->getUserInfo().")\n"
// ); // );
// file_put_contents($this->statusFile, 'fault|'.$replace->getMessage()."/".$replace->getUserInfo()); // file_put_contents($this->statusFile, 'fault|'.$replace->getMessage()."/".$replace->getUserInfo());
// return $replace; // return $replace;
// } // }
// #$this->addLogItem("replace it \n"); // #$this->addLogItem("replace it \n");
// } else { // } else {
// // add as new // // add as new
// $name = $tree->children[0]->children[0]->content; // $name = $tree->children[0]->children[0]->content;
// if (empty($name)) { // if (empty($name)) {
// $name = $tree->attrs['title']->val; // $name = $tree->attrs['title']->val;
// } // }
// if (empty($name)) { // if (empty($name)) {
// $name = '???'; // $name = '???';
// } // }
// if ($this->loglevel=='debug') { // if ($this->loglevel=='debug') {
// $this->addLogItem("-I- ".date("Ymd-H:i:s")." putFile\n". // $this->addLogItem("-I- ".date("Ymd-H:i:s")." putFile\n".
// "$name, $mediaFileLP, $file, {$this->sessid}, $gunid, $type \n" // "$name, $mediaFileLP, $file, {$this->sessid}, $gunid, $type \n"
// ); // );
// } // }
// $values = array( // $values = array(
// "filename" => $name, // "filename" => $name,
// "filepath" => $mediaFileLP, // "filepath" => $mediaFileLP,
// "metadata" => $file, // "metadata" => $file,
// "gunid" => $gunid, // "gunid" => $gunid,
// "filetype" => $type // "filetype" => $type
// ); // );
// $put = $this->gb->putFile($values, $this->sessid); // $put = $this->gb->putFile($values, $this->sessid);
// //$this->addLogItem("add as new \n"); // //$this->addLogItem("add as new \n");
// if (PEAR::isError($put)) { // if (PEAR::isError($put)) {
// $this->addLogItem("-E- ".date("Ymd-H:i:s"). // $this->addLogItem("-E- ".date("Ymd-H:i:s").
// " addFileToStorage - putFile Error ". // " addFileToStorage - putFile Error ".
// "(".$put->getMessage()."/".$put->getUserInfo().")\n" // "(".$put->getMessage()."/".$put->getUserInfo().")\n"
// ."\n---\n".file_get_contents($file)."\n---\n" // ."\n---\n".file_get_contents($file)."\n---\n"
// ); // );
// file_put_contents($this->statusFile, 'fault|'.$put->getMessage()."/".$put->getUserInfo()); // file_put_contents($this->statusFile, 'fault|'.$put->getMessage()."/".$put->getUserInfo());
// //$this->addLogItem("Error Object: ".print_r($put,true)."\n"); // //$this->addLogItem("Error Object: ".print_r($put,true)."\n");
// return $put; // return $put;
// } // }
// } // }
// $ac = StoredFile::RecallByGunid($gunid); // $ac = StoredFile::RecallByGunid($gunid);
// if (is_null($ac) || PEAR::isError($ac)) { // if (is_null($ac) || PEAR::isError($ac)) {
// return $ac; // return $ac;
// } // }
// $res = $ac->setState('ready'); // $res = $ac->setState('ready');
// if (PEAR::isError($res)) { // if (PEAR::isError($res)) {
// return $res; // return $res;
// } // }
// return true; // return true;
// } // }
/** /**
@ -433,4 +433,4 @@ class Restore {
} }
} // class Restore } // class Restore
?> ?>

View File

@ -4,402 +4,407 @@ require_once("BasicStor.php");
class ScheduleGroup { class ScheduleGroup {
private $groupId; private $groupId;
public function __construct($p_groupId = null) { public function __construct($p_groupId = null) {
$this->groupId = $p_groupId; $this->groupId = $p_groupId;
} }
/** /**
* Convert a date to an ID by stripping out all characters * Convert a date to an ID by stripping out all characters
* and padding with zeros. * and padding with zeros.
* *
* @param string $p_dateStr * @param string $p_dateStr
*/ */
public static function dateToId($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 = 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 = substr($p_dateStr, 0, 17);
$p_dateStr = str_pad($p_dateStr, 17, "0"); $p_dateStr = str_pad($p_dateStr, 17, "0");
return $p_dateStr; return $p_dateStr;
} }
/** /**
* Add the two times together, return the result. * Add the two times together, return the result.
* *
* @param string $p_baseTime * @param string $p_baseTime
* Specified as YYYY-MM-DD HH:MM:SS * Specified as YYYY-MM-DD HH:MM:SS
* *
* @param string $p_addTime * @param string $p_addTime
* Specified as HH:MM:SS.nnnnnn * Specified as HH:MM:SS.nnnnnn
* *
* @return string * @return string
* The end time, to the nearest second. * The end time, to the nearest second.
*/ */
// protected function calculateEndTime($p_startTime, $p_trackTime) { // protected function calculateEndTime($p_startTime, $p_trackTime) {
// $p_trackTime = substr($p_startTime, 0, ); // $p_trackTime = substr($p_startTime, 0, );
// $start = new DateTime(); // $start = new DateTime();
// $interval = new DateInterval() // $interval = new DateInterval()
// //
// } // }
/** /**
* Add a music clip or playlist to the schedule. * Add a music clip or playlist to the schedule.
* *
* @param $p_datetime * @param $p_datetime
* In the format YYYY-MM-DD HH:MM:SS.mmmmmm * In the format YYYY-MM-DD HH:MM:SS.mmmmmm
* @param $p_audioFileId * @param $p_audioFileId
* (optional, either this or $p_playlistId must be set) DB ID of the audio file * (optional, either this or $p_playlistId must be set) DB ID of the audio file
* @param $p_playlistId * @param $p_playlistId
* (optional, either this of $p_audioFileId must be set) DB ID of the playlist * (optional, either this of $p_audioFileId must be set) DB ID of the playlist
* @param $p_options * @param $p_options
* Does nothing at the moment. * Does nothing at the moment.
* *
* @return int|PEAR_Error * @return int|PEAR_Error
* Return PEAR_Error if the item could not be added. * Return PEAR_Error if the item could not be added.
* Error code 555 is a scheduling conflict. * Error code 555 is a scheduling conflict.
*/ */
public function add($p_datetime, $p_audioFileId = null, $p_playlistId = null, $p_options = null) { public function add($p_datetime, $p_audioFileId = null, $p_playlistId = null, $p_options = null) {
global $CC_CONFIG, $CC_DBC; global $CC_CONFIG, $CC_DBC;
if (!is_null($p_audioFileId)) { if (!is_null($p_audioFileId)) {
// Schedule a single audio track // Schedule a single audio track
// Load existing track // Load existing track
$track = StoredFile::Recall($p_audioFileId); $track = StoredFile::Recall($p_audioFileId);
if (is_null($track)) { if (is_null($track)) {
return new PEAR_Error("Could not find audio track."); return new PEAR_Error("Could not find audio track.");
} }
// Check if there are any conflicts with existing entries // Check if there are any conflicts with existing entries
$metadata = $track->getMetadata(); $metadata = $track->getMetadata();
$length = trim($metadata["length"]); $length = trim($metadata["length"]);
if (empty($length)) { if (empty($length)) {
return new PEAR_Error("Length is empty."); return new PEAR_Error("Length is empty.");
} }
if (!Schedule::isScheduleEmptyInRange($p_datetime, $length)) { if (!Schedule::isScheduleEmptyInRange($p_datetime, $length)) {
return new PEAR_Error("Schedule conflict.", 555); return new PEAR_Error("Schedule conflict.", 555);
} }
// Insert into the table // Insert into the table
$this->groupId = $CC_DBC->GetOne("SELECT nextval('schedule_group_id_seq')"); $this->groupId = $CC_DBC->GetOne("SELECT nextval('schedule_group_id_seq')");
$id = $this->dateToId($p_datetime); $id = $this->dateToId($p_datetime);
$sql = "INSERT INTO ".$CC_CONFIG["scheduleTable"] $sql = "INSERT INTO ".$CC_CONFIG["scheduleTable"]
." (id, playlist_id, starts, ends, clip_length, group_id, file_id)" ." (id, playlist_id, starts, ends, clip_length, group_id, file_id)"
." VALUES ($id, 0, TIMESTAMP '$p_datetime', " ." VALUES ($id, 0, TIMESTAMP '$p_datetime', "
." (TIMESTAMP '$p_datetime' + INTERVAL '$length')," ." (TIMESTAMP '$p_datetime' + INTERVAL '$length'),"
." '$length'," ." '$length',"
." {$this->groupId}, $p_audioFileId)"; ." {$this->groupId}, $p_audioFileId)";
$result = $CC_DBC->query($sql); $result = $CC_DBC->query($sql);
if (PEAR::isError($result)) { if (PEAR::isError($result)) {
var_dump($sql); var_dump($sql);
return $result; return $result;
} }
return $this->groupId; return $this->groupId;
} elseif (!is_null($p_playlistId)){ } elseif (!is_null($p_playlistId)){
// Schedule a whole playlist // Schedule a whole playlist
// Load existing playlist // Load existing playlist
$playlist = Playlist::Recall($p_playlistId); $playlist = Playlist::Recall($p_playlistId);
if (is_null($playlist)) { if (is_null($playlist)) {
return new PEAR_Error("Could not find playlist."); return new PEAR_Error("Could not find playlist.");
} }
// Check if there are any conflicts with existing entries // Check if there are any conflicts with existing entries
$length = trim($playlist->getLength()); $length = trim($playlist->getLength());
if (empty($length)) { var_dump($length);
return new PEAR_Error("Length is empty."); if (empty($length)) {
} return new PEAR_Error("Length is empty.");
if (!Schedule::isScheduleEmptyInRange($p_datetime, $length)) { }
return new PEAR_Error("Schedule conflict.", 555); if (!Schedule::isScheduleEmptyInRange($p_datetime, $length)) {
} return new PEAR_Error("Schedule conflict.", 555);
}
// Insert all items into the schedule // Insert all items into the schedule
$this->groupId = $CC_DBC->GetOne("SELECT nextval('schedule_group_id_seq')"); $this->groupId = $CC_DBC->GetOne("SELECT nextval('schedule_group_id_seq')");
$id = $this->dateToId($p_datetime); $id = $this->dateToId($p_datetime);
$itemStartTime = $p_datetime; $itemStartTime = $p_datetime;
$plItems = $playlist->getContents(); $plItems = $playlist->getContents();
foreach ($plItems as $row) { var_dump($plItems);
$trackLength = $row["cliplength"]; foreach ($plItems as $row) {
$sql = "INSERT INTO ".$CC_CONFIG["scheduleTable"] $trackLength = $row["cliplength"];
." (id, playlist_id, starts, ends, group_id, file_id," var_dump($trackLength);
." clip_length, cue_in, cue_out, fade_in, fade_out)" $sql = "INSERT INTO ".$CC_CONFIG["scheduleTable"]
." VALUES ($id, $p_playlistId, TIMESTAMP '$itemStartTime', " ." (id, playlist_id, starts, ends, group_id, file_id,"
." (TIMESTAMP '$itemStartTime' + INTERVAL '$trackLength')," ." clip_length, cue_in, cue_out, fade_in, fade_out)"
." '{$this->groupId}', '{$row['file_id']}', '$trackLength', '{$row['cuein']}'," ." VALUES ($id, $p_playlistId, TIMESTAMP '$itemStartTime', "
." '{$row['cueout']}', '{$row['fadein']}','{$row['fadeout']}')"; ." (TIMESTAMP '$itemStartTime' + INTERVAL '$trackLength'),"
$result = $CC_DBC->query($sql); ." '{$this->groupId}', '{$row['file_id']}', '$trackLength', '{$row['cuein']}',"
if (PEAR::isError($result)) { ." '{$row['cueout']}', '{$row['fadein']}','{$row['fadeout']}')";
var_dump($sql); $result = $CC_DBC->query($sql);
return $result; 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) { public function addAfter($p_groupId, $p_audioFileId) {
global $CC_CONFIG, $CC_DBC; global $CC_CONFIG, $CC_DBC;
// Get the end time for the given entry // Get the end time for the given entry
$sql = "SELECT ends FROM ".$CC_CONFIG["scheduleTable"] $sql = "SELECT ends FROM ".$CC_CONFIG["scheduleTable"]
." WHERE group_id=$p_groupId"; ." WHERE group_id=$p_groupId";
$startTime = $CC_DBC->GetOne($sql); $startTime = $CC_DBC->GetOne($sql);
return $this->add($startTime, $p_audioFileId); 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;
} }
$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. * Remove the group from the schedule.
* @return array * Note: does not check if it is in the past, you can remove anything.
*/ *
public function getItems() { * @return boolean
global $CC_CONFIG, $CC_DBC; * TRUE on success, false if there is no group ID defined.
$sql = "SELECT * FROM {$CC_CONFIG['scheduleTable']}" */
." WHERE group_id={$this->groupId}"; public function remove() {
return $CC_DBC->GetAll($sql); 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) { return $CC_DBC->query($sql);
global $CC_CONFIG, $CC_DBC; }
// $sql = "UPDATE ".$CC_CONFIG["scheduleTable"]. " SET id=, starts=,ends="
} /**
* 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 { 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) { /**
// * Return true if there is nothing in the schedule for the given times.
// } *
// * @param string $p_datetime
// public function onRemoveTrackFromPlaylist($playlistId, $audioTrackId) { * @param string $p_length
// *
// } * @return boolean|PEAR_Error
*/
/** public static function isScheduleEmptyInRange($p_datetime, $p_length) {
* Return TRUE if file is going to be played in the future. global $CC_CONFIG, $CC_DBC;
* if (empty($p_length)) {
* @param string $p_fileId return new PEAR_Error("Schedule::isSchedulerEmptyInRange: param p_length is empty.");
*/ }
public function IsFileScheduledInTheFuture($p_fileId) $sql = "SELECT COUNT(*) FROM ".$CC_CONFIG["scheduleTable"]
{ ." WHERE (starts >= '$p_datetime') "
global $CC_CONFIG, $CC_DBC; ." AND (ends <= (TIMESTAMP '$p_datetime' + INTERVAL '$p_length'))";
$sql = "SELECT COUNT(*) FROM ".$CC_CONFIG["scheduleTable"] //$_SESSION["debug"] = $sql;
." WHERE file_id = {$p_fileId} AND starts > NOW()"; var_dump($sql);
$count = $CC_DBC->GetOne($sql); $count = $CC_DBC->GetOne($sql);
if (is_numeric($count) && ($count != '0')) { var_dump($count);
return TRUE; return ($count == '0');
} else { }
return FALSE;
// 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: * Returns array indexed numberically of:
* "playlistId"/"playlist_id" (aliases to the same thing) * "playlistId"/"playlist_id" (aliases to the same thing)
* "start"/"starts" (aliases to the same thing) as YYYY-MM-DD HH:MM:SS.nnnnnn * "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 * "end"/"ends" (aliases to the same thing) as YYYY-MM-DD HH:MM:SS.nnnnnn
* "group_id"/"id" (aliases to the same thing) * "group_id"/"id" (aliases to the same thing)
* "clip_length" (for playlists only, this is the length of the entire playlist) * "clip_length" (for playlists only, this is the length of the entire playlist)
* "name" (playlist only) * "name" (playlist only)
* "creator" (playlist only) * "creator" (playlist only)
* "file_id" (audioclip only) * "file_id" (audioclip only)
* "count" (number of items in the playlist, always 1 for audioclips. * "count" (number of items in the playlist, always 1 for audioclips.
* Note that playlists with one item will also have count = 1. * Note that playlists with one item will also have count = 1.
* *
* @param string $p_fromDateTime * @param string $p_fromDateTime
* In the format YYYY-MM-DD HH:MM:SS.nnnnnn * In the format YYYY-MM-DD HH:MM:SS.nnnnnn
* @param string $p_toDateTime * @param string $p_toDateTime
* In the format YYYY-MM-DD HH:MM:SS.nnnnnn * In the format YYYY-MM-DD HH:MM:SS.nnnnnn
* @param boolean $p_playlistsOnly * @param boolean $p_playlistsOnly
* Retreive playlists as a single item. * Retreive playlists as a single item.
* @return array * @return array
* Returns empty array if nothing found * Returns empty array if nothing found
*/ */
public static function GetItems($p_fromDateTime, $p_toDateTime, $p_playlistsOnly = true) { public static function GetItems($p_fromDateTime, $p_toDateTime, $p_playlistsOnly = true) {
global $CC_CONFIG, $CC_DBC; global $CC_CONFIG, $CC_DBC;
$rows = array(); $rows = array();
if (!$p_playlistsOnly) { if (!$p_playlistsOnly) {
$sql = "SELECT * FROM ".$CC_CONFIG["scheduleTable"] $sql = "SELECT * FROM ".$CC_CONFIG["scheduleTable"]
." WHERE (starts >= TIMESTAMP '$p_fromDateTime') " ." WHERE (starts >= TIMESTAMP '$p_fromDateTime') "
." AND (ends <= TIMESTAMP '$p_toDateTime')"; ." AND (ends <= TIMESTAMP '$p_toDateTime')";
$rows = $CC_DBC->GetAll($sql); $rows = $CC_DBC->GetAll($sql);
foreach ($rows as &$row) { foreach ($rows as &$row) {
$row["count"] = "1"; $row["count"] = "1";
$row["playlistId"] = $row["playlist_id"]; $row["playlistId"] = $row["playlist_id"];
$row["start"] = $row["starts"]; $row["start"] = $row["starts"];
$row["end"] = $row["ends"]; $row["end"] = $row["ends"];
$row["id"] = $row["group_id"]; $row["id"] = $row["group_id"];
} }
} else { } else {
$sql = "SELECT MIN(name) AS name, MIN(creator) AS creator, group_id, " $sql = "SELECT MIN(name) AS name, MIN(creator) AS creator, group_id, "
." SUM(clip_length) AS clip_length," ." SUM(clip_length) AS clip_length,"
." MIN(file_id) AS file_id, COUNT(*) as count," ." MIN(file_id) AS file_id, COUNT(*) as count,"
." MIN(playlist_id) AS playlist_id, MIN(starts) AS starts, MAX(ends) AS ends" ." MIN(playlist_id) AS playlist_id, MIN(starts) AS starts, MAX(ends) AS ends"
." FROM ".$CC_CONFIG["scheduleTable"] ." FROM ".$CC_CONFIG["scheduleTable"]
." LEFT JOIN ".$CC_CONFIG["playListTable"]." ON playlist_id = ".$CC_CONFIG["playListTable"].".id" ." LEFT JOIN ".$CC_CONFIG["playListTable"]." ON playlist_id = ".$CC_CONFIG["playListTable"].".id"
." WHERE (starts >= TIMESTAMP '$p_fromDateTime') AND (ends <= TIMESTAMP '$p_toDateTime')" ." WHERE (starts >= TIMESTAMP '$p_fromDateTime') AND (ends <= TIMESTAMP '$p_toDateTime')"
." GROUP BY group_id" ." GROUP BY group_id"
." ORDER BY starts"; ." ORDER BY starts";
//var_dump($sql); //var_dump($sql);
$rows = $CC_DBC->GetAll($sql); $rows = $CC_DBC->GetAll($sql);
if (!PEAR::isError($rows)) { if (!PEAR::isError($rows)) {
foreach ($rows as &$row) { foreach ($rows as &$row) {
$row["playlistId"] = $row["playlist_id"]; $row["playlistId"] = $row["playlist_id"];
$row["start"] = $row["starts"]; $row["start"] = $row["starts"];
$row["end"] = $row["ends"]; $row["end"] = $row["ends"];
$row["id"] = $row["group_id"]; $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) { private static function CcTimeToPypoTime($p_time) {
$p_time = substr($p_time, 0, 19); $p_time = substr($p_time, 0, 19);
$p_time = str_replace(" ", "-", $p_time); $p_time = str_replace(" ", "-", $p_time);
$p_time = str_replace(":", "-", $p_time); $p_time = str_replace(":", "-", $p_time);
return $p_time; return $p_time;
} }
private static function PypoTimeToCcTime($p_time) { private static function PypoTimeToCcTime($p_time) {
$t = explode("-", $p_time); $t = explode("-", $p_time);
return $t[0]."-".$t[1]."-".$t[2]." ".$t[3].":".$t[4].":00"; return $t[0]."-".$t[1]."-".$t[2]." ".$t[3].":".$t[4].":00";
} }
/** /**
* Export the schedule in json formatted for pypo (the liquidsoap scheduler) * Export the schedule in json formatted for pypo (the liquidsoap scheduler)
* *
* @param string $range * @param string $range
* In the format "YYYY-MM-DD HH:mm:ss" * In the format "YYYY-MM-DD HH:mm:ss"
* @param string $source * @param string $source
* In the format "YYYY-MM-DD HH:mm:ss" * In the format "YYYY-MM-DD HH:mm:ss"
*/ */
public static function ExportRangeAsJson($p_fromDateTime, $p_toDateTime) public static function ExportRangeAsJson($p_fromDateTime, $p_toDateTime)
{ {
global $CC_CONFIG, $CC_DBC; global $CC_CONFIG, $CC_DBC;
$range_start = Schedule::PypoTimeToCcTime($p_fromDateTime); $range_start = Schedule::PypoTimeToCcTime($p_fromDateTime);
$range_end = Schedule::PypoTimeToCcTime($p_toDateTime); $range_end = Schedule::PypoTimeToCcTime($p_toDateTime);
$range_dt = array('start' => $range_start, 'end' => $range_end); $range_dt = array('start' => $range_start, 'end' => $range_end);
//var_dump($range_dt); //var_dump($range_dt);
// Scheduler wants everything in a playlist // Scheduler wants everything in a playlist
$data = Schedule::GetItems($range_start, $range_end, true); $data = Schedule::GetItems($range_start, $range_end, true);
//echo "<pre>";var_dump($data); //echo "<pre>";var_dump($data);
$playlists = array(); $playlists = array();
if (is_array($data) && count($data) > 0) if (is_array($data) && count($data) > 0)
{ {
foreach ($data as $dx) foreach ($data as $dx)
{ {
// Is this the first item in the playlist? // Is this the first item in the playlist?
$start = $dx['start']; $start = $dx['start'];
// chop off subseconds // chop off subseconds
$start = substr($start, 0, 19); $start = substr($start, 0, 19);
// Start time is the array key, needs to be in the format "YYYY-MM-DD-HH-mm-ss" // Start time is the array key, needs to be in the format "YYYY-MM-DD-HH-mm-ss"
$pkey = Schedule::CcTimeToPypoTime($start); $pkey = Schedule::CcTimeToPypoTime($start);
$timestamp = strtotime($start); $timestamp = strtotime($start);
$playlists[$pkey]['source'] = "PLAYLIST"; $playlists[$pkey]['source'] = "PLAYLIST";
$playlists[$pkey]['x_ident'] = $dx["playlist_id"]; $playlists[$pkey]['x_ident'] = $dx["playlist_id"];
$playlists[$pkey]['subtype'] = '1'; // Just needs to be between 1 and 4 inclusive $playlists[$pkey]['subtype'] = '1'; // Just needs to be between 1 and 4 inclusive
$playlists[$pkey]['timestamp'] = $timestamp; $playlists[$pkey]['timestamp'] = $timestamp;
$playlists[$pkey]['duration'] = $dx['clip_length']; $playlists[$pkey]['duration'] = $dx['clip_length'];
$playlists[$pkey]['played'] = '0'; $playlists[$pkey]['played'] = '0';
$playlists[$pkey]['schedule_id'] = $dx['group_id']; $playlists[$pkey]['schedule_id'] = $dx['group_id'];
} }
} }
foreach ($playlists as &$playlist) foreach ($playlists as &$playlist)
{ {
$scheduleGroup = new ScheduleGroup($playlist["schedule_id"]); $scheduleGroup = new ScheduleGroup($playlist["schedule_id"]);
$items = $scheduleGroup->getItems(); $items = $scheduleGroup->getItems();
$medias = array(); $medias = array();
$playlist['subtype'] = '1'; $playlist['subtype'] = '1';
foreach ($items as $item) foreach ($items as $item)
{ {
$storedFile = StoredFile::Recall($item["file_id"]); $storedFile = StoredFile::Recall($item["file_id"]);
$uri = $storedFile->getFileUrl(); $uri = $storedFile->getFileUrl();
$medias[] = array( $medias[] = array(
'id' => $storedFile->getGunid(), //$item["file_id"], 'id' => $storedFile->getGunid(), //$item["file_id"],
'uri' => $uri, 'uri' => $uri,
'fade_in' => $item["fade_in"], 'fade_in' => $item["fade_in"],
@ -407,18 +412,18 @@ class Schedule {
'fade_cross' => 0, 'fade_cross' => 0,
'cue_in' => $item["cue_in"], 'cue_in' => $item["cue_in"],
'cue_out' => $item["cue_out"], 'cue_out' => $item["cue_out"],
); );
} }
$playlist['medias'] = $medias; $playlist['medias'] = $medias;
} }
$result = array(); $result = array();
$result['status'] = array('range' => $range_dt, 'version' => 0.2); $result['status'] = array('range' => $range_dt, 'version' => 0.2);
$result['playlists'] = $playlists; $result['playlists'] = $playlists;
$result['check'] = 1; $result['check'] = 1;
print json_encode($result); print json_encode($result);
} }
} }

View File

@ -58,24 +58,24 @@ class SmilPlaylist {
} }
$lspl = SmilPlaylist::convert2lspl($gb, $path, $gunids, $parr); $lspl = SmilPlaylist::convert2lspl($gb, $path, $gunids, $parr);
if (PEAR::isError($lspl)) { if (PEAR::isError($lspl)) {
return $lspl; return $lspl;
} }
require_once("Playlist.php"); require_once("Playlist.php");
$pl =& Playlist::create($gb, $plid, "imported_SMIL"); $pl =& Playlist::create($gb, $plid, "imported_SMIL");
if (PEAR::isError($pl)) { if (PEAR::isError($pl)) {
return $pl; return $pl;
} }
$r = $pl->lock($gb, $subjid); $r = $pl->lock($gb, $subjid);
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
} }
$r = $pl->setMetadata($lspl, 'string', 'playlist'); $r = $pl->setMetadata($lspl, 'string', 'playlist');
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
} }
$r = $pl->unlock($gb); $r = $pl->unlock($gb);
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
} }
return $pl; return $pl;
} }
@ -99,7 +99,7 @@ class SmilPlaylist {
extract($parr); extract($parr);
$tree = SmilPlaylist::parse($data); $tree = SmilPlaylist::parse($data);
if (PEAR::isError($tree)) { if (PEAR::isError($tree)) {
return $tree; return $tree;
} }
if ($tree->name != 'smil') { if ($tree->name != 'smil') {
return PEAR::raiseError("SmilPlaylist::parse: smil tag expected"); return PEAR::raiseError("SmilPlaylist::parse: smil tag expected");
@ -107,11 +107,11 @@ class SmilPlaylist {
if (isset($tree->children[1])) { if (isset($tree->children[1])) {
return PEAR::raiseError(sprintf( return PEAR::raiseError(sprintf(
"SmilPlaylist::parse: unexpected tag %s in tag smil", "SmilPlaylist::parse: unexpected tag %s in tag smil",
$tree->children[1]->name $tree->children[1]->name
)); ));
} }
$res = SmilPlaylistBodyElement::convert2lspl( $res = SmilPlaylistBodyElement::convert2lspl(
$gb, $tree->children[0], &$gunids, $parr); $gb, $tree->children[0], &$gunids, $parr);
return $res; return $res;
} }
@ -136,13 +136,13 @@ class SmilPlaylistBodyElement {
if (isset($tree->children[1])) { if (isset($tree->children[1])) {
return PEAR::raiseError(sprintf( return PEAR::raiseError(sprintf(
"SmilPlaylist::parse: unexpected tag %s in tag body", "SmilPlaylist::parse: unexpected tag %s in tag body",
$tree->children[1]->name $tree->children[1]->name
)); ));
} }
$res = SmilPlaylistParElement::convert2lspl( $res = SmilPlaylistParElement::convert2lspl(
$gb, $tree->children[0], &$gunids, $parr, $ind2); $gb, $tree->children[0], &$gunids, $parr, $ind2);
if (PEAR::isError($res)) { if (PEAR::isError($res)) {
return $res; return $res;
} }
$title = basename($rPath); $title = basename($rPath);
$playlength = '0'; $playlength = '0';
@ -165,7 +165,7 @@ class SmilPlaylistBodyElement {
*/ */
class SmilPlaylistParElement { class SmilPlaylistParElement {
public static function convert2lspl(&$gb, &$tree, &$gunids, $parr, $ind='') public static function convert2lspl(&$gb, &$tree, &$gunids, $parr, $ind='')
{ {
extract($parr); extract($parr);
if ($tree->name != 'par') { if ($tree->name != 'par') {
@ -176,7 +176,7 @@ class SmilPlaylistParElement {
$ch =& $tree->children[$i]; $ch =& $tree->children[$i];
$r = SmilPlaylistAudioElement::convert2lspl($gb, $ch, &$gunids, $parr, $ind.INDCH); $r = SmilPlaylistAudioElement::convert2lspl($gb, $ch, &$gunids, $parr, $ind.INDCH);
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
} }
$res .= $r; $res .= $r;
} }
@ -204,7 +204,7 @@ class SmilPlaylistAudioElement {
if (isset($tree->children[2])) { if (isset($tree->children[2])) {
return PEAR::raiseError(sprintf( return PEAR::raiseError(sprintf(
"SmilPlaylist::parse: unexpected tag %s in tag audio", "SmilPlaylist::parse: unexpected tag %s in tag audio",
$tree->children[2]->name $tree->children[2]->name
)); ));
} }
$res = ''; $fadeIn = 0; $fadeOut = 0; $res = ''; $fadeIn = 0; $fadeOut = 0;
@ -212,7 +212,7 @@ class SmilPlaylistAudioElement {
$ch =& $tree->children[$i]; $ch =& $tree->children[$i];
$r = SmilPlaylistAnimateElement::convert2lspl($gb, $ch, &$gunids, $parr, $ind2); $r = SmilPlaylistAnimateElement::convert2lspl($gb, $ch, &$gunids, $parr, $ind2);
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
} }
switch ($r['type']) { switch ($r['type']) {
case "fadeIn": $fadeIn = $r['val']; break; case "fadeIn": $fadeIn = $r['val']; break;
@ -225,7 +225,7 @@ class SmilPlaylistAudioElement {
$fadeOut = Playlist::secondsToPlaylistTime($fadeOut); $fadeOut = Playlist::secondsToPlaylistTime($fadeOut);
$fInfo = "$ind2<fadeInfo id=\"$fiGunid\" fadeIn=\"$fadeIn\" fadeOut=\"$fadeOut\"/>\n"; $fInfo = "$ind2<fadeInfo id=\"$fiGunid\" fadeIn=\"$fadeIn\" fadeOut=\"$fadeOut\"/>\n";
} else { } else {
$fInfo = ''; $fInfo = '';
} }
$plElGunid = StoredFile::CreateGunid(); $plElGunid = StoredFile::CreateGunid();
$acGunid = $gunid; $acGunid = $gunid;
@ -238,19 +238,19 @@ class SmilPlaylistAudioElement {
case "m3u": case "m3u":
$type = 'playlist'; $type = 'playlist';
$acId = $gb->bsImportPlaylistRaw($gunid, $acId = $gb->bsImportPlaylistRaw($gunid,
$aPath, $uri, $ext, $gunids, $subjid); $aPath, $uri, $ext, $gunids, $subjid);
if (PEAR::isError($acId)) { if (PEAR::isError($acId)) {
return $r; return $r;
} }
//break; //break;
default: default:
$ac = StoredFile::RecallByGunid($gunid); $ac = StoredFile::RecallByGunid($gunid);
if (is_null($ac) || PEAR::isError($ac)) { if (is_null($ac) || PEAR::isError($ac)) {
return $ac; return $ac;
} }
$r = $ac->md->getMetadataElement('dcterms:extent'); $r = $ac->md->getMetadataElement('dcterms:extent');
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
} }
$playlength = $r[0]['value']; $playlength = $r[0]['value'];
} }
@ -263,7 +263,7 @@ class SmilPlaylistAudioElement {
$clipLength = Playlist::secondsToPlaylistTime($tree->attrs['clipLength']->val); $clipLength = Playlist::secondsToPlaylistTime($tree->attrs['clipLength']->val);
$res = "$ind<playlistElement id=\"$plElGunid\" relativeOffset=\"$offset\" clipStart=\"$clipStart\" clipEnd=\"$clipEnd\" clipLength=\"$clipLength\">\n". $res = "$ind<playlistElement id=\"$plElGunid\" relativeOffset=\"$offset\" clipStart=\"$clipStart\" clipEnd=\"$clipEnd\" clipLength=\"$clipLength\">\n".
"$ind2<$type id=\"$acGunid\" playlength=\"$playlength\" title=\"$title\"/>\n". "$ind2<$type id=\"$acGunid\" playlength=\"$playlength\" title=\"$title\"/>\n".
$fInfo. $fInfo.
"$ind</playlistElement>\n"; "$ind</playlistElement>\n";
return $res; return $res;
} }
@ -278,35 +278,35 @@ class SmilPlaylistAudioElement {
*/ */
class SmilPlaylistAnimateElement { class SmilPlaylistAnimateElement {
public static function convert2lspl(&$gb, &$tree, &$gunids, $parr, $ind='') public static function convert2lspl(&$gb, &$tree, &$gunids, $parr, $ind='')
{ {
extract($parr); extract($parr);
if ($tree->name != 'animate') { if ($tree->name != 'animate') {
return PEAR::raiseError("SmilPlaylist::parse: animate tag expected"); return PEAR::raiseError("SmilPlaylist::parse: animate tag expected");
} }
if ($tree->attrs['attributeName']->val == 'soundLevel' && if ($tree->attrs['attributeName']->val == 'soundLevel' &&
$tree->attrs['from']->val == '0%' && $tree->attrs['from']->val == '0%' &&
$tree->attrs['to']->val == '100%' && $tree->attrs['to']->val == '100%' &&
$tree->attrs['calcMode']->val == 'linear' && $tree->attrs['calcMode']->val == 'linear' &&
$tree->attrs['fill']->val == 'freeze' && $tree->attrs['fill']->val == 'freeze' &&
$tree->attrs['begin']->val == '0s' && $tree->attrs['begin']->val == '0s' &&
preg_match("|^([0-9.]+)s$|", $tree->attrs['end']->val, $va) preg_match("|^([0-9.]+)s$|", $tree->attrs['end']->val, $va)
) { ) {
return array('type'=>'fadeIn', 'val'=>intval($va[1])); return array('type'=>'fadeIn', 'val'=>intval($va[1]));
} }
if ($tree->attrs['attributeName']->val == 'soundLevel' && if ($tree->attrs['attributeName']->val == 'soundLevel' &&
$tree->attrs['from']->val == '100%' && $tree->attrs['from']->val == '100%' &&
$tree->attrs['to']->val == '0%' && $tree->attrs['to']->val == '0%' &&
$tree->attrs['calcMode']->val == 'linear' && $tree->attrs['calcMode']->val == 'linear' &&
$tree->attrs['fill']->val == 'freeze' && $tree->attrs['fill']->val == 'freeze' &&
preg_match("|^([0-9.]+)s$|", $tree->attrs['begin']->val, $vaBegin) && preg_match("|^([0-9.]+)s$|", $tree->attrs['begin']->val, $vaBegin) &&
preg_match("|^([0-9.]+)s$|", $tree->attrs['end']->val, $vaEnd) preg_match("|^([0-9.]+)s$|", $tree->attrs['end']->val, $vaEnd)
) { ) {
return array('type'=>'fadeOut', 'val'=>($vaEnd[1] - $vaBegin[1])); return array('type'=>'fadeOut', 'val'=>($vaEnd[1] - $vaBegin[1]));
} }
return PEAR::raiseError( return PEAR::raiseError(
"SmilPlaylistAnimateElement::convert2lspl: animate parameters too general" "SmilPlaylistAnimateElement::convert2lspl: animate parameters too general"
); );
} }
} // class SmilPlaylistAnimateElement } // class SmilPlaylistAnimateElement

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -12,9 +12,9 @@ define('TR_LEAVE_CLOSED', TRUE);
*/ */
class TransportRecord class TransportRecord
{ {
/** /**
* @var DB * @var DB
*/ */
//public $dbc; //public $dbc;
/** /**
@ -72,12 +72,12 @@ class TransportRecord
$trec = new TransportRecord($tr); $trec = new TransportRecord($tr);
$trec->trtok = $trtok = $tr->_createTransportToken(); $trec->trtok = $trtok = $tr->_createTransportToken();
$trec->row = array_merge($defaults, $trec->row = array_merge($defaults,
array('trtype'=>$trtype, 'direction'=>$direction)); array('trtype'=>$trtype, 'direction'=>$direction));
$trec->recalled = TRUE; $trec->recalled = TRUE;
if (!isset($defaults['title'])) { if (!isset($defaults['title'])) {
$defaults['title'] = $trec->getTitle(); $defaults['title'] = $trec->getTitle();
if (PEAR::isError($defaults['title'])) { if (PEAR::isError($defaults['title'])) {
return $defaults['title']; return $defaults['title'];
} }
} }
$id = $CC_DBC->nextId($CC_CONFIG['transSequence']); $id = $CC_DBC->nextId($CC_CONFIG['transSequence']);
@ -96,7 +96,7 @@ class TransportRecord
"; ";
$res = $CC_DBC->query($query); $res = $CC_DBC->query($query);
if (PEAR::isError($res)) { if (PEAR::isError($res)) {
return $res; return $res;
} }
return $trec; return $trec;
} }
@ -126,7 +126,7 @@ class TransportRecord
WHERE trtok='$trtok' WHERE trtok='$trtok'
"); ");
if (PEAR::isError($row)) { if (PEAR::isError($row)) {
return $row; return $row;
} }
if (is_null($row)) { if (is_null($row)) {
return PEAR::raiseError("TransportRecord::recall:". return PEAR::raiseError("TransportRecord::recall:".
@ -170,16 +170,16 @@ class TransportRecord
UPDATE ".$CC_CONFIG['transTable']." UPDATE ".$CC_CONFIG['transTable']."
SET $set SET $set
WHERE trtok='{$this->trtok}'". WHERE trtok='{$this->trtok}'".
(is_null($oldState) ? '' : " AND state='$oldState'"). (is_null($oldState) ? '' : " AND state='$oldState'").
(is_null($lock) ? '' : " AND lock = '$slock'") (is_null($lock) ? '' : " AND lock = '$slock'")
); );
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
} }
// return TRUE; // return TRUE;
$affRows = $CC_DBC->affectedRows(); $affRows = $CC_DBC->affectedRows();
if (PEAR::isError($affRows)) { if (PEAR::isError($affRows)) {
return $affRows; return $affRows;
} }
return ($affRows == 1); return ($affRows == 1);
} }
@ -217,7 +217,7 @@ class TransportRecord
global $CC_CONFIG, $CC_DBC; global $CC_CONFIG, $CC_DBC;
$pidsql = (is_null($pid) ? "NULL" : "$pid" ); $pidsql = (is_null($pid) ? "NULL" : "$pid" );
if ($this->dropped) { if ($this->dropped) {
return TRUE; return TRUE;
} }
$slock = ($lock ? 'Y' : 'N'); $slock = ($lock ? 'Y' : 'N');
$nlock = (!$lock); $nlock = (!$lock);
@ -228,11 +228,11 @@ class TransportRecord
WHERE trtok='{$this->trtok}' AND lock = '$snlock'" WHERE trtok='{$this->trtok}' AND lock = '$snlock'"
); );
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
} }
$affRows = $CC_DBC->affectedRows(); $affRows = $CC_DBC->affectedRows();
if (PEAR::isError($affRows)) { if (PEAR::isError($affRows)) {
return $affRows; return $affRows;
} }
if ($affRows === 0) { if ($affRows === 0) {
$ltxt = ($lock ? 'lock' : 'unlock' ); $ltxt = ($lock ? 'lock' : 'unlock' );
@ -303,7 +303,7 @@ class TransportRecord
} }
$r = $this->setState('failed', array('errmsg'=>$msg)); $r = $this->setState('failed', array('errmsg'=>$msg));
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
} }
return TRUE; return TRUE;
} }
@ -326,7 +326,7 @@ class TransportRecord
if (TR_LEAVE_CLOSED) { if (TR_LEAVE_CLOSED) {
$r = $this->setState('closed'); $r = $this->setState('closed');
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
} }
} else { } else {
$r = $CC_DBC->query(" $r = $CC_DBC->query("
@ -334,7 +334,7 @@ class TransportRecord
WHERE trtok='{$this->trtok}' WHERE trtok='{$this->trtok}'
"); ");
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
} }
$this->recalled = FALSE; $this->recalled = FALSE;
$this->dropped = TRUE; $this->dropped = TRUE;
@ -383,7 +383,7 @@ class TransportRecord
$defStr = 'unknown'; $defStr = 'unknown';
$trtype = $this->getTransportType(); //contains recall check $trtype = $this->getTransportType(); //contains recall check
if (PEAR::isError($trtype)) { if (PEAR::isError($trtype)) {
return $trtype; return $trtype;
} }
switch ($trtype) { switch ($trtype) {
case "audioclip": case "audioclip":
@ -396,9 +396,9 @@ class TransportRecord
} }
if (PEAR::isError($title)) { if (PEAR::isError($title)) {
if ($title->getCode() == GBERR_FOBJNEX) { if ($title->getCode() == GBERR_FOBJNEX) {
$title = $defStr; $title = $defStr;
} else { } else {
return $title; return $title;
} }
} }
break; break;
@ -407,10 +407,10 @@ class TransportRecord
break; break;
case "file": case "file":
$title = ( isset($this->row['localfile']) ? $title = ( isset($this->row['localfile']) ?
basename($this->row['localfile']) : 'regular file'); basename($this->row['localfile']) : 'regular file');
break; break;
default: default:
$title = $defStr; $title = $defStr;
} }
return $title; return $title;
} }

View File

@ -67,12 +67,12 @@ class Validator {
'webstream' => "webstreamFormat", 'webstream' => "webstreamFormat",
); );
if (!isset($formats[$format])) { if (!isset($formats[$format])) {
return $this->_err(VAL_FORMAT); return $this->_err(VAL_FORMAT);
} }
$formatName = $formats[$format]; $formatName = $formats[$format];
$formatFile = dirname(__FILE__)."/$formatName.php"; $formatFile = dirname(__FILE__)."/$formatName.php";
if (!file_exists($formatFile)) { if (!file_exists($formatFile)) {
return $this->_err(VAL_FORMAT); return $this->_err(VAL_FORMAT);
} }
require($formatFile); require($formatFile);
$this->formTree = $$formatName; $this->formTree = $$formatName;
@ -151,15 +151,15 @@ class Validator {
$dname = (($node->ns? $node->ns.":" : '').$node->name); $dname = (($node->ns? $node->ns.":" : '').$node->name);
$formTree =& $this->formTree; $formTree =& $this->formTree;
if (DEBUG) { if (DEBUG) {
echo"\nVAL::validateNode: 1 $dname/$fname\n"; echo"\nVAL::validateNode: 1 $dname/$fname\n";
} }
// check root node name: // check root node name:
if ($dname != $fname) { if ($dname != $fname) {
return $this->_err(VAL_ROOT, $fname); return $this->_err(VAL_ROOT, $fname);
} }
// check if this element is defined in format: // check if this element is defined in format:
if (!isset($formTree[$fname])) { if (!isset($formTree[$fname])) {
return $this->_err(VAL_NOTDEF, $fname); return $this->_err(VAL_NOTDEF, $fname);
} }
// check element content // check element content
if (isset($formTree[$fname]['regexp'])) { if (isset($formTree[$fname]['regexp'])) {
@ -171,12 +171,12 @@ class Validator {
// validate attributes: // validate attributes:
$ra = $this->validateAttributes($node, $fname); $ra = $this->validateAttributes($node, $fname);
if (PEAR::isError($ra)) { if (PEAR::isError($ra)) {
return $ra; return $ra;
} }
// validate children: // validate children:
$r = $this->validateChildren($node, $fname); $r = $this->validateChildren($node, $fname);
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
} }
return TRUE; return TRUE;
} }
@ -251,7 +251,7 @@ class Validator {
// call children recursive: // call children recursive:
$r = $this->validateNode($node->children[$i], $chname); $r = $this->validateNode($node->children[$i], $chname);
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
} }
$childs[$chname] = TRUE; $childs[$chname] = TRUE;
} }
@ -269,13 +269,13 @@ class Validator {
foreach ($fchilds['oneof'] as $i => $ch) { foreach ($fchilds['oneof'] as $i => $ch) {
if (isset($childs[$ch])) { if (isset($childs[$ch])) {
if ($one) { if ($one) {
return $this->_err(VAL_UNEXPONEOF, "$ch in $fname"); return $this->_err(VAL_UNEXPONEOF, "$ch in $fname");
} }
$one = TRUE; $one = TRUE;
} }
} }
if (!$one) { if (!$one) {
return $this->_err(VAL_NOONEOF); return $this->_err(VAL_NOONEOF);
} }
} }
} }
@ -340,9 +340,9 @@ class Validator {
{ {
$formTree =& $this->formTree; $formTree =& $this->formTree;
$listed = ( $listed = (
isset($formTree[$fname][$nType][$reqType]) ? isset($formTree[$fname][$nType][$reqType]) ?
array_search($chname, $formTree[$fname][$nType][$reqType]) : array_search($chname, $formTree[$fname][$nType][$reqType]) :
FALSE FALSE
); );
return $listed; return $listed;
} }
@ -360,22 +360,22 @@ class Validator {
function _err($errno, $par='') function _err($errno, $par='')
{ {
$msg = array( $msg = array(
VAL_ROOT => 'Wrong root element', VAL_ROOT => 'Wrong root element',
VAL_NOREQE => 'Required element missing', VAL_NOREQE => 'Required element missing',
VAL_NOONEOF => 'One-of element missing', VAL_NOONEOF => 'One-of element missing',
VAL_UNKNOWNE => 'Unknown element', VAL_UNKNOWNE => 'Unknown element',
VAL_UNKNOWNA => 'Unknown attribute', VAL_UNKNOWNA => 'Unknown attribute',
VAL_NOTDEF => 'Not defined', VAL_NOTDEF => 'Not defined',
VAL_UNEXPONEOF => 'Unexpected second object from one-of set', VAL_UNEXPONEOF => 'Unexpected second object from one-of set',
VAL_FORMAT => 'Unknown format', VAL_FORMAT => 'Unknown format',
VAL_CONTENT => 'Invalid content', VAL_CONTENT => 'Invalid content',
VAL_NOREQA => 'Required attribute missing', VAL_NOREQA => 'Required attribute missing',
VAL_ATTRIB => 'Invalid attribute format', VAL_ATTRIB => 'Invalid attribute format',
VAL_PREDXML => 'Invalid predicate type', VAL_PREDXML => 'Invalid predicate type',
); );
return PEAR::raiseError( return PEAR::raiseError(
"Validator: {$msg[$errno]} #$errno ($par, gunid={$this->gunid})", "Validator: {$msg[$errno]} #$errno ($par, gunid={$this->gunid})",
$errno $errno
); );
} }

View File

@ -164,12 +164,12 @@ class XmlParser {
$res = xml_parse($xml_parser, $data, TRUE); $res = xml_parse($xml_parser, $data, TRUE);
if (!$res) { if (!$res) {
$this->err = array(TRUE, $this->err = array(TRUE,
sprintf("XML error: %s at line %d\n", sprintf("XML error: %s at line %d\n",
xml_error_string(xml_get_error_code($xml_parser)), xml_error_string(xml_get_error_code($xml_parser)),
xml_get_current_line_number($xml_parser) xml_get_current_line_number($xml_parser)
) )
); );
// var_dump($data); // var_dump($data);
} }
xml_parser_free($xml_parser); xml_parser_free($xml_parser);
} }
@ -188,31 +188,31 @@ class XmlParser {
function &parse($data='', $loc='file') function &parse($data='', $loc='file')
{ {
switch ($loc) { switch ($loc) {
case "file": case "file":
if (!is_file($data)) { if (!is_file($data)) {
return PEAR::raiseError( return PEAR::raiseError(
"XmlParser::parse: file not found ($data)" "XmlParser::parse: file not found ($data)"
); );
} }
if (!is_readable($data)) { if (!is_readable($data)) {
return PEAR::raiseError( return PEAR::raiseError(
"XmlParser::parse: can't read file ($data)" "XmlParser::parse: can't read file ($data)"
); );
} }
$data = file_get_contents($data); $data = file_get_contents($data);
case "string": case "string":
$parser = new XmlParser($data); $parser = new XmlParser($data);
if ($parser->isError()) { if ($parser->isError()) {
return PEAR::raiseError( return PEAR::raiseError(
"XmlParser::parse: ".$parser->getError() "XmlParser::parse: ".$parser->getError()
); );
} }
$tree = $parser->getTree(); $tree = $parser->getTree();
break; break;
default: default:
return PEAR::raiseError( return PEAR::raiseError(
"XmlParser::parse: unsupported source location ($loc)" "XmlParser::parse: unsupported source location ($loc)"
); );
} }
return $tree; return $tree;
} }
@ -237,7 +237,7 @@ class XmlParser {
$atnm = $a['localPart']; $atnm = $a['localPart'];
unset($attrs[$atn]); unset($attrs[$atn]);
if ($atns == 'xmlns') { if ($atns == 'xmlns') {
$nSpaces[$atnm] = $atv; $nSpaces[$atnm] = $atv;
} else if ($atns == NULL && $atnm == 'xmlns') { } else if ($atns == NULL && $atnm == 'xmlns') {
$nSpaces[''] = $atv; $nSpaces[''] = $atv;
} else { } else {
@ -280,7 +280,7 @@ class XmlParser {
function characterData($parser, $data) { function characterData($parser, $data) {
$cnt = count($this->stack); $cnt = count($this->stack);
if (trim($data)!='') { 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) == ";"){ //if(substr($data, 0, 1) == "&" && substr($data, -1, 1) == ";"){
// $this->stack[$cnt-1]->content .= trim($data); // $this->stack[$cnt-1]->content .= trim($data);
//}else{ //}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}"); $res .= XML_Util::replaceEntities("{$el->content}");
if ($haveCh) { if ($haveCh) {
$res .= "\n{$ind}"; $res .= "\n{$ind}";
} }
$res .= "</{$fullName}>"; $res .= "</{$fullName}>";
return $res; return $res;

View File

@ -5,7 +5,7 @@ require_once('Common.php');
/** /**
* Skeleton subclass for representing a row from the 'cc_playlistcontents' table. * Skeleton subclass for representing a row from the 'cc_playlistcontents' table.
* *
* *
* *
* You should add additional methods to this class to meet the * You should add additional methods to this class to meet the
* application requirements. This class will only be generated as * application requirements. This class will only be generated as
@ -15,55 +15,55 @@ require_once('Common.php');
*/ */
class CcPlaylistcontents extends BaseCcPlaylistcontents { class CcPlaylistcontents extends BaseCcPlaylistcontents {
public function getDbFadein() public function getDbFadein()
{
return $this->fadein;
}
public function setDbFadein($time)
{ {
$this->fadein = $time; return $this->fadein;
//$this->modifiedColumns[] = CcPlaylistcontentsPeer::FADEIN; }
public function setDbFadein($time)
{
$this->fadein = $time;
//$this->modifiedColumns[] = CcPlaylistcontentsPeer::FADEIN;
return Common::setTimeInSub($this, 'FADEIN', $time); return Common::setTimeInSub($this, 'FADEIN', $time);
} }
public function getDbFadeout() public function getDbFadeout()
{ {
return $this->fadeout; return $this->fadeout;
} }
public function setDbFadeout($time) public function setDbFadeout($time)
{ {
$this->fadeout = $time; $this->fadeout = $time;
//$this->modifiedColumns[] = CcPlaylistcontentsPeer::FADEOUT; //$this->modifiedColumns[] = CcPlaylistcontentsPeer::FADEOUT;
return Common::setTimeInSub($this, 'FADEOUT', $time); return Common::setTimeInSub($this, 'FADEOUT', $time);
} }
public function getDbCuein() public function getDbCuein()
{ {
return $this->cuein; return $this->cuein;
} }
public function setDbCuein($time) public function setDbCuein($time)
{ {
$this->cuein = $time; $this->cuein = $time;
//$this->modifiedColumns[] = CcPlaylistcontentsPeer::CUEIN; //$this->modifiedColumns[] = CcPlaylistcontentsPeer::CUEIN;
return Common::setTimeInSub($this, 'CUEIN', $time); return Common::setTimeInSub($this, 'CUEIN', $time);
} }
public function getDbCueout() public function getDbCueout()
{ {
return $this->cueout; return $this->cueout;
} }
public function setDbCueout($time) public function setDbCueout($time)
{ {
$this->cueout = $time; $this->cueout = $time;
//$this->modifiedColumns[] = CcPlaylistcontentsPeer::CUEOUT; //$this->modifiedColumns[] = CcPlaylistcontentsPeer::CUEOUT;
return Common::setTimeInSub($this, 'CUEOUT', $time); return Common::setTimeInSub($this, 'CUEOUT', $time);
} }
public function getDbCliplength() public function getDbCliplength()
{ {
return $this->cliplength; return $this->cliplength;
} }
@ -71,11 +71,8 @@ class CcPlaylistcontents extends BaseCcPlaylistcontents {
public function setDbCliplength($time) public function setDbCliplength($time)
{ {
$this->cliplength = $time; $this->cliplength = $time;
//$this->modifiedColumns[] = CcPlaylistcontentsPeer::CLIPLENGTH; //$this->modifiedColumns[] = CcPlaylistcontentsPeer::CLIPLENGTH;
return Common::setTimeInSub($this, 'CLIPLENGTH', $time); return Common::setTimeInSub($this, 'CLIPLENGTH', $time);
} }
} // CcPlaylistcontents } // CcPlaylistcontents

View File

@ -1,19 +1,19 @@
<?php <?php
class Common { class Common {
public static function setTimeInSub($row, $col, $time)
{
$class = get_class($row).'Peer';
$con = Propel::getConnection($class::DATABASE_NAME);
$sql = 'UPDATE '.$class::TABLE_NAME public static function setTimeInSub($row, $col, $time)
. ' SET '.$col.' = :f1' {
. ' WHERE ' .$class::ID. ' = :p1'; $class = get_class($row).'Peer';
$stmt = $con->prepare($sql);
$stmt->bindValue(':f1', $time); $con = Propel::getConnection($class::DATABASE_NAME);
$stmt->bindValue(':p1', $row->getDbId());
$stmt->execute(); $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();
}
} }

View File

@ -40,7 +40,7 @@ function errHndl($errno, $errmsg, $filename, $linenum, $vars)
break; break;
default: default:
$xr = new XML_RPC_Response(0, 805, $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"); header("Content-type: text/xml");
echo $xr->serialize(); echo $xr->serialize();
exit($errno); exit($errno);
@ -159,10 +159,10 @@ $defs = array();
foreach ($methods as $method => $description) { foreach ($methods as $method => $description) {
$defs["locstor.$method"] = array( $defs["locstor.$method"] = array(
"function" => array(&$locStor, "xr_$method"), "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( "signature" => array(
array($GLOBALS['XML_RPC_Struct'], $GLOBALS['XML_RPC_Struct']) array($GLOBALS['XML_RPC_Struct'], $GLOBALS['XML_RPC_Struct'])
), ),
"docstring" => $description "docstring" => $description
); );
} }

View File

@ -14,71 +14,71 @@ $g_inputErrors = array();
* @package Campsite * @package Campsite
*/ */
class Input { class Input {
/** /**
* Please see: {@link http://ca.php.net/manual/en/function.get-magic-quotes-gpc.php * 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}, * this PHP.net page specifically the user note by php at kaiundina dot de},
* for why this is so complicated. * for why this is so complicated.
* *
* @param array $p_array * @param array $p_array
* @return array * @return array
*/ */
function CleanMagicQuotes($p_array) function CleanMagicQuotes($p_array)
{ {
$gpcList = array(); $gpcList = array();
foreach ($p_array as $key => $value) { foreach ($p_array as $key => $value) {
$decodedKey = stripslashes($key); $decodedKey = stripslashes($key);
if (is_array($value)) { if (is_array($value)) {
$decodedValue = Input::CleanMagicQuotes($value); $decodedValue = Input::CleanMagicQuotes($value);
} else { } else {
$decodedValue = stripslashes($value); $decodedValue = stripslashes($value);
} }
$gpcList[$decodedKey] = $decodedValue; $gpcList[$decodedKey] = $decodedValue;
} }
return $gpcList; return $gpcList;
} // fn CleanMagicQuotes } // fn CleanMagicQuotes
/** /**
* Get an input value from the $_REQUEST array and check its type. * 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 * 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. * $_REQUEST array, or if the value does not match the required type.
* *
* The type 'checkbox' is special - you cannot specify a default * The type 'checkbox' is special - you cannot specify a default
* value for this. The return value will be TRUE or FALSE, but * value for this. The return value will be TRUE or FALSE, but
* you can change this by specifying 'numeric' as the 3rd parameter * you can change this by specifying 'numeric' as the 3rd parameter
* in which case it will return '1' or '0'. * in which case it will return '1' or '0'.
* *
* Use Input::IsValid() to check if any errors were generated. * Use Input::IsValid() to check if any errors were generated.
* *
* @param string $p_varName * @param string $p_varName
* The index into the $_REQUEST array. * The index into the $_REQUEST array.
* *
* @param string $p_type * @param string $p_type
* The type of data expected; can be: * The type of data expected; can be:
* "int" * "int"
* "string" * "string"
* "array" * "array"
* "checkbox" * "checkbox"
* "boolean" * "boolean"
* *
* Default is 'string'. * Default is 'string'.
* *
* @param mixed $p_defaultValue * @param mixed $p_defaultValue
* The default value to return if the value is not defined in * The default value to return if the value is not defined in
* the $_REQUEST array, or if the value does not match * the $_REQUEST array, or if the value does not match
* the required type. * the required type.
* *
* @param boolean $p_errorsOk * @param boolean $p_errorsOk
* Set to true to ignore any errors for this variable (i.e. * Set to true to ignore any errors for this variable (i.e.
* Input::IsValid() will still return true even if there * Input::IsValid() will still return true even if there
* are errors for this varaible). * are errors for this varaible).
* *
* @return mixed * @return mixed
*/ */
function Get($p_varName, $p_type = 'string', $p_defaultValue = null, $p_errorsOk = false) function Get($p_varName, $p_type = 'string', $p_defaultValue = null, $p_errorsOk = false)
{ {
global $g_inputErrors; global $g_inputErrors;
$p_type = strtolower($p_type); $p_type = strtolower($p_type);
if ($p_type == 'checkbox') { if ($p_type == 'checkbox') {
@ -88,99 +88,99 @@ class Input {
return isset($_REQUEST[$p_varName]) ? '1' : '0'; return isset($_REQUEST[$p_varName]) ? '1' : '0';
} }
} }
if (!isset($_REQUEST[$p_varName])) { if (!isset($_REQUEST[$p_varName])) {
if (!$p_errorsOk) { if (!$p_errorsOk) {
$g_inputErrors[$p_varName] = 'not set'; $g_inputErrors[$p_varName] = 'not set';
} }
return $p_defaultValue; return $p_defaultValue;
} }
// Clean the slashes // Clean the slashes
if (get_magic_quotes_gpc()) { if (get_magic_quotes_gpc()) {
if (is_array($_REQUEST[$p_varName])) { if (is_array($_REQUEST[$p_varName])) {
$_REQUEST[$p_varName] = Input::CleanMagicQuotes($_REQUEST[$p_varName]); $_REQUEST[$p_varName] = Input::CleanMagicQuotes($_REQUEST[$p_varName]);
} else { } else {
$_REQUEST[$p_varName] = stripslashes($_REQUEST[$p_varName]); $_REQUEST[$p_varName] = stripslashes($_REQUEST[$p_varName]);
} }
} }
switch ($p_type) { switch ($p_type) {
case 'boolean': case 'boolean':
$value = strtolower($_REQUEST[$p_varName]); $value = strtolower($_REQUEST[$p_varName]);
if ( ($value == "true") || (is_numeric($value) && ($value > 0)) ) { if ( ($value == "true") || (is_numeric($value) && ($value > 0)) ) {
return true; return true;
} else { } else {
return false; return false;
} }
break; break;
case 'int': case 'int':
if (!is_numeric($_REQUEST[$p_varName])) { if (!is_numeric($_REQUEST[$p_varName])) {
if (!$p_errorsOk) { if (!$p_errorsOk) {
$g_inputErrors[$p_varName] = 'Incorrect type. Expected type '.$p_type $g_inputErrors[$p_varName] = 'Incorrect type. Expected type '.$p_type
.', but received type '.gettype($_REQUEST[$p_varName]).'.' .', but received type '.gettype($_REQUEST[$p_varName]).'.'
.' Value is "'.$_REQUEST[$p_varName].'".'; .' Value is "'.$_REQUEST[$p_varName].'".';
} }
return $p_defaultValue; return $p_defaultValue;
} }
break; break;
case 'string': case 'string':
if (!is_string($_REQUEST[$p_varName])) { if (!is_string($_REQUEST[$p_varName])) {
if (!$p_errorsOk) { if (!$p_errorsOk) {
$g_inputErrors[$p_varName] = 'Incorrect type. Expected type '.$p_type $g_inputErrors[$p_varName] = 'Incorrect type. Expected type '.$p_type
.', but received type '.gettype($_REQUEST[$p_varName]).'.' .', but received type '.gettype($_REQUEST[$p_varName]).'.'
.' Value is "'.$_REQUEST[$p_varName].'".'; .' Value is "'.$_REQUEST[$p_varName].'".';
} }
return $p_defaultValue; return $p_defaultValue;
} }
break; break;
case 'array': case 'array':
if (!is_array($_REQUEST[$p_varName])) { if (!is_array($_REQUEST[$p_varName])) {
// Create an array if it isnt one already. // Create an array if it isnt one already.
// Arrays are used with checkboxes and radio buttons. // Arrays are used with checkboxes and radio buttons.
// The problem with them is that if there is only one // The problem with them is that if there is only one
// checkbox, the given value will not be an array. So // checkbox, the given value will not be an array. So
// we make it easy for the programmer by always returning // we make it easy for the programmer by always returning
// an array. // an array.
$newArray = array(); $newArray = array();
$newArray[] = $_REQUEST[$p_varName]; $newArray[] = $_REQUEST[$p_varName];
return $newArray; return $newArray;
// if (!$p_errorsOk) { // if (!$p_errorsOk) {
// $g_inputErrors[$p_varName] = 'Incorrect type. Expected type '.$p_type // $g_inputErrors[$p_varName] = 'Incorrect type. Expected type '.$p_type
// .', but received type '.gettype($_REQUEST[$p_varName]).'.' // .', but received type '.gettype($_REQUEST[$p_varName]).'.'
// .' Value is "'.$_REQUEST[$p_varName].'".'; // .' Value is "'.$_REQUEST[$p_varName].'".';
// } // }
// return $p_defaultValue; // return $p_defaultValue;
} }
} }
return $_REQUEST[$p_varName]; return $_REQUEST[$p_varName];
} // fn get } // fn get
/** /**
* Return FALSE if any calls to Input::Get() resulted in an error. * Return FALSE if any calls to Input::Get() resulted in an error.
* @return boolean * @return boolean
*/ */
function IsValid() function IsValid()
{ {
global $g_inputErrors; global $g_inputErrors;
if (count($g_inputErrors) > 0) { if (count($g_inputErrors) > 0) {
return false; return false;
} else { } else {
return true; return true;
} }
} // fn isValid } // fn isValid
/** /**
* Return a default error string. * Return a default error string.
* @return string * @return string
*/ */
function GetErrorString() function GetErrorString()
{ {
global $g_inputErrors; global $g_inputErrors;
ob_start(); ob_start();
print_r($g_inputErrors); print_r($g_inputErrors);
$str = ob_get_clean(); $str = ob_get_clean();
return $str; return $str;
} // fn GetErrorString } // fn GetErrorString
} // class Input } // class Input

View File

@ -47,7 +47,7 @@ class twitter{
var $username=''; var $username='';
var $password=''; var $password='';
var $user_agent=''; var $user_agent='';
/////////////// ///////////////
// //
// I don't know if these headers have become standards yet // I don't know if these headers have become standards yet
@ -59,16 +59,16 @@ class twitter{
var $headers=array('X-Twitter-Client: ', var $headers=array('X-Twitter-Client: ',
'X-Twitter-Client-Version: ', 'X-Twitter-Client-Version: ',
'X-Twitter-Client-URL: '); 'X-Twitter-Client-URL: ');
var $responseInfo=array(); var $responseInfo=array();
function twitter(){} function twitter(){}
///////////////////////////////////////// /////////////////////////////////////////
// //
// Twitter API calls // 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. // Requires the status parameter specified below.
// //
// status. (string) Required. The text of your status update. Must not be // status. (string) Required. The text of your status update. Must not be
@ -105,7 +105,7 @@ class twitter{
$postargs = 'status='.urlencode($status); $postargs = 'status='.urlencode($status);
return $this->process($request,$postargs); return $this->process($request,$postargs);
} }
// Returns the 20 most recent statuses from non-protected users who have // Returns the 20 most recent statuses from non-protected users who have
// set a custom user icon. Does not require authentication. // set a custom user icon. Does not require authentication.
// //
@ -114,12 +114,13 @@ class twitter{
// //
function publicTimeline($sinceid=false){ function publicTimeline($sinceid=false){
$qs=''; $qs='';
if($sinceid!==false) if($sinceid!==false) {
$qs='?since_id='.intval($sinceid); $qs='?since_id='.intval($sinceid);
}
$request = 'http://twitter.com/statuses/public_timeline.xml'.$qs; $request = 'http://twitter.com/statuses/public_timeline.xml'.$qs;
return $this->process($request); return $this->process($request);
} }
// Returns the 20 most recent statuses posted in the last 24 hours from the // 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 // authenticating user and that user's friends. It's also possible to request
// another user's friends_timeline via the id parameter below. // 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 // to return the friends_timeline. (set to false if you
// want to use authenticated user). // want to use authenticated user).
// since. (HTTP-formatted date) Optional. Narrows the returned results to just those // 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){ function friendsTimeline($id=false,$since=false){
$qs=''; $qs='';
if($since!==false) if($since!==false) {
$qs='?since='.urlencode($since); $qs='?since='.urlencode($since);
}
if($id===false)
if($id===false) {
$request = 'http://twitter.com/statuses/friends_timeline.xml'.$qs; $request = 'http://twitter.com/statuses/friends_timeline.xml'.$qs;
else } else {
$request = 'http://twitter.com/statuses/friends_timeline/'.urlencode($id).'.xml'.$qs; $request = 'http://twitter.com/statuses/friends_timeline/'.urlencode($id).'.xml'.$qs;
}
return $this->process($request); return $this->process($request);
} }
// Returns the 20 most recent statuses posted in the last 24 hours from the // 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 // authenticating user. It's also possible to request another user's timeline
// via the id parameter below. // via the id parameter below.
@ -157,16 +159,17 @@ class twitter{
function userTimeline($id=false,$count=20,$since=false){ function userTimeline($id=false,$count=20,$since=false){
$qs='?count='.intval($count); $qs='?count='.intval($count);
if($since!==false) if($since!==false)
$qs .= '&since='.urlencode($since); $qs .= '&since='.urlencode($since);
if($id===false) if($id===false) {
$request = 'http://twitter.com/statuses/user_timeline.xml'.$qs; $request = 'http://twitter.com/statuses/user_timeline.xml'.$qs;
else } else {
$request = 'http://twitter.com/statuses/user_timeline/'.urlencode($id).'.xml'.$qs; $request = 'http://twitter.com/statuses/user_timeline/'.urlencode($id).'.xml'.$qs;
}
return $this->process($request); return $this->process($request);
} }
// Returns a single status, specified by the id parameter below. The status's author // Returns a single status, specified by the id parameter below. The status's author
// will be returned inline. // will be returned inline.
// //
@ -184,25 +187,25 @@ class twitter{
// //
function friends($id=false){ function friends($id=false){
if($id===false) if($id===false)
$request = 'http://twitter.com/statuses/friends.xml'; $request = 'http://twitter.com/statuses/friends.xml';
else else
$request = 'http://twitter.com/statuses/friends/'.urlencode($id).'.xml'; $request = 'http://twitter.com/statuses/friends/'.urlencode($id).'.xml';
return $this->process($request); return $this->process($request);
} }
// Returns the authenticating user's followers, each with current status inline. // Returns the authenticating user's followers, each with current status inline.
// //
function followers(){ function followers(){
$request = 'http://twitter.com/statuses/followers.xml'; $request = 'http://twitter.com/statuses/followers.xml';
return $this->process($request); return $this->process($request);
} }
// Returns a list of the users currently featured on the site with their current statuses inline. // Returns a list of the users currently featured on the site with their current statuses inline.
function featured(){ function featured(){
$request = 'http://twitter.com/statuses/featured.xml'; $request = 'http://twitter.com/statuses/featured.xml';
return $this->process($request); return $this->process($request);
} }
// Returns extended information of a given user, specified by ID or screen name as per the required // 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 // id parameter below. This information includes design settings, so third party developers can theme
// their widgets according to a given user's preferences. // their widgets according to a given user's preferences.
@ -213,52 +216,54 @@ class twitter{
$request = 'http://twitter.com/users/show/'.urlencode($id).'.xml'; $request = 'http://twitter.com/users/show/'.urlencode($id).'.xml';
return $this->process($request); return $this->process($request);
} }
// Returns a list of the direct messages sent to the authenticating user. // 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 // 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){ function directMessages($since=false){
$qs=''; $qs='';
if($since!==false) if($since!==false) {
$qs='?since='.urlencode($since); $qs='?since='.urlencode($since);
}
$request = 'http://twitter.com/direct_messages.xml'.$qs; $request = 'http://twitter.com/direct_messages.xml'.$qs;
return $this->process($request); return $this->process($request);
} }
// Sends a new direct message to the specified user from the authenticating user. Requires both the user // Sends a new direct message to the specified user from the authenticating user. Requires both the user
// and text parameters below. // and text parameters below.
// //
// user. (string OR int) Required. The ID or screen name of the recipient user. // 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 // 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){ function sendDirectMessage($user,$text){
$request = 'http://twitter.com/direct_messages/new.xml'; $request = 'http://twitter.com/direct_messages/new.xml';
$postargs = 'user='.urlencode($user).'&text='.urlencode($text); $postargs = 'user='.urlencode($user).'&text='.urlencode($text);
return $this->process($request,$postargs); return $this->process($request,$postargs);
} }
// internal function where all the juicy curl fun takes place // internal function where all the juicy curl fun takes place
// this should not be called by anything external unless you are // this should not be called by anything external unless you are
// doing something else completely then knock youself out. // doing something else completely then knock youself out.
function process($url,$postargs=false){ function process($url,$postargs=false){
$ch = curl_init($url); $ch = curl_init($url);
if($postargs !== false){ if($postargs !== false){
curl_setopt ($ch, CURLOPT_POST, true); curl_setopt ($ch, CURLOPT_POST, true);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postargs); 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_USERPWD, $this->username.':'.$this->password);
}
curl_setopt($ch, CURLOPT_VERBOSE, 0); curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_NOBODY, 0); curl_setopt($ch, CURLOPT_NOBODY, 0);
curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_HEADER, 0);
@ -268,17 +273,17 @@ class twitter{
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers); curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers);
$response = curl_exec($ch); $response = curl_exec($ch);
$this->responseInfo=curl_getinfo($ch); $this->responseInfo=curl_getinfo($ch);
curl_close($ch); curl_close($ch);
if(intval($this->responseInfo['http_code'])==200){ if(intval($this->responseInfo['http_code'])==200){
if(class_exists('SimpleXMLElement')){ if(class_exists('SimpleXMLElement')){
$xml = new SimpleXMLElement($response); $xml = new SimpleXMLElement($response);
return $xml; return $xml;
}else{ }else{
return $response; return $response;
} }
}else{ }else{
return false; return false;

View File

@ -80,18 +80,18 @@ function _getDArr($format)
{ {
#$arr[''] = '00'; #$arr[''] = '00';
switch($format) { switch($format) {
case 'h': case 'h':
for($n=0; $n<=23; $n++) { for($n=0; $n<=23; $n++) {
$arr[sprintf('%02d', $n)] = sprintf('%02d', $n); $arr[sprintf('%02d', $n)] = sprintf('%02d', $n);
} }
break; break;
case 'm': case 'm':
case 's': case 's':
for($n=0; $n<=59; $n++) { for($n=0; $n<=59; $n++) {
$arr[sprintf('%02d', $n)] = sprintf('%02d', $n); $arr[sprintf('%02d', $n)] = sprintf('%02d', $n);
} }
break; break;
} }
return $arr; return $arr;
@ -238,9 +238,9 @@ class uiBase
'EXCHANGE' => array('class' => 'uiexchange', 'file' => 'ui_exchange.class.php'), 'EXCHANGE' => array('class' => 'uiexchange', 'file' => 'ui_exchange.class.php'),
'TRANSFERS' => array('class' => 'uitransfers', 'file' => 'ui_transfers.class.php'), 'TRANSFERS' => array('class' => 'uitransfers', 'file' => 'ui_transfers.class.php'),
'CALENDAR' => array('class' => 'uicalendar', 'file' => 'ui_calendar.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'), '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; global $CC_DBC, $CC_CONFIG;
$this->gb = new GreenBox(); $this->gb = new GreenBox();
$CC_CONFIG['accessRawAudioUrl'] = $CC_CONFIG['storageUrlPath'].'/xmlrpc/simpleGet.php'; $CC_CONFIG['accessRawAudioUrl'] = $CC_CONFIG['storageUrlPath'].'/xmlrpc/simpleGet.php';
$this->sessid = isset($_REQUEST[$CC_CONFIG['authCookieName']]) ? $this->sessid = isset($_REQUEST[$CC_CONFIG['authCookieName']]) ? $_REQUEST[$CC_CONFIG['authCookieName']] : null;
$_REQUEST[$CC_CONFIG['authCookieName']] : null;
$this->userid = GreenBox::GetSessUserId($this->sessid); $this->userid = GreenBox::GetSessUserId($this->sessid);
$this->login = Alib::GetSessLogin($this->sessid); $this->login = Alib::GetSessLogin($this->sessid);
if (PEAR::isError($this->login)) { if (PEAR::isError($this->login)) {
@ -269,8 +268,8 @@ class uiBase
$this->id = $this->gb->storId; $this->id = $this->gb->storId;
} }
if (!is_null($this->id)) { if (!is_null($this->id)) {
$f = StoredFile::Recall($this->id); $f = StoredFile::Recall($this->id);
$this->type = $f->getType(); $this->type = $f->getType();
} }
} }
@ -314,10 +313,10 @@ class uiBase
{ {
global $CC_CONFIG; global $CC_CONFIG;
if (!is_array($this->STATIONPREFS) || ($reload === TRUE) ) { if (!is_array($this->STATIONPREFS) || ($reload === TRUE) ) {
$this->STATIONPREFS = array(); $this->STATIONPREFS = array();
foreach ($mask as $key => $val) { foreach ($mask as $key => $val) {
if (isset($val['isPref']) && $val['isPref']) { 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)) { if (is_string($setting)) {
$this->STATIONPREFS[$val['element']] = $setting; $this->STATIONPREFS[$val['element']] = $setting;
} elseif ($val['required']) { } elseif ($val['required']) {
@ -399,9 +398,9 @@ class uiBase
} }
$elem[$v['element']] =& $form->createElement($type, $elem[$v['element']] =& $form->createElement($type,
$v['element'], $v['element'],
$label, $label,
$attrs); $attrs);
if (!$groupit) { if (!$groupit) {
$form->addElement($elem[$v['element']]); $form->addElement($elem[$v['element']]);
} }
@ -458,21 +457,21 @@ class uiBase
* @param array $input * @param array $input
* array of form-elements * array of form-elements
*/ */
// function _dateArr2Str(&$input) // function _dateArr2Str(&$input)
// { // {
// foreach ($input as $k => $v){ // foreach ($input as $k => $v){
// if (is_array($v)) { // if (is_array($v)) {
// if ( ( isset($v['d']) ) && ( isset($v['M']) || isset($v['m']) ) && ( isset($v['Y']) || isset($v['y']) ) ) { // 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']); // $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']) ) ) { // 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']); // $input[$k] = sprintf('%02d', $v['H'].$v['h']).':'.sprintf('%02d', $v['i']).':'.sprintf('%02d', $v['s']);
// } // }
// } // }
// } // }
// //
// return $input; // return $input;
// } // fn _dateArr2Str // } // fn _dateArr2Str
/** /**
@ -482,35 +481,35 @@ class uiBase
* local ID of file * local ID of file
* @param string $format * @param string $format
*/ */
// public function analyzeFile($id, $format) // public function analyzeFile($id, $format)
// { // {
// $ia = $this->gb->analyzeFile($id, $this->sessid); // $ia = $this->gb->analyzeFile($id, $this->sessid);
// $s = $ia['playtime_seconds']; // $s = $ia['playtime_seconds'];
// $extent = date('H:i:s', floor($s)-date('Z')).substr(number_format($s, 6), strpos(number_format($s, 6), '.')); // $extent = date('H:i:s', floor($s)-date('Z')).substr(number_format($s, 6), strpos(number_format($s, 6), '.'));
// //
// if ($format=='text') { // if ($format=='text') {
// return "<div align='left'><pre>".var_export($ia, TRUE)."</pre></div>"; // return "<div align='left'><pre>".var_export($ia, TRUE)."</pre></div>";
// } // }
// return FALSE; // return FALSE;
// } // }
// public function toHex($gunid) // public function toHex($gunid)
// { // {
// global $CC_DBC; // global $CC_DBC;
// $res = $CC_DBC->query("SELECT to_hex($gunid)"); // $res = $CC_DBC->query("SELECT to_hex($gunid)");
// $row = $res->fetchRow(); // $row = $res->fetchRow();
// return $row['to_hex']; // return $row['to_hex'];
// } // }
// public function toInt8($gunid) // public function toInt8($gunid)
// { // {
// global $CC_DBC; // global $CC_DBC;
// $res = $CC_DBC->query("SELECT x'$gunid'::bigint"); // $res = $CC_DBC->query("SELECT x'$gunid'::bigint");
// $row = $res->fetchRow(); // $row = $res->fetchRow();
// return $row['int8']; // return $row['int8'];
// } // }
/** /**
@ -535,8 +534,8 @@ class uiBase
'creator' => $this->gb->getPLMetadataValue($id, UI_MDATA_KEY_CREATOR), 'creator' => $this->gb->getPLMetadataValue($id, UI_MDATA_KEY_CREATOR),
'duration' => $this->gb->getPLMetadataValue($id, UI_MDATA_KEY_DURATION), 'duration' => $this->gb->getPLMetadataValue($id, UI_MDATA_KEY_DURATION),
'type' => 'playlist', 'type' => 'playlist',
); );
return ($data); return ($data);
} }
public function getMetaInfo($id) public function getMetaInfo($id)
@ -552,8 +551,8 @@ class uiBase
'source' => $type == 'audioclip' ? $media->getMetadataValue($id, UI_MDATA_KEY_SOURCE) : NULL, 'source' => $type == 'audioclip' ? $media->getMetadataValue($id, UI_MDATA_KEY_SOURCE) : NULL,
'bitRate' => $type == 'audioclip' ? $media->getMetadataValue($id, UI_MDATA_KEY_BITRATE) : NULL, 'bitRate' => $type == 'audioclip' ? $media->getMetadataValue($id, UI_MDATA_KEY_BITRATE) : NULL,
'sampleRate' => $type == 'audioclip' ? $media->getMetadataValue($id, UI_MDATA_KEY_SAMPLERATE) : NULL, 'sampleRate' => $type == 'audioclip' ? $media->getMetadataValue($id, UI_MDATA_KEY_SAMPLERATE) : NULL,
); );
return ($data); return ($data);
} }
@ -594,5 +593,5 @@ class uiBase
return $str; return $str;
} }
} // class uiBase } // class uiBase
?> ?>

View File

@ -102,7 +102,7 @@ class uiBrowse
$this->setCategory(array('col' => $col, $this->setCategory(array('col' => $col,
'category' => $this->col[$col]['category'])); 'category' => $this->col[$col]['category']));
$this->setValue( $this->setValue(
array('col' => $col, array('col' => $col,
'category' => $this->col[$col]['category'], 'category' => $this->col[$col]['category'],
'value' => $this->col[$col]['value'])); 'value' => $this->col[$col]['value']));
} }
@ -118,7 +118,7 @@ class uiBrowse
*/ */
public function getCriteria() public function getCriteria()
{ {
return $this->criteria; return $this->criteria;
} // fn getCriteria } // fn getCriteria
@ -152,8 +152,8 @@ class uiBrowse
'category' => uiBase::formElementEncode($this->col[$n]['category']))); 'category' => uiBase::formElementEncode($this->col[$n]['category'])));
$mask2['browse_columns']['value']['options'] = $this->options($this->col[$n]['values']['results']); $mask2['browse_columns']['value']['options'] = $this->options($this->col[$n]['values']['results']);
$mask2['browse_columns']['category']['attributes']['id'] = "category_" . $n; $mask2['browse_columns']['category']['attributes']['id'] = "category_" . $n;
$mask2['browse_columns']['value']['attributes']['id'] = "category_value_" . $n; $mask2['browse_columns']['value']['attributes']['id'] = "category_value_" . $n;
$mask2['browse_columns']['value']['default'] = $this->col[$n]['form_value']; $mask2['browse_columns']['value']['default'] = $this->col[$n]['form_value'];
uiBase::parseArrayToForm($form, $mask2['browse_columns']); uiBase::parseArrayToForm($form, $mask2['browse_columns']);
@ -214,7 +214,7 @@ class uiBrowse
// reload the values. // reload the values.
for ($i = $columnNumber; $i <= 3; $i++) { for ($i = $columnNumber; $i <= 3; $i++) {
$browseValues = $this->Base->gb->browseCategory( $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)) { if (!PEAR::isError($browseValues)) {
$this->col[$i]['values'] = $browseValues; $this->col[$i]['values'] = $browseValues;
} }
@ -222,7 +222,7 @@ class uiBrowse
} }
if($redirect) { if($redirect) {
$this->Base->redirUrl = UI_BROWSER.'?act='.$this->prefix; $this->Base->redirUrl = UI_BROWSER.'?act='.$this->prefix;
} }
} // fn setCategory } // fn setCategory
@ -249,10 +249,10 @@ class uiBrowse
if ($value == '%%all%%') { if ($value == '%%all%%') {
unset($this->col[$columnNumber]['criteria']['conditions']); unset($this->col[$columnNumber]['criteria']['conditions']);
} else { } else {
$conditions = array('cat' => uiBase::formElementDecode($category), $conditions = array('cat' => uiBase::formElementDecode($category),
'op' => '=', 'op' => '=',
'val' => $value); 'val' => $value);
$this->col[$columnNumber]['criteria']['conditions'] = $conditions; $this->col[$columnNumber]['criteria']['conditions'] = $conditions;
} }
// Clear all columns above this one of selected values. // Clear all columns above this one of selected values.
@ -273,64 +273,64 @@ class uiBrowse
for ($tmpColNum = $columnNumber + 1; $tmpColNum <= 3; $tmpColNum++) { for ($tmpColNum = $columnNumber + 1; $tmpColNum <= 3; $tmpColNum++) {
$tmpCategory = $this->col[$tmpColNum]['category']; $tmpCategory = $this->col[$tmpColNum]['category'];
$browseValues = $this->Base->gb->browseCategory( $browseValues = $this->Base->gb->browseCategory(
$tmpCategory, $tmpCriteria, $this->Base->sessid); $tmpCategory, $tmpCriteria, $this->Base->sessid);
if (!PEAR::isError($browseValues)) { if (!PEAR::isError($browseValues)) {
$this->col[$tmpColNum]['values'] = $browseValues; $this->col[$tmpColNum]['values'] = $browseValues;
} }
} }
if($redirect) { if($redirect) {
$this->Base->redirUrl = UI_BROWSER.'?act='.$this->prefix; $this->Base->redirUrl = UI_BROWSER.'?act='.$this->prefix;
} }
} // fn setValue } // fn setValue
public function refresh($p_param){ public function refresh($p_param){
$category_1 = array( $category_1 = array(
'col' => 1, 'col' => 1,
'category' => $p_param['cat1'] 'category' => $p_param['cat1']
); );
$value_1 = array( $value_1 = array(
'col' => 1, 'col' => 1,
'category' => $p_param['cat1'], 'category' => $p_param['cat1'],
'value' => array( 'value' => array(
0 => $p_param['val1'] 0 => $p_param['val1']
) )
); );
$category_2 = array( $category_2 = array(
'col' => 2, 'col' => 2,
'category' => $p_param['cat2'] 'category' => $p_param['cat2']
); );
$value_2 = array( $value_2 = array(
'col' => 2, 'col' => 2,
'category' => $p_param['cat2'], 'category' => $p_param['cat2'],
'value' => array( 'value' => array(
0 => $p_param['val2'] 0 => $p_param['val2']
) )
); );
$category_3 = array( $category_3 = array(
'col' => 3, 'col' => 3,
'category' => $p_param['cat3'] 'category' => $p_param['cat3']
); );
$value_3 = array( $value_3 = array(
'col' => 3, 'col' => 3,
'category' => $p_param['cat3'], 'category' => $p_param['cat3'],
'value' => array( 'value' => array(
0 => $p_param['val3'] 0 => $p_param['val3']
) )
); );
$this->setCategory($category_1, false); $this->setCategory($category_1, false);
$this->setCategory($category_2, false); $this->setCategory($category_2, false);
$this->setCategory($category_3, false); $this->setCategory($category_3, false);
$this->setValue($value_1, false); $this->setValue($value_1, false);
$this->setValue($value_2, false); $this->setValue($value_2, false);
$this->setValue($value_3, true); $this->setValue($value_3, true);
} }
/** /**
@ -414,10 +414,10 @@ class uiBrowse
} }
if (!isset($this->results['pagination'][1])) { if (!isset($this->results['pagination'][1])) {
$this->results['pagination'][1] = '|<<'; $this->results['pagination'][1] = '|<<';
} }
if (!isset($this->results['pagination'][$maxp])) { 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['next'] = ($results['cnt'] > ($this->criteria['offset'] + $this->criteria['limit'])) ? TRUE : FALSE;
$this->results['prev'] = ($this->criteria['offset'] > 0) ? TRUE : FALSE; $this->results['prev'] = ($this->criteria['offset'] > 0) ? TRUE : FALSE;
@ -490,9 +490,9 @@ class uiBrowse
for ($n = 1; $n <= 3; $n++) { for ($n = 1; $n <= 3; $n++) {
$browseValues = $this->Base->gb->browseCategory( $browseValues = $this->Base->gb->browseCategory(
$this->col[$n]['category'], $this->col[$n]['category'],
$tmpCriteria, $tmpCriteria,
$this->Base->sessid); $this->Base->sessid);
if (!PEAR::isError($browseValues)) { if (!PEAR::isError($browseValues)) {
$this->col[$n]['values'] = $browseValues; $this->col[$n]['values'] = $browseValues;
} }

View File

@ -10,10 +10,10 @@ define('ACTION_BASE', '/actions' ) ;
* @copyright 2010 Sourcefabric O.P.S. * @copyright 2010 Sourcefabric O.P.S.
*/ */
class uiHandler extends uiBase { class uiHandler extends uiBase {
/** /**
* @var string * @var string
*/ */
public $redirUrl; public $redirUrl;
/** /**
* Initialize a new Browser Class * Initialize a new Browser Class
@ -28,12 +28,12 @@ class uiHandler extends uiBase {
// --- authentication --- // --- authentication ---
/** /**
* Login to the storageServer. * Login to the storageServer.
* It set sessid to the cookie with name defined in ../conf.php * It set sessid to the cookie with name defined in ../conf.php
* *
* @param array $formdata * @param array $formdata
* The REQUEST array. * The REQUEST array.
*/ */
function login($formdata, $mask) function login($formdata, $mask)
{ {
global $CC_CONFIG; global $CC_CONFIG;
@ -65,7 +65,7 @@ class uiHandler extends uiBase {
$this->langid = $formdata['langid']; $this->langid = $formdata['langid'];
$this->redirUrl = UI_BROWSER.'?popup[]=_2SCHEDULER&popup[]=_close'; $this->redirUrl = UI_BROWSER.'?popup[]=_2SCHEDULER&popup[]=_close';
return TRUE; return TRUE;
} // fn login } // fn login
/** /**
@ -84,164 +84,164 @@ class uiHandler extends uiBase {
session_destroy(); session_destroy();
if ($trigger_login) { if ($trigger_login) {
$this->redirUrl = UI_BROWSER.'?popup[]=_clear_parent&popup[]=login'; $this->redirUrl = UI_BROWSER.'?popup[]=_clear_parent&popup[]=login';
} else { } else {
$this->redirUrl = UI_BROWSER.'?popup[]=_clear_parent&popup[]=_close'; $this->redirUrl = UI_BROWSER.'?popup[]=_clear_parent&popup[]=_close';
} }
} // fn logout } // fn logout
// --- files --- // --- files ---
function processFile($audio_file, $caller){ function processFile($audio_file, $caller){
global $CC_CONFIG; global $CC_CONFIG;
if ($this->testForAudioType($audio_file) === FALSE) { if ($this->testForAudioType($audio_file) === FALSE) {
die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "uses an unsupported file type."}}'); die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "uses an unsupported file type."}}');
} }
$md5 = md5_file($audio_file); $md5 = md5_file($audio_file);
$duplicate = StoredFile::RecallByMd5($md5); $duplicate = StoredFile::RecallByMd5($md5);
if ($duplicate) { if ($duplicate) {
if (PEAR::isError($duplicate)) { if (PEAR::isError($duplicate)) {
die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": ' . $duplicate->getMessage() .'}}'); die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": ' . $duplicate->getMessage() .'}}');
} }
else { else {
$duplicateName = $this->gb->getMetadataValue($duplicate->getId(), UI_MDATA_KEY_TITLE, $this->sessid); $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."}}'); 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)) { if (PEAR::isError($metadata)) {
die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": ' + $metadata->getMessage() + '}}'); die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": ' + $metadata->getMessage() + '}}');
} }
// #2196 no id tag -> use the original filename // #2196 no id tag -> use the original filename
if (basename($audio_file) == $metadata['dc:title']) { if (basename($audio_file) == $metadata['dc:title']) {
$metadata['dc:title'] = basename($audio_file); $metadata['dc:title'] = basename($audio_file);
$metadata['ls:filename'] = basename($audio_file); $metadata['ls:filename'] = basename($audio_file);
} }
// setMetadataBatch doesnt like these values // setMetadataBatch doesnt like these values
unset($metadata['audio']); unset($metadata['audio']);
unset($metadata['playtime_seconds']); unset($metadata['playtime_seconds']);
$values = array( $values = array(
"filename" => basename($audio_file), "filename" => basename($audio_file),
"filepath" => $audio_file, "filepath" => $audio_file,
"filetype" => "audioclip", "filetype" => "audioclip",
"mime" => $metadata["dc:format"], "mime" => $metadata["dc:format"],
"md5" => $md5 "md5" => $md5
); );
$storedFile = $this->gb->putFile($values, $this->sessid); $storedFile = $this->gb->putFile($values, $this->sessid);
if (PEAR::isError($storedFile)) { if (PEAR::isError($storedFile)) {
die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": ' + $storedFile->getMessage() + '}}'); 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) function pluploadFile($data)
{ {
header('Content-type: text/plain; charset=UTF-8'); header('Content-type: text/plain; charset=UTF-8');
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " 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: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false); header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache"); header("Pragma: no-cache");
// Settings // Settings
$targetDir = ini_get("upload_tmp_dir") . DIRECTORY_SEPARATOR . "plupload"; $targetDir = ini_get("upload_tmp_dir") . DIRECTORY_SEPARATOR . "plupload";
$cleanupTargetDir = false; // Remove old files $cleanupTargetDir = false; // Remove old files
$maxFileAge = 60 * 60; // Temp file age in seconds $maxFileAge = 60 * 60; // Temp file age in seconds
// 5 minutes execution time // 5 minutes execution time
@set_time_limit(5 * 60); @set_time_limit(5 * 60);
// Get parameters // Get parameters
$chunk = isset($_REQUEST["chunk"]) ? $_REQUEST["chunk"] : 0; $chunk = isset($_REQUEST["chunk"]) ? $_REQUEST["chunk"] : 0;
$chunks = isset($_REQUEST["chunks"]) ? $_REQUEST["chunks"] : 0; $chunks = isset($_REQUEST["chunks"]) ? $_REQUEST["chunks"] : 0;
$fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : ''; $fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : '';
// Clean the fileName for security reasons // Clean the fileName for security reasons
//$fileName = preg_replace('/[^\w\._]+/', '', $fileName); //$fileName = preg_replace('/[^\w\._]+/', '', $fileName);
// Create target dir // Create target dir
if (!file_exists($targetDir)) { if (!file_exists($targetDir)) {
@mkdir($targetDir); @mkdir($targetDir);
} }
// Remove old temp files // Remove old temp files
if (is_dir($targetDir) && ($dir = opendir($targetDir))) { if (is_dir($targetDir) && ($dir = opendir($targetDir))) {
while (($file = readdir($dir)) !== false) { while (($file = readdir($dir)) !== false) {
$filePath = $targetDir . DIRECTORY_SEPARATOR . $file; $filePath = $targetDir . DIRECTORY_SEPARATOR . $file;
// Remove temp files if they are older than the max age // Remove temp files if they are older than the max age
if (preg_match('/\\.tmp$/', $file) && (filemtime($filePath) < time() - $maxFileAge)) if (preg_match('/\\.tmp$/', $file) && (filemtime($filePath) < time() - $maxFileAge))
@unlink($filePath); @unlink($filePath);
} }
closedir($dir); closedir($dir);
} }
else { else {
die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}'); die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
} }
// Look for the content type header // Look for the content type header
if (isset($_SERVER["HTTP_CONTENT_TYPE"])) if (isset($_SERVER["HTTP_CONTENT_TYPE"]))
$contentType = $_SERVER["HTTP_CONTENT_TYPE"]; $contentType = $_SERVER["HTTP_CONTENT_TYPE"];
if (isset($_SERVER["CONTENT_TYPE"])) if (isset($_SERVER["CONTENT_TYPE"]))
$contentType = $_SERVER["CONTENT_TYPE"]; $contentType = $_SERVER["CONTENT_TYPE"];
if (strpos($contentType, "multipart") !== false) { if (strpos($contentType, "multipart") !== false) {
if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) { if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
// Open temp file // Open temp file
$out = fopen($targetDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab"); $out = fopen($targetDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab");
if ($out) { if ($out) {
// Read binary input stream and append it to temp file // Read binary input stream and append it to temp file
$in = fopen($_FILES['file']['tmp_name'], "rb"); $in = fopen($_FILES['file']['tmp_name'], "rb");
if ($in) { if ($in) {
while ($buff = fread($in, 4096)) while ($buff = fread($in, 4096))
fwrite($out, $buff); fwrite($out, $buff);
} else } else
die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}'); die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
fclose($out); fclose($out);
unlink($_FILES['file']['tmp_name']); unlink($_FILES['file']['tmp_name']);
} else } else
die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}'); die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
} else } else
die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}'); die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
} else { } else {
// Open temp file // Open temp file
$out = fopen($targetDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab"); $out = fopen($targetDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab");
if ($out) { if ($out) {
// Read binary input stream and append it to temp file // Read binary input stream and append it to temp file
$in = fopen("php://input", "rb"); $in = fopen("php://input", "rb");
if ($in) { if ($in) {
while ($buff = fread($in, 4096)) while ($buff = fread($in, 4096))
fwrite($out, $buff); fwrite($out, $buff);
} else } else
die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}'); die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
fclose($out); fclose($out);
return $this->processFile($targetDir . DIRECTORY_SEPARATOR . $fileName); return $this->processFile($targetDir . DIRECTORY_SEPARATOR . $fileName);
} else } else
die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}'); die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
} }
// Return JSON-RPC response // Return JSON-RPC response
die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}'); die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');
} }
/** /**
* Provides file upload and store it to the storage * Provides file upload and store it to the storage
@ -254,7 +254,7 @@ class uiHandler extends uiBase {
global $CC_CONFIG; global $CC_CONFIG;
if ($this->testForAudioType($formdata['mediafile']['name']) === FALSE) { if ($this->testForAudioType($formdata['mediafile']['name']) === FALSE) {
if (UI_ERROR) { 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']; $this->redirUrl = UI_BROWSER."?act=addFileData&folderId=".$formdata['folderId'];
return FALSE; return FALSE;
@ -347,45 +347,45 @@ class uiHandler extends uiBase {
* @param unknown_type $langid * @param unknown_type $langid
* @return void * @return void
*/ */
// function translateMetadata($id, $langid=UI_DEFAULT_LANGID) // function translateMetadata($id, $langid=UI_DEFAULT_LANGID)
// { // {
// include(dirname(__FILE__).'/formmask/metadata.inc.php'); // include(dirname(__FILE__).'/formmask/metadata.inc.php');
// //
// $ia = $this->gb->analyzeFile($id, $this->sessid); // $ia = $this->gb->analyzeFile($id, $this->sessid);
// if (PEAR::isError($ia)) { // if (PEAR::isError($ia)) {
// $this->_retMsg($ia->getMessage()); // $this->_retMsg($ia->getMessage());
// return; // return;
// } // }
// // This is really confusing: the import script does not do it // // This is really confusing: the import script does not do it
// // this way. Which way is the right way? // // 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_DURATION, Playlist::secondsToPlaylistTime($ia['playtime_seconds']));
//// $this->setMetadataValue($id, UI_MDATA_KEY_FORMAT, UI_MDATA_VALUE_FORMAT_FILE); //// $this->setMetadataValue($id, UI_MDATA_KEY_FORMAT, UI_MDATA_VALUE_FORMAT_FILE);
// //
// // some data from raw audio // // some data from raw audio
//// if (isset($ia['audio']['channels'])) { //// if (isset($ia['audio']['channels'])) {
//// $this->setMetadataValue($id, UI_MDATA_KEY_CHANNELS, $ia['audio']['channels']); //// $this->setMetadataValue($id, UI_MDATA_KEY_CHANNELS, $ia['audio']['channels']);
//// } //// }
//// if (isset($ia['audio']['sample_rate'])) { //// if (isset($ia['audio']['sample_rate'])) {
//// $this->setMetadataValue($id, UI_MDATA_KEY_SAMPLERATE, $ia['audio']['sample_rate']); //// $this->setMetadataValue($id, UI_MDATA_KEY_SAMPLERATE, $ia['audio']['sample_rate']);
//// } //// }
//// if (isset($ia['audio']['bitrate'])) { //// if (isset($ia['audio']['bitrate'])) {
//// $this->setMetadataValue($id, UI_MDATA_KEY_BITRATE, $ia['audio']['bitrate']); //// $this->setMetadataValue($id, UI_MDATA_KEY_BITRATE, $ia['audio']['bitrate']);
//// } //// }
//// if (isset($ia['audio']['codec'])) { //// if (isset($ia['audio']['codec'])) {
//// $this->setMetadataValue($id, UI_MDATA_KEY_ENCODER, $ia['audio']['codec']); //// $this->setMetadataValue($id, UI_MDATA_KEY_ENCODER, $ia['audio']['codec']);
//// } //// }
// //
// // from id3 Tags // // from id3 Tags
// // loop main, music, talk // // loop main, music, talk
// foreach ($mask['pages'] as $key => $val) { // foreach ($mask['pages'] as $key => $val) {
// // loop through elements // // loop through elements
// foreach ($mask['pages'][$key] as $k => $v) { // foreach ($mask['pages'][$key] as $k => $v) {
// if (isset($v['element']) && isset($ia[$v['element']])) { // if (isset($v['element']) && isset($ia[$v['element']])) {
// $this->setMetadataValue($id, $v['element'], $ia[$v['element']], $langid); // $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'] as $key => $val) {
foreach ($mask['pages'][$key] as $k => $v) { foreach ($mask['pages'][$key] as $k => $v) {
$element = uiBase::formElementEncode($v['element']); $element = uiBase::formElementEncode($v['element']);
if ($formdata[$key.'___'.$element]) if ($formdata[$key.'___'.$element])
$mData[uiBase::formElementDecode($v['element'])] = $formdata[$key.'___'.$element]; $mData[uiBase::formElementDecode($v['element'])] = $formdata[$key.'___'.$element];
} }
} }
$_SESSION["debug"] = $mData; $_SESSION["debug"] = $mData;
if (!count($mData)) { if (!count($mData)) {
return; return;
} }
foreach ($mData as $key => $val) { foreach ($mData as $key => $val) {
@ -491,15 +491,15 @@ class uiHandler extends uiBase {
* @param int $id * @param int $id
* destination folder id * destination folder id
*/ */
// function rename($newname, $id) // function rename($newname, $id)
// { // {
// $r = $this->gb->renameFile($id, $newname, $this->sessid); // $r = $this->gb->renameFile($id, $newname, $this->sessid);
// if (PEAR::isError($r)) { // if (PEAR::isError($r)) {
// $this->_retMsg($r->getMessage()); // $this->_retMsg($r->getMessage());
// } // }
// //$this->redirUrl = UI_BROWSER."?act=fileList&id=".$this->pid; // //$this->redirUrl = UI_BROWSER."?act=fileList&id=".$this->pid;
// $this->redirUrl = UI_BROWSER."?act=fileList&id=".$this->pid; // $this->redirUrl = UI_BROWSER."?act=fileList&id=".$this->pid;
// } // fn rename // } // fn rename
/** /**
@ -517,19 +517,19 @@ class uiHandler extends uiBase {
$this->redirUrl = UI_BROWSER."?popup[]=_reload_parent&popup[]=_close"; $this->redirUrl = UI_BROWSER."?popup[]=_reload_parent&popup[]=_close";
if (is_array($id)) { if (is_array($id)) {
$ids = $id; $ids = $id;
} else { } else {
$ids[] = $id; $ids[] = $id;
} }
foreach ($ids as $id) { foreach ($ids as $id) {
$media = StoredFile::Recall($id); $media = StoredFile::Recall($id);
$r = $media->delete(); $r = $media->delete();
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
$this->_retMsg($r->getMessage()); $this->_retMsg($r->getMessage());
return FALSE; return FALSE;
} }
} }
return TRUE; return TRUE;
@ -548,9 +548,9 @@ class uiHandler extends uiBase {
{ {
$r = $this->gb->access($id, $this->sessid); $r = $this->gb->access($id, $this->sessid);
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
$this->_retMsg($r->getMessage()); $this->_retMsg($r->getMessage());
} else { } else {
echo $r; echo $r;
} }
} // fn getFile } // fn getFile
@ -571,24 +571,24 @@ class uiHandler extends uiBase {
// --- perms --- // --- perms ---
/** /**
* Add new permission record * Add new permission record
* *
* @param int $subj * @param int $subj
* local user/group id * local user/group id
* @param string $permAction * @param string $permAction
* type of action from set predefined in conf.php * type of action from set predefined in conf.php
* @param int $id * @param int $id
* local id of file/object * local id of file/object
* @param char $allowDeny * @param char $allowDeny
* 'A' or 'D' * 'A' or 'D'
* @return boolean * @return boolean
*/ */
function addPerm($subj, $permAction, $id, $allowDeny) function addPerm($subj, $permAction, $id, $allowDeny)
{ {
if (PEAR::isError( if (PEAR::isError(
$this->gb->addPerm( $this->gb->addPerm(
$subj, $permAction, $id, $allowDeny, $this->sessid $subj, $permAction, $id, $allowDeny, $this->sessid
) )
)) { )) {
$this->_retMsg('Access denied.'); $this->_retMsg('Access denied.');
return FALSE; return FALSE;
@ -665,14 +665,14 @@ class uiHandler extends uiBase {
} }
} }
/* /*
foreach($mask as $k) { foreach($mask as $k) {
if ($k['type']=='file' && $k['required']==TRUE) { if ($k['type']=='file' && $k['required']==TRUE) {
if ($_FILES[$k['element']]['error']) { if ($_FILES[$k['element']]['error']) {
$_SESSION['retransferFormData'] = array_merge($_REQUEST, $_FILES); $_SESSION['retransferFormData'] = array_merge($_REQUEST, $_FILES);
return FALSE; return FALSE;
} }
} }
} */ } */
return TRUE; return TRUE;
} // fn _validateForm } // fn _validateForm
@ -694,17 +694,17 @@ class uiHandler extends uiBase {
foreach ($mask as $key => $val) { foreach ($mask as $key => $val) {
if (isset($val['isPref']) && $val['isPref']) { if (isset($val['isPref']) && $val['isPref']) {
if (!empty($formdata[$val['element']])) { 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)) if (PEAR::isError($result))
$this->_retMsg('Error while saving settings.'); $this->_retMsg('Error while saving settings.');
} else { } else {
$this->gb->delGroupPref($this->sessid, $CC_CONFIG['StationPrefsGr'], $val['element']); $this->gb->delGroupPref($this->sessid, $CC_CONFIG['StationPrefsGr'], $val['element']);
} }
} }
if (isset($val['type']) if (isset($val['type'])
&& ($val['type'] == 'file') && ($val['type'] == 'file')
&& ($val['element'] == "stationlogo") && ($val['element'] == "stationlogo")
&& !empty($formdata[$val['element']]['name'])) { && !empty($formdata[$val['element']]['name'])) {
$stationLogoPath = $this->gb->loadGroupPref($CC_CONFIG['StationPrefsGr'], 'stationLogoPath'); $stationLogoPath = $this->gb->loadGroupPref($CC_CONFIG['StationPrefsGr'], 'stationLogoPath');
$filePath = $formdata[$val['element']]['tmp_name']; $filePath = $formdata[$val['element']]['tmp_name'];
if (function_exists("getimagesize")) { if (function_exists("getimagesize")) {
@ -731,7 +731,7 @@ class uiHandler extends uiBase {
} }
return TRUE; return TRUE;
} // fn changeStationPrefs }
} // class uiHandler }
?> ?>

View File

@ -14,526 +14,526 @@ if (get_magic_quotes_gpc()) {
switch ($_REQUEST['act']) { switch ($_REQUEST['act']) {
case "login": case "login":
if ($uiHandler->login($_REQUEST, $ui_fmask["login"]) === TRUE) { if ($uiHandler->login($_REQUEST, $ui_fmask["login"]) === TRUE) {
$uiHandler->loadStationPrefs($ui_fmask['stationPrefs'], TRUE); $uiHandler->loadStationPrefs($ui_fmask['stationPrefs'], TRUE);
# $uiHandler->PLAYLIST->reportLookedPL(); # $uiHandler->PLAYLIST->reportLookedPL();
$uiHandler->PLAYLIST->loadLookedFromPref(); $uiHandler->PLAYLIST->loadLookedFromPref();
} }
include(dirname(__FILE__).'/templates/loader/index.tpl'); include(dirname(__FILE__).'/templates/loader/index.tpl');
include(dirname(__FILE__).'/templates/popup/_reload_parent.tpl'); include(dirname(__FILE__).'/templates/popup/_reload_parent.tpl');
include(dirname(__FILE__).'/templates/popup/_close.tpl'); include(dirname(__FILE__).'/templates/popup/_close.tpl');
exit; exit;
case "logout": case "logout":
$uiHandler->SCRATCHPAD->save(); $uiHandler->SCRATCHPAD->save();
$uiHandler->PLAYLIST->release(); $uiHandler->PLAYLIST->release();
$uiHandler->logout(); $uiHandler->logout();
break; break;
case "signover": case "signover":
$uiHandler->SCRATCHPAD->save(); $uiHandler->SCRATCHPAD->save();
$uiHandler->PLAYLIST->release(); $uiHandler->PLAYLIST->release();
$uiHandler->logout(TRUE); $uiHandler->logout(TRUE);
break; break;
case "plupload": case "plupload":
$ui_tmpid = $uiHandler->pluploadFile($_REQUEST); $ui_tmpid = $uiHandler->pluploadFile($_REQUEST);
if($ui_tmpid) { if($ui_tmpid) {
$uiHandler->SCRATCHPAD->addItem($ui_tmpid); $uiHandler->SCRATCHPAD->addItem($ui_tmpid);
} }
ob_end_clean(); ob_end_clean();
die('{"jsonrpc" : "2.0", "error" : {}}'); die('{"jsonrpc" : "2.0", "error" : {}}');
// file/webstream handling // file/webstream handling
case "addFileData": case "addFileData":
if (($ui_tmpid = $uiHandler->uploadFile(array_merge($_REQUEST, $_FILES), $ui_fmask["file"])) !== FALSE) { if (($ui_tmpid = $uiHandler->uploadFile(array_merge($_REQUEST, $_FILES), $ui_fmask["file"])) !== FALSE) {
$uiHandler->SCRATCHPAD->addItem($ui_tmpid); $uiHandler->SCRATCHPAD->addItem($ui_tmpid);
} }
break; break;
case "addWebstreamData": case "addWebstreamData":
$ui_tmpid = $uiHandler->addWebstream($_REQUEST, $ui_fmask['webstream']); $ui_tmpid = $uiHandler->addWebstream($_REQUEST, $ui_fmask['webstream']);
$uiHandler->SCRATCHPAD->addItem($ui_tmpid); $uiHandler->SCRATCHPAD->addItem($ui_tmpid);
break; break;
case "addWebstreamMData": case "addWebstreamMData":
case "editWebstreamData": case "editWebstreamData":
$uiHandler->editWebstream($_REQUEST, $ui_fmask['webstream']); $uiHandler->editWebstream($_REQUEST, $ui_fmask['webstream']);
$uiHandler->SCRATCHPAD->reloadMetadata(); $uiHandler->SCRATCHPAD->reloadMetadata();
break; break;
case "editMetaData": case "editMetaData":
$uiHandler->editMetaData($_REQUEST); $uiHandler->editMetaData($_REQUEST);
$uiHandler->SCRATCHPAD->reloadMetadata(); $uiHandler->SCRATCHPAD->reloadMetadata();
break; break;
case "rename": case "rename":
$uiHandler->rename($_REQUEST["newname"], $uiHandler->id); $uiHandler->rename($_REQUEST["newname"], $uiHandler->id);
break; break;
case "delete": case "delete":
if ($uiHandler->delete($_REQUEST['id'], $_REQUEST['delOverride'])) { if ($uiHandler->delete($_REQUEST['id'], $_REQUEST['delOverride'])) {
if ($uiHandler->type != 'Folder') { if ($uiHandler->type != 'Folder') {
$uiHandler->SCRATCHPAD->removeItems($_REQUEST['id']); $uiHandler->SCRATCHPAD->removeItems($_REQUEST['id']);
} }
} }
break; break;
case "addPerm": case "addPerm":
$uiHandler->addPerm($_REQUEST["subj"], $_REQUEST["permAction"], $uiHandler->id, $_REQUEST["allowDeny"]); $uiHandler->addPerm($_REQUEST["subj"], $_REQUEST["permAction"], $uiHandler->id, $_REQUEST["allowDeny"]);
break; break;
case "removePerm": case "removePerm":
$uiHandler->removePerm($_REQUEST["permid"], $_REQUEST["oid"]); $uiHandler->removePerm($_REQUEST["permid"], $_REQUEST["oid"]);
break; break;
case "SUBJECTS.addSubj": case "SUBJECTS.addSubj":
$uiHandler->SUBJECTS->addSubj($_REQUEST); $uiHandler->SUBJECTS->addSubj($_REQUEST);
break; break;
case "SUBJECTS.removeSubj": case "SUBJECTS.removeSubj":
$uiHandler->SUBJECTS->removeSubj($_REQUEST); $uiHandler->SUBJECTS->removeSubj($_REQUEST);
break; break;
case "SUBJECTS.addSubj2Gr": case "SUBJECTS.addSubj2Gr":
$uiHandler->SUBJECTS->addSubj2Gr($_REQUEST); $uiHandler->SUBJECTS->addSubj2Gr($_REQUEST);
break; break;
case "SUBJECTS.removeSubjFromGr": case "SUBJECTS.removeSubjFromGr":
$uiHandler->SUBJECTS->removeSubjFromGr($_REQUEST); $uiHandler->SUBJECTS->removeSubjFromGr($_REQUEST);
break; break;
case "SUBJECTS.chgPasswd": case "SUBJECTS.chgPasswd":
$uiHandler->SUBJECTS->chgPasswd($_REQUEST); $uiHandler->SUBJECTS->chgPasswd($_REQUEST);
break; break;
case "changeStationPrefs": case "changeStationPrefs":
$uiHandler->changeStationPrefs(array_merge($_REQUEST, $_FILES), $ui_fmask["stationPrefs"]); $uiHandler->changeStationPrefs(array_merge($_REQUEST, $_FILES), $ui_fmask["stationPrefs"]);
$uiHandler->redirUrl = UI_BROWSER."?act=changeStationPrefs"; $uiHandler->redirUrl = UI_BROWSER."?act=changeStationPrefs";
break; break;
case "SP.addItem": case "SP.addItem":
$uiHandler->SCRATCHPAD->addItem($_REQUEST['id'], $_REQUEST['type']); $uiHandler->SCRATCHPAD->addItem($_REQUEST['id'], $_REQUEST['type']);
$uiHandler->SCRATCHPAD->setReload(); $uiHandler->SCRATCHPAD->setReload();
break; break;
case "SP.removeItem": case "SP.removeItem":
$uiHandler->SCRATCHPAD->removeItems($_REQUEST['id']); $uiHandler->SCRATCHPAD->removeItems($_REQUEST['id']);
$uiHandler->SCRATCHPAD->setReload(); $uiHandler->SCRATCHPAD->setReload();
break; break;
case "SP.reorder": case "SP.reorder":
$uiHandler->SCRATCHPAD->reorder($_REQUEST['by']); $uiHandler->SCRATCHPAD->reorder($_REQUEST['by']);
$uiHandler->SCRATCHPAD->setReload(); $uiHandler->SCRATCHPAD->setReload();
break; break;
case "SEARCH.newSearch": case "SEARCH.newSearch":
$uiHandler->SEARCH->newSearch($_REQUEST); $uiHandler->SEARCH->newSearch($_REQUEST);
$NO_REDIRECT = true; $NO_REDIRECT = true;
$_REQUEST["act"] = "SEARCH"; $_REQUEST["act"] = "SEARCH";
include("ui_browser.php"); include("ui_browser.php");
break; break;
case "SEARCH.simpleSearch": case "SEARCH.simpleSearch":
$uiHandler->SEARCH->simpleSearch($_REQUEST); $uiHandler->SEARCH->simpleSearch($_REQUEST);
$NO_REDIRECT = true; $NO_REDIRECT = true;
$_REQUEST["act"] = "SEARCH"; $_REQUEST["act"] = "SEARCH";
include("ui_browser.php"); include("ui_browser.php");
break; break;
case "SEARCH.reorder": case "SEARCH.reorder":
$uiHandler->SEARCH->reorder($_REQUEST['by']); $uiHandler->SEARCH->reorder($_REQUEST['by']);
$NO_REDIRECT = true; $NO_REDIRECT = true;
$_REQUEST["act"] = "SEARCH"; $_REQUEST["act"] = "SEARCH";
include("ui_browser.php"); include("ui_browser.php");
break; break;
case "SEARCH.clear": case "SEARCH.clear":
$uiHandler->SEARCH->clear(); $uiHandler->SEARCH->clear();
$NO_REDIRECT = true; $NO_REDIRECT = true;
$_REQUEST["act"] = "SEARCH"; $_REQUEST["act"] = "SEARCH";
include("ui_browser.php"); include("ui_browser.php");
break; break;
case "SEARCH.setOffset": case "SEARCH.setOffset":
$uiHandler->SEARCH->setOffset($_REQUEST['page']); $uiHandler->SEARCH->setOffset($_REQUEST['page']);
$NO_REDIRECT = true; $NO_REDIRECT = true;
$_REQUEST["act"] = "SEARCH"; $_REQUEST["act"] = "SEARCH";
include("ui_browser.php"); include("ui_browser.php");
break; break;
case "BROWSE.refresh": case "BROWSE.refresh":
$uiHandler->BROWSE->refresh($_REQUEST); $uiHandler->BROWSE->refresh($_REQUEST);
$NO_REDIRECT = true; $NO_REDIRECT = true;
$_REQUEST["act"] = "BROWSE"; $_REQUEST["act"] = "BROWSE";
include("ui_browser.php"); include("ui_browser.php");
break; break;
case "BROWSE.setCategory": case "BROWSE.setCategory":
$uiHandler->BROWSE->setCategory($_REQUEST); $uiHandler->BROWSE->setCategory($_REQUEST);
$NO_REDIRECT = true; $NO_REDIRECT = true;
$_REQUEST["act"] = "BROWSE"; $_REQUEST["act"] = "BROWSE";
include("ui_browser.php"); include("ui_browser.php");
break; break;
case "BROWSE.setValue": case "BROWSE.setValue":
$uiHandler->BROWSE->setValue($_REQUEST); $uiHandler->BROWSE->setValue($_REQUEST);
$NO_REDIRECT = true; $NO_REDIRECT = true;
$_REQUEST["act"] = "BROWSE"; $_REQUEST["act"] = "BROWSE";
include("ui_browser.php"); include("ui_browser.php");
break; break;
case "BROWSE.reorder": case "BROWSE.reorder":
$uiHandler->BROWSE->reorder($_REQUEST['by']); $uiHandler->BROWSE->reorder($_REQUEST['by']);
$NO_REDIRECT = true; $NO_REDIRECT = true;
$_REQUEST["act"] = "BROWSE"; $_REQUEST["act"] = "BROWSE";
include("ui_browser.php"); include("ui_browser.php");
break; break;
case "BROWSE.setDefaults": case "BROWSE.setDefaults":
$uiHandler->BROWSE->setDefaults(TRUE); $uiHandler->BROWSE->setDefaults(TRUE);
$NO_REDIRECT = true; $NO_REDIRECT = true;
$_REQUEST["act"] = "BROWSE"; $_REQUEST["act"] = "BROWSE";
include("ui_browser.php"); include("ui_browser.php");
break; break;
case "BROWSE.setOffset": case "BROWSE.setOffset":
$uiHandler->BROWSE->setOffset($_REQUEST['page']); $uiHandler->BROWSE->setOffset($_REQUEST['page']);
$NO_REDIRECT = true; $NO_REDIRECT = true;
$_REQUEST["act"] = "BROWSE"; $_REQUEST["act"] = "BROWSE";
include("ui_browser.php"); include("ui_browser.php");
break; break;
case "BROWSE.setLimit": case "BROWSE.setLimit":
$uiHandler->BROWSE->setLimit($_REQUEST['limit']); $uiHandler->BROWSE->setLimit($_REQUEST['limit']);
$NO_REDIRECT = true; $NO_REDIRECT = true;
$_REQUEST["act"] = "BROWSE"; $_REQUEST["act"] = "BROWSE";
include("ui_browser.php"); include("ui_browser.php");
break; break;
case "BROWSE.setFiletype": case "BROWSE.setFiletype":
$uiHandler->BROWSE->setFiletype($_REQUEST['filetype']); $uiHandler->BROWSE->setFiletype($_REQUEST['filetype']);
$NO_REDIRECT = true; $NO_REDIRECT = true;
$_REQUEST["act"] = "BROWSE"; $_REQUEST["act"] = "BROWSE";
include("ui_browser.php"); include("ui_browser.php");
break; break;
case "HUBBROWSE.setCategory": case "HUBBROWSE.setCategory":
$uiHandler->HUBBROWSE->setCategory($_REQUEST); $uiHandler->HUBBROWSE->setCategory($_REQUEST);
break; break;
case "HUBBROWSE.setValue": case "HUBBROWSE.setValue":
$uiHandler->HUBBROWSE->setValue($_REQUEST); $uiHandler->HUBBROWSE->setValue($_REQUEST);
break; break;
case "HUBBROWSE.reorder": case "HUBBROWSE.reorder":
$uiHandler->HUBBROWSE->reorder($_REQUEST['by']); $uiHandler->HUBBROWSE->reorder($_REQUEST['by']);
break; break;
case "HUBBROWSE.setDefaults": case "HUBBROWSE.setDefaults":
$uiHandler->HUBBROWSE->setDefaults(TRUE); $uiHandler->HUBBROWSE->setDefaults(TRUE);
break; break;
case "HUBBROWSE.setOffset": case "HUBBROWSE.setOffset":
$uiHandler->HUBBROWSE->setOffset($_REQUEST['page']); $uiHandler->HUBBROWSE->setOffset($_REQUEST['page']);
break; break;
case "HUBBROWSE.setLimit": case "HUBBROWSE.setLimit":
$uiHandler->HUBBROWSE->setLimit($_REQUEST['limit']); $uiHandler->HUBBROWSE->setLimit($_REQUEST['limit']);
break; break;
case "HUBBROWSE.setFiletype": case "HUBBROWSE.setFiletype":
$uiHandler->HUBBROWSE->setFiletype($_REQUEST['filetype']); $uiHandler->HUBBROWSE->setFiletype($_REQUEST['filetype']);
break; break;
case "HUBSEARCH.newSearch": case "HUBSEARCH.newSearch":
$uiHandler->HUBSEARCH->newSearch($_REQUEST); $uiHandler->HUBSEARCH->newSearch($_REQUEST);
break; break;
case "HUBSEARCH.reorder": case "HUBSEARCH.reorder":
$uiHandler->HUBSEARCH->reorder($_REQUEST['by']); $uiHandler->HUBSEARCH->reorder($_REQUEST['by']);
break; break;
case "HUBSEARCH.clear": case "HUBSEARCH.clear":
$uiHandler->HUBSEARCH->clear(); $uiHandler->HUBSEARCH->clear();
break; break;
case "HUBSEARCH.setOffset": case "HUBSEARCH.setOffset":
$uiHandler->HUBSEARCH->setOffset($_REQUEST['page']); $uiHandler->HUBSEARCH->setOffset($_REQUEST['page']);
$NO_REDIRECT = true; $NO_REDIRECT = true;
$_REQUEST["act"] = "HUBSEARCH"; $_REQUEST["act"] = "HUBSEARCH";
include("ui_browser.php"); include("ui_browser.php");
break; break;
case "TRANSFERS.reorder": case "TRANSFERS.reorder":
$uiHandler->TRANSFERS->reorder($_REQUEST['by']); $uiHandler->TRANSFERS->reorder($_REQUEST['by']);
break; break;
case "TRANSFERS.setOffset": case "TRANSFERS.setOffset":
$uiHandler->TRANSFERS->setOffset($_REQUEST['page']); $uiHandler->TRANSFERS->setOffset($_REQUEST['page']);
break; break;
case "TR.pause": case "TR.pause":
case "TR.resume": case "TR.resume":
case "TR.cancel": case "TR.cancel":
$ids = ''; $ids = '';
if (is_array($_REQUEST['id'])) { if (is_array($_REQUEST['id'])) {
foreach ($_REQUEST['id'] as $id) { foreach ($_REQUEST['id'] as $id) {
$ids .= '&id[]='.$id; $ids .= '&id[]='.$id;
} }
} else { } else {
$ids = '&id='.$_REQUEST['id']; $ids = '&id='.$_REQUEST['id'];
} }
//echo '<XMP>_REQUEST:'; print_r($_REQUEST); echo "</XMP>\n"; //echo '<XMP>_REQUEST:'; print_r($_REQUEST); echo "</XMP>\n";
$uiHandler->redirUrl = UI_BROWSER."?popup[]={$_REQUEST['act']}{$ids}"; $uiHandler->redirUrl = UI_BROWSER."?popup[]={$_REQUEST['act']}{$ids}";
break; break;
case "TR.cancelConfirm": case "TR.cancelConfirm":
//echo '<XMP>_REQUEST:'; print_r($_REQUEST); echo "</XMP>\n"; //echo '<XMP>_REQUEST:'; print_r($_REQUEST); echo "</XMP>\n";
$uiHandler->TRANSFERS->doTransportAction($_REQUEST['id'],'cancel'); $uiHandler->TRANSFERS->doTransportAction($_REQUEST['id'],'cancel');
$uiHandler->redirUrl = UI_BROWSER.'?popup[]=_reload_parent&popup[]=_close'; $uiHandler->redirUrl = UI_BROWSER.'?popup[]=_reload_parent&popup[]=_close';
break; break;
case "PL.activate": case "PL.activate":
if ($uiHandler->PLAYLIST->activate($_REQUEST['id']) === TRUE) { if ($uiHandler->PLAYLIST->activate($_REQUEST['id']) === TRUE) {
$uiHandler->SCRATCHPAD->addItem($_REQUEST['id'], 'playlist'); $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(); $uiHandler->PLAYLIST->setReload();
break; 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": case "SPL.addItem":
if (isset($_REQUEST['id'])) { if (isset($_REQUEST['id'])) {
if ($uiHandler->PLAYLIST->addItem($_REQUEST['id']) === TRUE) { if ($uiHandler->PLAYLIST->addItem($_REQUEST['id']) === TRUE) {
$uiHandler->SCRATCHPAD->addItem($_REQUEST['id']); $uiHandler->SCRATCHPAD->addItem($_REQUEST['id']);
} }
} }
die('{"jsonrpc" : "2.0"}'); die('{"jsonrpc" : "2.0"}');
case "PL.setClipLength":
$uiHandler->PLAYLIST->setClipLength($_REQUEST['pos'], $_REQUEST['cueIn'], $_REQUEST['cueOut']);
break;
case "PL.setFadeLength": case "PL.setClipLength":
$uiHandler->PLAYLIST->setFadeLength($_REQUEST['pos'], $_REQUEST['fadeIn'], $_REQUEST['fadeOut']); $uiHandler->PLAYLIST->setClipLength($_REQUEST['pos'], $_REQUEST['cueIn'], $_REQUEST['cueOut']);
break; break;
case "PL.setFadeLength":
$uiHandler->PLAYLIST->setFadeLength($_REQUEST['pos'], $_REQUEST['fadeIn'], $_REQUEST['fadeOut']);
break;
case "PL.removeItem": case "PL.removeItem":
$uiHandler->PLAYLIST->removeItem($_REQUEST['id']); $uiHandler->PLAYLIST->removeItem($_REQUEST['id']);
$uiHandler->PLAYLIST->setReload(); $uiHandler->PLAYLIST->setReload();
break; break;
case "PL.release": case "PL.release":
$uiHandler->PLAYLIST->release(); $uiHandler->PLAYLIST->release();
$uiHandler->PLAYLIST->setReload(); $uiHandler->PLAYLIST->setReload();
break; break;
case "PL.save": case "PL.save":
if (($ui_tmpid = $uiHandler->PLAYLIST->save()) !== FALSE) { if (($ui_tmpid = $uiHandler->PLAYLIST->save()) !== FALSE) {
$uiHandler->SCRATCHPAD->addItem($ui_tmpid); $uiHandler->SCRATCHPAD->addItem($ui_tmpid);
} }
$uiHandler->PLAYLIST->setReload(); $uiHandler->PLAYLIST->setReload();
break; break;
case "PL.revert": case "PL.revert":
if (($ui_tmpid = $uiHandler->PLAYLIST->revert()) !== FALSE) { if (($ui_tmpid = $uiHandler->PLAYLIST->revert()) !== FALSE) {
$uiHandler->SCRATCHPAD->addItem($ui_tmpid); $uiHandler->SCRATCHPAD->addItem($ui_tmpid);
} }
$uiHandler->PLAYLIST->setReload(); $uiHandler->PLAYLIST->setReload();
break; break;
case "PL.revertANDclose": case "PL.revertANDclose":
$uiHandler->PLAYLIST->revert(); $uiHandler->PLAYLIST->revert();
$uiHandler->PLAYLIST->release(); $uiHandler->PLAYLIST->release();
$uiHandler->PLAYLIST->setReload(); $uiHandler->PLAYLIST->setReload();
break; break;
case"PL.unlook": case"PL.unlook":
$uiHandler->PLAYLIST->loadLookedFromPref(); $uiHandler->PLAYLIST->loadLookedFromPref();
$uiHandler->PLAYLIST->setReload(); $uiHandler->PLAYLIST->setReload();
break; break;
case "PL.changeTransition": case "PL.changeTransition":
$uiHandler->PLAYLIST->changeTransition($_REQUEST['id'], $_REQUEST['type'], $_REQUEST['duration']); $uiHandler->PLAYLIST->changeTransition($_REQUEST['id'], $_REQUEST['type'], $_REQUEST['duration']);
$uiHandler->PLAYLIST->setReload(); $uiHandler->PLAYLIST->setReload();
break; break;
case "PL.moveItem": case "PL.moveItem":
$uiHandler->PLAYLIST->moveItem($_REQUEST['oldPos'], $_REQUEST['newPos']); $uiHandler->PLAYLIST->moveItem($_REQUEST['oldPos'], $_REQUEST['newPos']);
break; break;
case "PL.reorder": case "PL.reorder":
$uiHandler->PLAYLIST->reorder($_REQUEST['pl_items']); $uiHandler->PLAYLIST->reorder($_REQUEST['pl_items']);
$uiHandler->PLAYLIST->setReturn(); $uiHandler->PLAYLIST->setReturn();
break; break;
case "PL.reArrange": case "PL.reArrange":
$uiHandler->PLAYLIST->reorder($_REQUEST['pl_items']); $uiHandler->PLAYLIST->reorder($_REQUEST['pl_items']);
$uiHandler->PLAYLIST->setReload(); $uiHandler->PLAYLIST->setReload();
break; break;
case "PL.editMetaData": case "PL.editMetaData":
$uiHandler->PLAYLIST->editMetaData($_REQUEST); $uiHandler->PLAYLIST->editMetaData($_REQUEST);
//$uiHandler->SCRATCHPAD->addItem($_REQUEST['id']); //$uiHandler->SCRATCHPAD->addItem($_REQUEST['id']);
break; break;
case "PL.deleteActive": case "PL.deleteActive":
if (($ui_tmpid = $uiHandler->PLAYLIST->deleteActive()) !== FALSE) { if (($ui_tmpid = $uiHandler->PLAYLIST->deleteActive()) !== FALSE) {
$uiHandler->SCRATCHPAD->removeItems($ui_tmpid); $uiHandler->SCRATCHPAD->removeItems($ui_tmpid);
} }
$uiHandler->PLAYLIST->setReload(); $uiHandler->PLAYLIST->setReload();
break; break;
case "PL.delete": case "PL.delete":
if (($ui_tmpid = $uiHandler->PLAYLIST->delete($_REQUEST['id'])) !== FALSE) { if (($ui_tmpid = $uiHandler->PLAYLIST->delete($_REQUEST['id'])) !== FALSE) {
$uiHandler->SCRATCHPAD->removeItems($ui_tmpid); $uiHandler->SCRATCHPAD->removeItems($ui_tmpid);
} }
$uiHandler->PLAYLIST->setReload(); $uiHandler->PLAYLIST->setReload();
break; break;
case "PL.export": case "PL.export":
$uiHandler->redirUrl = UI_BROWSER."?popup[]=PL.redirect2DownloadExportedFile&id={$_REQUEST['id']}&playlisttype={$_REQUEST['playlisttype']}&exporttype={$_REQUEST['exporttype']}"; $uiHandler->redirUrl = UI_BROWSER."?popup[]=PL.redirect2DownloadExportedFile&id={$_REQUEST['id']}&playlisttype={$_REQUEST['playlisttype']}&exporttype={$_REQUEST['exporttype']}";
break; break;
case "PL.import": case "PL.import":
//echo '_FILES:'; print_r($_FILES); //echo '_FILES:'; print_r($_FILES);
$importedPlaylist = $uiHandler->gb->importPlaylistOpen($uiHandler->sessid); $importedPlaylist = $uiHandler->gb->importPlaylistOpen($uiHandler->sessid);
//echo 'importPlaylistOpen:'; print_r($importedPlaylist); //echo 'importPlaylistOpen:'; print_r($importedPlaylist);
copy($_FILES['playlist']['tmp_name'],$importedPlaylist['fname']); copy($_FILES['playlist']['tmp_name'],$importedPlaylist['fname']);
$uiHandler->gb->importPlaylistClose($importedPlaylist['token']); $uiHandler->gb->importPlaylistClose($importedPlaylist['token']);
$uiHandler->redirUrl = UI_BROWSER."?act=PL.import"; $uiHandler->redirUrl = UI_BROWSER."?act=PL.import";
break; break;
case "SCHEDULER.set": case "SCHEDULER.set":
$uiHandler->SCHEDULER->set($_REQUEST); $uiHandler->SCHEDULER->set($_REQUEST);
//$uiHandler->SCHEDULER->setReload(); //$uiHandler->SCHEDULER->setReload();
$NO_REDIRECT = true; $NO_REDIRECT = true;
$_REQUEST["act"] = "SCHEDULER"; $_REQUEST["act"] = "SCHEDULER";
include("ui_browser.php"); include("ui_browser.php");
break; break;
case "SCHEDULER.setScheduleAtTime": case "SCHEDULER.setScheduleAtTime":
$uiHandler->SCHEDULER->setScheduleAtTime($_REQUEST); $uiHandler->SCHEDULER->setScheduleAtTime($_REQUEST);
$uiHandler->SCHEDULER->setClose(); $uiHandler->SCHEDULER->setClose();
break; break;
case "SCHEDULER.addItem": case "SCHEDULER.addItem":
$groupId = $uiHandler->SCHEDULER->addItem($_REQUEST); $groupId = $uiHandler->SCHEDULER->addItem($_REQUEST);
if (PEAR::isError($groupId) && $groupId->getCode() == 555) { if (PEAR::isError($groupId) && $groupId->getCode() == 555) {
$Smarty->assign("USER_ERROR", "Scheduling conflict."); $Smarty->assign("USER_ERROR", "Scheduling conflict.");
} }
$NO_REDIRECT = true; $NO_REDIRECT = true;
$_REQUEST["act"] = "SCHEDULER"; $_REQUEST["act"] = "SCHEDULER";
include("ui_browser.php"); include("ui_browser.php");
break; break;
case "SCHEDULER.removeItem": case "SCHEDULER.removeItem":
$uiHandler->SCHEDULER->removeFromScheduleMethod($_REQUEST['scheduleId']); $uiHandler->SCHEDULER->removeFromScheduleMethod($_REQUEST['scheduleId']);
$uiHandler->SCHEDULER->setReload(); $uiHandler->SCHEDULER->setReload();
break; break;
case "SCHEDULER.startDaemon": case "SCHEDULER.startDaemon":
$uiHandler->SCHEDULER->startDaemon(TRUE); $uiHandler->SCHEDULER->startDaemon(TRUE);
$uiHandler->SCHEDULER->setReload(); $uiHandler->SCHEDULER->setReload();
break; break;
case "SCHEDULER.stopDaemon": case "SCHEDULER.stopDaemon":
$uiHandler->SCHEDULER->stopDaemon(TRUE); $uiHandler->SCHEDULER->stopDaemon(TRUE);
$uiHandler->SCHEDULER->setReload(); $uiHandler->SCHEDULER->setReload();
break; break;
case 'SCHEDULER.scheduleExportOpen': case 'SCHEDULER.scheduleExportOpen':
// Make sure days are always 2 digits. // Make sure days are always 2 digits.
$_REQUEST['fromDay'] = (strlen($_REQUEST['fromDay'])>1)?$_REQUEST['fromDay']:'0'.$_REQUEST['fromDay']; $_REQUEST['fromDay'] = (strlen($_REQUEST['fromDay'])>1)?$_REQUEST['fromDay']:'0'.$_REQUEST['fromDay'];
$_REQUEST['toDay'] = (strlen($_REQUEST['toDay'])>1)?$_REQUEST['toDay']:'0'.$_REQUEST['toDay']; $_REQUEST['toDay'] = (strlen($_REQUEST['toDay'])>1)?$_REQUEST['toDay']:'0'.$_REQUEST['toDay'];
$fromTime = $_REQUEST['fromYear'].'-'.$_REQUEST['fromMonth'].'-'.$_REQUEST['fromDay'].' ' $fromTime = $_REQUEST['fromYear'].'-'.$_REQUEST['fromMonth'].'-'.$_REQUEST['fromDay'].' '
.$_REQUEST['fromHour'].':'.$_REQUEST['fromMinute'].':00'; .$_REQUEST['fromHour'].':'.$_REQUEST['fromMinute'].':00';
$toTime = $_REQUEST['toYear'].'-'.$_REQUEST['toMonth'].'-'.$_REQUEST['toDay'].' ' $toTime = $_REQUEST['toYear'].'-'.$_REQUEST['toMonth'].'-'.$_REQUEST['toDay'].' '
.$_REQUEST['toHour'].':'.$_REQUEST['toMinute'].':00'; .$_REQUEST['toHour'].':'.$_REQUEST['toMinute'].':00';
//echo '<XMP style="background:yellow;">';echo "fromTime:$fromTime | toTime:$toTime";echo'</XMP>'."\n"; //echo '<XMP style="background:yellow;">';echo "fromTime:$fromTime | toTime:$toTime";echo'</XMP>'."\n";
$uiHandler->SCHEDULER->scheduleExportOpen($fromTime, $toTime); $uiHandler->SCHEDULER->scheduleExportOpen($fromTime, $toTime);
$uiHandler->redirUrl = UI_BROWSER.'?act=SCHEDULER'; $uiHandler->redirUrl = UI_BROWSER.'?act=SCHEDULER';
break; break;
case 'SCHEDULER.setImportFile': case 'SCHEDULER.setImportFile':
$uiHandler->SCHEDULER->scheduleImportOpen($_REQUEST['target']); $uiHandler->SCHEDULER->scheduleImportOpen($_REQUEST['target']);
$uiHandler->redirUrl = UI_BROWSER.'?act=SCHEDULER'; $uiHandler->redirUrl = UI_BROWSER.'?act=SCHEDULER';
break; break;
case 'BACKUP.createBackupOpen': case 'BACKUP.createBackupOpen':
$uiHandler->EXCHANGE->createBackupOpen(); $uiHandler->EXCHANGE->createBackupOpen();
$uiHandler->redirUrl = UI_BROWSER.'?act=BACKUP'; $uiHandler->redirUrl = UI_BROWSER.'?act=BACKUP';
break; break;
case 'BACKUP.copy2target': case 'BACKUP.copy2target':
$uiHandler->EXCHANGE->copy2target($_REQUEST['target']); $uiHandler->EXCHANGE->copy2target($_REQUEST['target']);
$uiHandler->redirUrl = UI_BROWSER.'?act=BACKUP'; $uiHandler->redirUrl = UI_BROWSER.'?act=BACKUP';
break; break;
case 'BACKUP.createBackupClose': case 'BACKUP.createBackupClose':
$uiHandler->EXCHANGE->createBackupClose(); $uiHandler->EXCHANGE->createBackupClose();
$uiHandler->redirUrl = UI_BROWSER.'?act=BACKUP'; $uiHandler->redirUrl = UI_BROWSER.'?act=BACKUP';
break; break;
case 'RESTORE.setBackupFileToRestore': case 'RESTORE.setBackupFileToRestore':
$uiHandler->EXCHANGE->backupRestoreOpen($_REQUEST['target']); $uiHandler->EXCHANGE->backupRestoreOpen($_REQUEST['target']);
$uiHandler->redirUrl = UI_BROWSER.'?act=RESTORE'; $uiHandler->redirUrl = UI_BROWSER.'?act=RESTORE';
break; break;
case 'RESTORE.backupRestoreClose': case 'RESTORE.backupRestoreClose':
$uiHandler->EXCHANGE->backupRestoreClose(); $uiHandler->EXCHANGE->backupRestoreClose();
$uiHandler->redirUrl = UI_BROWSER.'?act=RESTORE'; $uiHandler->redirUrl = UI_BROWSER.'?act=RESTORE';
break; break;
case 'SESSION.CLEAR': case 'SESSION.CLEAR':
$_SESSION = array(); $_SESSION = array();
die(); die();
break; break;
case 'twitter.saveSettings': case 'twitter.saveSettings':
$uiHandler->TWITTER->saveSettings(); $uiHandler->TWITTER->saveSettings();
$uiHandler->redirUrl = UI_BROWSER.'?act=twitter.settings'; $uiHandler->redirUrl = UI_BROWSER.'?act=twitter.settings';
break; break;
case NULL: case NULL:
if ($uiHandler->userid) { if ($uiHandler->userid) {
$uiHandler->_retMsg('The uploaded file is bigger than allowed in system settings. See "Help", chapter "Troubleshooting" for more information.'); $uiHandler->_retMsg('The uploaded file is bigger than allowed in system settings. See "Help", chapter "Troubleshooting" for more information.');
} }
$uiHandler->redirUrl = UI_BROWSER; $uiHandler->redirUrl = UI_BROWSER;
if ($_REQUEST['is_popup']) { if ($_REQUEST['is_popup']) {
$uiHandler->redirUrl = UI_BROWSER.'?popup[]=_reload_parent&popup[]=_close'; $uiHandler->redirUrl = UI_BROWSER.'?popup[]=_reload_parent&popup[]=_close';
} }
break; break;
default: default:
$uiHandler->_retMsg(tra('Unknown method: $1', $_REQUEST['act'])); $uiHandler->_retMsg(tra('Unknown method: $1', $_REQUEST['act']));
$uiHandler->redirUrl = UI_BROWSER; $uiHandler->redirUrl = UI_BROWSER;
if ($_REQUEST['is_popup']) { if ($_REQUEST['is_popup']) {
$uiHandler->redirUrl = UI_BROWSER.'?popup[]=_reload_parent&popup[]=_close'; $uiHandler->redirUrl = UI_BROWSER.'?popup[]=_reload_parent&popup[]=_close';
} }
//break; //break;
} }
@ -544,9 +544,9 @@ if ($uiHandler->alertMsg) {
ob_end_flush(); ob_end_flush();
if (!isset($NO_REDIRECT)) { if (!isset($NO_REDIRECT)) {
if (isset($_REQUEST['target'])) { if (isset($_REQUEST['target'])) {
header('Location: ui_browser.php?act='.$_REQUEST['target']); header('Location: ui_browser.php?act='.$_REQUEST['target']);
} else { } else {
header("Location: ".$uiHandler->redirUrl); header("Location: ".$uiHandler->redirUrl);
} }
} }
exit; exit;

View File

@ -8,15 +8,15 @@ require_once(dirname(__FILE__)."/../backend/Playlist.php");
*/ */
class uiPlaylist class uiPlaylist
{ {
public $activeId; public $activeId;
public $title; public $title;
public $duration; public $duration;
private $Base; private $Base;
private $reloadUrl; private $reloadUrl;
private $redirectUrl; private $redirectUrl;
private $returnUrl; private $returnUrl;
private $flat; private $flat;
public function __construct($uiBase) public function __construct($uiBase)
{ {
@ -32,11 +32,11 @@ class uiPlaylist
public function setReload($url=NULL) public function setReload($url=NULL)
{ {
if($url) if($url) {
$this->Base->redirUrl = $url; $this->Base->redirUrl = $url;
else } else {
$this->Base->redirUrl = $this->reloadUrl; $this->Base->redirUrl = $this->reloadUrl;
}
} // fn setReload } // fn setReload
@ -94,15 +94,15 @@ class uiPlaylist
$userid = $this->Base->gb->playlistIsAvailable($plid, $this->Base->sessid); $userid = $this->Base->gb->playlistIsAvailable($plid, $this->Base->sessid);
if ($userid !== TRUE) { if ($userid !== TRUE) {
if (UI_WARNING) { if (UI_WARNING) {
$this->Base->_retMsg('Playlist has been locked by "$1".', Subjects::GetSubjName($userid)); $this->Base->_retMsg('Playlist has been locked by "$1".', Subjects::GetSubjName($userid));
} }
return FALSE; return FALSE;
} }
$res = $this->Base->gb->lockPlaylistForEdit($plid, $this->Base->sessid); $res = $this->Base->gb->lockPlaylistForEdit($plid, $this->Base->sessid);
if (PEAR::isError($res) || $res === FALSE) { if (PEAR::isError($res) || $res === FALSE) {
if (UI_VERBOSE === TRUE) { 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)); $this->Base->_retMsg('Unable to open playlist "$1".', $this->Base->getMetadataValue($plid, UI_MDATA_KEY_TITLE));
return FALSE; return FALSE;
@ -112,7 +112,7 @@ class uiPlaylist
$this->activeId = $plid; $this->activeId = $plid;
if ($msg && UI_VERBOSE) { 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; return TRUE;
@ -125,17 +125,17 @@ class uiPlaylist
// delete PL from session // delete PL from session
if (!$this->activeId) { if (!$this->activeId) {
if (UI_WARNING) { 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; return FALSE;
} }
$res = $this->Base->gb->releaseLockedPlaylist($this->activeId, $this->Base->sessid); $res = $this->Base->gb->releaseLockedPlaylist($this->activeId, $this->Base->sessid);
if (PEAR::isError($res) || $res === FALSE) { if (PEAR::isError($res) || $res === FALSE) {
if (UI_VERBOSE === TRUE) { if (UI_VERBOSE === TRUE) {
print_r($res); print_r($res);
} }
if (UI_WARNING) { if (UI_WARNING) {
$this->Base->_retMsg('Unable to release playlist.'); $this->Base->_retMsg('Unable to release playlist.');
} }
return FALSE; return FALSE;
} }
@ -150,7 +150,7 @@ class uiPlaylist
{ {
if (is_string($this->Base->gb->loadPref($this->Base->sessid, UI_PL_ACCESSTOKEN_KEY))) { if (is_string($this->Base->gb->loadPref($this->Base->sessid, UI_PL_ACCESSTOKEN_KEY))) {
if ($setMsg == TRUE) { if ($setMsg == TRUE) {
$this->Base->_retMsg('Found locked playlist.'); $this->Base->_retMsg('Found locked playlist.');
} }
return TRUE; return TRUE;
} }
@ -194,15 +194,15 @@ class uiPlaylist
$cueIn = NULL; $cueIn = NULL;
/* /*
gstreamer bug: gstreamer bug:
Warning: The clipEnd can't be bigger than ninety nine percent (99%) of the clipLength, 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. this means also if no clipEnd is defined it should be 00:00:00.000000 and not the clipLength.
$clipend = '00:00:00.000000'; $clipend = '00:00:00.000000';
*/ */
if (!$elemIds) { if (!$elemIds) {
if (UI_WARNING) { if (UI_WARNING) {
$this->Base->_retMsg('No item(s) selected.'); $this->Base->_retMsg('No item(s) selected.');
} }
return FALSE; return FALSE;
} }
@ -217,7 +217,7 @@ class uiPlaylist
$r = $this->Base->gb->addAudioClipToPlaylist($this->activeId, $elemId, $pos, $fadeIn, $fadeOut, $cliplength, $cueIn, $cueOut); $r = $this->Base->gb->addAudioClipToPlaylist($this->activeId, $elemId, $pos, $fadeIn, $fadeOut, $cliplength, $cueIn, $cueOut);
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
if (UI_VERBOSE === TRUE) { if (UI_VERBOSE === TRUE) {
print_r($r); print_r($r);
} }
$this->Base->_retMsg('Error while trying to add item to playlist.'); $this->Base->_retMsg('Error while trying to add item to playlist.');
return FALSE; return FALSE;
@ -234,12 +234,12 @@ class uiPlaylist
{ {
if (!$positions) { if (!$positions) {
if (UI_WARNING) { if (UI_WARNING) {
$this->Base->_retMsg('No item(s) selected.'); $this->Base->_retMsg('No item(s) selected.');
} }
return FALSE; return FALSE;
} }
if (!is_array($positions)) if (!is_array($positions))
$positions = array($positions); $positions = array($positions);
//so the automatic updating of playlist positioning doesn't affect removal. //so the automatic updating of playlist positioning doesn't affect removal.
sort($positions); sort($positions);
@ -312,7 +312,7 @@ class uiPlaylist
$response["newPos"] = $newPos; $response["newPos"] = $newPos;
} }
else{ else{
$response["error"] = FALSE; $response["error"] = FALSE;
} }
die(json_encode($response)); die(json_encode($response));
@ -364,7 +364,7 @@ class uiPlaylist
$form->setConstants(array('act' => 'PL.editMetaData', $form->setConstants(array('act' => 'PL.editMetaData',
'id' => $id, 'id' => $id,
'curr_langid' => $langid 'curr_langid' => $langid
) )
); );
$renderer = new HTML_QuickForm_Renderer_Array(true, true); $renderer = new HTML_QuickForm_Renderer_Array(true, true);
$form->accept($renderer); $form->accept($renderer);
@ -402,20 +402,20 @@ class uiPlaylist
} }
if (!count($mData)) { if (!count($mData)) {
return; return;
} }
foreach ($mData as $key => $val) { foreach ($mData as $key => $val) {
$r = $this->Base->gb->setPLMetadataValue($id, $key, $val, $curr_langid); $r = $this->Base->gb->setPLMetadataValue($id, $key, $val, $curr_langid);
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
if (UI_VERBOSE === TRUE) { if (UI_VERBOSE === TRUE) {
print_r($r); print_r($r);
} }
$this->Base->_retMsg('Unable to set "$1" to value "$2".', $key, $val); $this->Base->_retMsg('Unable to set "$1" to value "$2".', $key, $val);
} }
} }
if (UI_VERBOSE) { if (UI_VERBOSE) {
$this->Base->_retMsg('Metadata saved.'); $this->Base->_retMsg('Metadata saved.');
} }
$this->Base->SCRATCHPAD->reloadMetadata(); $this->Base->SCRATCHPAD->reloadMetadata();
@ -459,7 +459,7 @@ class uiPlaylist
function isUsedBy($id) function isUsedBy($id)
{ {
if (($userid = $this->Base->gb->playlistIsAvailable($id, $this->Base->sessid)) !== TRUE) { if (($userid = $this->Base->gb->playlistIsAvailable($id, $this->Base->sessid)) !== TRUE) {
return Subjects::GetSubjName($userid); return Subjects::GetSubjName($userid);
} }
return FALSE; return FALSE;
} // fn isUsedBy } // fn isUsedBy

View File

@ -1,36 +1,32 @@
<?php <?php
/** /**
* @package Campcaster
* @subpackage htmlUI
* @package Campcaster * @copyright 2010 Sourcefabric O.P.S.
* @subpackage htmlUI */
* @copyright 2010 Sourcefabric O.P.S.
*/
class uiScratchPad class uiScratchPad
{ {
/** /**
* @var uiBase * @var uiBase
*/ */
private $Base; private $Base;
/** /**
* The contents of the scratchpad. * The contents of the scratchpad.
* *
* @var array * @var array
*/ */
private $items; private $items;
/** /**
* @var array * @var array
*/ */
private $order; private $order;
/** /**
* @var string * @var string
*/ */
private $reloadUrl; private $reloadUrl;
public function __construct(&$uiBase) public function __construct(&$uiBase)
{ {
@ -77,7 +73,7 @@ class uiScratchPad
// get the scratchpad list // get the scratchpad list
$arr = explode(' ', $spData); $arr = explode(' ', $spData);
$maxLength = $this->Base->STATIONPREFS[UI_SCRATCHPAD_MAXLENGTH_KEY]; $maxLength = $this->Base->STATIONPREFS[UI_SCRATCHPAD_MAXLENGTH_KEY];
$arr = array_slice($arr, 0, $maxLength); $arr = array_slice($arr, 0, $maxLength);
foreach ($arr as $item) { foreach ($arr as $item) {
//for audiofiles. //for audiofiles.
list($type, $savedId) = explode(":", $item); list($type, $savedId) = explode(":", $item);
@ -91,8 +87,8 @@ class uiScratchPad
else { else {
$gunid = $savedId; $gunid = $savedId;
if (preg_match('/[0-9]{1,20}/', $gunid)) { if (preg_match('/[0-9]{1,20}/', $gunid)) {
$f = StoredFile::RecallByGunid($gunid); $f = StoredFile::RecallByGunid($gunid);
//$id = BasicStor::IdFromGunid($this->Base->toHex($gunid)); //$id = BasicStor::IdFromGunid($this->Base->toHex($gunid));
if (!PEAR::isError($f)) { if (!PEAR::isError($f)) {
if ($i = $this->Base->getMetaInfo($f->getId())) { if ($i = $this->Base->getMetaInfo($f->getId())) {
$this->items[] = $i; $this->items[] = $i;
@ -134,13 +130,13 @@ class uiScratchPad
{ {
if (!$this->Base->STATIONPREFS[UI_SCRATCHPAD_MAXLENGTH_KEY]) { if (!$this->Base->STATIONPREFS[UI_SCRATCHPAD_MAXLENGTH_KEY]) {
if (UI_WARNING) { 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; return false;
} }
if (!$ids) { if (!$ids) {
if (UI_WARNING) { if (UI_WARNING) {
$this->Base->_retMsg('No item(s) selected.'); $this->Base->_retMsg('No item(s) selected.');
} }
return FALSE; return FALSE;
} }
@ -150,16 +146,17 @@ class uiScratchPad
$scratchpad = $this->get(); $scratchpad = $this->get();
foreach ($ids as $id) { foreach ($ids as $id) {
if($type === 'playlist') if($type === 'playlist') {
$item = $this->Base->getPLMetaInfo($id); $item = $this->Base->getPLMetaInfo($id);
else } else {
$item = $this->Base->getMetaInfo($id); $item = $this->Base->getMetaInfo($id);
}
foreach ($scratchpad as $key => $val) { foreach ($scratchpad as $key => $val) {
if ($val['id'] == $item['id']) { if ($val['id'] == $item['id']) {
unset($scratchpad[$key]); unset($scratchpad[$key]);
if (UI_VERBOSE) { 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 { } else {
#$this->Base->incAccessCounter($id); #$this->Base->incAccessCounter($id);
@ -170,11 +167,11 @@ class uiScratchPad
$maxScratchpadLength = $this->Base->STATIONPREFS[UI_SCRATCHPAD_MAXLENGTH_KEY]; $maxScratchpadLength = $this->Base->STATIONPREFS[UI_SCRATCHPAD_MAXLENGTH_KEY];
for ($n = 0; $n < $maxScratchpadLength; $n++) { for ($n = 0; $n < $maxScratchpadLength; $n++) {
if (!isset($scratchpad[$n])) { if (!isset($scratchpad[$n])) {
break; break;
} }
if (is_array($scratchpad[$n])) { if (is_array($scratchpad[$n])) {
$this->items[$n] = $scratchpad[$n]; $this->items[$n] = $scratchpad[$n];
} }
} }
ksort($this->items); ksort($this->items);
@ -192,7 +189,7 @@ class uiScratchPad
{ {
if (!$ids) { if (!$ids) {
if (UI_WARNING) { if (UI_WARNING) {
$this->Base->_retMsg('No item(s) selected.'); $this->Base->_retMsg('No item(s) selected.');
} }
return FALSE; return FALSE;
} }
@ -232,17 +229,17 @@ class uiScratchPad
$curr = $this->order[$by]; $curr = $this->order[$by];
$this->order = array(); $this->order = array();
if (is_null($curr) || $curr=='DESC') { if (is_null($curr) || $curr=='DESC') {
$this->order[$by] = 'ASC'; $this->order[$by] = 'ASC';
} else { } else {
$this->order[$by] = 'DESC'; $this->order[$by] = 'DESC';
} }
switch ($this->order[$by]) { switch ($this->order[$by]) {
case "ASC": case "ASC":
asort($s); asort($s);
break; break;
case "DESC": case "DESC":
arsort($s); arsort($s);
break; break;
} }
foreach ($s as $key=>$val) { foreach ($s as $key=>$val) {
$res[] = $this->items[$key]; $res[] = $this->items[$key];
@ -259,10 +256,11 @@ class uiScratchPad
public function reloadMetadata() public function reloadMetadata()
{ {
foreach ($this->items as $key => $val) { foreach ($this->items as $key => $val) {
if($val['type'] === 'playlist') if ($val['type'] === 'playlist') {
$this->items[$key] = $this->Base->getPLMetaInfo($val['id']); $this->items[$key] = $this->Base->getPLMetaInfo($val['id']);
else } else {
$this->items[$key] = $this->Base->getMetaInfo($val['id']); $this->items[$key] = $this->Base->getMetaInfo($val['id']);
}
} }
} }
@ -277,4 +275,4 @@ class uiScratchPad
} }
} // class uiScratchPad } // class uiScratchPad
?> ?>

View File

@ -6,10 +6,10 @@
*/ */
class uiSubjects class uiSubjects
{ {
public $Base; public $Base;
private $reloadUrl; private $reloadUrl;
private $suRedirUrl; private $suRedirUrl;
private $redirUrl; private $redirUrl;
public function __construct(&$uiBase) public function __construct(&$uiBase)
{ {
@ -22,19 +22,19 @@ class uiSubjects
public function setReload() public function setReload()
{ {
$this->Base->redirUrl = $this->reloadUrl; $this->Base->redirUrl = $this->reloadUrl;
} }
public function setSuRedir() public function setSuRedir()
{ {
$this->Base->redirUrl = $this->suRedirUrl; $this->Base->redirUrl = $this->suRedirUrl;
} }
public function setRedir() 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). * Create a new user or group (empty password => create group).
* *
* @param array $request * @param array $request
* Must have keys -> value: * Must have keys -> value:
* login - string * login - string
* passwd - string * passwd - string
* @return string * @return string
*/ */
public function addSubj($request) public function addSubj($request)
{ {
include(dirname(__FILE__). '/formmask/subjects.inc.php'); include(dirname(__FILE__). '/formmask/subjects.inc.php');

View File

@ -32,22 +32,22 @@ echo " *** Database Installation ***\n";
// Create the database user // Create the database user
$command = "sudo -u postgres psql postgres --command \"CREATE USER {$CC_CONFIG['dsn']['username']} " $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"; //echo $command."\n";
@exec($command, $output, $results); @exec($command, $output, $results);
if ($results == 0) { if ($results == 0) {
echo " * User {$CC_CONFIG['dsn']['username']} created.\n"; echo " * User {$CC_CONFIG['dsn']['username']} created.\n";
} else { } 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"; $command = "sudo -u postgres createdb {$CC_CONFIG['dsn']['database']} --owner {$CC_CONFIG['dsn']['username']} 2> /dev/null";
//echo $command."\n"; //echo $command."\n";
@exec($command, $output, $results); @exec($command, $output, $results);
if ($results == 0) { if ($results == 0) {
echo " * Database '{$CC_CONFIG['dsn']['database']}' created.\n"; echo " * Database '{$CC_CONFIG['dsn']['database']}' created.\n";
} else { } else {
echo " * Database '{$CC_CONFIG['dsn']['database']}' already exists.\n"; echo " * Database '{$CC_CONFIG['dsn']['database']}' already exists.\n";
} }
// Connect to DB // Connect to DB
@ -56,11 +56,11 @@ campcaster_db_connect(true);
// Install postgres scripting language // Install postgres scripting language
$langIsInstalled = $CC_DBC->GetOne('SELECT COUNT(*) FROM pg_language WHERE lanname = \'plpgsql\''); $langIsInstalled = $CC_DBC->GetOne('SELECT COUNT(*) FROM pg_language WHERE lanname = \'plpgsql\'');
if ($langIsInstalled == '0') { if ($langIsInstalled == '0') {
echo " * Installing Postgres scripting language...\n"; echo " * Installing Postgres scripting language...\n";
$sql = "CREATE LANGUAGE 'plpgsql'"; $sql = "CREATE LANGUAGE 'plpgsql'";
camp_install_query($sql, false); camp_install_query($sql, false);
} else { } 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); camp_install_query($sql, false);
// $sql = "CREATE UNIQUE INDEX ".$CC_CONFIG['filesTable']."_id_idx // $sql = "CREATE UNIQUE INDEX ".$CC_CONFIG['filesTable']."_id_idx
// ON ".$CC_CONFIG['filesTable']." (id)"; // ON ".$CC_CONFIG['filesTable']." (id)";
// camp_install_query($sql, false); // camp_install_query($sql, false);
$sql = "CREATE UNIQUE INDEX ".$CC_CONFIG['filesTable']."_gunid_idx $sql = "CREATE UNIQUE INDEX ".$CC_CONFIG['filesTable']."_gunid_idx
ON ".$CC_CONFIG['filesTable']." (gunid)"; 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'])) { if (!camp_db_table_exists($CC_CONFIG['scheduleTable'])) {
echo " * Creating database table ".$CC_CONFIG['scheduleTable']."..."; echo " * Creating database table ".$CC_CONFIG['scheduleTable']."...";
$sql = "CREATE TABLE ".$CC_CONFIG['scheduleTable']."(" $sql = "CREATE TABLE ".$CC_CONFIG['scheduleTable']."("
." id bigint NOT NULL," ." id bigint NOT NULL,"
." playlist_id integer NOT NULL," ." playlist_id integer NOT NULL,"
." starts timestamp without time zone NOT NULL," ." starts timestamp without time zone NOT NULL,"
." ends timestamp without time zone NOT NULL," ." ends timestamp without time zone NOT NULL,"
." group_id integer," ." group_id integer,"
." file_id integer," ." file_id integer,"
." clip_length time without time zone DEFAULT '00:00:00'::time without time zone," ." 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_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," ." 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_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," ." cue_out time without time zone DEFAULT '00:00:00'::time without time zone,"
." CONSTRAINT cc_schedule_pkey PRIMARY KEY (id)," ." CONSTRAINT cc_schedule_pkey PRIMARY KEY (id),"
." CONSTRAINT unique_id UNIQUE (id))"; ." CONSTRAINT unique_id UNIQUE (id))";
camp_install_query($sql); camp_install_query($sql);
} else { } else {
@ -477,11 +477,11 @@ if (!camp_db_table_exists($CC_CONFIG['scheduleTable'])) {
} }
if (!camp_db_sequence_exists("schedule_group_id_seq")) { if (!camp_db_sequence_exists("schedule_group_id_seq")) {
echo " * Creating sequence 'schedule_group_id_seq'..."; echo " * Creating sequence 'schedule_group_id_seq'...";
$sql = "CREATE SEQUENCE schedule_group_id_seq"; $sql = "CREATE SEQUENCE schedule_group_id_seq";
camp_install_query($sql); camp_install_query($sql);
} else { } 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'])) { 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']."..."; echo " * Inserting starting data into table ".$CC_CONFIG['prefTable']."...";
$stPrefGr = Subjects::GetSubjId($CC_CONFIG['StationPrefsGr']); $stPrefGr = Subjects::GetSubjId($CC_CONFIG['StationPrefsGr']);
Prefs::Insert($CC_CONFIG["systemPrefId"], 'stationName', "Radio Station 1"); Prefs::Insert($CC_CONFIG["systemPrefId"], 'stationName', "Radio Station 1");
// $genres = file_get_contents( dirname(__FILE__).'/../genres.xml'); // $genres = file_get_contents( dirname(__FILE__).'/../genres.xml');
// Prefs::Insert($CC_CONFIG["systemPrefId"], 'genres', $genres); // Prefs::Insert($CC_CONFIG["systemPrefId"], 'genres', $genres);
echo "done.\n"; echo "done.\n";
} else { } else {
echo " * Skipping: database table already exists: ".$CC_CONFIG['prefTable']."\n"; echo " * Skipping: database table already exists: ".$CC_CONFIG['prefTable']."\n";

View File

@ -73,14 +73,14 @@ function install_setDirPermissions($filePath) {
$fileGroup = filegroup($CC_CONFIG["smartyTemplateCompiled"]); $fileGroup = filegroup($CC_CONFIG["smartyTemplateCompiled"]);
$groupOwner = (function_exists('posix_getgrgid'))?@posix_getgrgid($fileGroup):''; $groupOwner = (function_exists('posix_getgrgid'))?@posix_getgrgid($fileGroup):'';
if (!empty($groupOwner) && ($groupOwner["name"] != $CC_CONFIG["webServerUser"])) { if (!empty($groupOwner) && ($groupOwner["name"] != $CC_CONFIG["webServerUser"])) {
echo " * Error: Your directory permissions for {$filePath} are not set correctly.<br>\n"; echo " * Error: Your directory permissions for {$filePath} are not set correctly.<br>\n";
echo " * The group perms need to be set to the web server user, in this case '{$CC_CONFIG['webServerUser']}'.<br>\n"; echo " * The group perms need to be set to the web server user, in this case '{$CC_CONFIG['webServerUser']}'.<br>\n";
echo " * Currently the group is set to be '{$groupOwner['name']}'.<br>\n"; echo " * Currently the group is set to be '{$groupOwner['name']}'.<br>\n";
exit(1); exit(1);
} }
if (!($fileperms & 0x0400)) { if (!($fileperms & 0x0400)) {
echo " * Error: Sticky bit not set for {$filePath}.<br>\n"; echo " * Error: Sticky bit not set for {$filePath}.<br>\n";
exit(1); exit(1);
} }
} }

View File

@ -16,9 +16,9 @@ require_once('../backend/StoredFile.php');
function printUsage() { function printUsage() {
global $CC_CONFIG; global $CC_CONFIG;
echo "Usage:\n"; echo "Usage:\n";
echo " ./CleanStor [OPTION] \n"; echo " ./CleanStor [OPTION] \n";
echo "\n"; echo "\n";
echo "Options:\n"; echo "Options:\n";
@ -31,33 +31,33 @@ function printUsage() {
} }
function camp_clean_files($p_path) { 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); list($dirList,$fileList) = File_Find::maptree($p_path);
$array_mus; $array_mus;
foreach ($fileList as $filepath) { foreach ($fileList as $filepath) {
if (@substr($filepath, strlen($filepath) - 3) != "xml") { if (@substr($filepath, strlen($filepath) - 3) != "xml") {
$array_mus[] = $filepath; $array_mus[] = $filepath;
} }
} }
foreach ($array_mus as $audio_file) { 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. //filesystem clean up.
@unlink($audio_file); @unlink($audio_file);
echo "unlinked $audio_file\n"; echo "unlinked $audio_file\n";
@unlink($audio_file . ".xml"); @unlink($audio_file . ".xml");
echo "unlinked " . $audio_file . ".xml\n"; echo "unlinked " . $audio_file . ".xml\n";
@rmdir(@dirname($audio_file)); @rmdir(@dirname($audio_file));
echo "removed dir " . @dirname($audio_file) . "\n"; echo "removed dir " . @dirname($audio_file) . "\n";
//database clean up. //database clean up.
$stored_audio_file = StoredFile::RecallByGunid(@basename($audio_file)); $stored_audio_file = StoredFile::RecallByGunid(@basename($audio_file));
$stored_audio_file->delete(); $stored_audio_file->delete();
} }
} }
} }
@ -69,8 +69,8 @@ function camp_remove_files($p_path) {
list($dirList,$fileList) = File_Find::maptree($p_path); list($dirList,$fileList) = File_Find::maptree($p_path);
foreach ($fileList as $filepath) { foreach ($fileList as $filepath) {
echo " * Removing $filepath\n"; echo " * Removing $filepath\n";
@unlink($filepath); @unlink($filepath);
echo "done.\n"; echo "done.\n";
} }
foreach ($dirList as $dirpath) { foreach ($dirList as $dirpath) {
@ -82,18 +82,18 @@ function camp_remove_files($p_path) {
} }
function camp_empty_db($db) { function camp_empty_db($db) {
global $CC_CONFIG; global $CC_CONFIG;
if (!PEAR::isError($db)) { if (!PEAR::isError($db)) {
if (camp_db_table_exists($CC_CONFIG['filesTable'])) { if (camp_db_table_exists($CC_CONFIG['filesTable'])) {
echo " * Deleting from database table ".$CC_CONFIG['filesTable']."\n"; echo " * Deleting from database table ".$CC_CONFIG['filesTable']."\n";
$sql = "DELETE FROM ".$CC_CONFIG['filesTable']; $sql = "DELETE FROM ".$CC_CONFIG['filesTable'];
camp_install_query($sql, false); camp_install_query($sql, false);
} }
else { else {
echo " * Skipping: database table ".$CC_CONFIG['filesTable']."\n"; echo " * Skipping: database table ".$CC_CONFIG['filesTable']."\n";
} }
} }
} }
@ -104,17 +104,17 @@ $CC_DBC->setFetchMode(DB_FETCHMODE_ASSOC);
switch($argv[1]){ switch($argv[1]){
case '-e': case '-e':
case '--empty': case '--empty':
camp_empty_db($CC_DBC); camp_empty_db($CC_DBC);
camp_remove_files($CC_CONFIG['storageDir']); camp_remove_files($CC_CONFIG['storageDir']);
break; break;
case '-c': case '-c':
case '--clean': case '--clean':
camp_clean_files($CC_CONFIG['storageDir']); camp_clean_files($CC_CONFIG['storageDir']);
break; break;
default: default:
printUsage(); printUsage();
} }

View File

@ -20,18 +20,18 @@ $stid = $bs->storId;
function admDumpFolder(&$bs, $fid, $ind='') function admDumpFolder(&$bs, $fid, $ind='')
{ {
// NOTE: need to fix this, removed due to tree removal // NOTE: need to fix this, removed due to tree removal
// $name = M2tree::GetObjName($fid); // $name = M2tree::GetObjName($fid);
// if (PEAR::isError($name)) { // if (PEAR::isError($name)) {
// echo $name->getMessage(); // echo $name->getMessage();
// exit; // exit;
// } // }
$media = StoredFile::Recall($fid); $media = StoredFile::Recall($fid);
$type = $media->getType(); $type = $media->getType();
$gunid = $media->getGunid(); $gunid = $media->getGunid();
$pars = array(); $pars = array();
if ($gunid) { if ($gunid) {
$pars['id']="$gunid"; $pars['id']="$gunid";
} }
$pars['name'] = "$name"; $pars['name'] = "$name";
switch ($type) { switch ($type) {
@ -65,13 +65,13 @@ function admDumpGroup(&$bs, $gid, $ind='')
{ {
$name = Subjects::GetSubjName($gid); $name = Subjects::GetSubjName($gid);
if (PEAR::isError($name)) { if (PEAR::isError($name)) {
echo $name->getMessage(); echo $name->getMessage();
exit; exit;
} }
$isGr = Subjects::IsGroup($gid); $isGr = Subjects::IsGroup($gid);
if (PEAR::isError($isGr)) { if (PEAR::isError($isGr)) {
echo $isGr->getMessage(); echo $isGr->getMessage();
exit; exit;
} }
$pars = array('name'=>"$name"); $pars = array('name'=>"$name");
$pars['id'] = $gid; $pars['id'] = $gid;
@ -84,8 +84,8 @@ function admDumpGroup(&$bs, $gid, $ind='')
} }
$garr = Subjects::ListGroup($gid); $garr = Subjects::ListGroup($gid);
if (PEAR::isError($garr)) { if (PEAR::isError($garr)) {
echo $garr->getMessage(); echo $garr->getMessage();
exit; exit;
} }
$res = ''; $res = '';
foreach ($garr as $i => $member) { foreach ($garr as $i => $member) {
@ -99,98 +99,98 @@ function admDumpGroup(&$bs, $gid, $ind='')
); );
$prefs = admDumpPrefs($bs, $gid); $prefs = admDumpPrefs($bs, $gid);
if (!is_null($prefs)) { if (!is_null($prefs)) {
$res .= $prefs; $res .= $prefs;
} }
if ($res) { if ($res) {
$tagarr['content'] = $res; $tagarr['content'] = $res;
} }
return XML_Util::createTagFromArray($tagarr, $res === ''); return XML_Util::createTagFromArray($tagarr, $res === '');
// if (!$res) { // if (!$res) {
// } else { // } else {
// return XML_Util::createTagFromArray(array( // return XML_Util::createTagFromArray(array(
// 'namespace' => NSPACE, // 'namespace' => NSPACE,
// 'localPart' => 'group', // 'localPart' => 'group',
// 'attributes'=> $pars, // 'attributes'=> $pars,
// 'content' => $res, // 'content' => $res,
// ), FALSE); // ), FALSE);
// } // }
} }
function admDumpSubjects(&$bs, $ind='') function admDumpSubjects(&$bs, $ind='')
{ {
$res =''; $res ='';
$subjs = Subjects::GetSubjects('id, login, pass, type'); $subjs = Subjects::GetSubjects('id, login, pass, type');
foreach ($subjs as $i => $member) { foreach ($subjs as $i => $member) {
switch ($member['type']) { switch ($member['type']) {
case "U": case "U":
$prefs = admDumpPrefs($bs, $member['id']); $prefs = admDumpPrefs($bs, $member['id']);
$pars = array('login'=>"{$member['login']}", 'pass'=>"{$member['pass']}"); $pars = array('login'=>"{$member['login']}", 'pass'=>"{$member['pass']}");
$pars['id'] = $member['id']; $pars['id'] = $member['id'];
$tagarr = array( $tagarr = array(
'namespace' => NSPACE, 'namespace' => NSPACE,
'localPart' => 'user', 'localPart' => 'user',
'attributes'=> $pars, 'attributes'=> $pars,
); );
if (!is_null($prefs)) { if (!is_null($prefs)) {
$tagarr['content'] = $prefs; $tagarr['content'] = $prefs;
} }
$res .= XML_Util::createTagFromArray($tagarr , FALSE); $res .= XML_Util::createTagFromArray($tagarr , FALSE);
break; break;
case "G": case "G":
$res .= admDumpGroup($bs, $member['id'], "$ind "); $res .= admDumpGroup($bs, $member['id'], "$ind ");
break; break;
}
} }
} # return "$ind<subjects>\n$res$ind</subjects>\n";
# return "$ind<subjects>\n$res$ind</subjects>\n"; return XML_Util::createTagFromArray(array(
return XML_Util::createTagFromArray(array(
'namespace' => NSPACE, 'namespace' => NSPACE,
'localPart' => 'subjects', 'localPart' => 'subjects',
'content'=> $res, 'content'=> $res,
), FALSE); ), FALSE);
} }
function admDumpPrefs(&$bs, $subjid) function admDumpPrefs(&$bs, $subjid)
{ {
$res =''; $res ='';
$pr = new Prefs($bs); $pr = new Prefs($bs);
$prefkeys = $pr->readKeys($subjid); $prefkeys = $pr->readKeys($subjid);
# var_dump($subjid); var_dump($prefkeys); #exit; # var_dump($subjid); var_dump($prefkeys); #exit;
foreach ($prefkeys as $i => $prefk) { foreach ($prefkeys as $i => $prefk) {
$keystr = $prefk['keystr']; $keystr = $prefk['keystr'];
$prefval = $pr->readVal($subjid, $keystr); $prefval = $pr->readVal($subjid, $keystr);
$pars = array('name'=>"$keystr", 'val'=>"$prefval"); $pars = array('name'=>"$keystr", 'val'=>"$prefval");
$res .= XML_Util::createTagFromArray(array( $res .= XML_Util::createTagFromArray(array(
'namespace' => NSPACE, 'namespace' => NSPACE,
'localPart' => 'pref', 'localPart' => 'pref',
'attributes'=> $pars, 'attributes'=> $pars,
)); ));
} }
if (!$res) { if (!$res) {
return NULL; return NULL;
} }
return XML_Util::createTagFromArray(array( return XML_Util::createTagFromArray(array(
'namespace' => NSPACE, 'namespace' => NSPACE,
'localPart' => 'preferences', 'localPart' => 'preferences',
'content'=> $res, 'content'=> $res,
), FALSE); ), FALSE);
} }
$subjects = admDumpSubjects($bs, ' '); $subjects = admDumpSubjects($bs, ' ');
$tree = admDumpFolder($bs, $stid, ' '); $tree = admDumpFolder($bs, $stid, ' ');
$res = XML_Util::getXMLDeclaration("1.0", "UTF-8")."\n"; $res = XML_Util::getXMLDeclaration("1.0", "UTF-8")."\n";
$node = XML_Util::createTagFromArray(array( $node = XML_Util::createTagFromArray(array(
'namespace' => NSPACE, 'namespace' => NSPACE,
'localPart' => 'storageServer', 'localPart' => 'storageServer',
'content' => "$subjects$tree", 'content' => "$subjects$tree",
), FALSE); ), FALSE);
$res .= $node; $res .= $node;
$fmt = new XML_Beautifier(); $fmt = new XML_Beautifier();
$res = $fmt->formatString($res); $res = $fmt->formatString($res);
#var_export($res); #var_export($res);
#var_dump($res); #var_dump($res);
echo "$res"; echo "$res";
?> ?>

View File

@ -26,7 +26,7 @@ function camp_import_error_handler()
function printUsage() function printUsage()
{ {
global $CC_CONFIG; global $CC_CONFIG;
echo "There are two ways to import audio files into Campcaster: linking\n"; echo "There are two ways to import audio files into Campcaster: linking\n";
echo "or copying.\n"; echo "or copying.\n";
echo "\n"; echo "\n";
@ -71,11 +71,11 @@ function import_err($p_pearErrorObj, $txt='')
{ {
global $g_errors; global $g_errors;
if (PEAR::isError($p_pearErrorObj)) { if (PEAR::isError($p_pearErrorObj)) {
$msg = $p_pearErrorObj->getMessage()." ".$p_pearErrorObj->getUserInfo(); $msg = $p_pearErrorObj->getMessage()." ".$p_pearErrorObj->getUserInfo();
} }
echo "\nERROR: $msg\n"; echo "\nERROR: $msg\n";
if (!empty($txt)) { if (!empty($txt)) {
echo "ERROR: $txt\n"; echo "ERROR: $txt\n";
} }
$g_errors++; $g_errors++;
} }
@ -174,20 +174,20 @@ function camp_import_audio_file($p_filepath, $p_importMode = null, $p_testOnly =
global $g_errors; global $g_errors;
$g_errors++; $g_errors++;
echo "ERROR: $p_filepath\n" echo "ERROR: $p_filepath\n"
." When importing with the '--link' option, files must be set\n" ." When importing with the '--link' option, files must be set\n"
." world-readable. The file permissions for the file cannot be\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" ." changed. Check that you are not trying to import from a FAT32\n"
." drive. Otherwise, this problem might be fixed by running this \n" ." drive. Otherwise, this problem might be fixed by running this \n"
." script with 'sudo'.\n"; ." script with 'sudo'.\n";
return; return;
} }
} }
} }
// $timeBegin = microtime(true); // $timeBegin = microtime(true);
$md5sum = md5_file($p_filepath); $md5sum = md5_file($p_filepath);
// $timeEnd = microtime(true); // $timeEnd = microtime(true);
// echo " * MD5 time: ".($timeEnd-$timeBegin)."\n"; // echo " * MD5 time: ".($timeEnd-$timeBegin)."\n";
// Look up md5sum in database // Look up md5sum in database
$duplicate = StoredFile::RecallByMd5($md5sum); $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); $storedFile = StoredFile::Insert($values, $doCopyFiles);
if (PEAR::isError($storedFile)) { if (PEAR::isError($storedFile)) {
import_err($storedFile, "Error in StoredFile::Insert()"); import_err($storedFile, "Error in StoredFile::Insert()");
echo var_export($metadata)."\n"; echo var_export($metadata)."\n";
return; return;
} }
} else { } else {
echo "==========================================================================\n"; echo "==========================================================================\n";
@ -250,8 +250,8 @@ if ($DEBUG_IMPORT) {
PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, "camp_import_error_handler"); PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, "camp_import_error_handler");
$CC_DBC = DB::connect($dsn, TRUE); $CC_DBC = DB::connect($dsn, TRUE);
if (PEAR::isError($CC_DBC)) { if (PEAR::isError($CC_DBC)) {
echo "ERROR: ".$CC_DBC->getMessage()." ".$CC_DBC->getUserInfo()."\n"; echo "ERROR: ".$CC_DBC->getMessage()." ".$CC_DBC->getUserInfo()."\n";
exit(1); exit(1);
} }
$CC_DBC->setFetchMode(DB_FETCHMODE_ASSOC); $CC_DBC->setFetchMode(DB_FETCHMODE_ASSOC);
@ -308,8 +308,8 @@ if (is_null($importMode)) {
global $CC_CONFIG; global $CC_CONFIG;
if (!is_writable($CC_CONFIG["storageDir"])) { 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"; echo "ERROR: You do not have write permissions to the directory you are trying to import to:\n " . $CC_CONFIG["storageDir"] . "\n\n";
exit; exit;
} }
global $g_fileCount; global $g_fileCount;
@ -335,9 +335,9 @@ if (is_array($files)) {
$end = intval(date('U')); $end = intval(date('U'));
$time = $end - $start; $time = $end - $start;
if ($time > 0) { if ($time > 0) {
$speed = round(($g_fileCount+$g_duplicates)/$time, 1); $speed = round(($g_fileCount+$g_duplicates)/$time, 1);
} else { } else {
$speed = ($g_fileCount+$g_duplicates); $speed = ($g_fileCount+$g_duplicates);
} }
echo "==========================================================================\n"; echo "==========================================================================\n";