function tweet($msg, $user)
 {
     global $IP;
     // set up the API and post the message
     $dbr = wfGetDB(DB_SLAVE);
     $account = $dbr->selectRow('twitterfeedusers', array('*'), array('tfu_user' => $user->getID()));
     $callback = $wgServer . '/Special:TwitterAccounts/' . urlencode($user->getName());
     require_once "{$IP}/extensions/wikihow/common/twitterapi.php";
     $twitter = new Twitter(WH_TWITTER_CONSUMER_KEY, WH_TWITTER_CONSUMER_SEC);
     $twitter->setOAuthToken($account->tfu_token);
     $twitter->setOAuthTokenSecret($account->tfu_secret);
     $result = $twitter->statusesUpdate($msg);
     $dbw = wfGetDB(DB_MASTER);
     $dbw->insert('twitterfeedlog', array('tfl_user' => $user->getID(), 'tfl_user_text' => $user->getName(), 'tfl_message' => $msg, 'tfl_timestamp' => wfTimestampNow()));
 }
Beispiel #2
0
 public function activityUpdatesBySubject($dryrun = false)
 {
     echo "<h3>Running Activity Tweet Update</h3><i>Date Started: " . date('r') . "</i>" . BR . BR;
     if ($dryrun == "true") {
         echo "<pre>RUNNING IN DRY-RUN MODE - NO ACTUAL TWEETS WILL BE SENT!!! Remove /true in the URL to run properly!</pre>";
     }
     // Setup our API access
     $this->load->library('twitter');
     $twitter = new Twitter(array('consumerKey' => $this->consumer_key, 'consumerSecret' => $this->consumer_secret));
     $twitter->setOAuthToken($this->oauth_access_token);
     $twitter->setOAuthTokenSecret($this->oauth_access_secret);
     // Go and get our activity information
     $service_url = registry_url('services/rda/getLatestActivityBySubject/' . $this->num_days_history);
     $data = @json_decode(@file_get_contents($service_url), true);
     if (!isset($data['results']) || count($data['results']) == 0) {
         echo "No activity information to be displayed. No updates matched the query at " . $service_url;
         return;
     } else {
         echo "<h4>Found " . count($data['results']) . " updates for the past " . $this->num_days_history . " days...</h4>";
         // Reverse the sort order so largest update counts come last (i.e. highest on the Twitter feed)
         krsort($data['results']);
         foreach ($data['results'] as $idx => $update) {
             try {
                 // Format our tweet message
                 $tweet = sprintf("%d %s added with the subject '%s' #ANZSRC%s", $update['num_records'], pluralise("collection", $update['num_records']), ellipsis($update['value']), $update['notation']);
                 echo "Sending Tweet: <i>" . $tweet . "</i>...";
                 flush();
                 if (!$dryrun) {
                     $twitter->statusesUpdate($tweet);
                     echo "sent " . BR;
                     flush();
                 }
                 sleep(0.5);
                 // Pause between big chunks of tweets
                 if ($idx % 5 == 0) {
                     sleep(5);
                 }
             } catch (TwitterException $e) {
                 echo BR . BR . "Unable to send Tweet to Twitter API: " . $e->getMessage() . BR . BR;
             } catch (Exception $e) {
                 echo BR . BR . "Unknown Exception: " . $e->getMessage() . BR . BR;
             }
         }
     }
     return;
 }
Beispiel #3
0
<?php

// Assign these variables.
$consumerKey = '';
$consumerSecret = '';
$OAuthToken = '';
$OAuthTokenSecret = '';
$twitterOwner = '';
// Your username to receive DM notices.
define('SAFE', TRUE);
include 'lib.twitter.php';
$t = new Twitter($consumerKey, $consumerSecret);
$t->setOAuthToken($OAuthToken);
$t->setOAuthTokenSecret($OAuthTokenSecret);
$tags = '#anime #torrent';
$series = array(array('name' => 'Naruto: Shippuden', 'tags' => '#Taka', 'prefix' => '[Taka]_Naruto_Shippuuden_', 'feed' => 'http://www.nyaa.eu/?page=rss&term=naruto+shippuuden+taka+720p&filter=2'), array('name' => 'Bleach', 'tags' => '#HorribleSubs', 'prefix' => '[HorribleSubs] Bleach - ', 'feed' => 'http://www.nyaa.eu/?page=rss&term=bleach+720p&filter=2'), array('name' => 'Gintama', 'tags' => '#HorribleSubs #MKV', 'prefix' => '[HorribleSubs] Gintama - ', 'feed' => 'http://www.nyaa.eu/?page=rss&term=Gintama+720p+HorribleSubs&filter=2'), array('name' => 'Gosick', 'tags' => '#HatsuyukiTsuki #MKV', 'prefix' => '[Hatsuyuki-Tsuki]_Gosick_-_', 'feed' => 'http://www.nyaa.eu/?page=rss&term=Gosick+Hatsuyuki-Tsuki+720&filter=2'));
header('Content-Type: text/plain');
$new = 0;
foreach ($series as $anime) {
    $feed = file_get_contents($anime['feed']);
    if (!$feed) {
        continue;
    }
    $feed = simplexml_load_string($feed);
    $seriesTweeted = false;
    foreach ($feed->channel->item as $release) {
        if (substr($release->title, 0, strlen($anime['prefix'])) == $anime['prefix']) {
            $episode = substr($release->title, strlen($anime['prefix']));
            @preg_match('/[0-9]{1,4}/', $episode, $episode);
            if (!isset($episode[0]) || !strlen($episode[0])) {
                continue;
Beispiel #4
0
function wfNotifyTwitter($cat, $t)
{
    global $wgUser, $IP;
    if (!$cat) {
        return true;
    }
    try {
        $dbr = wfGetDB(DB_SLAVE);
        // special case for rising star
        $account = $dbr->selectRow(array('twitterfeedaccounts', 'twitterfeedcatgories'), array('*'), array('tfc_username=tws_username', 'tfc_category' => $cat->getDBkey()));
        // anything to check?
        if (!$account) {
            return true;
        }
        $msg = TwitterAccounts::getUpdateMessage($t);
        // did we already do this?
        $count = $dbr->selectField('twitterfeedlog', '*', array('tfl_user' => $wgUser->getID(), 'tfl_message' => $msg, 'tfl_twitteraccount' => $account->tws_username));
        if ($count > 0) {
            return true;
        }
        // set up the API and post the message
        $callback = $wgServer . '/Special:TwitterAccounts/' . urlencode($account->tws_username);
        require_once "{$IP}/extensions/wikihow/common/twitterapi.php";
        $twitter = new Twitter(WH_TWITTER_CONSUMER_KEY, WH_TWITTER_CONSUMER_SEC);
        $twitter->setOAuthToken($account->tws_token);
        $twitter->setOAuthTokenSecret($account->tws_secret);
        #print_r($twitter); print_r($account);  exit;
        $result = $twitter->statusesUpdate($msg);
        #print_r($result); echo $msg; exit;
        // log it so we have a paper trail
        $dbw = wfGetDB(DB_MASTER);
        $dbw->insert('twitterfeedlog', array('tfl_user' => $wgUser->getID(), 'tfl_user_text' => $wgUser->getName(), 'tfl_message' => $msg, 'tfl_twitteraccount' => $account->tws_username, 'tfl_timestamp' => wfTimestampNow()));
    } catch (Exception $e) {
        #print_r($e); exit;
    }
    return true;
}
Beispiel #5
0
/* 
APPLICATION LEVEL DETAILS
Create new Twitter class instance with our 'consumer key' and 'consumer secret'
Find this on your Twitter app page. Example: http://screencast.com/t/a5s93L91V
*/
$twitter = new Twitter('2jSDrs6wyzxVyPKn4ex3LQ', 'vVXyzrcwPFDAQ8fxrgjgfkZ274QejvadOHKUp3MyNS0');
/*
USER LEVEL DETAILS
Uncomment the first chunk below ("GET TOKEN / SECRET") to find out this information
*/
$token = "252211321-1twXTQ78LW0WmynHQQN50WTP9yecDyixSWlm1N3v";
$secret = "V7vQD4X873ELJP2Oeje9fbCcB71jTPtY7m6jtJhg";
//$userId     = "252211321";
//$screenName = "upennClassDemo";
$twitter->setOAuthToken($token);
$twitter->setOAuthTokenSecret($secret);
?>

<br/><br/>
<a href='/classes/viewSource/?path=<?php 
echo $_SERVER['PHP_SELF'];
?>
' target='_blank'>View Source</a><br/><br/><br/>
<a href='http://classes.verkoyen.eu/modules/twitter_oauth/files/php_twitter_2_0_3.zip'>Download twitter.php (wrapper library)</a><br/><br/>

<?php 
/*-------------------------------------------------------------------------------------------------
GET USER TIMELINE
-------------------------------------------------------------------------------------------------*/
echo "<h2>User Timeline (upennClassDemos)</h2>";
$userTimeline = $twitter->statusesUserTimeline();
Beispiel #6
0
            $w3 = array();
            $w3["question"] = $frageid;
            $w3["tag"] = $a;
            $db->CreateUpdate(0, "question_tags", $w3);
        }
        $_SESSION["myuser"]["lastwritten"]["question"][$frageid] = true;
        Karma::RuleAction("CREATE_QUESTION", array("user" => MyUser::id(), "question" => $frageid));
        Badges::add(3, MyUser::id(), array("question" => $frageid));
        //Erste Frage geschrieben
        @file_get_contents("www.google.com/webmasters/tools/ping?sitemap=" . urlencode(SiteConfig::val("baseurl") . "sitemap.xml"));
        $m = SiteConfig::get(0);
        if ($m["twitter"]["consumer"]["secret"] . "" != "" && $m["twitter"]["access"]["secret"] . "" != "") {
            try {
                $twitter = new Twitter($m["twitter"]["consumer"]["key"], $m["twitter"]["consumer"]["secret"]);
                $twitter->setOAuthToken($m["twitter"]["access"]["key"]);
                $twitter->setOAuthTokenSecret($m["twitter"]["access"]["secret"]);
                $url = API_urlshortener::add(Question::PermalinkByData($w3["question"], $w["title"]));
                if (strlen($w["title"]) > 100) {
                    $tweet = substr($w["title"], 0, 100) . "... " . $url . " #wikihelp";
                } else {
                    $tweet = substr($w["title"], 0, 100) . " " . $url . " #wikihelp";
                }
                $twitter->statusesUpdate($tweet);
            } catch (Exception $ex) {
            }
        }
        header("Location: " . Question::PermalinkByData($frageid));
    }
}
function tags2array($text)
{
Beispiel #7
0
 function _send($token, $secret, $row)
 {
     require_lang('twitter');
     require_code('twitter');
     list($message) = render_activity($row, false);
     $link = static_evaluate_tempcode(pagelink_to_tempcode($row['a_pagelink_1']));
     // Shorten message for Twitter purposes
     $chopped_message = html_entity_decode(strip_tags($message->evaluate()), ENT_COMPAT, get_charset());
     $max_length = 255;
     $shortened_link = mixed();
     if ($link != '') {
         $shortened_link = http_download_file('http://is.gd/api.php?longurl=' . urlencode($link));
         $max_length -= strlen($shortened_link) + 1;
     }
     if (strlen($chopped_message) > $max_length) {
         $chopped_message = substr($chopped_message, 0, $max_length - 3) . '...';
     }
     if ($link != '') {
         $chopped_message .= ' ' . $shortened_link;
     }
     require_code('character_sets');
     $chopped_message = convert_to_internal_encoding($chopped_message, get_charset(), 'utf-8');
     require_code('developer_tools');
     destrictify();
     // Initiate Twitter connection
     $api_key = get_option('twitter_api_key');
     $api_secret = get_option('twitter_api_secret');
     $twitter = new Twitter($api_key, $api_secret);
     $twitter->setOAuthToken($token);
     $twitter->setOAuthTokenSecret($secret);
     // Send message
     try {
         $twitter->statusesUpdate($chopped_message);
     } catch (TwitterException $e) {
         attach_message($e->getMessage(), 'warn');
         return false;
     }
     return true;
 }
Beispiel #8
0
 public function getCallback()
 {
     $token = Input::get('oauth_token');
     $verifier = Input::get('oauth_verifier');
     $accessToken = Twitter::oAuthAccessToken($token, $verifier);
     if (isset($accessToken['user_id'])) {
         $user_id = $accessToken['user_id'];
         $user = User::find($user_id);
         if (empty($user)) {
             $user = new User();
             $user->id = $user_id;
         }
         Twitter::setOAuthToken($accessToken['oauth_token']);
         Twitter::setOAuthTokenSecret($accessToken['oauth_token_secret']);
         $timeline = Twitter::statusesUserTimeline($user->id);
         $user->screen_name = $accessToken['screen_name'];
         $user->profile_image_url = $timeline[0]['user']['profile_image_url'];
         $user->oauth_token = $accessToken['oauth_token'];
         $user->oauth_token_secret = $accessToken['oauth_token_secret'];
         $user->save();
         Auth::login($user);
         return Redirect::to('/');
         exit;
     } else {
         return Redirect::to('login')->with('message', 'Twitter認証できませんでした。');
         exit;
     }
 }
 /**
  * Delete the Tweet
  */
 public function delete_retweet()
 {
     if (!empty($this->config['consumer_key']) && !empty($this->params['id'])) {
         // create instance
         $twitter = new Twitter($this->config['consumer_key'], $this->config['consumer_secret']);
         // set tokens
         $twitter->setOAuthToken($this->config['oauth_token']);
         $twitter->setOAuthTokenSecret($this->config['oauth_token_secret']);
         $twitter->statusesDestroy($this->params['id']);
     }
     expHistory::back();
 }
Beispiel #10
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>";
    }
}
Beispiel #11
0
 public function fire($job, $data)
 {
     $post_id = $data['post_id'];
     $post = Post::find($post_id);
     if (!empty($post)) {
         $user_id = $post->user_id;
         $post_url = '';
         preg_match_all('#[-a-zA-Z0-9@:%_\\+.~\\#?&//=]{2,256}\\.[a-z]{2,4}\\b(\\/[-a-zA-Z0-9@:%_\\+.~\\#?&//=]*)?#si', $post->content, $url_matches);
         if (!empty($url_matches)) {
             $all_urls = $url_matches[0];
             $post_url = !empty($all_urls[0]) ? $all_urls[0] : '';
         }
         $network_ids = PostNetwork::where('post_id', '=', $post_id)->lists('network_id');
         $network = Network::where('user_id', '=', $user_id)->select('user_token', 'user_secret', 'network')->whereIn('id', $network_ids)->get();
         $client = new GuzzleHttp\Client();
         if (!empty($network)) {
             foreach ($network as $s) {
                 if ($s->network == 'twitter') {
                     try {
                         Twitter::setOAuthToken($s->user_token);
                         Twitter::setOAuthTokenSecret($s->user_secret);
                         $twitter_response = Twitter::statusesUpdate($post->content);
                     } catch (Exception $e) {
                     }
                 } else {
                     if ($s->network == 'linkedin') {
                         if (!empty($post_url)) {
                             try {
                                 $post_data = array('comment' => $post->content, 'content' => array('description' => $post->content), 'visibility' => array('code' => 'anyone'));
                                 $post_data['content']['submittedUrl'] = $post_url;
                                 $request_body = $post_data;
                                 $linkedin_resource = '/v1/people/~/shares';
                                 $request_format = 'json';
                                 $linkedin_params = array('oauth2_access_token' => $s->user_token, 'format' => $request_format);
                                 $linkedinurl_info = parse_url('https://api.linkedin.com' . $linkedin_resource);
                                 if (isset($linkedinurl_info['query'])) {
                                     $query = parse_str($linkedinurl_info['query']);
                                     $linkedin_params = array_merge($linkedin_params, $query);
                                 }
                                 $request_url = 'https://api.linkedin.com' . $linkedinurl_info['path'] . '?' . http_build_query($linkedin_params);
                                 $request_body = json_encode($request_body);
                                 $linkedin_response = CurlRequester::requestCURL('POST', $request_url, $request_body, $request_format);
                             } catch (Exception $e) {
                             }
                         }
                     } else {
                         if ($s->network == 'facebook') {
                             try {
                                 $post_data = array('access_token' => $s->user_token, 'message' => $post->content);
                                 if (!empty($post_url)) {
                                     $post_data['link'] = $post_url;
                                 }
                                 $res = $client->post('https://graph.facebook.com/me/feed', array('query' => $post_data));
                                 $response_body = $res->getBody();
                                 $response_body = json_decode($response_body, true);
                             } catch (Exception $e) {
                             }
                         }
                     }
                 }
             }
         }
     }
     $post->published = 1;
     $post->save();
     $job->delete();
 }
 /**
  * holds an instance of the Twitter Connect Class
  * @return Twitter Class
  */
 private static function get_twitter_class()
 {
     if (!self::$twitter_class) {
         $member = Member::currentUser();
         if ($member && $member->TwitterID) {
             require_once dirname(dirname(dirname(__FILE__))) . '/thirdparty/twitter/Twitter.php';
             require_once dirname(dirname(dirname(__FILE__))) . '/thirdparty/twitter/Exception.php';
             self::$twitter_class = new TijsVerkoyen\Twitter\Twitter(self::$consumer_key, self::$consumer_secret);
             if ($member->TwitterToken && $member->TwitterSecret) {
                 self::$twitter_class->setOAuthToken($member->TwitterToken);
                 self::$twitter_class->setOAuthTokenSecret($member->TwitterSecret);
             }
         }
     }
     return self::$twitter_class;
 }