Skip to content

Commit

Permalink
Objectify MythBackend, port everything over to it, some general clean…
Browse files Browse the repository at this point in the history
…up with unused functions, fix a small issue with the Video Class, and query the frontends on demand rather the every time. Add some caching to myht proto version and timezone checks.

git-svn-id: http://svn.mythtv.org/svn/trunk@19189 7dbf422c-18fa-0310-86e9-fd20926502f2
  • Loading branch information
kormoc committed Dec 1, 2008
1 parent e94b0a8 commit 391513e
Show file tree
Hide file tree
Showing 18 changed files with 346 additions and 477 deletions.
184 changes: 184 additions & 0 deletions classes/MythBackend.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
<?php
/**
*
* @url $URL: svn+ssh://svn.mythtv.org/var/lib/svn/trunk/mythplugins/mythweb/classes/MythFrontend.php $
* @date $Date: 2008-11-25 22:47:35 -0800 (Tue, 25 Nov 2008) $
* @version $Revision: 19160 $
* @author $Author: kormoc $
* @license GPL
*
* @package MythTV
*
/**/

class MythBackend {

// MYTH_PROTO_VERSION is defined in libmyth in mythtv/libs/libmyth/mythcontext.h
// and should be the current MythTV protocol version.
static $protocol_version = 42;

// The character string used by the backend to separate records
static $backend_separator = '[]:[]';

// NUMPROGRAMLINES is defined in mythtv/libs/libmythtv/programinfo.h and is
// the number of items in a ProgramInfo QStringList group used by
// ProgramInfo::ToSringList and ProgramInfo::FromStringList.
static $program_line_number = 47;

private $fp = null;
private $connected = false;
private $host = null;
private $port = null;

static function find($host = null, $port = 6543) {
static $Backends = array();

// Looking for the master backend?
if (is_null($host)) {
$host = setting('MasterServerIP');
$port = setting('MasterServerPort');
if (!$host || !$port)
trigger_error("MasterServerIP or MasterServerPort not found! You may"
."need to check your settings.php file or re-run mythtv-setup",
FATAL);
}

if (!isset($Backend[$host][$port]))
$Backend[$host][$port] = new MythBackend($host, $port);
return $Backend[$host][$port];
}

function __construct($host, $port) {
$this->host = $host;
$this->port = $port;
}

function __destruct() {
$this->disconnect();
}

private function connect() {
if ($this->connected)
return;
$this->fp = @fsockopen($this->host, $this->port, $errno, $errstr, 25);
if (!$this->fp)
custom_error("Unable to connect to the master backend at {$this->host}:{$this->port}.\nIs it running?");
$this->connected = true;
socket_set_timeout($this->fp, 20);
$this->checkProtocolVersion();
$this->announce();
}

private function disconnect() {
if (!$this->connected)
return;
$this->sendCommand('DONE');
fclose($this->fp);
$this->connected = false;
}

private function checkProtocolVersion() {
// Allow overriding this check
if ($_SERVER['ignore_proto'] == true )
return true;

if ($_SESSION['backend']['proto_version']['last_check_time'] - time() < 60*60*24)
return true;

$response = $this->sendCommand('MYTH_PROTO_VERSION '.MythBackend::$protocol_version);

if ($response == 'ACCEPT') {
$_SESSION['backend']['proto_version']['last_check_time'] = time();
return true;
}

if ($response == 'REJECT')
trigger_error("Incompatible protocol version (mythweb=" . MythBackend::$protocol_version . ", backend=" . $response . ")");
else
trigger_error("Unexpected response to MYTH_PROTO_VERSION '".MythBackend::$protocol_version."': ".$response);
return false;
}

private function announce() {
$response = $this->sendCommand('ANN Monitor '.hostname.' 0');
if ($response == 'OK')
return true;
return false;
}

public function setTimezone() {
if (!is_string($_SESSION['backend']['timezone']['value']) || $_SESSION['backend']['timezone']['last_check_time'] - time() > 60*60*24) {
$timezone = $this->sendCommand('QUERY_TIME_ZONE');
$timezone = str_replace(' ', '_', $timezone[0]);
$_SESSION['backend']['timezone']['value'] = $timezone;
$_SESSION['backend']['timezone']['last_check_time'] = time();
}

if (!@date_default_timezone_set($_SESSION['backend']['timezone']['value']))
trigger_error('Failed to set php timezone to '.$_SESSION['backend']['timezone']['value']);
}

public function sendCommand($command = null) {
$this->connect();
if (is_array($command))
$command = implode(MythBackend::$backend_separator, $command);
// The format should be <length + whitespace to 8 total bytes><data>
$command = strlen($command) . str_repeat(' ', 8 - strlen(strlen($command))) . $command;
fputs($this->fp, $command);

// Read the response header to find out how much data we'll be grabbing
$length = rtrim(fread($this->fp, 8));

// Read and return any data that was returned
$response = '';
while ($length > 0) {
$data = fread($this->fp, min(8192, $length));
if (strlen($data) < 1)
break; // EOF
$response .= $data;
$length -= strlen($data);
}
$response = explode(MythBackend::$backend_separator, $response);
if (count($response) == 1)
return $response[0];
if (count($response) == 0)
return false;
return $response;
}

public function queryProgramRows($query = null, $offset = 1) {
$records = $this->sendCommand($query);
// Parse the records, starting at the offset point
$row = 0;
$col = 0;
$count = count($records);
for($i = $offset; $i < $count; $i++) {
$rows[$row][$col] = $records[$i];
// Every $NUMPROGRAMLINES fields (0 through ($NUMPROGRAMLINES-1)) means
// a new row. Please note that this changes between myth versions
if ($col == (MythBackend::$program_line_number - 1)) {
$col = 0;
$row++;
}
// Otherwise, just increment the column
else
$col++;
}
// Lastly, grab the offset data (if there is any)
for ($i=0; $i < $offset; $i++) {
$rows['offset'][$i] = $recs[$i];
}
// Return the data
return $rows;
}

/**
* Tell the backend to reschedule a particular record entry. If the change
* isn't specific to a single record entry (e.g. channel or record type
* priorities), then use 0. I don't think mythweb should need it, but if you
* need to indicate every record rule is affected, then use -1.
/**/
public function rescheduleRecording($recordid = -1) {
$this->sendCommand('RESCHEDULE_RECORDINGS '.$recordid);
}
}
21 changes: 12 additions & 9 deletions classes/MythFrontend.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,19 +45,22 @@ public function __construct($host, $port) {
public static function findFrontends() {
global $db;
$frontends = array();
$frontends_sh = $db->query('SELECT DISTINCT settings.hostname,
settings.data
FROM settings
WHERE settings.hostname IS NOT NULL
AND settings.value = "NetworkControlPort"
AND settings.data > 0');
while ( $row = $frontends_sh->fetch_row()) {
list($host, $port) = $row;
$frontends_sh = $db->query('SELECT DISTINCT settings.hostname
FROM settings
WHERE settings.hostname IS NOT NULL
AND settings.value = "NetworkControlEnabled"
AND settings.data = 1');
while ( $host = $frontends_sh->fetch_col()) {

// Remove some characters that should never be here, anyway, and might
// confuse javascript/html
$host = preg_replace('/["\']+/', '', $host);

$port = setting('NetworkControlPort', $host);
$frontend = new MythFrontend($host, $port);
$frontend->connect(2);
if ($frontend->query_location() == 'OFFLINE')
continue;
$frontend->disconnect();
$frontends[$host] = $frontend;
}
return $frontends;
Expand Down
23 changes: 11 additions & 12 deletions classes/Video.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ class Video {
var $filename;
var $cover_file;
var $cover_url;
var $cover_scaled_width;
var $cover_scaled_height;
var $cover_scaled_width = video_img_width;
var $cover_scaled_height = video_img_height;
var $childid;
var $url;
var $browse;
Expand Down Expand Up @@ -52,17 +52,16 @@ function __construct($intid) {
// And the artwork URL
if ($this->cover_file != 'No Cover' && file_exists($this->cover_file) ) {
$this->cover_url = 'data/video_covers/'.substr($this->cover_file, strlen(setting('VideoArtworkDir', hostname)));
list($width, $height) = getimagesize($this->cover_file);
$wscale = video_img_width / $width;
$hscale = video_img_height / $height;
$scale = $wscale < $hscale ? $wscale : $hscale;
$this->cover_scaled_width = floor($width * $scale);
$this->cover_scaled_height = floor($height * $scale);
}
else {
$this->cover_scaled_height = video_img_height;
$this->cover_scaled_width = video_img_width;
list($width, $height) = @getimagesize($this->cover_file);
if ($width > 0 && $height > 0) {
$wscale = video_img_width / $width;
$hscale = video_img_height / $height;
$scale = $wscale < $hscale ? $wscale : $hscale;
$this->cover_scaled_width = floor($width * $scale);
$this->cover_scaled_height = floor($height * $scale);
}
}

$this->childid = $video['childid'];
// Figure out the URL
$this->url = '#';
Expand Down
35 changes: 35 additions & 0 deletions includes/cleanup.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,46 @@
// Clean the document root variable and make sure it doesn't have a trailing slash
$_SERVER['DOCUMENT_ROOT'] = preg_replace('/\/+$/', '', $_SERVER['DOCUMENT_ROOT']);

/**
* Recursively fixes silly \r\n stuff that some browsers send.
* Also adds a generic entry for fiends ending in _x or _y to better deal
* with image inputs.
/**/
function &fix_crlfxy(&$array) {
foreach ($array as $key => $val) {
if (is_array($val))
fix_crlfxy($array[$key]);
elseif (is_string($val)) {
$array[$key] = str_replace("\r\n", "\n", $val);
// Process any imagemap submissions to make sure we also get the name itself
if ($key != ($new_key = preg_replace('/_[xy]$/', '', $key))) {
if (!array_key_exists($new_key, $array))
$array[$new_key] = true;
}
}
}
return $array;
}

// Clean up input data
fix_crlfxy($_GET);
fix_crlfxy($_POST);
fix_crlfxy($_REQUEST);
if (get_magic_quotes_gpc()) {

/**
* Recursively strip slashes from an array (eg. $_GET).
/**/
function &fix_magic_quotes(&$array) {
foreach ($array as $key => $val) {
if (is_array($val))
fix_magic_quotes($array[$key]);
else
$array[$key] = stripslashes($val);
}
return $array;
}

fix_magic_quotes($_COOKIE);
fix_magic_quotes($_ENV);
fix_magic_quotes($_GET);
Expand Down
6 changes: 3 additions & 3 deletions includes/init.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,6 @@
require_once 'includes/css.php';
require_once 'includes/mouseovers.php';

// Connect to the backend and load some more handy utilities
require_once 'includes/mythbackend.php';

// Detect mobile users
require_once 'includes/mobile.php';

Expand All @@ -70,3 +67,6 @@

// Load the session defaults and other config info
require_once 'includes/config.php';

// And do some quick setup...
MythBackend::find()->setTimezone();
Loading

0 comments on commit 391513e

Please sign in to comment.