Example #1
0
<?php

/**
 * Sample file for the boxcar php provider client
 * 
 * @author Russell Smith <*****@*****.**>
 * @copyright UKD1 Limited 2010
 * @license licence.txt ISC license
 * @see https://github.com/ukd1/Boxcar
 */
define('API_KEY', 'key');
define('API_SEC', 'secret');
define('YOUR_EMAIL', 'your email');
if (!function_exists('curl_init')) {
    trigger_error('CURL must be enabled for boxcar_api to function', E_USER_ERROR);
}
// load the api class
require_once 'boxcar_api.php';
// this is needed to stop warnings when using the date functions
date_default_timezone_set('Europe/London');
// instantiate a new instance of the boxcar api
$b = new boxcar_api(API_KEY, API_SEC, 'http://store.ukd1.co.uk.s3.amazonaws.com/ukd1_small.png');
// send a broadcast (to all your subscribers)
$b->broadcast('Test Name', 'Test Broadcast, this was sent at ' . date('r'));
// send a message to a specific user, with an ID of 999
$b->notify(YOUR_EMAIL, 'Test name', 'Hey ' . YOUR_EMAIL . ' this was sent at ' . date('r'), 999);
// you can also do with a default icon
boxcar_api::factory(API_KEY, API_SEC, 'http://store.ukd1.co.uk.s3.amazonaws.com/ukd1_small.png')->broadcast('Test broadcast', 'Another test broadcast with icon');
Example #2
0
<?php

include "config.php";
include "lib/functions.php";
require_once 'lib/boxcar/boxcar_api.php';
mysql_connect($host, $user, $pass) or die(mysql_error());
mysql_select_db($table) or die(mysql_error());
$config = getsettings();
$boxemail = $config['boxemail']['config'];
if (!function_exists('curl_init')) {
    trigger_error('CURL must be enabled for boxcar_api to function', E_USER_ERROR);
}
$b = new boxcar_api($boxcarapi, $boxcarsec);
$emails = explode(",", $boxemail);
foreach ($emails as $boxalert) {
    try {
        $b->notify($boxalert, 'SUCCES', 'Your first notification for SSMS, you are a champ!');
    } catch (Exception $e) {
        echo "Seems that something went wrong, did you type in the correct email? And did you also subscribed to the SSMS feed in boxcar?";
        echo "Double check that, you will be send back to the config page in 10 seconds. Otherwise just press the back button.";
        echo '<meta http-equiv="refresh" content="10; URL=ssmsconfig.php">';
        echo $e;
        die;
    }
}
?>
<meta http-equiv="refresh" content="0; URL=ssmsconfig.php">

Example #3
0
function renewserver($server, $cmd = false)
{
    $settings = getsettings();
    if ($settings['usegrowl']['config'] == 'yes') {
        require_once 'lib/growl/class.growl.php';
        $growlip = $settings['growlip']['config'];
        $growlpass = $settings['growlpass']['config'];
    }
    if ($settings['usetwitter']['config'] == 'yes') {
        require_once 'lib/twitter/twitter.php';
        $consumerkey = $settings['consumerkey']['config'];
        $consumersecret = $settings['consumersecret']['config'];
        $OAuthToken = $settings['OAuthToken']['config'];
        $OAuthTokenSecret = $settings['OAuthTokenSecret']['config'];
        $twitter = new Twitter("{$consumerkey}", "{$consumersecret}");
        $twitter->setOAuthToken("{$OAuthToken}");
        $twitter->setOAuthTokenSecret("{$OAuthTokenSecret}");
    }
    if ($settings['useboxcar']['config'] == 'yes') {
        require_once 'lib/boxcar/boxcar_api.php';
        $boxemail = $settings['boxemail']['config'];
    }
    $gametypes = gametypes();
    if ($server == "all") {
        $server = '%';
    }
    //if (!$cmd == 'true') { $game = $_GET[ 'game' ];}
    //else { $game = '%'; }
    $fails = array();
    $result = mysql_query_trace("SELECT * from servers where serverid like '{$server}' and type like '" . $_GET['game'] . "'") or die(mysql_error());
    while ($row = mysql_fetch_array($result)) {
        foreach ($row as $key => $value) {
            ${$key} = $value;
        }
        $info = "";
        $serverIP = $ip;
        $server = new SourceServer($serverIP, $port);
        try {
            $info = $server->getServerInfo();
            $rules = $server->getRules();
            print $rules['sv_registration_succesful'];
        } catch (Exception $e) {
            // $fails[] = $serverid;
            // no longer needed, since we just want it to continue
        }
        if ($info && $info['serverName']) {
            $network = $info['networkVersion'];
            $version = $info['gameVersion'];
            $servername = trim($info['serverName']);
            $type = $info['gameDir'];
            $os = $info['operatingSystem'];
            $map = $info['mapName'];
            $pwpro = $info['passwordProtected'];
            $nplayers = $info['numberOfPlayers'];
            $mplayers = $info['maxPlayers'];
            $bots = $info['botNumber'];
            $protected = $info['passwordProtected'];
            $servertags = $info['serverTags'];
            if ($replaymatch == "yes") {
                try {
                    $server->rconAuth($rconpass);
                    $matchid = $server->rconExec('steamworks_sessionid_server');
                } catch (Exception $e) {
                    echo $e;
                }
                $pattern = '([0-9][0-9][0-9]+)';
                preg_match($pattern, $matchid, $matches);
                if ($matches[0]) {
                    mysql_query_trace("INSERT INTO matchids ( serverid, mapname, sessionid ) VALUES( '{$serverid}','{$map}','{$matches['0']}' )");
                }
            }
            if ($retries > "9") {
                if ($settings['useemail']['config'] == 'yes') {
                    $subject = "{$servername} seems to be back up after it was down for {$retries}, which is in minutes";
                    $message = "Like the topic says, {$servername} seems to be back up after it was down for {$retries}";
                    $smtpmails = $settings['emailalert']['config'];
                    $allmails = explode(",", $smtpmails);
                    foreach ($allmails as $sendto) {
                        mail($sendto, $subject, $message, null);
                    }
                }
                if ($settings['usegrowl']['config'] == 'yes') {
                    $growl = new Growl();
                    //$growl->setAddress($growlip, $growlpass);
                    $connection = array('address' => '$growlip', 'password' => '$growlpass');
                    $growl->notify($connection, "{$type}", "RESTORED: {$servername}", "Instance {$servername} was down for {$retries} minutes. It is now back up again");
                }
                if ($settings['usetwitter']['config'] == 'yes') {
                    try {
                        $twitter->statusesUpdate("RESTORED: {$servername}. It was down for {$retries} minutes.");
                    } catch (Exception $e) {
                        echo $e;
                    }
                }
                if ($settings['useboxcar']['config'] == 'yes') {
                    include "config.php";
                    $b = new boxcar_api($boxcarapi, $boxcarsec);
                    $emails = explode(",", $boxemail);
                    foreach ($emails as $boxalert) {
                        try {
                            $b->notify($boxalert, 'RESTORED', 'Instance ' . $servername . ' was down for ' . $retries . ' minutes. It is now back up again');
                        } catch (Exception $e) {
                            echo $e;
                        }
                    }
                }
            }
            // since we are in this loop the server has been reached so we can reset retry's back to 0.
            $retries = "0";
            //store match ID
            if ($gametypes[$type]['expired'] == "yes") {
                if (version_compare($version, $gametypes[$type]['version'], '>')) {
                    // if something was expired, check to see if a server has a newer version. If yes update version in games db and set expired to no.
                    mysql_query_trace("UPDATE games SET version='{$version}', expired='no' WHERE shortname='{$type}'");
                    // reset so it wont go restart if valve has the coffee break.
                    $gametypes[$type]['expired'] = "no";
                }
                if (version_compare($version, $gametypes[$type]['version'], '=')) {
                    // if for some reason the gametype was changed but not the version then get out of that loop (rare condition, still on yes but already updated to both new version)
                    echo "test";
                }
            }
            if ($restartsend == 'yes' || $restartsend == 'restart' || $restartsend == 'optional') {
                // this is set after a _restart, so if we see it , then server is restarted and need to set restartsend=no.
                if ($goingdown == 'no') {
                    mysql_query_trace("UPDATE servers SET restartsend='no' WHERE serverid = '{$serverid}'");
                } else {
                    if ($type == "left4dead" || $type == "left4dead2") {
                        // hate to do this part, but if the last 'fork' is restarted, it can all be up within a minute. So the fork responded normally
                        // while all the other ones get caught in the 'else' routine below if the servers does not respond, setting the flag that its part of a forked stop.
                        $server->rconAuth($rconpass);
                        $uptime = $server->rconExec('stats');
                        $pieces = explode("\n", $uptime);
                        $pieces[1] = trim($pieces[1]);
                        $morepieces = preg_split('/[\\s]+/', $pieces[1]);
                        $uptime = $morepieces[3];
                        echo "Hey we zijn er";
                        echo "uptime is {$uptime}";
                        // can be buggy too, if you shutdown it quickly again and then servers are still full, it would make them optional again and send them into download state
                        // need a better way for this.
                        if ($uptime < "2") {
                            // if its up this short it restarted shortly ago, so reset it for this one.
                            echo "Resetting all forks to normal since 1 servers has low uptime";
                            mysql_query_trace("UPDATE servers SET restartsend='no',goingdown='no' WHERE netconport = '{$netconport}'");
                        }
                    }
                    if ($restartsend == 'restart') {
                        mysql_query_trace("UPDATE servers SET restartsend='no' WHERE serverid = '{$serverid}'");
                    }
                }
            }
            if ($autoupdate == 'yes' || $dlyrestart == 'yes') {
                if ($restartsend == 'update') {
                    if (!$netconport) {
                        // if restartsend is 'update' or that means something triggered it, meaning a _restart will be send
                        try {
                            // choose which command to run, was it a optional/normal update or a daily restart that triggered the update?
                            $server->rconAuth($rconpass);
                            if ($cmdtosend == "daily") {
                                $server->rconExec("{$dlycmd}");
                            } elseif ($cmdtosend == "normal") {
                                // replace _restart by config for restart command.
                                $server->rconExec('_restart');
                            }
                            // restarten bug?
                        } catch (RCONNoAuthException $e) {
                            trigger_error('Could not authenticate with the game server.', E_USER_ERROR);
                        } catch (TimeoutException $e) {
                        } catch (Exception $e) {
                        }
                        // trigger the optional restarts to show as normal restarts instead of downloading.
                        if ($goingdown == "yes") {
                            // do the update here, since after a _restart it throws a exception and wont update the DB otherwise.
                            mysql_query_trace("UPDATE servers SET restartsend='restart',goingdown='no',cmdtosend='normal' WHERE serverid = '{$serverid}'");
                        } else {
                            mysql_query_trace("UPDATE servers SET restartsend='yes',cmdtosend='normal' WHERE serverid = '{$serverid}'");
                        }
                        next;
                    } else {
                        if (!$netforkrestart[$netconport] == "yes") {
                            $timeout = '2';
                            $usenet = fsockopen($ip, $netconport, $errno, $errstr, $timeout);
                            if (!$usenet) {
                                // to make sure they dont stay in "update" state, or we get 2x a restart of netcon!
                                // pretty pointless in the end, since netcon port is down = all is down.
                                // mysql_query_trace("UPDATE servers SET restartsend='optional' WHERE netconport = '$netconport'");
                                next;
                            } else {
                                $netconding = $settings['netconrestart']['config'];
                                fputs($usenet, "PASS {$netconpasswd}\r\n");
                                fputs($usenet, "{$netconding}\r\n");
                                mysql_query_trace("UPDATE servers SET restartsend='yes',goingdown='yes' WHERE netconport = '{$netconport}'");
                                $netforkrestart[$netconport] = "yes";
                            }
                        }
                    }
                }
                // we got 3 routines down here
                // 1. expired = yes, this to 'issue' the first signal if a update came out so it goes into 'update' fase.
                //  and version < version in the db, this to update any servers that came up later.
                // 2. reset the expired = no for the gametype if the version of the server is HIGHER then the one in the db.
                // Routine 2 is needed also to reset the version number to the correct one for gametypes that do not require auto update.
                // extra part is done for netcon ports for l4d(2) to only issue 1 command which is shutdown or quit for ALL instances.
                // 3. is for daily restarts, also we need to have a "optional" restart, meaning it will restart when the server is empty or less then xx players
                if ($gametypes[$type]['expired'] == "yes" || version_compare($version, $gametypes[$type]['version'], '<')) {
                    // if a server is already updated and THEN the update comes out then it would still update it again, check for this
                    if (version_compare($version, $gametypes[$type]['version'], '=')) {
                        next;
                    }
                    if (!$netconport) {
                        try {
                            $server->rconAuth($rconpass);
                            $server->rconExec($settings['defaultannounce']['config']);
                            echo 'fout update kwam uit';
                            mysql_query_trace("UPDATE servers SET restartsend='update' WHERE serverid = '{$serverid}' AND autoupdate = 'yes'");
                        } catch (RCONNoAuthException $e) {
                            //trigger_error('Could not authenticate with the game server.',E_USER_ERROR);
                            echo 'error kan niet rconnen boeien, verder gaan';
                        } catch (Exception $e) {
                        }
                    } else {
                        // we have found a gametype l4d(2) which uses forks. Use the netcon port
                        if (!$netforkupdate[$netconport] == "yes") {
                            $timeout = '2';
                            $usenet = fsockopen($ip, $port, $errno, $errstr, $timeout);
                            if (!$usenet) {
                                next;
                            } else {
                                $announcing = $settings['defaultannounce']['config'];
                                fputs($usenet, "PASS {$netconpasswd}\r\n");
                                fputs($usenet, "{$announcing}\r\n");
                                mysql_query_trace("UPDATE servers SET restartsend='update' WHERE serverid = '{$serverid}'");
                                $netforkupdate[$neGotconport] = "yes";
                            }
                        } else {
                            // since a broadcast is send, all the other nodes dont need to have this send out again.
                            mysql_query_trace("UPDATE servers SET restartsend='update' WHERE serverid = '{$serverid}'");
                        }
                    }
                }
            }
            if ($dlyrestart == "yes" || $restartsend == "optional" || $restartsend == "emptyserver") {
                // the daily restart part, or the optional part. First get the time as we want it.
                $playercount = $nplayers - $bots;
                //echo "dus $playercount zoveel players \n"; (debug stuff)
                $hhmm = date('H:i', strtotime($dlytime));
                $currenthhmm = date('H:i');
                if ($hhmm == $currenthhmm) {
                    //	try {
                    //		$server->rconAuth($rconpass);
                    //		$server->rconExec($dlycmd);
                    //	} catch(Exception $e) {}
                    mysql_query_trace("UPDATE servers SET restartsend='optional',goingdown='yes' WHERE serverid = '{$serverid}'");
                }
                if ($restartsend == "optional" && $goingdown == "yes") {
                    // check number of players online, if less it meets min players then go
                    if ($playercount <= $dlyusers || ($dlyusers = "NULL")) {
                        echo "ja dat klopt, we zitten onder de 10";
                        // add new field in db, to say it was a daily
                        // add this part to not make l4d2 forks in update mode.
                        //if ($goingdown != 'yes' ) {
                        echo "set update en daily\n";
                        if (!$netconport) {
                            mysql_query_trace("UPDATE servers SET restartsend='update', cmdtosend='daily' WHERE serverid = '{$serverid}'");
                        }
                        //}
                    }
                }
                if ($restartsend == "emptyserver") {
                    // check number of players online, if less it meets min players then go
                    if ($playercount == '0') {
                        echo "ja dat klopt, we zitten onder de 10";
                        // add new field in db, to say it was a daily
                        mysql_query_trace("UPDATE servers SET restartsend='update', cmdtosend='normal' WHERE serverid = '{$serverid}'");
                    }
                }
            }
            // we are going to check for the daily time
            mysql_query_trace("UPDATE servers SET servername = '{$servername}', type = '{$type}', version = '{$version}', network = '{$network}', os = '{$os}', lastupdate = NOW(), currentmap = '{$map}', currentplayers = '{$nplayers}', maxplayers = '{$mplayers}', retries = '{$retries}', currentbots = '{$bots}', protected = '{$protected}', servertags = '{$servertags}' WHERE serverid = '{$serverid}'");
        } else {
            if ($goingdown == 'yes' && $restartsend != 'emptyserver') {
                mysql_query_trace("UPDATE servers SET restartsend='optional',goingdown='no' WHERE serverid = '{$serverid}'");
            }
            if ($restartsend == 'no') {
                $fails[] = $serverid;
                if ($retries == "10") {
                    if ($settings['useemail']['config'] == 'yes') {
                        $subject = "{$servername} seems to be down after 10 retries";
                        $message = "Like the topic says, {$servername} @ {$serverIP} seems to be down for 10 retries so thats 10 minutes\n Last map it was on: {$currentmap}";
                        $smtpmails = $settings['emailalert']['config'];
                        $allmails = explode(",", $smtpmails);
                        foreach ($allmails as $sendto) {
                            mail($sendto, $subject, $message, null);
                        }
                    }
                    if ($settings['usegrowl']['config'] == 'yes') {
                        $growl = new Growl();
                        //$growl->setAddress($growlip, $growlpass);
                        $connection = array('address' => '$growlip', 'password' => '$growlpass');
                        $growl->notify($connection, "{$type}", "DOWN: {$servername}", "Instance {$servername} is down for {$retries} minutes. Please check");
                    }
                    if ($settings['usetwitter']['config'] == 'yes') {
                        try {
                            $twitter->statusesUpdate("DOWN: {$servername}. It has been down for 10 minutes");
                        } catch (Exception $e) {
                            echo $e;
                        }
                    }
                    if ($settings['useboxcar']['config'] == 'yes') {
                        include "config.php";
                        $b = new boxcar_api($boxcarapi, $boxcarsec);
                        $emails = explode(",", $boxemail);
                        foreach ($emails as $boxalert) {
                            try {
                                $b->notify($boxalert, 'DOWN', 'Instance ' . $servername . ' is down for ' . $retries . ' minutes');
                            } catch (Exception $e) {
                                echo $e;
                            }
                        }
                    }
                }
                if (!$_GET['update'] == 'all') {
                    mysql_query_trace("UPDATE servers SET retries=retries+1  WHERE serverid = '{$serverid}'");
                }
                // so that web updates for all dont screw up the retry count. Assuming people run the php in cron.
            }
        }
    }
    if ($cmd) {
        //echo $servername;
        die;
        // commandline, no need for fancy stuff
    } else {
        echo "<script type=\"text/javascript\">\n\t\t\t\nwindow.onload = function() { ";
        if (mysql_num_rows($result) == 1) {
            if (count($fails)) {
                echo "alert( 'Updating failed, perhaps its a solar flare?\\n" . mysql_real_escape_string(mysql_error()) . "' );";
            } else {
                echo "alert( 'Server \\'" . mysql_real_escape_string($servername) . "\\' was updated succesfully.' );";
            }
        } else {
            echo "alert( 'All servers" . (!empty($fails) ? ' but ID ' . implode($fails, ', ') : '') . " were updated succesfully.' );";
        }
        //echo "<p>All servers" . ( !empty( $fails ) ? " but ID " . implode( $fails, ', ' ) : '' ) . " were updated succesfully.</p>";
        //echo "<p>
        echo "\n}\n\n\t\t\t</script>";
    }
}