TP-Docs
HTML5 Icon HTML5 Icon HTML5 Icon
TP on Social Media

Recent

Welcome to TinyPortal. Please login or sign up.

April 25, 2024, 02:07:53 PM

Login with username, password and session length
Members
  • Total Members: 3,885
  • Latest: Growner
Stats
  • Total Posts: 195,173
  • Total Topics: 21,219
  • Online today: 59
  • Online ever: 3,540 (September 03, 2022, 01:38:54 AM)
Users Online
  • Users: 0
  • Guests: 52
  • Total: 52

[Block] WoW Login Information Block

Started by Karma, January 29, 2009, 05:12:41 AM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

Karma

So I got bored at work today, and threw together a block which will display the login information shown on the World of Warcraft login screen. Downtimes, etc. You know what I'm talking about. I'd recommend putting it in either an upper or lower block, it's a lot of information that will probably look terribad in a side block. Ultimately, it's up to you :p

It's my first PHP, and my first interaction with SMF really, so any improvements/suggestions are welcome. When I can be bothered I'll move from file to DB storage, but one step at a time ;o)

Edit: Have done database storage, pretty much a rewrite, two posts down.

Configurables allow you to cache the data to a file, or pull it from the WoW servers every time it's loaded, and give your users an option to refresh the file. You'll need to change the url variable if you're not using US servers.

Enjoy <3

// Code to display the World of Warcraft login information in a TP block.
// Revision 0.01

global $boarddir, $scripturl;

$jlk_sacf = array(
// Configurables: //////////////////////////////////
// Local file to cache to (Blank = no cache)
'cachefile' => $boarddir . '/attachments/jlk_srvalert.html',
// Url to ServerAlert:
// http://status.wow-europe.com/en/alert for Europe (English)
// http://status.wow-europe.com/de/alert for Europe (German)
// http://status.wow-europe.com/fr/alert for Europe (French) etc..
'url' => 'http://launcher.worldofwarcraft.com/alert',
// Maximum age (Minutes) of cache.
'expiry' => 60,
// Minimum age (Minutes) to allow user refresh.
// Set above expiry to disable, 0 = always allow.
'minlife' => 5);
// End of Configurables /////////////////////////////////////////////////////
// The working Parts: /////////////////////////////////////////////////////
jlk_dispServerAlert($jlk_sacf);

function jlk_dispServerAlert($jlk_sacf)
{
  global $scripturl;
  $dsa_data = '';
  $dsa_fdate = 0;
  $dsa_sdate = time();
  $dsa_fetch = 0;
  $dsa_giveurl = 0;
  $dsa_age = '';

  if (empty($jlk_sacf['cachefile']))
  {
    echo jlk_getServerAlert($jlk_sacf['url']) . '<div style="text-align: right; font-style: italic; font-size: 8pt">Data is live.</div>';
    return;
  }
  if (file_exists($jlk_sacf['cachefile']))
    $dsa_data = file_get_contents($jlk_sacf['cachefile']);

  if (empty($dsa_data) || (strlen($dsa_data) < 17))
  {
    $dsa_data = str_pad(time(), 16) . "\n" . jlk_getServerAlert($jlk_sacf['url']);
    $dsa_fetch = 1;
    $dsa_fdate = $dsa_sdate;
  }
  if ($dsa_fetch == 0)
  {
    $dsa_fdate = trim(substr($dsa_data,0,16));
    $dsa_ddiff = $dsa_sdate - $dsa_fdate;
    $dsa_ddiffS = $dsa_ddiff % 60;
    $dsa_ddiffM = floor($dsa_ddiff / 60);
    $dsa_ddiffH = floor($dsa_ddiffM / 60);
    if (($dsa_ddiffM >= $jlk_sacf['expiry']) ||
        (!empty($_GET['jlksar']) && $_GET['jlksar'] == 1 &&
         $dsa_ddiffM >= $jlk_sacf['minlife']))
    {
      $dsa_fetch = 1;
      // Thx "odsign" for pointing this out & fixing.
      $dsa_fdate = $dsa_sdate;
      $dsa_data = str_pad(time(), 16) . "\n" . jlk_getServerAlert($jlk_sacf['url']);
    } else if ($dsa_ddiffM >= $jlk_sacf['minlife'])
      $dsa_giveurl = 1;
    $dsa_ddiffM = $dsa_ddiffM % 60;
    if ($dsa_fetch == 0)
      $dsa_age = ($dsa_ddiffH > 0 ? $dsa_ddiffH . 'h' : '') .
                 ($dsa_ddiffM > 0 ? $dsa_ddiffM . 'm' : '') .
                 (($dsa_ddiffS > 0 && $dsa_ddiffH < 1) ? $dsa_ddiffS . 's' : '');
  }
  if ($dsa_fetch == 1)
  {
    file_put_contents($jlk_sacf['cachefile'], $dsa_data);
    echo substr($dsa_data, 17) . '<div style="text-align: right; font-style: italic; font-size: 8pt">Data was fetched from server.</div>';
    return;
  }
  echo substr($dsa_data, 17) .  '<div style="text-align: right; font-style: italic; font-size: 8pt">Data is ' .  $dsa_age . ' old.' .  ($dsa_giveurl == 1 ? '   (<A HREF="'. $scripturl . ((empty($_SERVER['QUERY_STRING'])) ? '?jlksar=1' : '?' . trim($_SERVER['QUERY_STRING']) . ((strpos($_SERVER['QUERY_STRING'], 'jlksar=1') === FALSE) ? '&jlksar=1' : '')) . '">Refresh</A>)' : '');
  return;
}

function jlk_getServerAlert($gsa_url)
{
  $gsa_ret = '';
  $gsa_ch = curl_init();
  curl_setopt($gsa_ch, CURLOPT_URL, $gsa_url);
  curl_setopt($gsa_ch, CURLOPT_HEADER, false);
  curl_setopt($gsa_ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($gsa_ch, CURLOPT_FAILONERROR, true);
  $gsa_sares = curl_exec($gsa_ch);
  if (curl_errno($gsa_ch))
  {
    if ((curl_errno($gsa_ch) == 22) && (substr(trim(curl_error($gsa_ch)), -3) == '404'))
    {
      $gsa_ret = 'No notifications to display.';
    } else {
      $gsa_ret = 'Unable to retrieve Server Alert:<BR>' .
                       curl_error($gsa_ch);
    }
  } else {
    $gsa_sares = str_replace('SERVERALERT:', '', $gsa_sares);
    $gsa_sares = str_replace("\r", '', $gsa_sares);
    $gsa_sares = str_replace("\n", "<br />\n", trim($gsa_sares));
    $gsa_ret = $gsa_sares;
  }
  curl_close($gsa_ch);
  return $gsa_ret;
}

Dramber

Very nice! Just added to my site and it works great. Thanks!

Karma

#2
Glad it's working for someone other than me ;o)

So I finally re-wrote it to store in the database.. Added a couple of other things like height limitations, error handling, meh.

This is quite lengthy, sorry.

// Code to display the World of Warcraft login information in a TP block.
// Revision 0.4.2
global $db_prefix, $scripturl;

$jlk_sacf = array(
// Configurables: //////////////////////////////////
// Cache Locally (0: Never; 1: Current+Previous; 2: All)
'cache' => 2,
// Url to ServerAlert:
// http://status.wow-europe.com/en/alert for Europe (English)
// http://status.wow-europe.com/de/alert for Europe (German)
// http://status.wow-europe.com/fr/alert for Europe (French) etc..
'url' => 'http://launcher.worldofwarcraft.com/alert',
// Maximum age (Minutes) of cache.
'expiry' => 60,
// Maximum age (Minutes) before retrying on error (0 = always retry).
'expiry-error' => 5,
// Minimum age (Minutes) to allow user refresh.
// Set above expiry to disable, 0 = always allow.
'minlife' => 5,
// Maximum height of text (Browsers that support css overflow ;o)
'max-height' => '300px',
// Table name to cache in:
'cache_table' => $db_prefix . 'jlk_srvalert',
// Set this to 1 to remove database entries.
'uninstall' => 0,
// Verbose Curl Errors? (0 = No, 1 = Admins, 2 = Everyone)
// Note: Not used for cache-less operation.
'verbose-errors' => 1
);
// End of Configurables /////////////////////////////////////////////////////
// The working Parts: /////////////////////////////////////////////////////
$jlk_sacf['txt-refresh'] = '   (<A HREF="' . $scripturl . (empty($_SERVER['QUERY_STRING']) ? '?jlksar=1' : '?' . trim($_SERVER['QUERY_STRING']) . (strpos($_SERVER['QUERY_STRING'], 'jlksar=1') === FALSE ? '&jlksar=1' : '')) . '">Refresh</A>)';
$q = db_query("SELECT UNIX_TIMESTAMP(NOW())", __FILE__, __LINE__);
$r = mysql_fetch_row($q);
$jlk_sacf['now'] = $r[0];
mysql_free_result($q);

echo '<div class="smalltext" style="max-height: ' . $jlk_sacf['max-height'] .
     '; overflow: auto; position: relative">';
jlk_dispServerAlert($jlk_sacf);
echo '</div>';

function jlk_dispServerAlert($cf)
{
  // No Cache
  if (empty($cf['cache']) || $cf['cache'] == 0)
  {
    echo jlk_parseServerAlert(jlk_liveServerAlert($cf['url'])) .
         '<div style="text-align: right; font-style: italic; font-size: 8pt">Data is live.</div>';
    return;
  }

  // Uninstall.
  if ($cf['uninstall'] === 1)
  {
    db_query('DROP TABLE IF EXISTS `' . $cf['cache_table'] . '`', __FILE__,
             __LINE__);
    echo 'Server Alerts are no longer enabled.';
    return;
  }

  list($dsa, $pdsa) = jlk_getDBServerAlert($cf);

  if (empty($dsa))
  { // First Entry Ever:
    $dsa = array('original' => '', 'parsed' => '', 'added' => 0,
                 'updated' => 0, 'oldage' => '', 'age' => '', 'ageM' => 0,
                 'giveurl' => ($cf['minlife'] == 0 ? 1 : 0), 'SAID' => 0);
    $dsa['updated'] = $cf['now'];
    $dsa['added'] = $cf['now'];
    $dsa['original'] = jlk_liveServerAlert($cf['url']);
    $dsa['parsed'] = jlk_parseServerAlert($dsa['original']);
    $dsa['SAID'] = jlk_writeDBServerAlert($cf, $dsa);
    jlk_sendServerAlert($cf, $dsa, null);
    return;
  }
  // Lets determine if we're getting a new one.
  if (strcmp(substr($dsa['original'], 0, 9), 'CURLERROR') == 0)
  {
    if (($dsa['ageM'] >= $cf['expiry-error']) ||
        ($dsa['ageM'] >= $cf['minlife'] && !empty($_GET['jlksar'])))
    {
      $dsatmporig = jlk_liveServerAlert($cf['url']);
      if (strcmp(substr($dsatmporig, 0, 9), 'CURLERROR') == 0)
      {
        $dsa['original'] = $dsatmporig;
        $dsa['parsed'] = jlk_parseServerAlert($dsatmporig);
        $dsa['age'] = '';
        $dsa['updated'] = $cf['now'];
        $q = db_query('UPDATE `' . $cf['cache_table'] . '` SET Date_Updated=FROM_UNIXTIME(' . $cf['now'] . '), Original=\'' . addslashes__recursive($dsa['original']) . '\', Parsed=\'' . addslashes__recursive($dsa['parsed']) . '\' WHERE SAID=' . $dsa['SAID'], __FILE__, __LINE__);
        mysql_free_result($q);
        jlk_sendServerAlert($cf, $dsa, $pdsa);
        return;
      }
      $dsa = array('original' => '', 'parsed' => '', 'added' => 0,
                   'updated' => 0, 'oldage' => '', 'age' => '', 'ageM' => 0,
                   'giveurl' => ($cf['minlife'] == 0 ? 1 : 0), 'SAID' => 0);
      $dsa['updated'] = $cf['now'];
      $dsa['added'] = $cf['now'];
      $dsa['original'] = $dsatmporig;
      $dsa['parsed'] = jlk_parseServerAlert($dsa['original']);
      $dsa['SAID'] = jlk_writeDBServerAlert($cf, $dsa);
      jlk_sendServerAlert($cf, $dsa, null);
      return;
    }
  } else if (($dsa['ageM'] >= $cf['expiry']) ||
    (!empty($_GET['jlksar']) && $dsa['ageM'] >= $cf['minlife']))
  {
    // Get New (Old was OK)
    $pdsa = $dsa;
    $dsatmporig = jlk_liveServerAlert($cf['url']);
    $dsa['ageM'] = 0;
    $dsa['age'] = '';
    $dsa['giveurl'] = ($cf['minlife'] == 0 ? 1 : 0);
    if (strcmp($dsatmporig, $dsa['original']) == 0)
    {
      $dsa['updated'] = $cf['now'];
      jlk_writeDBServerAlert($cf, $dsa);
      jlk_sendServerAlert($cf, $dsa, null);
      return;
    }
    $dsa = array('original' => $dsatmporig,
                 'parsed' => jlk_parseServerAlert($dsatmporig),
                 'added' => $cf['now'], 'updated' => $cf['now'],
                 'oldage' => '', 'age' => '', 'ageM' => 0,
                 'giveurl' => ($cf['minlife'] == 0 ? 1 : 0), 'SAID' => 0);
    jlk_writeDBServerAlert($cf, $dsa);
    jlk_sendServerAlert($cf, $dsa, $pdsa);
    return;
  }
  // Just display what we had in the database.
  jlk_sendServerAlert($cf, $dsa, $pdsa);
}

// Actually send the server alert to the client.
function jlk_sendServerAlert($cf, $curr, $prev)
{
  global $context;
  // Current was an Error:
  if (strcmp(substr($curr['original'], 0, 9), 'CURLERROR') == 0)
  {
    if (!empty($prev))
    {
      echo $prev['parsed'] . '<div style="text-align: right; font-style: italic">Data is ' . $prev['oldage'] . ' old. Last checked ' . $prev['age'] . ' ago.<br />';
      if (($context['user']['is_admin'] && $cf['verbose-errors'] == 1) ||
          ($cf['verbose-errors'] == 2))
        echo $curr['parsed'];
      else
        echo 'Check failed';
      if (empty($curr['age']))
        echo ' just now.';
      else
        echo ' ' . $curr['age'] . ' ago.';
    } else {
      if (($context['user']['is_admin'] && $cf['verbose-errors'] == 1) ||
          ($cf['verbose-errors'] == 2))
        echo $curr['parsed'];
      else
        echo 'Check failed.';
      echo ' <div style="text-align: right; font-style: italic">Attempted ' . ($curr['age'] == '' ? 'just now.' : $curr['age'] . ' ago.');
    }
    if ($curr['giveurl'] == 1)
      echo $cf['txt-refresh'];
    echo '</div>';
    return;
  }
  // Current was good.
  echo $curr['parsed'] . '<div style="text-align: right; font-style: italic">';
  if ($curr['oldage'] == '')
    echo 'Data was fetched from the server.';
  else
  {
    echo 'Data is ' . $curr['oldage'] . ' old. Checked ' .
         ($curr['age'] == '' ? 'now.' : $curr['age'] . ' ago.');

    if ($curr['giveurl'] == 1)
      echo $cf['txt-refresh'];
  }
  echo '</div>';
}

// Write the values to the database.
function jlk_writeDBServerAlert($cf, $dsa, $pdsa)
{
  // Insert or Update?
  if ($dsa['SAID'] == 0)
  {
    $q = db_query('INSERT INTO `' . $cf['cache_table'] . '` (
                    `Date_Added`, `Date_Updated`, `Original`, `Parsed`)
                    VALUES (FROM_UNIXTIME('.$dsa['added'].'), FROM_UNIXTIME('.
                      $dsa['updated'] .'), \''.
                      addslashes__recursive($dsa['original']) .'\', \''.
                      addslashes__recursive($dsa['parsed']) . '\')', __FILE__,
                  __LINE__);
    $newid = db_insert_id();
    mysql_free_result($q);
    // Caching only current and previous? Get rid of old news.
    if ($cf['cache'] == 1 && !empty($pdsa) && $pdsa['SAID'] != 0)
    {
      $q = db_query('DELETE FROM `' . $cf['cache_table'] . '` WHERE `SAID` < ' . $pdsa['SAID'], __FILE__, __LINE__);
      mysql_free_result($q);
    }
    return($newid);
  }
  $q = db_query('UPDATE `' . $cf['cache_table'] . '`
                   SET `Date_Updated`=FROM_UNIXTIME('.$dsa['updated'].
                   ') WHERE `SAID`=' . $dsa['SAID'], __FILE__, __LINE__);
  mysql_free_result($q);
  return $dsa['SAID'];
}

// Get the values from the database.
function jlk_getDBServerAlert($cf)
{
  // Create The Table on First Use.
  $q = db_query('CREATE TABLE IF NOT EXISTS `' . $cf['cache_table'] . '` (
    `SAID` INT(8) UNSIGNED NOT NULL AUTO_INCREMENT,
    `Date_Added` DATETIME NOT NULL,
    `Date_Updated` DATETIME NOT NULL,
    `Original` Text,
    `Parsed` Text,
    PRIMARY KEY (SAID)
  )', __FILE__, __LINE__);
  mysql_free_result($q);

  $dsa = array ('original' => '', 'parsed' => '', 'added' => 0,
                'updated' => 0, 'oldage' => '', 'age' => '', 'ageM' => 0,
                'now' => $cf['now'],
                 'giveurl' => ($cf['minlife'] == 0 ? 1 : 0), 'SAID' => 0);
  $pdsa = array ('original' => '', 'parsed' => '', 'added' => 0,
                 'updated' => 0, 'oldage' => '', 'age' => '', 'ageM' => 0,
                 'now' => $dsa['now'],
                 'giveurl' => ($cf['minlife'] == 0 ? 1 : 0), 'SAID' => 0);
  $q = db_query('SELECT SAID, UNIX_TIMESTAMP(Date_Added),
                              UNIX_TIMESTAMP(Date_Updated), Original, Parsed
                   FROM `'.$cf['cache_table'].'`
                   ORDER BY SAID DESC LIMIT 2', __FILE__, __LINE__);

  if (mysql_num_rows($q) < 1)
    return array(null, null);

  $r = mysql_fetch_row($q);
  $dsa['SAID'] = $r[0];
  $dsa['added'] = $r[1];
  $dsa['updated'] = $r[2];
  $dsa['original'] = $r[3];
  $dsa['parsed'] = $r[4];
  list($dsa['ageM'], $dsa['age']) = jlk_dateDiff($cf['now'], $dsa['updated']);
  if ($dsa['ageM'] >= $cf['minlife'])
    $dsa['giveurl'] = 1;
  list(,$dsa['oldage']) = jlk_dateDiff($cf['now'], $dsa['added']);

  if (mysql_num_rows($q) < 2)
  {
    mysql_free_result($q);
    return array($dsa, null);
  }

  $r = mysql_fetch_row($q);
  $dsa['error'] = $r[0];
  $pdsa['SAID'] = $r[0];
  $pdsa['added'] = $r[1];
  $pdsa['updated'] = $r[2];
  $pdsa['original'] = $r[3];
  $pdsa['parsed'] = $r[4];
  list($pdsa['ageM'], $pdsa['age']) = jlk_dateDiff($cf['now'], $pdsa['updated']);
  list(,$pdsa['oldage']) = jlk_dateDiff($cf['now'], $pdsa['added']);

  mysql_free_result($q);
  return array($dsa, $pdsa);
}

// Determine the difference between two dates.
// Returns Array (Total Minutes, #d#h#m#s)
function jlk_dateDiff($jddx, $jddy)
{
  if ($jddx == $jddy)
    return array(0, '');
  $jddm = 0;
  $jddiff = ($jddx > $jddy ? $jddx - $jddy : $jddy - $jddx);
  $jddiffS = $jddiff % 60;
  $jddiffM = floor($jddiff / 60);
  $jddm = $jddiffM;
  $jddiffH = floor($jddiffM / 60);
  $jddiffD = floor($jddiffH / 24);
  $jddiffM %= 60;
  $jddiffH %= 24;
  return array($jddm, ($jddiffD > 0 ? $jddiffD . 'd' : '') .
                      ($jddiffH > 0 ? $jddiffH . 'h' : '') .
                      (($jddiffM > 0 && $jddiffD < 1) ? $jddiffM . 'm' : '') .
                      (($jddiffS > 0 && $jddiffD < 1 && $jddiffH < 1) ? $jddiffS . 's' : ''));
}

function jlk_parseServerAlert($source)
{
  if (strcmp($source, 'NOALERT') == 0)
    return 'No current Server Alert posted.';
  if (strcmp(substr($source, 0, 9), 'CURLERROR') == 0)
    return 'Unable to retrieve Server Alert: ' . substr($source, 11);
  $source = trim($source);
  if (strcasecmp(substr($source, 0, 11), 'SERVERALERT') == 0)
    $source = trim(substr($source,12));
  return(str_replace("\n", '<br />', str_replace("\r", '', trim($source))));
}

function jlk_liveServerAlert($gsa_url)
{
  $gsa_ret = '';
  $gsa_ch = curl_init();
  curl_setopt($gsa_ch, CURLOPT_URL, $gsa_url);
  curl_setopt($gsa_ch, CURLOPT_HEADER, false);
  curl_setopt($gsa_ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($gsa_ch, CURLOPT_FAILONERROR, true);
  $gsa_sares = curl_exec($gsa_ch);
  if (curl_errno($gsa_ch))
  {
    if ((curl_errno($gsa_ch) == 22) &&
        (strcmp(substr(trim(curl_error($gsa_ch)), -3), '404') == 0))
    {
      $gsa_ret = 'NOALERT';
    } else {
      $gsa_ret = 'CURLERROR: '. curl_error($gsa_ch);
    }
  } else {
    if (empty($gsa_sares) || (strlen(trim($gsa_sares)) < 10))
      $gsa_ret = 'NOALERT';
    else
      $gsa_ret = $gsa_sares;
  }
  curl_close($gsa_ch);
  return $gsa_ret;
}


Dramber


Dark-Wolf

Someone can post a screenshot please?

Inny

#5
Quote from: Dark-Wolf on March 03, 2009, 01:18:40 AM
Someone can post a screenshot please?

Here - Tho i dont remember which one of the 2 codes i use.

Karma

Sorry guys, my bad.. I missed the topic reply notification :p..

I fudged it a little bit (there's no ServerAlert posted atm) to pull out some old data.. Usually I have the ServerAlert on a Lower Panel, the SS is for demonstration purposes only.

Apologies for not just linking the forums, only displaying the alert for guild members ;p.

Attached.

Karma

Updated in This Post (A link, if it's not obvious in your skin)

Revision 0.4:

* Fixed a bug where the first 12 characters would be trimmed from messages not beginning with 'SERVERALERT:'
* All time conversions and reads are now being done on the MySQL server. DST caused some time compares to be an hour out. Also means good news for people with MySQL servers in different timezones to their web servers (wtf? :o).

Enjoy.

mekon

Great block, but I am receiving the following code errors in the error log once the block is enabled.

2: Missing argument 2 for db_query(), called in /home/nomekcou/public_html/tsbguild/Sources/Load.php(1735) : eval()'d code(48) : eval()'d code on line 235 and defined
File: home/********/public_html/tsbguild/Sources/Subs.php
Line: 238

Kazie

How come it doesn't show all the breaking news?

I just checked for fun, and it's not including migration news and stuff..
Is this intentional, or you just didn't notice? :)

Brilliant block btw.