Example #1
0
 public static function safe_json_encode($value)
 {
     if (version_compare(PHP_VERSION, '5.4.0') >= 0) {
         $encoded = json_encode($value, JSON_PRETTY_PRINT);
     } else {
         $encoded = json_encode($value);
     }
     switch (json_last_error()) {
         case JSON_ERROR_NONE:
             return $encoded;
         case JSON_ERROR_DEPTH:
             return 'Maximum stack depth exceeded';
             // or trigger_error() or throw new Exception()
         // or trigger_error() or throw new Exception()
         case JSON_ERROR_STATE_MISMATCH:
             return 'Underflow or the modes mismatch';
             // or trigger_error() or throw new Exception()
         // or trigger_error() or throw new Exception()
         case JSON_ERROR_CTRL_CHAR:
             return 'Unexpected control character found';
         case JSON_ERROR_SYNTAX:
             return 'Syntax error, malformed JSON';
             // or trigger_error() or throw new Exception()
         // or trigger_error() or throw new Exception()
         case JSON_ERROR_UTF8:
             $clean = utf8ize($value);
             return safe_json_encode($clean);
         default:
             return 'Unknown error';
             // or trigger_error() or throw new Exception()
     }
 }
Example #2
0
 /**
  * Responds to a search request for a choice.
  *
  * @return string a JSON response string.
  */
 public function respond_to_js()
 {
     $requestval = required_param('val', PARAM_CLEAN);
     $ret = array();
     $requestval = strtolower($requestval);
     foreach ($this->choices as $choice) {
         if (strpos(strtolower($choice), $requestval) !== false) {
             $ret[] = array('id' => $choice, 'label' => $choice);
         }
     }
     return safe_json_encode($ret);
 }
Example #3
0
function updateAddPlay()
{
    global $cfg, $db;
    //authenticate('access_playlist', false, false, true);
    sleep(1);
    $album_id = get('album_id');
    $query = mysql_query('SELECT COUNT(c.album_id) as counter, c.time FROM (SELECT time, album_id FROM counter WHERE album_id = "' . mysql_real_escape_string($album_id) . '" ORDER BY time DESC) c ORDER BY c.time');
    $played = mysql_fetch_assoc($query);
    $query = mysql_query('SELECT artist, artist_alphabetic, album, image_id, album.album_id, COUNT(*) AS counter
			FROM counter, album
			WHERE counter.album_id = album.album_id
			GROUP BY album.album_id
			ORDER BY counter DESC, time DESC
			LIMIT 1');
    $max_played = mysql_fetch_assoc($query);
    $popularity = round($played['counter'] / $max_played['counter'] * 100);
    $data = array();
    $data['played'] = (string) $played['counter'] . ' ' . ($played['counter'] == 1 ? ' time' : ' times');
    $data['last_played'] = date("Y-m-d H:i", $played['time']);
    $data['popularity'] = (int) $popularity;
    //$data['bar_popularity']		= (string) floor($popularity * 1.8);
    echo safe_json_encode($data);
}
Example #4
0
var previous_listpos		= <?php 
echo $listpos;
?>
;
var previous_isplaying		= -1; // force update
var previous_repeat			= -1;
var previous_shuffle		= -1;
var previous_gain			= -1;
var previous_miliseconds	= -1;
var previous_volume			= -1;
var playtime				= <?php 
echo safe_json_encode($playtime);
?>
;
var track_id				= <?php 
echo safe_json_encode($track_id);
?>
;
var timer_id				= 0;
var timer_function			= 'ajaxRequest("play.php?action=playlistStatus&menu=playlist", evaluateStatus)';
//var timer_function			= '';
var timer_delay				= 1000;
var list_length				= <?php 
echo $listlength;
?>
;
//console.trace();

function deletePLitem(data) {
	//console.trace();
	
Example #5
0
$mngr = rRatioRulesList::load();
$val = null;
switch ($cmd) {
    case "setrules":
        $mngr->set();
        break;
    case "checklabels":
        $hash = array();
        if (!isset($HTTP_RAW_POST_DATA)) {
            $HTTP_RAW_POST_DATA = file_get_contents("php://input");
        }
        if (isset($HTTP_RAW_POST_DATA)) {
            $vars = explode('&', $HTTP_RAW_POST_DATA);
            foreach ($vars as $var) {
                $parts = explode("=", $var);
                switch ($parts[0]) {
                    case "hash":
                        $hash[] = $parts[1];
                        break;
                }
            }
        }
        $mngr->checkLabels($hash);
        $val = array();
        break;
}
if (is_null($val)) {
    $val = $mngr->getContents();
}
cachedEcho(safe_json_encode($val), "application/json", true);
Example #6
0
function authenticateOpensearch($input)
{
    global $cfg, $db;
    header('Expires: Mon, 9 Oct 2000 18:00:00 GMT');
    header('Cache-Control: no-store, no-cache, must-revalidate');
    $sid = cookie('netjukebox_sid');
    $version = get('version');
    $query = mysql_query('SELECT logged_in, idle_time, ip, user_agent FROM session WHERE sid = BINARY "' . mysql_real_escape_string($sid) . '"');
    $session = mysql_fetch_assoc($query);
    if ($sid == '') {
        $data = array('Allow third-party cookies,', 'or add an exception for this domain!');
        $data = array($input, $data);
        echo safe_json_encode($data);
        exit;
    }
    if ($version != 1) {
        $data = array('Reinstall opensearch plugin!');
        $data = array($input, $data);
        echo safe_json_encode($data);
        exit;
    }
    if ($session['logged_in'] && $session['ip'] == $_SERVER['REMOTE_ADDR'] && $session['user_agent'] == substr($_SERVER['HTTP_USER_AGENT'], 0, 255) && $session['idle_time'] + $cfg['session_lifetime'] > time()) {
        return true;
    }
    $data = array('Login netjukebox!');
    $data = array($input, $data);
    echo safe_json_encode($data);
    exit;
}
Example #7
0
 /**
  * Responds to a search request for a choice.
  *
  * @return string a JSON response string.
  */
 public function respond_to_js()
 {
     $requestval = required_param('val', PARAM_CLEAN);
     $ret = array();
     $sql = 'SELECT DISTINCT ' . $this->choicesfield . '
               FROM {' . $this->choicestable . '}
              WHERE ' . $this->choicesfield . ' LIKE ?';
     $vals = $this->DB->get_recordset_sql($sql, array('%' . $requestval . '%'));
     $choicesfield = $this->choicesfield;
     foreach ($vals as $val) {
         $ret[] = array('id' => $val->{$choicesfield}, 'label' => ucwords($val->{$choicesfield}));
     }
     return safe_json_encode($ret);
 }
//  | along with this program.  If not, see <http://www.gnu.org/licenses/>.  |
//  +------------------------------------------------------------------------+
global $cfg, $db;
require_once 'include/initialize.inc.php';
require_once 'include/play.inc.php';
if ($cfg['player_type'] == NJB_MPD) {
    $data = array();
    $query1 = mysql_query('SELECT player.player_name as pl, player_host, player_port FROM player, session WHERE (sid = BINARY "' . cookie('netjukebox_sid') . '") and player.player_id=session.player_id');
    $session1 = mysql_fetch_assoc($query1);
    $data['player'] = $session1['pl'];
    //$data['host'] = $session1['player_host'];
    $cfg['player_host'] = $data['host'] = $session1['player_host'];
    $cfg['player_port'] = $session1['player_port'];
    $cfg['player_pass'] = $session1['player_pass'];
    $status = mpdSilent('status');
    if ($status != false) {
        $data['volume'] = (int) $status['volume'];
    } else {
        $data['volume'] = -1;
    }
    // get mute volume
    if ($data['volume'] == 0) {
        $query = mysql_query('SELECT mute_volume FROM player WHERE player_id = ' . (int) $cfg['player_id']);
        $temp = mysql_fetch_assoc($query);
        $data['volume'] = -$temp['mute_volume'];
    }
    echo safe_json_encode($data);
}
?>
	
Example #9
0
 public function get()
 {
     return safe_json_encode($this->list);
 }
 /**
  * Test AJAX responses
  */
 public function test_responses()
 {
     global $DB, $SESSION;
     $name = 'datatable';
     $endpoint = 'test.php';
     $datatable = new deepsight_datatable_mock($DB, $name, $endpoint);
     // Test basic response.
     ob_start();
     $datatable->respond('mock');
     $contents = ob_get_contents();
     ob_end_clean();
     $this->assertEquals('Success', $contents);
     // Test nonexistent respond.
     ob_start();
     $datatable->respond('nonexistent');
     $contents = ob_get_contents();
     ob_end_clean();
     $expected = 'throw 1;{"result":"fail","msg":"Do not know how to respond to that request."}';
     $this->assertEquals($expected, $contents);
     // Test filter response.
     ob_start();
     $_POST['filtername'] = 'testfilter1';
     $datatable->respond('filter');
     $actual = ob_get_contents();
     ob_end_clean();
     $expected = 'success';
     $this->assertEquals($expected, $actual);
     // Test action response.
     ob_start();
     $_POST['actionname'] = 'testaction';
     $_POST['sesskey'] = sesskey();
     $_POST['elements'] = safe_json_encode(array());
     $datatable->respond('action');
     $actual = ob_get_contents();
     ob_end_clean();
     $expected = safe_json_encode(array('result' => 'success'));
     $this->assertEquals($expected, $actual);
     // Empty bulklist list.
     ob_start();
     $datatable->respond('bulklist_get');
     $actual = ob_get_contents();
     ob_end_clean();
     $actual = safe_json_decode($actual);
     $expected = array('result' => 'success', 'page_results_ids' => array(), 'page_results_values' => array(), 'total_results' => 0);
     $this->assertEquals($expected, $actual);
     // Test bulklist list with items.
     $bulklistparam = $datatable->get_bulklist_sess_param();
     $generatedids = array();
     for ($i = 0; $i < 2; $i++) {
         $user = new stdClass();
         $user->firstname = 'Test';
         $user->lastname = 'User ' . $i;
         $id = $DB->insert_record('local_elisprogram_usr', $user);
         $generatedids[] = $id;
         $SESSION->{$bulklistparam}[$id] = $id;
     }
     ob_start();
     $datatable->respond('bulklist_get');
     $actual = ob_get_contents();
     ob_end_clean();
     $actual = safe_json_decode($actual);
     $expected = array('result' => 'success', 'page_results_ids' => array_reverse($generatedids), 'page_results_values' => array('Test User 1', 'Test User 0'), 'total_results' => 2);
     $this->assertEquals($expected, $actual);
     // Test bulklist modify - removing.
     $_POST['modify'] = 'remove';
     $_POST['ids'] = array(2);
     ob_start();
     $datatable->respond('bulklist_modify');
     $actual = ob_get_contents();
     ob_end_clean();
     $actual = safe_json_decode($actual);
     $expected = array('result' => 'success', 'page_results_ids' => array(1), 'page_results_values' => array('Test User 0'), 'total_results' => 1);
     $this->assertEquals($expected, $actual);
     // Test bulklist modify - adding.
     $_POST['modify'] = 'add';
     $_POST['ids'] = array(2);
     ob_start();
     $datatable->respond('bulklist_modify');
     $actual = ob_get_contents();
     ob_end_clean();
     $actual = safe_json_decode($actual);
     $expected = array('result' => 'success', 'page_results_ids' => array(2, 1), 'page_results_values' => array('Test User 1', 'Test User 0'), 'total_results' => 2);
     $this->assertEquals($expected, $actual);
     // Test bulklist modify - deduplication.
     $_POST['modify'] = 'add';
     $_POST['ids'] = array(2);
     ob_start();
     $datatable->respond('bulklist_modify');
     $actual = ob_get_contents();
     ob_end_clean();
     $actual = safe_json_decode($actual);
     $expected = array('result' => 'success', 'page_results_ids' => array(2, 1), 'page_results_values' => array('Test User 1', 'Test User 0'), 'total_results' => 2);
     $this->assertEquals($expected, $actual);
 }
Example #11
0
function playlistTrack()
{
    global $cfg, $db;
    authenticate('access_playlist', false, false, true);
    $track_id = get('track_id');
    $query = mysql_query('SELECT track.artist, album.artist AS album_artist, title, featuring, miliseconds, relative_file, album, album.image_id, album.album_id, track.genre, track.audio_bitrate, track.audio_dataformat, track.audio_bits_per_sample, track.audio_sample_rate, album.genre_id, track.audio_profile, track.track_artist, album.year as year, track.number, track.comment, track.track_id, track.year as trackYear, track.dr, album.album_dr
		FROM track, album 
		WHERE track.album_id = album.album_id
		AND track_id = "' . mysql_real_escape_string($track_id) . '"');
    $track = mysql_fetch_assoc($query);
    $query = mysql_query('SELECT image_front FROM bitmap WHERE image_id="' . mysql_real_escape_string($track['image_id']) . '"');
    $bitmap = mysql_fetch_assoc($query);
    $title = $track['title'];
    /* $query_ = mysql_query('SELECT title FROM track
    		WHERE DIFFERENCE(SOUNDEX(title), SOUNDEX("' . (mysql_real_escape_like($title)) . '")) > 0');
    	$query_ = mysql_query('SELECT SOUNDEX(title) FROM track');
    	 */
    /* $title = strtolower($title);
    	$separator = $cfg['separator'];
    	$count = count($separator);
    	$i=0;
    	
    	for ($i=0; $i<$count; $i++) {
    		$pos = strpos($title,strtolower($separator[$i]));
    		if ($pos !== false) {
    			$title = trim(substr($title, 0 , $pos));
    			//break;
    		}
    	}  */
    $other_track_version = false;
    if ($cfg['enable_core_track_search'] === TRUE) {
        $title = findCoreTrackTitle($title);
        $title = mysql_real_escape_like($title);
        $separator = $cfg['separator'];
        $count = count($separator);
        $query_string = '';
        $i = 0;
        for ($i = 0; $i < $count; $i++) {
            $query_string = $query_string . ' OR LOWER(title) LIKE "' . $title . $separator[$i] . '%"';
        }
        $filter_query = 'WHERE (LOWER(title) = "' . $title . '" ' . $query_string . ')';
        $query = mysql_query('SELECT title FROM track ' . $filter_query);
        if (strlen($title) > 0) {
            $num_rows = mysql_num_rows($query);
            if ($num_rows > 1) {
                $other_track_version = true;
            }
        }
    }
    $exploded = multiexplode($cfg['artist_separator'], $track['track_artist']);
    $inFavorite = false;
    if (isset($cfg['favorite_id'])) {
        $query = mysql_query("SELECT track_id FROM favoriteitem WHERE track_id = '" . $track_id . "' AND favorite_id = '" . $cfg['favorite_id'] . "' LIMIT 1");
        if (mysql_num_rows($query) > 0) {
            $inFavorite = true;
        }
    }
    $data = array();
    $data['album_artist'] = (string) ($track['album_artist'] == "Various Artists") ? rawurlencode($track['track_artist']) : rawurlencode($track['album_artist']);
    $data['track_artist'] = $exploded;
    $data['track_artist_url'] = $exploded;
    $data['track_artist_url_all'] = (string) rawurlencode($track['track_artist']);
    $data['title'] = (string) (trim($track['title']) !== '') ? $track['title'] : basename($track['relative_file']);
    $data['album'] = (string) (trim($track['album']) !== '') ? $track['album'] : basename(dirname($track['relative_file']));
    //$data['album']		= (string) $title;
    $data['by'] = (string) $by;
    $data['image_id'] = (string) $track['image_id'];
    $data['album_id'] = (string) $track['album_id'];
    $data['year'] = is_null($track['year']) ? (string) $track['trackYear'] : (string) $track['year'];
    $data['genre'] = (string) $track['genre'];
    $data['audio_dataformat'] = (string) strtoupper($track['audio_dataformat']);
    $data['audio_bits_per_sample'] = (string) $track['audio_bits_per_sample'];
    $data['audio_sample_rate'] = (string) $track['audio_sample_rate'];
    $data['genre_id'] = (string) $track['genre_id'];
    if ($track['audio_profile'] == 'Lossless compression') {
        $data['audio_profile'] = (string) floor($track['audio_bitrate'] / 1000) . ' kbps';
    } else {
        $data['audio_profile'] = (string) $track['audio_profile'];
    }
    $data['number'] = (string) $track['number'] . '. ';
    $data['miliseconds'] = (string) $track['miliseconds'];
    $data['other_track_version'] = (bool) $other_track_version;
    $data['comment'] = (string) $track['comment'];
    $data['track_id'] = (string) $track['track_id'];
    $data['relative_file'] = (string) $track['relative_file'];
    $data['inFavorite'] = (bool) $inFavorite;
    $data['dr'] = (string) $track['dr'];
    $data['album_dr'] = (string) $track['album_dr'];
    $data['title_core'] = $title;
    echo safe_json_encode($data);
}
Example #12
0
 /**
  * Routes ajax requests to the applicable object and displays response.
  */
 public function do_deepsight_response()
 {
     global $DB;
     $mode = $this->required_param('m');
     $classid = $this->required_param('id', PARAM_INT);
     $tabletype = $this->required_param('tabletype', PARAM_ALPHA);
     if (!in_array($tabletype, array('assigned', 'unassigned'), true)) {
         throw new Exception('Invalid table type specified');
     }
     // Authorization.
     $assignedauthorized = $tabletype === 'assigned' && $this->can_do_default() === true ? true : false;
     $unassignedauthorized = $tabletype === 'unassigned' && $this->can_do_add() === true ? true : false;
     if ($assignedauthorized !== true && $unassignedauthorized !== true) {
         echo safe_json_encode(array('result' => 'fail', 'msg' => get_string('not_permitted', 'local_elisprogram')));
     }
     // Build the table.
     $uniqid = optional_param('uniqid', null, PARAM_CLEAN);
     $table = $tabletype === 'assigned' ? $this->construct_assigned_table($uniqid) : $this->construct_unassigned_table($uniqid);
     if ($mode === 'action') {
         // We'll use page-specific can_do actions to authorize access to each requested action.
         $actionname = required_param('actionname', PARAM_ALPHAEXT);
         $candoactionmethod = 'can_do_action_' . $actionname;
         if (method_exists($this, $candoactionmethod) && $this->{$candoactionmethod}() === true) {
             $table->respond($mode);
         } else {
             echo safe_json_encode(array('result' => 'fail', 'msg' => get_string('not_permitted', 'local_elisprogram')));
         }
     } else {
         $table->respond($mode);
     }
 }
Example #13
0
 /**
  * Test the searchselect filter's search function.
  *
  * @dataProvider searchselectfilter_respond_dataprovider
  */
 public function test_filter_searchselect_respond($filterdata, $expectedresponse)
 {
     global $DB;
     $expectedresponse = safe_json_encode($expectedresponse);
     // Insert test data.
     $cities = array('Springfield', 'Springfield', 'Springfield', 'Toronto', 'Toronto', 'Waterloo');
     foreach ($cities as $i => $city) {
         $user = new stdClass();
         $user->username = '******' . $i;
         $user->idnumber = 'testuser' . $i;
         $user->city = $city;
         $DB->insert_record('local_elisprogram_usr', $user);
     }
     $name = 'searchselect';
     $label = 'Search Select';
     $endpoint = 'test.php';
     $fielddata = array('city' => 'City');
     $filter = new deepsight_filter_searchselect($DB, $name, $label, $fielddata, $endpoint, 'local_elisprogram_usr', 'city');
     $_POST['val'] = $filterdata;
     $response = $filter->respond_to_js();
     $this->assertEquals($expectedresponse, $response);
 }
Example #14
0
 public function pushBulletNotify($data)
 {
     global $pushBulletNotifications, $pushBulletEndpoint;
     $actions = array(1 => 'addition', 2 => 'finish', 3 => 'deletion');
     $section = $pushBulletNotifications[$actions[$data['action']]];
     $fields = array('{name}', '{label}', '{size}', '{downloaded}', '{uploaded}', '{ratio}', '{creation}', '{added}', '{finished}', '{tracker}');
     $values = array($data['name'], $data['label'], self::bytes($data['size']), self::bytes($data['downloaded']), self::bytes($data['uploaded']), $data['ratio'], strftime('%c', $data['creation']), strftime('%c', $data['added']), strftime('%c', $data['finished']), $data['tracker']);
     $title = str_replace($fields, $values, $section['title']);
     $body = str_replace($fields, $values, $section['body']);
     $client = new Snoopy();
     $client->user = $this->log["pushbullet_key"];
     $client->fetch($pushBulletEndpoint, "POST", "application/json", safe_json_encode(array('type' => 'note', 'title' => $title, 'body' => $body)));
 }
Example #15
0
<?php

require_once '../../php/util.php';
eval(getPluginConf('geoip'));
require_once 'ip_db.php';
$db = new ipDB();
$db->add($_REQUEST["ip"], $_REQUEST["comment"]);
cachedEcho(safe_json_encode(array("ip" => $_REQUEST["ip"], "comment" => $_REQUEST["comment"])), "application/json");
Example #16
0
<?php

require_once 'cookies.php';
$cmd = '';
if (isset($_REQUEST['mode'])) {
    $cmd = $_REQUEST['mode'];
}
switch ($cmd) {
    case 'info':
        $cookies = rCookies::load();
        if (isset($_REQUEST['host'])) {
            cachedEcho(safe_json_encode($cookies->getCookiesForHost($_REQUEST['host'])), "application/json");
        } else {
            cachedEcho(safe_json_encode($cookies->getInfo()), "application/json");
        }
    case 'add':
        $cookies = rCookies::load();
        if (isset($_REQUEST['host'])) {
            $cookies->add($_REQUEST['host'], rawurldecode($_REQUEST['cookies']));
        }
        cachedEcho(safe_json_encode($cookies->getInfo()), "application/json");
    default:
        $cookies = new rCookies();
        $cookies->set();
        cachedEcho($cookies->get(), "application/javascript");
}
Example #17
0
<?php

eval(getPluginConf('screenshots'));
if (!$theSettings->isPluginRegistered("explorer")) {
    require_once "ffmpeg.php";
}
$st = ffmpegSettings::load();
$jResult .= "plugin.ffmpegSettings = " . safe_json_encode($st->get()) . "; plugin.extensions = " . safe_json_encode($extensions) . ";";
$theSettings->registerPlugin($plugin["name"], $pInfo["perms"]);
Example #18
0
require_once 'history.php';
if (isset($_REQUEST['cmd'])) {
    $cmd = $_REQUEST['cmd'];
    switch ($cmd) {
        case "set":
            $up = rHistory::load();
            $up->set();
            cachedEcho($up->get(), "application/javascript");
            break;
        case "get":
            $up = rHistoryData::load();
            cachedEcho(safe_json_encode($up->get($_REQUEST['mark'])), "application/json");
            break;
        case "delete":
            $up = rHistoryData::load();
            $hashes = array();
            if (!isset($HTTP_RAW_POST_DATA)) {
                $HTTP_RAW_POST_DATA = file_get_contents("php://input");
            }
            if (isset($HTTP_RAW_POST_DATA)) {
                $vars = explode('&', $HTTP_RAW_POST_DATA);
                foreach ($vars as $var) {
                    $parts = explode("=", $var);
                    $hashes[] = $parts[1];
                }
                $up->delete($hashes);
            }
            cachedEcho(safe_json_encode($up->get(0)), "application/json");
            break;
    }
}
Example #19
0
if (isset($_REQUEST['hash']) && isset($_REQUEST['no']) && isset($_REQUEST['cmd'])) {
    switch ($_REQUEST['cmd']) {
        case "mediainfo":
            $req = new rXMLRPCRequest(new rXMLRPCCommand("f.get_frozen_path", array($_REQUEST['hash'], intval($_REQUEST['no']))));
            if ($req->success()) {
                $filename = $req->val[0];
                if ($filename == '') {
                    $req = new rXMLRPCRequest(array(new rXMLRPCCommand("d.open", $_REQUEST['hash']), new rXMLRPCCommand("f.get_frozen_path", array($_REQUEST['hash'], intval($_REQUEST['no']))), new rXMLRPCCommand("d.close", $_REQUEST['hash'])));
                    if ($req->success()) {
                        $filename = $req->val[1];
                    }
                }
                if ($filename !== '') {
                    $commands = array();
                    $flags = '';
                    $st = mediainfoSettings::load();
                    $task = new rTask(array('arg' => call_user_func('getFileName', $filename), 'requester' => 'mediainfo', 'name' => 'mediainfo', 'hash' => $_REQUEST['hash'], 'no' => $_REQUEST['no']));
                    if ($st && !empty($st->data["mediainfousetemplate"])) {
                        $randName = $task->makeDirectory() . "/opts";
                        file_put_contents($randName, $st->data["mediainfotemplate"]);
                        $flags = "--Inform=file://" . escapeshellarg($randName);
                    }
                    $commands[] = getExternal("mediainfo") . " " . $flags . " " . escapeshellarg($filename);
                    $ret = $task->start($commands, rTask::FLG_WAIT);
                }
            }
            break;
    }
}
cachedEcho(safe_json_encode($ret), "application/json");
Example #20
0
 /**
  * Responds to a request from js for a page of results for a given set of filters.
  *
  * Parameters from $_REQUEST:
  *     array $filters         An array of filters to use when getting the results formatted like [filtername]=>[data]
  *     array $sort            (Optional) An array of sorting information, formatted like [fieldname]=>[direction].
  *     int   $limit_from      (Optional) The position in the entire result set to start returning rows.
  *     int   $limit_num       (Optional) The number of rows to return.
  *     array $bulklist_add    (Optional) An array of IDs to add to the bulklist before the results are fetched.
  *     array $bulklist_remove (Optional) An array of IDs to remove from the bulklist before the results are fetched.
  *
  * Outputs XSSI-safe-JSON containing two possible members: 'bulklist_modify' and 'datatable_results', outlined below.
  *
  *     bulklist_modify
  *         Will be present if $bulklist_add or $bulklist_remove were included with the original request.
  *         Contains updated bulklist data used by the bulk action panel.
  *         Contains the following:
  *             string result              'success' to indicate we successfully completed the request.
  *             array  page_results_ids    Array of IDs for current page of results in the same order as page_results_values.
  *             array  page_results_values Array of labels for current page of results in the same order as page_results_ids.
  *             int    total_results       The total number of results in the dataset.
  *
  *     datatable_results
  *         Will always be present and holds the results for the datatable.
  *             string result        'success' to indicate we successfully completed the request.
  *             array  column_labels An array of column labels formatted like [fieldname]=>[label]
  *             array  results       An array of results for the requested page.
  *             int    total_results A number of results in the entire dataset for the given filters.
  */
 protected function respond_datatable_results()
 {
     require_sesskey();
     $response = array();
     // Inputs.
     $sort = optional_param_array('sort', array(), PARAM_CLEAN);
     $limitfrom = optional_param('limit_from', 1, PARAM_INT);
     $limitnum = optional_param('limit_num', static::RESULTSPERPAGE, PARAM_INT);
     // Parse incoming filters.
     $filters = required_param('filters', PARAM_CLEAN);
     $filters = @json_decode($filters, true);
     if (empty($filters) || !is_array($filters)) {
         $filters = array();
     }
     // Modify bulklist, if necessary.
     $bulklistadd = optional_param_array('bulklist_add', array(), PARAM_INT);
     $bulklistremove = optional_param_array('bulklist_remove', array(), PARAM_CLEAN);
     if (!empty($bulklistadd) || !empty($bulklistremove)) {
         $this->bulklist_modify($bulklistadd, $bulklistremove);
         list($pageresults, $totalresults) = $this->bulklist_get_display(1);
         $response['bulklist_modify'] = array('result' => 'success', 'page_results_ids' => array_keys($pageresults), 'page_results_values' => array_values($pageresults), 'total_results' => $totalresults);
     }
     // Determine display fields - i.e. columns of the table.
     $columnlabels = $this->get_column_labels($filters);
     $sort = array_intersect_key($sort, $columnlabels);
     // Get results.
     list($pageresults, $totalresults) = $this->get_search_results($filters, $sort, $limitfrom, $limitnum);
     $disabledresults = $this->get_num_disabled_search_results();
     $response['datatable_results'] = array('result' => 'success', 'column_labels' => $columnlabels, 'results' => $pageresults, 'total_results' => $totalresults, 'usable_results' => $totalresults - $disabledresults);
     // Respond to js.
     echo safe_json_encode($response);
 }
Example #21
0
                        if (WAIT_AFTER_LOADING) {
                            sleep(WAIT_AFTER_LOADING);
                        }
                    }
                }
            }
            $mngr->saveHistory();
        }
        break;
}
if ($val === null) {
    $val = $mngr->get();
    $errorsReported = true;
}
if ($dataType == "text/xml") {
    cachedEcho('<?xml version="1.0" encoding="UTF-8"?><data><![CDATA[' . $val . ']]></data>', "text/xml", true, false);
} else {
    cachedEcho(safe_json_encode($val), $dataType, true, false);
}
ob_flush();
flush();
if (connection_aborted()) {
    if ($mngr->isErrorsOccured()) {
        $mngr->saveState(false);
    }
} else {
    if ($errorsReported && $mngr->hasErrors()) {
        $mngr->clearErrors();
        $mngr->saveState(false);
    }
}
Example #22
0
 public function get()
 {
     return "theWebUI.retrackers = " . safe_json_encode($this) . ";\n";
 }
Example #23
0
                            }
                        }
                        if (isset($torrent->{'rtorrent'})) {
                            unset($torrent->{'rtorrent'});
                        }
                        if (count($req->val) > 9) {
                            $throttle = getCmd("d.set_throttle_name=") . $req->val[9];
                        }
                        $eReq = new rXMLRPCRequest(new rXMLRPCCommand("d.erase", $hash));
                        if ($eReq->run() && !$eReq->fault) {
                            $label = rawurldecode($req->val[5]);
                            if (!rTorrent::sendTorrent($torrent, $isStart, false, $req->val[6], $label, false, $req->val[8] == 1, false, array(getCmd("d.set_custom3") . "=1", getCmd("d.set_connection_seed=") . $req->val[7], $throttle))) {
                                $errors[] = array('desc' => "theUILang.errorAddTorrent", 'prm' => $fname);
                            }
                        } else {
                            $errors[] = array('desc' => "theUILang.badLinkTorTorrent", 'prm' => '');
                        }
                    } else {
                        $errors[] = array('desc' => "theUILang.errorReadTorrent", 'prm' => $fname);
                    }
                } else {
                    $errors[] = array('desc' => "theUILang.cantFindTorrent", 'prm' => '');
                }
            } else {
                $errors[] = array('desc' => "theUILang.badLinkTorTorrent", 'prm' => '');
            }
        }
    }
}
cachedEcho(safe_json_encode(array("errors" => $errors, "hash" => $hashes)), "application/json");
Example #24
0
function loginStage1()
{
    global $cfg, $db;
    header('Expires: Mon, 9 Oct 2000 18:00:00 GMT');
    header('Cache-Control: no-store, no-cache, must-revalidate');
    $sid = cookie('netjukebox_sid');
    $username = post('username');
    $sign = post('sign');
    $query = mysql_query('SELECT seed FROM user WHERE username = "******"');
    $user = mysql_fetch_assoc($query);
    $query = mysql_query('SELECT ip, seed, sign FROM session WHERE sid = BINARY "' . mysql_real_escape_string($sid) . '"');
    $session = mysql_fetch_assoc($query);
    if ($session['ip'] == '') {
        message(__FILE__, __LINE__, 'error', '[b]Login failed[/b][br]netjukebox requires cookies to login.[br]Enable cookies in your browser and try again.[br][url=index.php][img]small_login.png[/img]login[/url]');
    }
    if ($session['ip'] != $_SERVER['REMOTE_ADDR']) {
        message(__FILE__, __LINE__, 'error', '[b]Login failed[/b][br]Unexpected IP address[br][url=index.php][img]small_login.png[/img]login[/url]');
    }
    if (hmacsha1($cfg['server_seed'], $session['sign']) == $sign) {
        $sign = randomKey();
        mysql_query('UPDATE session
			SET	sign		= "' . mysql_real_escape_string($sign) . '",
			pre_login_time	= ' . (string) round(microtime(true) * 1000) . '
			WHERE sid		= BINARY "' . mysql_real_escape_string($sid) . '"');
    } else {
        // login will fail!
        $sign = randomKey();
    }
    // Always calculate fake seed to prevent script execution time differences
    $fake_seed = substr(hmacsha1($cfg['server_seed'], $username . 'NeZlFgqDoh9hc-BkczryQFIcpoBng3I_vXaWtOKS'), 0, 30);
    $fake_seed .= substr(hmacsha1($cfg['server_seed'], $username . 'g-FE6H0MJ1n0lNo2D7XLachV8WE-xmEcwsXNZqlQ'), 0, 30);
    $fake_seed = base64_encode(pack('H*', $fake_seed));
    $fake_seed = str_replace('+', '-', $fake_seed);
    // modified Base64 for URL
    $fake_seed = str_replace('/', '_', $fake_seed);
    $data = array();
    $data['user_seed'] = $user['seed'] == '' ? $fake_seed : $user['seed'];
    $data['session_seed'] = $session['seed'];
    $data['sign'] = $sign;
    echo safe_json_encode($data);
}