Archive

Archive for the ‘PHP’ Category

Status Press Widget

December 23rd, 2009 No comments

I’ve been playing around a bit with Status Press Widget by Brian D. Goad.

I found that the data it fetched also showed the nick-/username which I think is kinda redundant so I modified the plugin a bit to let me manage it from the admin interface. While at it I also modified so URL’s are made clickable and cleaned up the code a bit.

Here’s the modified status-press-widget.php file:

<?php
/*
Plugin Name: Status Press Widget
Plugin URI: http://www.briandgoad.com/blog/status-press-widget/
Description: Adds a Widget to display your Facebook/Twitter/Last.FM/Pownce status in your sidebar.
Version: 1.14
Author: Brian D. Goad
Author URI: http://www.briandgoad.com/blog
*/

/*
    Copyright 2008  Brian D. Goad  (email : bdgoad@gmail.com)
            & Adam Walker Cleaveland &  C. Scott Andreas,
            Authors of the original Status Press Plugin

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

if (!function_exists("htmlspecialchars_decode")) {
    function htmlspecialchars_decode($string,$style=ENT_COMPAT){
        $translation = array_flip(get_html_translation_table(HTML_SPECIALCHARS,$style));
        if ($style === ENT_QUOTES) {
            $translation['&#039;'] = '\'';
        }
        return strtr($string,$translation);
    }
}

class SPWidget {
    //Set Defaults
    var $default_options = array(
        'title' => "",
        'social' => "",
        'url' => "",
        'num' => "1",
        'status_mods' => "",
        'show_time' => 1,
        'time_mods' => ""
    );

    var $o;

    function SPWidget() {}

    //Begin By Checking to See if Widget Can Exist
    function init() {
        if (!function_exists('register_sidebar_widget')) {
            return;
        }
        if (!$options = get_option('widget_status_press')) {
            $options = array();
        }
        $widget_ops = array('classname' => 'widget_status_press', 'description' => 'Add a Social Status to your sidebar');
        $control_ops = array('width' => 200, 'height' => 350, 'id_base' => 'status_press');
        $name = 'Status Press';
        $registered = false;

        //Register Widgets
        foreach (array_keys($options) as $o) {
            if (!isset($options[$o]['title'])) {
                continue;
            }
            $id = "status_press-$o";
            $registered = true;
            wp_register_sidebar_widget($id, $name, array(&$this, 'widget'), $widget_ops, array( 'number' => $o ) );
            wp_register_widget_control($id, $name, array(&$this, 'control'), $control_ops, array( 'number' => $o ) );
        }
        if (!$registered) {
            wp_register_sidebar_widget('status_press-1', $name, array(&$this, 'widget'), $widget_ops, array( 'number' => -1 ) );
            wp_register_widget_control('status_press-1', $name, array(&$this, 'control'), $control_ops, array( 'number' => -1 ) );
        }
    }

    function widget($args, $widget_args = 1) {
        //Retrieve Any Arguments
        extract($args);

        if (is_numeric($widget_args)) {
            $widget_args = array('number' => $widget_args);
        }

        $widget_args = wp_parse_args($widget_args, array( 'number' => -1 ));
        extract($widget_args, EXTR_SKIP);

        //Get Options Saved in Control
        $options_all = get_option('widget_status_press');

        if (!isset($options_all[$number])) {
            return;
        }

        $this->o = $options_all[$number];
        //Set Temp Values (in case they have changed)
        $title = htmlspecialchars($this->o['title'], ENT_QUOTES);
        $url = $this->o['url'];
        $num = htmlspecialchars($this->o['num'], ENT_NOQUOTES);
        $status_mods = htmlspecialchars_decode($this->o['status_mods'], ENT_QUOTES);
        $show_time = $this->o['show_time'];
        $show_nick = $this->o['show_nick'];
        $time_mods = htmlspecialchars_decode($this->o['time_mods'], ENT_QUOTES);
        //Begin Status Press Functions

        require_once (ABSPATH . WPINC . '/rss.php');

        if ($url == '' ) {
            if ($title == '') {
                $title = 'Status Press';
            }
            $disp .= '<p>You Must Supply the URL to your Facebook Status RSS Feed </p>';
        } else {
            //Adjust cache setting
            if ( !defined('MAGPIE_CACHE_AGE') ) {
                define('MAGPIE_CACHE_AGE', 5*60); // five minutes
            }
            $rss = fetch_rss($url);
            if($rss) {
                if ($title == '') {
                    $title = $rss->channel[title];
                }
                if ($num > 0) {
                    $rss->items = array_slice($rss->items, 0, $num);
                }
                foreach($rss->items as $item) {
                    //Get Status Text
                    $status = $item[title];
                    if ($status != '') {
                        // Removes the nick in front of status text and makes any URL's into clickable links.
                        if (!$show_nick) {
                            $status = trim(substr($status, stripos($status, ':')+1));
                        }
                        $status = make_clickable($status);
                        $disp .= "\t<p " . $status_mods . ">" . $status;
                        if ($show_time) {
                            // Get the date + time of the last update from the RSS feed.
                            $pubdate = $item[pubdate];
                            // Convert this string to a time.
                            $pubdate = strtotime($pubdate);
                            // Calculate how long it's been since the status was updated.
                            $today = time();
                            $difference = $today - $pubdate;
                            // Display how long it's been since the last update.
                            $disp .= "</p><p ". $time_mods . ">(Updated ";
                            // Show days if it's been more than a day.
                            if (floor($difference / 86400) > 0) {
                                $disp .= floor($difference / 86400);
                                if (floor($difference / 86400) == 1) {
                                    $disp .= ' day, ';
                                } else {
                                    $disp .= ' days, ';
                                }
                                $difference -= 86400 * floor($difference / 86400);
                            }
                            // Show hours if it's been more than an hour.
                            if (floor($difference / 3600) > 0) {
                                $disp .= floor($difference / 3600);
                                if (floor($difference / 3600) == 1) {
                                    $disp .= ' hour, ';
                                } else {
                                    $disp .= ' hours, ';
                                }
                                $difference -= 3600 * floor($difference / 3600);
                            }
                            // Show minutes if it's been more than a minute.
                            $disp .= floor($difference / 60);
                            $difference -= 60 * floor($difference / 60);
                            if (floor($difference / 60) == 1) {
                                $disp .= ' minute, ';
                            } else {
                                $disp .= ' minutes ago)';
                            }
                        }
                        $disp .= "</p>\n";
                    }
                }
            } else {
                if ($title == '') {
                    $title = "Status Press";
                }
                $disp .= "\t<p>Status Press Error: Something bad happened! <br /> Here are the variables you entered: <ul><li> Title:".$title."</li><li>URL:".$url."</li><li>Number:".$num."</li><li>RSS: ".$rss."\t</li></ul></p>\n";
            }
        }
        //Call Widget
?>
                <?php echo $before_widget; ?>
                <?php echo $before_title . $title . $after_title; ?>

                <div>
                    <?php echo $disp; // Display Widget Content ?>
                </div>

                <?php echo $after_widget; ?>
<?php
    }
    function control($widget_args = 1) {
        global $wp_registered_widgets;
        static $updated = false;
        if (is_numeric($widget_args)) {
            $widget_args = array('number' => $widget_args);
        }
        $widget_args = wp_parse_args($widget_args, array('number' => -1));
        extract($widget_args, EXTR_SKIP);
        $options_all = get_option('widget_status_press');
        if (!is_array($options_all)) {
            $options_all = array();
        }
        if (!$updated && !empty($_POST['sidebar'])) {
            $sidebar = (string)$_POST['sidebar'];
            $sidebars_widgets = wp_get_sidebars_widgets();
            if (isset($sidebars_widgets[$sidebar])) {
                $this_sidebar =& $sidebars_widgets[$sidebar];
            } else {
                $this_sidebar = array();
            }
            foreach ($this_sidebar as $_widget_id) {
                if ('widget_status_press' == $wp_registered_widgets[$_widget_id]['callback'] && isset($wp_registered_widgets[$_widget_id]['params'][0]['number'])) {
                    $widget_number = $wp_registered_widgets[$_widget_id]['params'][0]['number'];
                    if (!in_array("status_press-$widget_number", $_POST['widget-id'])) {
                        unset($options_all[$widget_number]);
                    }
                }
            }
            foreach ((array)$_POST['status_press'] as $widget_number => $posted) {
                if (!isset($posted['title']) && isset($options_all[$widget_number])) {
                    continue;
                }
                $options = array();
                $options['title'] = strip_tags(stripslashes($posted['title']));
                $options['social'] = $posted['social'];
                $options['url'] = sanitize_url(strip_tags($posted['url']));
                $options['show_nick'] = $posted['show_nick'];
                $options['num'] = intval($posted['num']);
                $options['status_mods'] = strip_tags(stripslashes($posted['status_mods']));
                $options['show_time'] = isset($posted['show_time']);
                $options['time_mods'] = strip_tags(stripslashes($posted['time_mods']));
                $options_all[$widget_number] = $options;
            }
            update_option('widget_status_press', $options_all);
            $updated = true;
        }
        if (-1 == $number) {
            $wpnm = '%i%';
            $values = $this->default_options;
        } else {
            update_option('widget_status_press', $options_all);
            $wpnm = $number;
            $values = $options_all[$number];
        }

        //Show Admin Screen
?>
        <p style="text-align:left;">
            <label for="status_press-title"><?php _e('Title (Leave Blank to Pull Title From Feed):', 'status-press-widget'); ?></label><br />
            <input style="width: 200px;" id="status_press-title" name="status_press[<?php echo $wpnm; ?>][title]" type="text" value="<?php echo htmlspecialchars($values['title'], ENT_QUOTES); ?>" />
        </p>
        <script language="javascript">
            function rss(social) {
                actSocial = social.value;
                var txtUrl = document.getElementById("status_press-url[<?php echo $wpnm; ?>]")
                function getUserName(actSocial) {
                    do {
                        var name = prompt("Please input your " + actSocial + " username here:", "");
                    } while (name == "");
                    if (name!=null && name!="") {
                        return name;
                    } else {
                        social.selectedIndex = 0;
                    }
                }
                switch (actSocial) {
                    case "Facebook":
                        okFB = confirm('Please ensure that you are already logged in to Facebook.');
                        if (okFB) {
                            alert('On the following page, please find the My Status RSS feed and copy it into the box below.');
                            window.open("http://www.facebook.com/minifeed.php?filter=11");
                        }
                    break;
                    case "Twitter":
                        name = getUserName(actSocial);
                        if (name != null) {
                            txtUrl.value = "http://twitter.com/statuses/user_timeline/" + name + ".rss";
                        }
                    break;
                    case "Last.FM":
                        name = getUserName(actSocial);
                        if (name != null) {
                            txtUrl.value = "http://ws.audioscrobbler.com/1.0/user/" + name + "/recenttracks.rss";
                        }
                    break;
                }
            }
            function showHide(that, element) {
                e = document.getElementById(element);
                if (that.checked) {
                    e.style.visibility = "visible";
                } else {
                    e.style.visibility = "hidden";
                }
            }
            //showHide(document.getElementById("status_press-show_time[<? echo $wpnm; ?>]"), "status_press-time_mods[<? echo $wpnm; ?>]");
        </script>

        <p style="text-align:left;">
            <span style="vertical-align: bottom;"><?php _e('Social Status Network:  ', 'status-press-widget'); ?></span>
            <select name="status_press[<?php echo $wpnm; ?>][social]" id="status_press-social" onchange="rss(this)">
                <option value=""<?php if($values['social'] == '') echo ' selected="selected"'; ?>></option>
                <option value="Facebook"<?php if($values['social'] == "Facebook") echo ' selected="selected"'; ?>><?php _e('Facebook', 'status-press-widget'); ?></option>
                <option value="Twitter"<?php if($values['social'] == "Twitter") echo ' selected="selected"'; ?>><?php _e('Twitter', 'status-press-widget'); ?></option>
                <option value="Last.FM"<?php if($values['social'] == "Last.FM") echo ' selected="selected"'; ?>><?php _e('Last.FM', 'status-press-widget'); ?></option>
            </select>
        </p>
        <p>
            <label for="status_press-url[<?php echo $wpnm; ?>]"><?php _e('Status URL Feed:', 'status-press-widget'); ?></label><br />
            <input style="width: 230px;" id="status_press-url[<?php echo $wpnm; ?>]" name="status_press[<?php echo $wpnm; ?>][url]" type="text" value="<?php echo $values['url']; ?>" />
        </p>
        <p><?php if($values['show_nick']) $values['show_nick'] = ' checked="checked"';?>
            <label for="status_press-show_nick"><?php _e( 'Show nick-/username: ', 'status-press-widget'); ?></label>
            <input type="checkbox" class="checkbox" id="status_press-show_nick[<?php echo $wpnm; ?>]" name="status_press[<?php echo $wpnm; ?>][show_nick]"<?php echo $values['show_nick']; ?> />
        </p>
        <p style="text-align:left;">
            <label for="status_press-num"><?php _e('Number of Status Feeds to Display <br/>(Use "0" to display All):', 'status-press-widget'); ?></label><br />
            <input style="width: 20px;" id="status_press-num" name="status_press[<?php echo $wpnm; ?>][num]" type="text" value="<?php echo htmlspecialchars($values['num'], ENT_NOQUOTES); ?>" />
        </p>
        <p style="text-align:left;">
            <label for="status_press-status_mods"><?php _e('Stylizing Modifications for Status Tags<br/>(i.e. id="status_press", etc):', 'status-press-widget'); ?></label><br />
            <input style="width: 230px;" id="status_press-status_mods" name="status_press[<?php echo $wpnm; ?>][status_mods]" type="text" value="<?php echo htmlspecialchars($values['status_mods'], ENT_QUOTES); ?>" />
        </p>
        <p><?php if($values['show_time']) $values['show_time'] = ' checked="checked"'; ?>
            <label for="status_press-show_time"><?php _e( 'Show Time Since Status Update: ', 'status-press-widget'); ?></label>
            <input type="checkbox" class="checkbox" id="status_press-show_time[<?php echo $wpnm; ?>]" name="status_press[<?php echo $wpnm; ?>][show_time]" onClick="showHide(this, \'status_press-time_mods[<?php echo $wpnm; ?>]\')"<?php echo $values['show_time']; ?> />
        </p>
        <p style="text-align:left;" id="status_press-time_mods[<?php echo $wpnm; ?>]">
            <label for="status_press-time_mods[<?php echo $wpnm; ?>]"><?php _e('Stylizing Modifications for Time Since Tags <br/>(i.e. id="status-time", etc):', 'status-press-widget'); ?></label><br />
            <input style="width: 230px;" id="status_press-time_mods[<?php echo $wpnm; ?>]" name="status_press[<?php echo $wpnm; ?>][time_mods]" type="text" value="<?php echo htmlspecialchars($values['time_mods'], ENT_QUOTES); ?>" />
        </p>
        <input type="hidden" id="status_press-submit" name="status_press[<?php echo $wpnm; ?>][submit]" value="1" />
<?php
    }
}
$spw = new SPWidget();
//Initialize Widget on Run
add_action('widgets_init', array($spw, 'init'));

?>
Categories: Blog, PHP Tags: , , ,

mirc.php for GeSHi

December 12th, 2007 1 comment

Seems there were a minor issue with the mirc.php file from GeSHi causing all code entries set to be parsed as mIRC scripts to stop with an error. Fixed (or rather made a dirty hack) it so my mIRC scripts once again could be highlighted :)

<?php
/*************************************************************************************
* mirc.php
* -----
* Author: Alberto 'Birckin' de Areba (Birckin@hotmail.com)
* Copyright: (c) 2006 Alberto de Areba
* Release Version: 1.0.7.20
* Date Started: 2006/05/29
*
* mIRC Scripting language file for GeSHi.
*
* CHANGES
* -------
* 2006/05/29 (1.0.0)
*   -  First Release
*
* 2007/12/12 (1.0.1) - Brian Schmidt Pedersen
*   -  Removed the forward slash from all mIRC keywords, since in actual
*       mIRC scripts, they're often written without the slash.
*   -  Entry 6 (timer parsing) under REGEXPS caused GeSHi to halt with an error
*       simple solution was to remove the slash(es)
*
*************************************************************************************
*
*     This file is part of GeSHi.
*
*   GeSHi is free software; you can redistribute it and/or modify
*   it under the terms of the GNU General Public License as published by
*   the Free Software Foundation; either version 2 of the License, or
*   (at your option) any later version.
*
*   GeSHi is distributed in the hope that it will be useful,
*   but WITHOUT ANY WARRANTY; without even the implied warranty of
*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*   GNU General Public License for more details.
*
*   You should have received a copy of the GNU General Public License
*   along with GeSHi; if not, write to the Free Software
*   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*
************************************************************************************/


$language_data = array (
    'LANG_NAME' => 'mIRC Scripting',
    'COMMENT_SINGLE' => array(
        1 => ';'
    ),
    'COMMENT_MULTI' => array(),
    'CASE_KEYWORDS' => GESHI_CAPS_NO_CHANGE,
    'QUOTEMARKS' => array(),
    'ESCAPE_CHAR' => '',
    'KEYWORDS' => array(
        1 => array(
            'alias', 'menu', 'dialog'
        ),
        2 => array(
            'if', 'elseif', 'else', 'while', 'return', 'goto'
        ),
        3 => array(
            'action', 'ajinvite', 'alias', 'aline', 'amsg', 'ame', 'anick',
            'aop','auser', 'avoice', 'auto', 'autojoin', 'away', 'background',
            'ban', 'beep', 'channel', 'clear', 'clearall', 'clipboard',
            'close', 'closemsg', 'color', 'copy', 'creq', 'ctcp', 'ctcpreply',
            'ctcps', 'dcc', 'dde', 'ddeserver', 'debug', 'describe', 'disable',
            'disconnect', 'dlevel', 'dll', 'dns', 'dqwindow', 'ebeeps', 'echo',
            'editbox', 'emailaddr', 'enable', 'events', 'exit', 'filter',
            'findtext', 'finger', 'flash', 'flood', 'flush', 'flushini',
            'font', 'fsend', 'fserve', 'fullname', 'ghide', 'gload', 'gmove',
            'gopts', 'gplay', 'gpoint', 'gqreq', 'groups', 'gshow', 'gsize',
            'gstop', 'gtalk', 'gunload', 'guser', 'halt', 'haltdef', 'help',
            'hop', 'ignore', 'inc', 'invite', 'join', 'kick', 'linesep',
            'links', 'list', 'load', 'loadbuf', 'localinfo', 'log', 'me',
            'mdi', 'mkdir', 'mnick', 'mode', 'msg', 'names', 'nick', 'noop',
            'notice', 'notify', 'omsg', 'onotice', 'part', 'partall', 'pdcc',
            'perform', 'ping', 'play', 'pop', 'protect', 'pvoice', 'qmsg',
            'qme', 'query', 'queryrn', 'quit', 'raw', 'remini', 'remote',
            'remove', 'rename', 'renwin', 'resetidle', 'rlevel', 'rmdir',
            'run', 'ruser', 'save', 'savebuf', 'save', 'saveini', 'say',
            'server', 'set', 'showmirc', 'sline', 'sound', 'speak', 'splay',
            'sreq', 'strip', 'time', 'timers', 'timestamp', 'titlebar',
            'tnick', 'tokenize', 'topic', 'ulist', 'unload', 'updatenl', 'url',
            'uwho', 'var', 'window', 'winhelp', 'write', 'writeini', 'who',
            'whois', 'whowas'
        )
    ),
    'SYMBOLS' => array(
        '(', ')', '{', '}', '[', ']', '|'
    ),
    'CASE_SENSITIVE' => array(
        GESHI_COMMENTS => true,
        1 => false,
        2 => false
    ),
    'STYLES' => array(
        'KEYWORDS' => array(
            1 => 'color: #994444;',
            2 => 'color: #000000; font-weight: bold;',
            3 => 'color: #990000; font-weight: bold;'
        ),
        'COMMENTS' => array(
            1 => 'color: #808080; font-style: italic;'
        ),
        'ESCAPE_CHAR' => array(),
        'BRACKETS' => array(
            0 => 'color: #FF0000;'
        ),
        'STRINGS' => array(),
        'NUMBERS' => array(
            0 => ''
        ),
        'METHODS' => array(),
        'SYMBOLS' => array(
            0 => 'color: #FF0000;'
        ),
        'REGEXPS' => array(
            0 => 'color: #000099;',
            1 => 'color: #990000;',
            2 => 'color: #888800;',
            3 => 'color: #888800;',
            4 => 'color: #000099;',
            5 => 'color: #000099;',
            6 => 'color: #990000; font-weight: bold;'
        ),
        'SCRIPT' => array()
    ),
    'URLS' => array(
        1 => '',
        2 => '',
        3 => '',
        4 => ''
    ),
    'OOLANG' => false,
    'OBJECT_SPLITTERS' => array(),
    'REGEXPS' => array(
        0 => '\$[^$][^ ,\(\)]*',
        1 => '(%|&).+?[^ ,\)]*',
        2 => '(#|@).+?[^ ,\)]*',
        3 => '-[a-z\d]+',
        4 => '(on|ctcp) (!|@|&)?(\d|\*):[a-zA-Z]+:',
        /*
        4 => array(
        GESHI_SEARCH => '((on|ctcp) (!|@|&)?(\d|\*):(Action|Active|Agent|AppActive|Ban|Chat|Close|Connect|Ctcp|CtcpReply|DccServer|DeHelp|DeOp|DeVoice|Dialog|Dns|Error|Exit|FileRcvd|FileSent|GetFail|Help|Hotlink|Input|Invite|Join|KeyDown|KeyUp|Kick|Load|Logon|MidiEnd|Mode|Mp3End|Nick|NoSound|Notice|Notify|Op|Open|Part|Ping|Pong|PlayEnd|Quit|Raw|RawMode|SendFail|Serv|ServerMode|ServerOp|Signal|Snotice|Start|Text|Topic|UnBan|Unload|Unotify|User|Mode|Voice|Wallops|WaveEnd):)',
        GESHI_REPLACE => '\\1',
        GESHI_MODIFIERS => 'i',
        GESHI_BEFORE => '',
        GESHI_AFTER => ''
        ),
        */

        5 => 'raw (\d|\*):',
        6 => 'timer(?!s\b)[0-9a-zA-Z_]+'
    ),
    'STRICT_MODE_APPLIES' => GESHI_NEVER,
    'SCRIPT_DELIMITERS' => array(),
    'HIGHLIGHT_STRICT_BLOCK' => array()
);
?>
Categories: Code, mIRC, PHP Tags: , , , ,

class IMDb

<?php
require_once('HTTP/Request.php');
class imdb
{
    var $id             = '';

    var $host           = 'www.imdb.com';
    var $agent          = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)';
    var $body           = '';

    var $title          = '';
    var $year           = '';
    var $aka            = '';
    var $genre          = '';

    function open($id)
    {
        $this->id = $id;
        $req =& new HTTP_Request('');
        $req->addHeader('User-Agent', $this->agent);
        $req->setURL('http://'.$this->host.'/title/tt'.$this->id.'/');

        if (!PEAR::isError($req->sendRequest())) {
            $this->body = $req->getResponseBody();
        }
    }

    function title()
    {
        if ($this->title == '') {
            $this->title = stristr($this->body, '<title>');
            $title_e = strpos(strtolower($this->title), '</title>');
            $this->title = substr($this->title, 7, $title_e - 7);
            $this->title = substr($this->title, 0, strpos(strtolower($this->title), '(', 0) - 1);
        }
        return $this->title;
    }

    function year()
    {
        if ($this->year == '') {
            $title_e = strpos(strtolower($this->body), ')</title>');
            $this->year = substr($this->body, $title_e - 4, 4);
        }
        return $this->year;
    }

    function aka()
    {
        if ($this->aka == '') {
            $aka_s = strpos(strtolower($this->body), 'also known as');
            if ($aka_s == 0) {
                return array();
            }
            $aka_e = strpos(strtolower($this->body), "\n", $aka_s);
            $arr_aka_all = explode('<br />', str_replace('&#32;', ' ', substr($this->body, $aka_s, $aka_e - $aka_s)));
            array_shift($arr_aka_all);
            foreach ($arr_aka_all as $str_aka) {
                $arr_aka = explode(' (', $str_aka);
                if (count($arr_aka) < 2) {
                    continue;
                }
                $this->aka[] = array(
                    'title'     => $arr_aka[0],
                    'year'      => substr($arr_aka[1], 0, strlen($arr_aka[1])-1),
                    'country'   => (strlen(trim($arr_aka[2])) != 0) ? substr(trim($arr_aka[2]), 0, strlen(trim($arr_aka[2]))-1) : NULL,
                    'comment'   => (strlen(trim($arr_aka[3])) != 0) ? substr(trim($arr_aka[3]), 0, strlen(trim($arr_aka[3]))-1) : NULL
                );
            }
        }
        return $this->aka;
    }

    function genre()
    {
        if ($this->genre == '') {
            $genre_s = strpos(strtolower($this->body), '/sections/genres/');
            if ($genre_s == 0) {
                return array();
            }
            $genre_s = strpos(strtolower($this->body), '>', $genre_s);
            $genre_e = strpos(strtolower($this->body), "\n", $genre_s);
            $this->genre = explode(' / ', substr(strip_tags(substr($this->body, $genre_s + 1, $genre_e - $genre_s + 1)), 0, strlen(strip_tags(substr($this->body, $genre_s + 1, $genre_e - $genre_s + 1))) - 7));
        }
        return $this->genre;
    }

}
?>
Categories: Code, PHP Tags: ,

class SlidePager

<?php
class SlidePager
{
    /**
     * Personalised/simplified version of PEAR::Pager (sliding) class.
     * Example:
     *
     * require_once 'class.SlidePager.php';
     *
     * $params = array(
     *     'pagerData'     => $items,
     *     'urlVar'        => 'num',
     *     'urlPrepend'    => base_url() . '/page',
     *     'urlAppend'     => '/',
     *     'perPage'       => 10,
     *     'buffer'        => 4,
     *     'linkClass'     => 'paginator',
     *     'spanClass'     => 'paginator',
     *     'currentClass'  => 'pagiCurrent'
     * );
     *
     * $pager =& new SlidePager;
     * $pager->Pager($params);
     * $arr_posts = $pager->getData();
     */



    /**
     * @var integer total number of items
     * @access private
     */

    var $totalItems;

    /**
     * @var integer number of items per page
     * @access private
     */

    var $perPage        = 10;

    /**
     * @var integer number of items
     * @access private
     */

    var $buffer         = 4;

    /**
     * @var integer current (default) page number
     * @access private
     */

    var $currentPage    = 1;

    /**
     * @var integer total (default) number of pages
     * @access private
     */

    var $totalPages     = 1;

    /**
     * @var string string/file to prepend current page number
     * @access private
     */

    var $urlPrepend     = '';

    /**
     * @var string string to append current page number
     * @access private
     */

    var $urlAppend      = '';

    /**
     * @var string GET variable name which stores current page number
     * @access private
     */

    var $urlVar         = 'num';

    /**
     * @var array data to be paged
     * @access private
     */

    var $pagerData      = null;

    /**
     * @var string the finished paginator
     * @access public
     */

    var $pager          = '';

    /**
     * @var integer previous page numer
     * @access private
     */

    var $prevPage;

    /**
     * @var integer next page number
     * @access private
     */

    var $nextPage;

    /**
     *
     *
     */

    var $pagerSize;
    var $linkClass      = '';
    var $spanClass      = '';
    var $currentClass   = '';

    function Pager($options)
    {
        foreach ($options as $key => $value) {
            $this->{$key} = $value;
        }
        $this->currentPage = (isset($_REQUEST[$this->urlVar]) && $_REQUEST[$this->urlVar] != 0) ? $_REQUEST[$this->urlVar] : 1;
        $this->pagerSize = (2 * $this->buffer) + 1;
        $this->totalItems = count($this->pagerData);
        $this->totalPages = ceil($this->totalItems / $this->perPage);
        $this->prevPage = ($this->currentPage <= 1) ? NULL : $this->currentPage - 1;
        $this->nextPage = ($this->currentPage >= $this->totalPages) ? NULL : $this->currentPage + 1;
        if ($this->totalPages > 1) {
            if ($this->currentPage > 1) {
                $pagerPrev = '<a href="' . $this->urlPrepend . '1' . $this->urlAppend . '" class="' . $this->linkClass . '" title="First page">&lt;&lt;</a>';
                $pagerPrev .= '<a href="' . $this->urlPrepend . $this->prevPage . $this->urlAppend . '" class="' . $this->linkClass . '" title="Previous page (' . $this->prevPage . ')">&lt;</a>';
            }
            else {
                $pagerPrev = '<span class="' . $this->spanClass . '">&lt;&lt;</span>';
                $pagerPrev .= '<span class="' . $this->spanClass . '">&lt;</span>';
            }

            if ($this->currentPage < $this->totalPages) {
                $pagerNext = '<a href="' . $this->urlPrepend . $this->nextPage . $this->urlAppend . '" class="' . $this->linkClass . '" title="Next page (' . $this->nextPage . ')">&gt;</a>';
                $pagerNext .= '<a href="' . $this->urlPrepend . $this->totalPages . $this->urlAppend . '" class="' . $this->linkClass . '" title="Last page">&gt;&gt;</a>';
            }
            else {
                $pagerNext = '<span class="' . $this->spanClass . '">&gt;</span>';
                $pagerNext .= '<span class="' . $this->spanClass . '">&gt;&gt;</span>';
            }

            if (($this->currentPage - $this->buffer) <= 1) {
                $pagerOffset = 1;
                $pagerMax = ($this->totalPages < $this->pagerSize) ? $this->totalPages : $this->pagerSize;
            }
            elseif (($this->currentPage + $this->buffer) > $this->totalPages) {
                $pagerOffset = ((($this->totalPages - $this->pagerSize) + 1) <= 1) ? 1 : (($this->totalPages - $this->pagerSize) + 1);
                $pagerMax = (($this->pagerSize + $pagerOffset) > $this->totalPages) ? $this->totalPages : ($this->pagerSize + $pagerOffset);
            }
            else {
                $pagerOffset = (($this->currentPage + $this->buffer) > $this->totalPages) ? ($this->totalPages - ($this->pagerSize + 1)) : $this->currentPage - $this->buffer;
                $pagerMax = (($this->pagerSize + $pagerOffset) > $this->totalPages) ? $this->totalPages : (($this->pagerSize + $pagerOffset) - 1);
            }

            $pagerNumbers = '';
            for ($i = $pagerOffset; $i <= $pagerMax; $i++) {
                $pagerNumbers .= ($i == $this->currentPage) ? '<span class="' . $this->currentClass . '">' . $i . '</span>' : '<a href="' . $this->urlPrepend . $i . $this->urlAppend . '" class="' . $this->linkClass . '" title="Go to page ' . $i . '">' . $i . '</a>';
            }
            $this->pager = $pagerPrev . $pagerNext . $pagerNumbers;
        }
    }

    function GetData()
    {
        $itemsOffset = ($this->currentPage * $this->perPage) - $this->perPage;
        $itemsMax = (($itemsOffset + $this->perPage) > $this->totalItems) ? $this->totalItems : ($itemsOffset + $this->perPage);
        for ($i = $itemsOffset; $i < $itemsMax; $i++) {
            $data[] = $this->pagerData[$i];
        }
        return $data;
    }
}
?>
Categories: Code, PHP Tags: ,

function array_natsort()

<?php
/**
 * @author Brian Schmidt
 * @version 1.0
 * @return array
 * @param $arrData Array containing data to sort
 * @param $strIndex Name of column to use as an index
 * @param $strSortBy Column to sort the array by
 * @param $strSortType String containing either asc or desc [default to asc]
 * @access public
 * @desc Naturally sorts an array using the column $strSortBy
 * @example $arr_sorted = array_natsort(array(array('a' => 10, 'b' => 'foo'), array('a' => 2, 'b' => 'foo'), array('a' => 11, 'b' => 'foo')), 'a', 'a');
 */

function array_natsort($arrData, $strIndex, $strSortBy, $strSortType = FALSE)
{
    if (!is_array($arrData) || !$strIndex || !$strSortBy) {
        return $arrData;
    }
    $arrSort = $arrResult = array();
    foreach ($arrData as $arrRow) {
        $arrSort[$arrRow[$strIndex]] = $arrRow[$strSortBy];
    }
    natsort($arrSort);
    if ($strSortType == "desc") {
        arsort($arrSort);
    }
    foreach ($arrSort as $arrSortKey => $arrSorted) {
        foreach ($arrData as $arrOriginal) {
            if ($arrOriginal[$strIndex]==$arrSortKey) {
                array_push($arrResult, $arrOriginal);
            }
        }
    }
    return $arrResult;
}
?>
Categories: Code, PHP Tags: ,

function calc_age()

<?php
/**
 * @author Brian Schmidt
 * @version 1.0
 * @return array
 * @param string $str_birthday
 * @access public
 * @desc Returns the current age from a rough calculation of the birthdate.
 * @example echo calc_age('1976-12-13 19:00');
 */

function calc_age($str_birthday)
{
    if (!$str_birthday) {
        return FALSE;
    }
    $int_age = floor((time()-strtotime($str_birthday))/(60*60*24*365.22222222222));
    return $int_age;
}
?>
Categories: Code, PHP Tags: ,

function create_thumb()

<?php
/**
 * @author Brian Schmidt
 * @version 1.0
 * @return void
 * @param string $src_img
 * @param string $dst_img
 * @param integer $max_w
 * @param integer $max_h
 * @param array $bg
 * @access public
 * @uses imageCopyResampleBicubic()
 * @desc Creates a thumbnail dynamically, with correct aspect ratio.
 * @example create_thumb('old_img.png', 'new_img.png', '100', '100');
 */

function create_thumb($src_img, $dst_img, $max_w, $max_h, $bg = NULL)
{
    list($src_w, $src_h, $src_type, $src_attr) = getImageSize($src_img);
    if ($src_w > $max_w || $src_h > $max_h) {
        $ratio_w = $src_w / $max_w;
        $ratio_h = $src_h / $max_h;
        $dst_w = ($ratio_w > $ratio_h) ? $max_w : ($src_w / $ratio_h);
        $dst_h = ($ratio_w > $ratio_h) ? ($src_h / $ratio_w) : $max_h;
        $start_x = ($bg) ? (($max_w - $dst_w) / 2) : 0;
        $start_y = ($bg) ? (($max_h - $dst_h) / 2) : 0;
        switch ($src_type) {
            case 1:
                $img_src = imageCreateFromGif($src_img);
                break;
            case 2:
                $img_src = imageCreateFromJpeg($src_img);
                break;
            case 3:
                $img_src = imageCreateFromPng($src_img);
                break;
            case 6:
            default:
                $img_src = imageCreateFromGd2($src_img);
        }
        if (imageIsTrueColor($img_src)) {
            $img_dst = ($bg) ? @imageCreateTrueColor($max_w, $max_h) : @imageCreateTrueColor($dst_w, $dst_h);
        } else {
            $img_dst = ($bg) ? @imageCreate($max_w, $max_h) : @imageCreate($dst_w, $dst_h);
        }
        if ($bg) {
            $fill = imageColorAllocate($img_dst, $bg[0], $bg[1], $bg[2]);
            imageFill($img_dst, 0, 0, $fill);
        }
        imageCopyResampleBicubic($img_dst, $img_src, $start_x, $start_y, 0, 0, $dst_w, $dst_h, $src_w, $src_h);

        switch ($src_type) {
            case 1:
                imageGif($img_dst, $dst_img);
                break;
            case 2:
                imageJpeg($img_dst, $dst_img);
                break;
            case 3:
                imagePng($img_dst, $dst_img);
                break;
            case 6:
            default:
                imageGd2($img_dst, $dst_img);
        }

        imageDestroy($img_dst);
    } else {
        copy($src_img, $dst_img);
    }
}
?>
Categories: Code, PHP Tags: ,

function crypt_mail()

<?php
/**
 * @author Brian Schmidt
 * @version 1.0
 * @return string
 * @param string $mail
 * @access public
 * @desc Converts a mail address into HTML entities for simple encryption.
 * @example $str_crypted = crypt_mail('some.mail.address@example.com');
 */

function crypt_mail($mail)
{
    $i = 0;
    do {
        $char = substr($mail, $i, 1);
        $code = ord(substr($mail, $i, 1));
        if($code != "&#0") {
            $crypt .= '&#'.$code.';';
        }
        $i++;
    } while ($char != "");
    return $crypt;
}
?>
Categories: Code, PHP Tags: ,

function file_ext()

<?php
/**
 * @author Brian Schmidt
 * @version 1.0
 * @return string
 * @param $str_input
 * @access public
 * @desc returns the extension of a file
 * @example $str_extension = file_ext('image.png');
 */

function file_ext($str_input)
{
    return substr(strtolower(strrchr($str_input, '.')), 1);
}
?>
Categories: Code, PHP Tags: ,

function HTTPFetchList()

<?php
/**
 * @author  Brian Schmidt
 * @version 1.0
 * @return  array
 * @param   $url        The webpage that is to be parsed for elements
 * @param   $search     Array of search parameters
 * @access  public
 * @desc    Fetches a list/array of elements/strings from a given webpage.
 * @example
 *          $url = 'http://www.librarything.com/jswidget.php?reporton=brianman&show=recent&header=&num=200&covers=none&text=all&tag=wishlist&css=0&style=1&version=1';
 *          $search = array(
 *                  'book_url' => array(
 *                      's' => '<div class="LTitem LTodd"><a href=\"',
 *                      'e' => '\" target=\"_top\">'
 *                  ),
 *                  'book_title' => array(
 *                      's' => '<span class=\\'LTtitle\\'>',
 *                      'e' => '</span>'
 *                  ),
 *                  'author_url' => array(
 *                      's' => ' by <a href=\"',
 *                      'e' => '\" target=\"_top\">'
 *                  ),
 *                  'author_name' => array(
 *                      's' => '<span class=\\'LTauthor\\'>',
 *                      'e' => '</span>'
 *                  )
 *          );
 *          $arrayList = HTTPFetchList($url, $search);
 *          print_r($arrayList);
 */

function HTTPFetchList($url, $search)
{
    if (!class_exists('HTTP_Request')) {
        die(__FUNCTION__ . ' function requires the PEAR::HTTP_Request Class.');
    }
    $req =& new HTTP_Request('');
    $req->addHeader('User-Agent', 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)');
    $req->setURL($url);
    if (!PEAR::isError($req->sendRequest())) {
        $content  = explode("\n", $req->getResponseBody());
        foreach ($content as $line) {
            $pos1 = $pos2 = 0;
            foreach ($search as $k => $v) {
                if (stristr($line, $v['s'])) {
                    $found = TRUE;
                    $pos1 = ($pos2) ? strpos($line, $v['s'], $pos2)+strlen($v['s']) : strpos($line, $v['s'])+strlen($v['s']);
                    $pos2 = strpos($line, $v['e'], $pos1);
                    $element[$k] = stripslashes(substr($line, $pos1, $pos2-$pos1));
                }
            }
            if($found) {
                $found = FALSE;
                $elements[] = $element;
            }
        }
    }
    return $elements;
}
?>
Categories: Code, PHP Tags: ,