<?php

$plugin_info = array(
    'pi_name'        => 'Who\'s Online',
    'pi_version'     => '1.0',
    'pi_author'      => 'Jeff Barsky',
    'pi_author_url'  => 'http://www.miasmaofmusings.com',
    'pi_description' => 'Creates a configurable list of who is online, with supporting member info.',
    'pi_usage'       => whos_online::usage()
);

class Whos_online {  // Open Class

    var $return_data = '';

    function Whos_online() { // Open Cat_lister Function

    	  // Set Globals and Variables
        global $TMPL, $DB, $LOC;
        $return  = '';
        $tagdata = '';
        $fields = array(
                  'group_id','screen_name','email','url','location','occupation',
                  'interests','bday_d','bday_m','bday_y','avatar_filename',
                  'avatar_width','avatar_height','photo_filename','photo_width',
                  'photo_height','join_date','last_visit','last_entry_date',
                  'last_comment_date','last_forum_post_date','last_activity',
                  'total_entries','total_comments','total_forum_topics',
                  'total_forum_posts'
                  );
        $aa = 0;
        $ap = 0;
        
        // Fetch Parameters
        $max_select  = (!$TMPL->fetch_param('max_select') ) ? "0"                    : $TMPL->fetch_param('max_select') ;
        $jd_format   = (!$TMPL->fetch_param('jd_format')  ) ? "m/d/Y"                : $TMPL->fetch_param('jd_format')  ;
        $le_format   = (!$TMPL->fetch_param('le_format')  ) ? "m/d/Y"                : $TMPL->fetch_param('le_format')  ;
        $lc_format   = (!$TMPL->fetch_param('lc_format')  ) ? "m/d/Y"                : $TMPL->fetch_param('lc_format')  ;
        $lv_format   = (!$TMPL->fetch_param('lv_format')  ) ? "m/d/Y"                : $TMPL->fetch_param('lv_format')  ;
        $lf_format   = (!$TMPL->fetch_param('lf_format')  ) ? "m/d/Y"                : $TMPL->fetch_param('lf_format')  ;
        $la_format   = (!$TMPL->fetch_param('la_format')  ) ? "m/d/Y"                : $TMPL->fetch_param('la_format')  ;
        $alt_image   = (!$TMPL->fetch_param('alt_image')  ) ? "alt/image.jpg|50|50"  : $TMPL->fetch_param('alt_image')  ;
        $alt_avatar  = (!$TMPL->fetch_param('alt_avatar') ) ? "alt/avatar.jpg|50|50" : $TMPL->fetch_param('alt_avatar') ;
        $alt_loc     = (!$TMPL->fetch_param('alt_loc')    ) ? "Somewhere, USA"       : $TMPL->fetch_param('alt_loc')    ;

        // Validate Imported Data
        // Convert the archaic "date formating" to PHP formatting
        $jd_format = ereg_replace('%','',$jd_format);
        $le_format = ereg_replace('%','',$le_format);
        $lc_format = ereg_replace('%','',$lc_format);
        $lv_format = ereg_replace('%','',$lv_format);
        $lf_format = ereg_replace('%','',$lf_format);
        $la_format = ereg_replace('%','',$la_format);
        $max_select  = ereg('[:alpha:][:punct:]', $max_select ) ? "0" : $max_select;
        
        // Expand "Alt" variables (This is so much easier in PERL)
        $x = split('[|]', $alt_image) ;
        $alt_image = $x[0]; $alt_imgw  = $x[1]; $alt_imgh = $x[2];
        $x = split('[|]', $alt_avatar);
        $alt_avatar = $x[0]; $alt_avaw = $x[1]; $alt_avah = $x[2];

        // Create Query
        $sql = "Select ";
        foreach ($fields as $tmp) { $sql .= $tmp.", "; }
        // Clean off end of Query
        $sql = substr($sql, 0, (strlen($sql)-2));
        // More of the query
        $sql .= " FROM exp_members, exp_online_users WHERE exp_online_users.member_id = exp_members.member_id";
        // Limit List To X
        if ($max_select >= 1){ $sql .= " LIMIT ".$max_select; }

        // Run That Query
        $query = $DB->query($sql);

        // First Bail Out Point
        if ( $query->num_rows == 0 ) { return false; }

        // Prepare data for output, interate over rows
        foreach ($query->result as $row) {

           // Ok, get the TEMPLATE data, this will have to be "Clean" with each
           // interation so to have a place to put data.
           $tagdata = $TMPL->tagdata;

           // Run Date Logic (I do this here because it is easier to parse for "0" than "M/D/Y"
           // I use "join_date" as default since all users have to have a join date.
           $row['last_entry_date']      = ($row['last_entry_date'] == "0")      ? $row['join_date'] : $row['last_entry_date'] ;
           $row['last_comment_date']    = ($row['last_comment_date'] == "0")    ? $row['join_date'] : $row['last_comment_date'] ;
           $row['last_visit']           = ($row['last_visit'] == "0")           ? $row['join_date'] : $row['last_visit'] ;
           $row['last_forum_post_date'] = ($row['last_forum_post_date'] == "0") ? $row['join_date'] : $row['last_forum_post_date'] ;
           $row['last_activity']        = ($row['last_activity'] == "0")        ? $row['join_date'] : $row['last_activity'] ;

           // Prepare data for output, interate over cells
           foreach($row as $key => $val){

           	  // OK, I have the data exposed at last, lets make the changes to
           	  // the data that need to be made:

              // Change Dates and Location
           	  $val = ($key == "join_date")            ? date($jd_format, $val) : $val;
           	  $val = ($key == "last_entry_date")      ? date($le_format, $val) : $val;
           	  $val = ($key == "last_comment_date")    ? date($lc_format, $val) : $val;
           	  $val = ($key == "last_visit")           ? date($lv_format, $val) : $val;
           	  $val = ($key == "last_forum_post_date") ? date($lf_format, $val) : $val;
           	  $val = ($key == "last_activity")        ? date($la_format, $val) : $val;
              $val = ($key == "location"        && $val == "") ? $alt_loc    : $val ;
              
              // Change out Photo Alternative Data
              if ($key == "photo_filename"    && $val == ""){
                 $val = $alt_image;
                 $ap = 1;
               }
              $val = ($key == "photo_width"   && $ap) ? $alt_imgw  : $val ;
              $val = ($key == "photo_height"  && $ap) ? $alt_imgh  : $val ;

              // Change out Avatar Alternative Data
              if ($key == "avatar_filename"   && $val == ""){
                 $val = $alt_avatar;
                 $aa = 1;
               }
              $val = ($key == "avatar_width"  && $aa) ? $alt_avaw  : $val ;
              $val = ($key == "avatar_height" && $aa) ? $alt_avah  : $val ;

              // Move the new values back to array:
              $row[$key] = $val;

           }
           
           // Reset Flags
           $ap = "0";
           $aa = "0";

           // Now that I have changed the data, plug it into the output string
           // so it looks pretty and makes sense:
           foreach ($fields as $tmp){
           	  $qtmp = "{".$tmp."}";
              $tagdata = ereg_replace("$qtmp", $row[$tmp], $tagdata);
           }

           // Now concontate this row to the next row preparing for output
           $return .= $tagdata;

        }

        // Output all the data for output
        $this->return_data = $return;

    } // Close Cat_lister Function

    function usage() { // Open Usage

    	ob_start();

      ?>

------------------------------------
WHAT THIS DOES:
------------------------------------

This allows you to display a list of people currently online with more
information than just a name. This is not ordered in any way (this version) but
will allow you to limit the number shown as well. This does not support
conditionals within the tag (yet).

Personally I use it just to show the avatar of everyone who is online right now,
but ovbiously there is room for more uses than just that. The real time nature
of the plugin is nice because it is constantly changing the display, adds
interest.

------------------------------------
BASIC USAGE:
------------------------------------

{exp:whos_online}

   Available Fields:
   {group_id}, {screen_name}, {email}, {url}, {location}, {occupation}
   {interests}, {bday_d}, {bday_m}, {bday_y},
   {avatar_filename}, {avatar_width}, {avatar_height},
   {photo_filename}, {photo_width}, {photo_height},
   {join_date}, {last_visit}, {last_entry_date}, {last_comment_date}
   {last_forum_post_date}, {last_activity}, {total_entries}, {total_comments}
   {total_forum_topics}, {total_forum_posts}

{/exp:whos_online}

------------------------------------
EXAMPLE OF USAGE:
------------------------------------

<h2>Who's Online:</h2>
{exp:whos_online alt_avatar="alt/ava.jpg|50|50" alt_image="alt/img.jpg|50|50" alt_loc="Here, USA"}
<img src="http://www.yoursite.com/images/avatars/{avatar_filename}"
   width="{avatar_width}"
   height="{avatar_height}"
   align="left" hspace="4" vspace="5" border="1" />
{screen_name} from {location}<br />
Joined On:  {join_date}<br />
Total Entries: {total_entries}, last on  {last_entry_date}<br />
Total Comments: {total_comments}. last on {last_comment_date}<br />
Last Visit On: {last_visit}<br /><br />
{/exp:whos_online}

------------------------------------
PARAMETERS:
------------------------------------
[max_select="25"]
Limits the list length to whatever you like. The default is "0" and shows all.

[alt_image="alt/image.jpg|50|50"]
[alt_avatar="alt/avatar.jpg|50|50"]
These allow you to set a fallback or alternative image is the user has not
selected an image or avatar. Useful for keeping the list consistant. The first
element is the file name, the second is the width, the third is the height.

[alt_loc="Somewhere, USA"]
Allows you to set a alternative location when a user has not entered one. Useful
for keeping lists readable.

[jd_format="m/d/Y"] = join_date date format
[le_format="m/d/Y"] = last_entry_date date format
[lc_format="m/d/Y"] = last_comment_date date format
[lv_format="m/d/Y"] = last_visit date format
[lf_format="m/d/Y"] = last_forum_post_date date format
[la_format="m/d/Y"] = last_activity date format
This plugin uses the full power of the PHP date function. As a reminder, here
are the format parameters:

a - Lowercase am or pm
A - Uppercase AM or PM
B - Swatch Internet time - 000 through 999
d - Day of the month, 2 digits with leading zeros - 01 to 31
D - A textual representation of a day, three letters - Mon through Sun
F - A full text of a month, such as January or March - January through December
g - 12-hour format of an hour without leading zeros - 1 through 12
G - 24-hour format of an hour without leading zeros - 0 through 23
h - 12-hour format of an hour with leading zeros - 01 through 12
H - 24-hour format of an hour with leading zeros - 00 through 23
i - Minutes with leading zeros - 00 to 59
I - (capital i) Daylights savings time - 1 = DST, 0 = Not DST.
j - Day of the month without leading zeros - 1 to 31
l - (lowercase 'L') Text of the day of the week - Sunday through Saturday
L - Whether it's a leap year - 1 = leap year, 0 Not leap year.
m - Numeric representation of a month, with leading zeros - 01 through 12
M - Short text representation of a month, three letters - Jan through Dec
n - Numeric month, without leading zeros - 1 through 12
O - Difference to Greenwich time (GMT) in hours - Example: +0200
r - RFC 822 formatted date - Example: Thu, 21 Dec 2000 16:01:07 +0200
s - Seconds, with leading zeros - 00 through 59
S - Ordinal suffix for the day/month, 2 characters - st, nd, rd or th. Use w/ j.
t - Number of days in the given month - 28 through 31
T - Timezone setting of this machine - Examples: EST , MDT ...
U - Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) See also time()
w - Numeric representation of the day of the week - 0 (Sunday) to 6 (Saturday)
W - ISO-8601 week number of year, - Example: 42 (the 42nd week in the year)
Y - A full numeric representation of a year, 4 digits - Examples: 1999 or 2003
y - A two digit representation of a year - Examples: 99 or 03
z - The day of the year (starting from 0) - 0 through 365
Z - Timezone offset in seconds.

Example: M j, Y h:i:s a = September 7, 2005 09:39:23 pm
Example: m/d/Y H:i:s    = 09/07/2005 21:39:23
Example: F \t\he jS, Y  = September 8th, 2005

The " \ " in front of a character will "escape" the character and pass it
directly with in pattern. You can literally format the date any way you wish.

If you use the "%" traditional formatting syntax it will still work, but using
the PHP version gets you plenty more options.

------------------------------------
NOTES ABOUT THIS PLUGIN:
------------------------------------

This plugin will not support conditional statements within the tag. I have
offered "Alternate" options on what I consider the most likely fields that
would need alternative data. This is easier than trying to parse the tagadata
for conditionals, although I am working on this and when I have it down I will 
offer this "upgrade" to the public, along with the same options on my other
plugins.

------------------------------------
(ver 2.0) FUTURE WORK / ADDITIONS:
------------------------------------

Add conditional processing to the plugins.
Add ordering to the listing.
Add pagination for the plugin.

------------------------------------
COPYRIGHT INFORMATION:
------------------------------------
(c) 2005, Jeff Barsky and Miasma of Musings. You may use and distribute this
plugin as you wish, but please leave original creator information in the file.
If you have questions or suggestions, please email me at:

admin@miasmaofmusings.com or jbarsky@visual-impact.com

If you base another plugin on this software, please feel free to drop all
information if you change it more than 20% or so. Otherwise, I would appreciate
it if this information were to stay with the plugin.

Author: Jeff Barsky
Originating Site: http://www.miasmaofmusings.com
Version .9: 9/12/2005

------------------------------------
THANK YOU:
------------------------------------

This plugin was much easier to program than the last one, mostly because all
the little problems involved in programming these plugins was worked in
"Blogger Listing". But none the less thank you to:

- Yoshi (psychodaisy.com and whos module I used as an initial model)
- All the moderator on the pMachine Community Forums (I owe you all lunch)
- Ofer Nave, all around programming guru.
- Bob Karlin, SQL genius.

--END-- <?php

        $buffer = ob_get_contents();

        ob_end_clean();

        return $buffer;

    } // Close Usage

} // Close Class

?>