The story: One night I was looking over some code I had written for one of the servers at work. There was a function in particular that I did not like how it was done. Then the thought struck me to search the net to see if anyone else might have tried to do the same thing. Someone had. It did not produce output quite like I wanted, but I did like how it did its thing. So I copied and modified it. Thinking the original author might like what I had done, I posted a comment to his page (it was a blog entry) with a copy of my modified version. A couple of days later he asked me if I could post my code on my site and then he link to it from my comment. Either he liked the code or thought I could make the code display better than his blog comments could. That got me to thinking: "I bet I could whip up something to handle multiple code snippets I have done". And that is what you now behold. If you use any of this, just add link back to this page in your modified source code. At least then you will have some deniabilty.
- FormatPathsAsLinks.phps
<?php
//Will convert a path string to links for each sub-folder. See the example
// for more information
//
//USAGE: string FormatPathAsLinks( string $file_path )
//RETURNS: Returns a string containing <A HREF>'s for each path part
//DEPENDANCIES: MakeLink()
//NOTES: Should be cross-platform compliant (using DIRECTORY_SEPARATOR),
// but I don't know what might happen on Windows (with "c:\")
/******************************* EXAMPLES *******************************
<?php
echo FormatPathAsLinks('/path/file.ext') . "<br />\r";
echo FormatPathAsLinks('path/file.ext') . "<br />\r";
?>
/<a href="/path">path</a>/<a href="/path/file.ext">file.ext</a>
<a href="path">path</a>/<a href="path/file.ext">file.ext</a>
***************************************************************************/
function FormatPathAsLinks($file)
{
$RelRoot = ''; //Relative to web root setup
$return = ''; //The return var
$saved_path = ''; //Path HREF save var
//Is the file relative or absolute
if (substr($file, 0, 1) == DIRECTORY_SEPARATOR)
{
//Absolute path, strip out the web document root
$file = str_replace($_SERVER['DOCUMENT_ROOT'], '', $file);
//Set the path as absolute to web root
$RelRoot = DIRECTORY_SEPARATOR;
}
//Split the file path into an array and walk it
foreach(explode(DIRECTORY_SEPARATOR, $file) AS $data)
{
//Got data? (ie ignore the first empty element if the file path was anchored at '/')
if ($data)
{
//Save this path part for further use in the linking process
$saved_path .= $RelRoot . $data;
//Add an unlinked dir sep (not present if relative) and make a link of the path so far
$return .= $RelRoot . MakeLink($saved_path, $data);
//If this is a relative path, then this will be empty. Set it to the dir sep for the next loop
if (!$RelRoot) { $RelRoot=DIRECTORY_SEPARATOR; }
}
}
//All done.
return $return;
}
?>
- IsPlural.phps
<?php
//Simple string pluralization
//
//USAGE: string IsPlural( int NumberToCheck, string SinglularFormOfWord
// [, string PluralFormOfWord ] )
//RETURNS: the plural form of a word if the NumberToCheck is not 1
//DEPENDANCIES: <none>
//NOTES: Will add an "s" to the singluar if the plural is not passed.
// Hooray for argument defaults!
function IsPlural($num, $singular, $plural=null)
{
if ($num != 1)
{
if (is_null($plural))
{ $plural = $singular . 's'; }
return $plural;
}
else
{ return $singular; }
}
?>
- MakeLink.phps
<?php
//Simple link maker from a string
//
//USAGE: string MakeLink( string $URL_HREF [, string $link_name ] )
//RETURNS: Returns a string containing an anchor HREF
//DEPENDANCIES: ToolTips javascript library (http://www.walterzorn.com/tooltip/tooltip_e.htm),
// should ignore silently if unavailable
//NOTES: If the href is a local file or directory, MakeLink will add a
// onmouseover and onmouseout javascript event for use with ToolTips
// of the file permissions, owner name and group name. This ToolTip
// behavior may become a third optional paramter or moved into another
// function.
/******************************* EXAMPLES *******************************
<?php
echo MakeLink('/path/file.ext', 'The File') . "<br />\n";
echo MakeLink('/path/file.ext') . '<br />';
?>
<a href="/path/file.ext">The File</a><br />
<a href="/path/file.ext">/path/file.ext</a><br />
***************************************************************************/
function MakeLink($href, $name=null)
{
//Add file/folder permissions using ToolTips (http://www.walterzorn.com/tooltip/tooltip_e.htm).
GLOBAL $settings;
//$settings['tooltips'] = bool; true = yes, use tooltips
if ( $settings['tooltips'] AND file_exists($href) AND ($file_perms = stat($href)) !== FALSE )
{
//File permissions
$mouse_over = substr(sprintf('%o', $file_perms['mode']), -3) . "|";
//File owner
$user = posix_getpwuid($file_perms['uid']);
$mouse_over .= $user['name'] . "|";
//File group
$group = posix_getgrgid($file_perms['gid']);
$mouse_over .= $group['name'] . "|";
//Mod time, parsed by myDate()
$mouse_over .= myDate($file_perms['mtime']);
//Ballon ToolTips
//$mouse_over = "onmouseover=\"Tip('" . $mouse_over . '\', BALLOON, true, ABOVE, true)" onmouseout="UnTip()"';
//Regular ToolTips
$mouse_over = "onmouseover=\"Tip('" . $mouse_over . '\')" onmouseout="UnTip()"';
}
if($name==null)
{ $name=$href; }
return "<a href=\"$href\" $mouse_over>$name</a>";
}
?>
- myDate.phps
<?php
//Function to create a string of elapsed time differences
//
//USAGE: string myDate( int Unix_Epoch_Seconds [, bool AllValues ] )
//RETURNS: A string of the elapsed time relative to when the function is
// called. See examples for samples.
//DEPENDENCIES: Will use IsPlural, if available to handle pluralization.
//NOTES: Does not handle future dates at all, it will break and return
// "0 seconds". $AllValues allows one to include more time differences
// in the string. Change "$AllValues=true" to "$AllValues=false" to
// modifiy the default behavior.
/******************************* EXAMPLES *******************************
<?php
$time_to_use = strtotime("-1 year -2 months -3 days");
echo date('r', $time_to_use) . "\n";
echo myDate($time_to_use) . "\n";
echo myDate($time_to_use, false) . "\n";
?>
Sample results:
Tue, 04 Dec 2007 00:18:28 -0600
1 year, 2 months, 1 week, 4 days
1 year
***************************************************************************/
function myDate( $time, $AllValues=true )
{
//The elapsed amount of time in seconds (integers only please!)
$elapsed = time() - floor($time);
//Is there any real difference?
if ($elapsed < 1) { return '0 seconds'; }
//Setup an array of all possible time differences to check against
$times = array (
12 * 30 * 24 * 60 * 60 => 'year',
30 * 24 * 60 * 60 => 'month',
07 * 24 * 60 * 60 => 'week',
24 * 60 * 60 => 'day',
60 * 60 => 'hour',
60 => 'minute',
1 => 'second' );
//Setup a return string
$returned = '';
//Loop through all of the time "constants"
foreach ($times AS $seconds => $string)
{
//Get the difference
$difference = floor($elapsed / $seconds);
//Is there an actual (positive) difference?
if ($difference >= 1)
{
//Add this difference to the return string. Will use a
// pluralization sub-function if available. Modify as desired.
if (function_exists('IsPlural'))
{ $returned .= " $difference " . IsPlural($difference, $string) . ","; }
else
{ $returned .= " $difference $string" . ($difference > 1 ? 's' : '') . ','; }
//Should we continue adding all possible differences?
if (!$AllValues) { break; }
//Subtract this difference from the total elapsed for the next loop
$elapsed -= $difference * $seconds;
}
}
//Strip the first space and final comma from the string before returning it
return substr($returned, 1, -1) . ' ago';
}
?>
- phpBB_GetForumPosts.phps
<?php
/**********************************************************************
Author - Jason Kull
Date - 2011 05 06
About - An include script wrapper for simplifing access to a
phpBB forums. This script handles including all the necessary
phpBB files and the custom functions file
(phpBB_GetForumPosts.functions) AND starts up session
management for simple user read access authentication.
Notes - The file extension of this file MUST BE the same as the
extension of the forum files (usually php). YOU HAVE BEEN
WARNED!
**********************************************************************/
/**********************************************************************
phpBB stuff
**********************************************************************/
define('IN_PHPBB', true);
$phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : $_SERVER['DOCUMENT_ROOT'] . './forums/';
$phpEx = substr(strrchr(__FILE__, '.'), 1);
require_once($phpbb_root_path . 'common.' . $phpEx);
require_once($phpbb_root_path . 'includes/bbcode.' . $phpEx);
require_once($phpbb_root_path . 'includes/functions_display.' . $phpEx);
/**********************************************************************
phpBB session management
**********************************************************************/
$user->session_begin();
$auth->acl($user->data);
$user->setup('viewforum');
/**********************************************************************
Custom functions for simplier access to phpBB forum posts
**********************************************************************/
require_once('phpBB_GetForumPosts.functions');
/**********************************************************************
END OF FILE
**********************************************************************/
?>
- phpBB_GetForumPosts.functions
<?php
/**********************************************************************
Author - Jason Kull
Date - 2011 05 06
About - Some functions to make access a forum db from elsewhere
on a site easier. These functions are tuned specifically for phpBB,
but could be altered for other forum dbs.
**********************************************************************/
/************************************************
GetPosts()
************************************************/
//Get a bunch of forum posts as an array
//
//USAGE: mixed GetPosts( object $phpBB_auth, object $phpBB_db, int $max_posts, mixed $forum_ids)
//RETURNS: On success, returns an array of forum posts the user in $phpBB_auth can read. Returns
// null on failure.
//DEPENDANCIES:
// $phpBB_auth class object from phpBB's includes.
// $phpBB_db class object from phpBB's includes.
// CheckForumIDs() for input validation and user verification
// BuildQuery() for SQL abstraction.
//NOTES: $forum_ids can be empty, in which case it will return ALL forums the user has read
// access to. It can also be an integer for a single forum id. And lastly, it can be an
// array of integers for multiple forums. All forum IDs are check for read access
// by $phpBB_auth. If forum ids are passed, then the posts limit is required. A secondary
// function could be written with the input's swapped and passed off to this one if desired.
//
function GetPosts($auth, $db, $limit=5, $forum_ids="")
{
//Input validation and user access verification
$forum_ids = CheckForumIDs($auth, $forum_ids);
//SQL query abstraction
$query = BuildQuery($forum_ids);
//var setup
$id = null;
//Query and loop results
$result = $db->sql_query_limit($query, $limit);
while( $row = $db->sql_fetchrow($result) )
{
//Get a (should be) unique key for this post. May also come in handy some day.
$id = "{$row['forum_id']}_{$row['topic_id']}_{$row['post_id']}";
//Add this row into an array of all posts
$posts[$id] = $row;
//Parse the forum bbcode into HTML
$posts[$id]['body'] = nl2br($row['post_text']);
$bbcode = new bbcode(base64_encode($bbcode_bitfield));
$bbcode->bbcode_second_pass($posts[$id]['body'], $row['bbcode_uid'], $row['bbcode_bitfield']);
$posts[$id]['body'] = smiley_text($posts[$id]['body']);
//Make some handy links. These will need the correct path prepended later.
$posts[$id]['linkToAuthor'] = "memberlist.php?mode=viewprofile&u={$posts[$id]['user_id']}";
$posts[$id]['linkToPost'] = "viewtopic.php?f={$posts[$id]['forum_id']}&t={$posts[$id]['topic_id']}#p{$posts[$id]['post_id']}";
$posts[$id]['linkToTopic'] = "viewtopic.php?f={$posts[$id]['forum_id']}&t={$posts[$id]['topic_id']}";
$posts[$id]['linkToForum'] = "viewforum.php?f={$posts[$id]['forum_id']}";
}
//All done, return stuff
return $posts;
}
/************************************************
CheckForumIDs()
************************************************/
//Check if an array of phpBB forum IDs can be read by a user
//
//USAGE: array CheckForumIDs( object $phpBB_auth [, array $forum_ids ] )
//RETURNS: An array of forum ids the authenticated user has read access to.
//DEPENDANCIES: The phpBB class $phpBB_auth
//NOTES: The returned array can be empty!
//
function CheckForumIDs($auth, $forum_ids=null)
{
// Get a list of all forums the user has permissions to read
$auth_f_read = array_keys($auth->acl_getf('f_read', true));
//Input verification
if ( is_array($forum_ids) AND count($forum_ids>0) )
{
//Input is an array. Return only those passed the user has read access to.
return array_intersect($forum_ids, $auth_f_read);
}
elseif ( is_int($forum_ids) AND $forum_ids>0 )
{
//Input is a single forum id. Trick it into an array and check it
return array_intersect(array($forum_ids), $auth_f_read);
}
else
{
//Invalid input OR null. Return all ids accessable
return $auth_f_read;
}
}
/************************************************
BuildQuery()
************************************************/
//Pseudo SQL abstraction query
//
//USAGE: string BuildQuery( array $forum_ids )
//RETURNS: MySQL query for selecting posts in forums with passed ID(s)
//DEPENDANCIES:
//NOTES: Just moving the actual SQL query away from code logic.
//
function BuildQuery($forum_ids)
{
//Modifiy as necessary for the forum used.
return "
SELECT
p.forum_id,
p.post_id,
p.poster_id,
p.post_time,
p.post_approved,
p.post_subject,
p.post_text,
p.bbcode_bitfield,
p.bbcode_uid,
p.topic_id,
t.topic_approved,
t.topic_title,
t.topic_poster,
t.topic_time,
t.topic_time_limit,
t.topic_views,
t.topic_replies,
t.topic_replies_real,
t.topic_status,
t.topic_type,
t.topic_first_post_id,
t.topic_first_poster_name,
t.topic_last_post_id,
t.topic_last_poster_id,
t.topic_last_poster_name,
t.topic_last_post_time,
t.topic_last_view_time,
u.user_id,
u.group_id,
u.username,
u.user_email,
u.user_lastpost_time,
u.user_rank,
u.user_allow_viewemail,
u.user_avatar,
u.user_avatar_type,
u.user_avatar_width,
u.user_avatar_height,
u.user_icq,
u.user_aim,
u.user_yim,
u.user_msnm,
u.user_jabber,
u.user_website,
g.group_type,
g.group_name,
g.group_desc,
g.group_desc_bitfield,
g.group_desc_options,
g.group_desc_uid,
g.group_display,
g.group_avatar,
g.group_avatar_type,
g.group_avatar_width,
g.group_avatar_height,
g.group_rank,
g.group_colour,
f.parent_id,
f.forum_name,
f.forum_desc,
f.forum_type,
f.forum_status,
f.forum_posts,
f.forum_topics,
f.forum_topics_real,
f.forum_last_post_id,
f.forum_last_poster_id,
f.forum_last_post_subject,
f.forum_last_post_time,
f.forum_last_poster_name,
f.forum_options
FROM
" . POSTS_TABLE . " AS p
LEFT JOIN " . TOPICS_TABLE . " AS t
ON p.topic_id = t.topic_id
LEFT JOIN " . FORUMS_TABLE . " AS f
ON p.forum_id = f.forum_id
LEFT JOIN " . USERS_TABLE . " AS u
ON u.user_id = p.poster_id
LEFT JOIN " . GROUPS_TABLE . " AS g
ON u.group_id = g.group_id
WHERE
p.forum_id IN (" . implode($forum_ids, ',') . ")
AND t.topic_status <> " . ITEM_MOVED . "
AND t.topic_approved = 1
ORDER BY p.post_id DESC";
}
/************************************************
END OF FUNCTIONS
************************************************/
?>
- SelectTextOf.js
//Another text box contents selection script.
//
//USAGE: bool SelectTextOf( object TheObjectWithContentsToSelect )
//RETURNS: Returns true on success, false on failure
//DEPENDANCIES: none
//NOTES: I lightly searched for text box javascript selector scripts. Those
// I found all were hard-coded to select the contents of 1 element. This
// irked me. The selecting function should work for more than just one
// element. So I built this guy.
/******************************* EXAMPLES *******************************
<textarea onClick="SelectTextOf(this);">Some text to select</textarea>
***************************************************************************/
function SelectTextOf(PassedObj)
{
try
{
PassedObj.focus();
PassedObj.select();
return true;
}
catch(ErrorObj)
{
return false;
}
}
