/home/a/aquarion/sites/www.aquarionics.com/epistula/include/library.php
All my code (That is, anything not in the "Others" list on the right) is BSD licenced.
You can also view this page as text/plain or colour-coded source
<?PHP
/*******************************************************************************
Chapter - library
********************************************************************************
Genreally useful functions
$Id: library.php,v 1.4 2004/08/17 19:59:36 aquarion Exp $
$log$
*******************************************************************************/
include($_EP['codedir']."/include/dbconnect.inc");
$db = dbconnect($_EP['Database']['name']);
include("ext-libs.inc.php");
include("class.jabber.php");
function getImageInfo($file){
#echo "<H1>".$file."</H1>";
$image['file'] = $file;
if (($_EP['Moblog']['useExif'] != false && function_exists('exif_read_data'))){
if ($exifData = exif_read_data($file, $arrays = true)){
if ($exifData['DateTime']){
$image['DateTime'] = $exifData['DateTime'];
$image['alt'] = date("r", $exifData['DateTime']);
}
if ($exifData['COMPUTED']['html']){
$image['DateTime'] = $exifData['COMPUTED']['html'];
}
if ($exifData['COMMENT']){
$image['alt'] = implode("\n", $exifData['COMMENT']);
}
print_r($exifData);
}
} else {
$image['DateTime'] = filemtime($file);
$fileinfo = getimagesize($file);
$image['html'] = $fileinfo[3];
if (file_exists($file.".caption")){
$image['alt'] = implode("\n", file($file.".caption"))
."\n".date("r", $image['DateTime']);
} else {
$image['alt'] = date("r", $image['DateTime']);
}
}
return $image;
}
function isItSpam($area, $data){
global $_EP;
$checks = array(
"#fake\ ?id#",
"#".preg_quote("http://www.endofworld.net/","#")."#",
"#".preg_quote("poker","#")."#"
);
switch ($area){
case "ip":
$checks[] = "#195.57.165.180#";
$checks[] = "#81.118.4.16#";
#$checks[] = "#62.252.64.12#";
break;
case "url":
$checks[] = "#".preg_quote("viagra","#")."#";
$checks[] = "#".preg_quote("pclol","#")."#";
$checks[] = "#".preg_quote("gangbang","#")."#";
$checks[] = "#".preg_quote("fuck","#")."#";
$checks[] = "#".preg_quote("cialis","#")."#";
$checks[] = "#".preg_quote("ripway","#")."#";
$checks[] = "#raytop#";
$checks[] = "#phentermine#";
$checks[] = "#ass(.*)\.info#";
$checks[] = "#tits(.*)\.info#";
$checks[] = "#boobs(.*)\.info#";
$checks[] = "#fuck(.*)\.info#";
$checks[] = "#xxx(.*)\.info#";
$checks[] = "#blog\.info$#";
$checks[] = "#superjordan(.*)\.info#";
$checks[] = "#tophotshow(.*)\.info#";
$checks[] = "#topzig(.*)\.info#";
}
foreach ($checks as $check){
if (preg_match($check,$data)){
return true;
}
}
}
function trigger($item, $id, $event, $url = false, $content = false){
/*------------+-------------------+
| Field | Type |
+-------------+-------------------+
| id | int(10) unsigned |
| trig_item | tinytext |
| trig_id | tinytext |
| trig_action | tinytext |
| target | tinytext |
| action | tinytext |
| created | datetime |
| triggered | datetime |
+-------------+------------------*/
$q = "select * from event where trig_action=\"".$event."\" and trig_item = \"$item\" and (trig_id = 'any' or trig_id = \"".$id."\")";
$triggers_res = safeQuery($q);
$tripwires = 0;
if(mysql_num_rows($triggers_res) != 0){
$q = "select *, UNIX_TIMESTAMP(date_created) as epoch from $item where id = $id";
$res = safeQuery($q);
$object = mysql_fetch_assoc($res);
if(mysql_num_rows($res) == 0){
return $tripwires;
}
if (!$object['title']){
$threadBang = explode("-", $object['thread_id']);
$res = safeQuery("select title from ".$threadBang[0]." where id = ".$threadBang[1]);
$ref = mysql_fetch_assoc($res);
$object['title'] = $ref['title'];
}
#print_r($object);
$link = getPermalink($item, $id, $object);
while ($trigger = mysql_fetch_assoc($triggers_res)){
$tripwires ++;
$trigger['link'] = $link;
switch ($trigger['action']){
case "email":
trigger_email($item, $id, $event, $object['title'], $trigger, $url, $content);
break;
case "jabber":
break;
case "sms":
break;
case "ping":
break;
}
$q ="update event set triggered = NOW() where id = ".$trigger['id'];
$res = safeQuery($q);
}
} // end if rows != 0
return $tripwires;
} // End function trigger
function trigger_email ($item, $itemid, $event, $title, $trigger, $url, $content ){
global $_EP;
global $page;
/* $content = 'Hello.\n\n'
.'Once upon a time, an *awfully* long time ago, when I was young and you were '
.'even younger, you (or someone with your email) requested to be sent an '
.'email whenever a new '.$event.' appeared within the realm of '
.$item.'-'.$itemid."\n\n"
.'Well, the signs are right and the time has come for a new '.$event.' to '
.'enter the world.'."\n\n"
.'The $event has been attached to "'.$title.'", you can view its fearsome '
.'magnificence at the following URL:'."\n\n"
.'<'.$trigger['link'].'>'."\n\n"
.'It\'s possible, of course, that this is all a lie and you have no idea '
.'whatever the hell I\'m talking about, in which case your best bet is '
.'probably to go to one of the following URLs:'."\n\n"
.'To delete the trigger (You\'ll never recieve an email about this '
.'event again):'."\n\n"
.$_EP['url']."/trigger/delete/".$trigger['id']."\n\n"
.'To *BAN* the address (You\'ll never recieve an email from this site'
.' again):'."\n\n"
.$_EP['url']."/trigger/ban/".$trigger['id']
."\n\n".'(Use sparingly, and only if someone is using me to spam your address. '
.'If you ever want to cause a trigger again, you\'ll have to email me to '
.'remove the ban)'; */
$email = <<<EOW
Hello. This is an email to notify you that a new %s appeared in something you've
asked to be kept updated on. This was posted:
%s
You can view or edit it at the following URL:
<%s>
To delete this trigger and not get another email about it again, please visit this link:
<%s>
To *ban* this address from ever getting another email from this website (Not a currently
reversable act without emailing the admin) please visit this URL:
<%s>
Yours faithfully,
%s <%s>
%s
EOW;
// ' // (This stops editplus going crazy)
$email = sprintf($email,
$event, $content,
$trigger['link'],
$_EP['url']."/trigger/delete/".$trigger['id'],
$_EP['url']."/trigger/ban/".$trigger['id'],
$_EP['adminname'], $_EP['admin'], $_EP['url']
);
$subject = "[E] Message re ".$title;
mail($trigger['target'], $subject, $email,
"From: epistula@aquarionics.com (Epistula)\r\n"
."X-Mailer: Epistula/" .$_EP['version']);
#echo "mail(".$trigger['target'].", $subject, $content, 'From: epistula@aquarionics.com (Epistula)\r\nX-Mailer: PHP/" . phpversion();
return true;
}
function new_trigger($trig_item, $trig_id, $trig_action, $target, $action){
if(check_trigger($target, $action)
&& check_dup_trigger($trig_item, $trig_id, $trig_action, $action, $target)){
$q = "insert into event (trig_item, trig_id, trig_action, target, action, created) values "
. "('".$trig_item."', '".$trig_id."', '".$trig_action."', '".$target."', '".$action."', NOW())";
safequery($q);
return $true;
} else {
return false;
}
}
function check_trigger($target, $action){
$q = "select id from event where trig_action = 'banned' and action = \"$action\" and target = \"$target\"";
$r = safequery($q);
if (mysql_num_rows($r) == 0){
return true;
} else {
return false;
}
}
function check_dup_trigger($item, $id, $trig_action, $action, $target){
$q = "select id from event where trig_action = '$trig_action' and action = \"$action\" and target = \"$target\" and trig_id = $id and trig_item = \"$item\"";
$r = safequery($q);
if (mysql_num_rows($r) == 0){
return true;
} else {
return false;
}
}
function pingServices(){
require_once("IXR_Library.inc.php");
global $_EP;
$return = array();
foreach ($_EP['Pings'] as $name => $ping){
// Create the client object
$ping = parse_url($ping);
switch($ping['scheme']){
case "xmlrpc-ping":
case "xmlrpc-xping":
if ($ping['port']){
$client = new IXR_Client($ping['host'], $ping['path'], $ping['port']);
} else {
$client = new IXR_Client($ping['host'], $ping['path']);
}
if ($ping['scheme'] == "xmlrpc-xping"){
$result = $client->query('weblogUpdates.extendedPing', $_EP['book'], $_EP['url'], $_EP['url'], $_EP['url']."/meta/all.rss2");
} else {
$result = $client->query('weblogUpdates.ping', $_EP['book'], $_EP['url']);
}
if (!$result) {
$return[$name] = array ($client->getErrorCode(), $client->getErrorMessage());
} else {
$return[$name] = array (0, "$name ping successful");
}
break;
default:
$return[$name] = array (1, "Don't know how to handle pings of type ".$ping['scheme']);
}
}
return $return;
}
function jabber($to,$message){
global $_EP;
$JABBER = new Jabber;
$JABBER->server = $_EP['jabber']['server'];
$JABBER->port = $_EP['jabber']['port'];
$JABBER->username = $_EP['jabber']['username'];
$JABBER->password = $_EP['jabber']['password'];
$JABBER->resource = "ClassJabberPHP";
#$JABBER->enable_logging = TRUE;
#$JABBER->log_filename = '/tmp/jabberlog.txt';
$fail = false;
if ($JABBER->Connect()){
#
} elseif ($JABBER->SendAuth()) {
#
} else {
$fail = true;
}
if (!$fail){
$JABBER->SendPresence();
#$JABBER->CruiseControl(5);
$JABBER->SendMessage($to, "chat", NULL, array ("body" => htmlspecialchars($message)));
$JABBER->Disconnect();
}
}
/************************************************************
C A T E G O R I E S
************************************************************/
/* Get the name of a category */
function catName($cat) {
$r = safequery("select name from category where id = ".$cat);
$row = mysql_fetch_assoc($r);
return $row['name'];
}
function getSubCats($id){
$cats = array($id);
$r = safequery("select id from category where parent = \"".$id."\"");
if (mysql_num_rows($r) != 0){
while($row = mysql_fetch_assoc($r)){
#$cats[] = array($row['id']);
$cats = array_merge(getSubCats($row['id']),$cats);
}
}
return $cats;
}
function getCatID($name){
$r = safequery("select * from category where name = \"".$name."\"");
if (mysql_num_rows($r) != 0){
$row = mysql_fetch_assoc($r);
} else {
die("Unknown category".$file[0].", Sorry.");
}
return $row['id'];
}
/************************************************************
C O M M E N T S
************************************************************/
function make_seed() {
list($usec, $sec) = explode(' ', microtime());
return (float) $sec + ((float) $usec * 100000);
}
/* Return all the comments for an item */
function comments_recurse($page, $thread_id, $comments){
$out = '';
foreach($comments as $comment){
if ($thread_id == $comment['attachment']."-".$comment['attach_id']){
$thiscomment = $page->comment_display($comment, $comments = $comments);#Comment output
$thiscomment .= comments_recurse($page, "comment-".$comment['id'], $comments);
$out .= $page->comment_box($thiscomment, "comment-".$comment['id']);
}
}
return $out;
}
function checkCaps($content){ // Does the submitted content have too many capital letters in it?
$arr = array();
$upper = preg_match_all("/[A-Z]/",$content,$arr);
$len = strlen($content) - preg_match_all("/\W/",$content,$arr);
if (((($upper/$len)*100) > 80) && $len > 10){
return false; // Returns false if invalid
} else {
return true; // Returns true otherwise
}
}
/* Format a comment, neatly */
function comment_format($string, $display=false, $linecheck=false, $options = array()){
global $page;
#$string = preg_replace("/\r\n\r\n/", "§\r\n\r\n", $string);
$error = array();
// Options:
// nofollow - Put "rel='nofollow'" on links.
$moretranslate = array (
array("/([\w])\'([\w])/", "$1’$2"),
array("/\W\"(.*)\"(\W)/", " “$1”$2"),
array("/\S\'(.*)\'(\S)/", " ‘$1’$2"),
array("/\[strong\](.*?)\[\/strong\]/", "<strong>$1</strong>"),
array("/\[em\](.*?)\[\/em\]/", "<em>$1</em> "),
array("/^( *)/", ""),
array("/£/", "£"),
array("/([1-9])x([1-9])/", "$1×$2"),
);
$longstring = 80;
$string = strip_tags($string, ENT_NOQUOTES);
foreach ($moretranslate as $trans){
$regex = $trans[0];
$replace = $trans[1];
$matches = array();
$string = preg_replace($regex, $replace, $string);
}
if (in_array("nofollow", $options)){
$nofollow = ' rel="nofollow"';
} else {
$nofollow = "";
}
$string = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]\"/]", "<a href=\"\\0\"".$nofollow.">\\0</a>", $string);
$string = tagifythis($string);
$string = preg_replace("/^( *)/", "", $string);
$string = preg_replace("/( *)$/", "", $string);
$string_arr = explode("\n",$string);
foreach ($string_arr as $index => $thisline){
$stringout = "";
$number = $index +1;
$thisline = trim($thisline);
if (strlen(strip_tags($thisline)) > $longstring && $linecheck){
$line = array();
foreach ($words as $wordex => $word){
$line = explode(" ",$word);
foreach ($line as $linedex => $part){
if (strlen(strip_tags($part)) > $longstring){
$error[] = "Line $number word ".($linedex+1)
." is still a little long (Lines should be shorter than $longstring chars)<br>\n";
#if (!strstr($display)){
$line[$linedex] = "<span class=\"neutralthing\">".substr($part,0,$longstring)."</span>"
. "<span class=\"badthing\">".substr($part,$longstring)."</span>";
#}
}
}
$words[$wordex] = implode($line, " ");
}
}
}
return array(process($string, "textile"), $error);
}
/************************************************************
T E X T - F O R M A T I N G
************************************************************/
/* Break a string at the nearest space to $length */
function break_string($string_to_break, $length, $highlight=false) {
/* Breaks a string at $length chars.*/
$string_to_break = strip_tags($string_to_break);
if(strlen($string_to_break)>($length + ($length/10)))
{
$string = substr($string_to_break,0,($length-1));
if($string != " ")
{
$last_space = strrpos($string, " ");
$string = substr($string_to_break,0,$last_space);
return($string."...");
} else {
$return = $string."...";
}
} else {
$return = $string_to_break;
}
if ($highlight){
preg_replace("/($highlight)/i", "<span class=\"searchword\">\\1</span>",$return);
}
return $return;
}
/************************************************************
P A R S I N G
************************************************************/
/* Return an ESF file as a two dimentional array */
function parseESF($file){
$out = array( 'entries' => array());
$handle = @fopen ($file, "r");
if (!$handle){
$out[][] = array('date' => date("U"), 'title' => "ESF Failed", 'link' => $php_errormsg);
return $out;
}
$content = false;
while (!$content && !feof ($handle)) {
$buffer = fgets($handle, 4096);
#echo $buffer;
if ($buffer == "\n") {
$content = true;
} elseif (preg_match("/^(.*?)\: (.*)$/i",$buffer,$matches)){
$out[$matches[1]] = $matches[2];
}
}
$content = "";
while (!feof ($handle)) {
$buffer = fgets($handle, 4096);
$line = explode("\t",$buffer);
if ($line[0] != ""){
$out['entries'][] = array('date' => $line[0], 'title' => $line[1], 'link' => $line[2]);
}
}
return $out;
}
/* Return my blogroll (from blo.gs and an array of people who don't ping Blo.gs) */
function blo_gs_blogroll($page){
$people = array();
global $people;
include("people.inc");
include("blogroll.inc");
$people = array_merge($people, $normals);
asort($people);
/*foreach ($people as $person){
if (empty($person['update'])){
$class = "";
$title = $person['name'];
$suffix = "";
} else {
$class = "class=\"blogroll\"";
#$suffix = "?lastUpdated=".$person['update'].".0";
$title = date("r",$person['update']);
}
$out .= "<a $class href=\"".$person['link'].$suffix."\">".$person['name']."</a><br>\n";
}*/
return $people;
}
function aquaintances_blogroll($categories){
global $_EP;
function scanFile($file){
$handle = fopen ($file, "r");
while (!feof ($handle)) {
rtrim($buffer);
$buffer = fgets($handle, 4096);
#echo $buffer;
if ($buffer != ""){
$items[] = explode("\t",$buffer);
}
}
fclose ($handle);
return $items;
}
#include("people.inc");
#include("nonrss.inc");
foreach($categories as $cat){
$people = scanFile($_EP['aquaintances']."/categories/".$cat);
foreach($people as $item){
$blogroll[] = array (
"name" => stripslashes($item[0]),
"link" => $item[1]
);
}
}
return $blogroll;
}
/************************************************************
O T H E R
************************************************************/
/** e site admin about something
*/
function mailAdmin($place, $message)
{
global $_EP;
$message .= "\n\n"
. " IP: ".$_SERVER['REMOTE_ADDR']."\n"
. "CLT: ".$_SERVER['HTTP_USER_AGENT']."\n"
. "URL: ".$_SERVER['REQUEST_URI']."\n";
mail($_EP['admin'], "[E] ".$place, $message,
"From: epistula@aquarionics.com (Epistula)\r\n"
."Reply-To: ".$_EP['admin']."\r\n"
."X-Mailer: PHP/" . phpversion());
} // end func
/************************************************************
B U I L D I N G
************************************************************/
function buildIndex($type,$display,$limit, $queryextras="", $order = "desc"){
global $page;
$output = '';
$items = getIndex($type,$display,$limit, $queryextras, $order);
$index = array();
$group = false;
$groupBy = "Y-m-d";
$groupOut = "";
foreach ($items as $item) {
$date = date($groupBy, $item['epoch']);
#echo $date."§";
if (!$group){
$group = $date;
$groupOut = "<div class=\"dateheader\">". $page->itemdate($date)."</div>\n";
} elseif ($group != $date){
$group = $date;
$output .= $groupOut;
$groupOut = "<div class=\"dateheader\">".$page->itemdate($item['date_created'])."</div>\n";
} // end grouping
$eptype = $item['epistulatype'];
$groupOut .= $page->$eptype($item);
#$output .= $page->divider();
$index[] = array('name' => $item['title'],'link' => "#".$item['epistulatype']."-".$item['id']);
}
if ($groupOut != ""){
$output .= $groupOut;
}
$page->itemindex = $index;
return $output;
} // end buildIndex.
function calendar ($data, $month, $year, $prefix, $display=false) {
$out = "";
if ($month == "date"){
$month = date(m);
}
if ($year == "date"){
$year = date(Y);
}
$weekday = date("l",mktime(0,0,0,$month,1,$year));
$firstwas = date("w",mktime(0,0,0,$month,1,$year));
$daysinmonth = date("t",mktime(0,0,0,$month,1,$year));
$weekstart=01;
$nicedate = date("F Y",mktime(0,0,0,$month,1,$year));
$out .="<table class=\"archive\">\n";
$out .="<tr><th colspan=\"7\"><a href=\"$prefix/$year/$month\">$nicedate</a></th></tr>\n";
$out .="<tr><th>S</th><th>M</th><th>T</th><th>W</th><th>T</th><th>F</th><th>S</th></tr>\n";
$rows = array();
$current = "";
for ($i=0;$i <= $firstwas-1;$i++) {
$current .="<td> </td>";
}
for ($i=1;$i<=$daysinmonth ; $i++) {
$thedate = "$year-$month-$i";
$dow = date("w",mktime(0,0,0,$month,$i,$year));
$check = 0;
if ($dow == 0 || $dow == 6) {
$style="archiveWeekend";
} else {
$style="archiveDay";
}
if ($i <= 10){
$ii = "0$i";
} else {
$ii = $i;
}
$date = "$month-$ii";
if (isset($data[$date])) {
if ($display == "local") {
$link = "#".$data[$date];
} else {
$link = $prefix."/".$year."/".$month."/".$ii;
}
$current .="<td class=\"".$style."\"><a href=\"".$link."\" class=\"bold\">".$i."</a></td>";
} else {
$current .="<td class=\"".$style."\">".$i."</td>";
}
$out .="\n";
unset($details);
if ($dow == "6") {
#$out .="<td><a href=\"index.php?from=$year-$month-$weekstart&to=$year-$month-$ii\">W</a></td></tr>\n<tr>";
$rows[] = $current;
$current = "";
$weekstart=$ii+1;
}
}
for ($i = $dow;$i <= 5;$i++) {
$current .="<td> </td>";
}
if ($current != ""){
$rows[] = $current;
}
foreach ($rows as $row){
$out .= "<tr>".$row."</tr>\n";
}
$out .="</table>";
return $out;
}
/* Build a gallery from a given directory and a gallery name*/
function gallery($relative_dir, $gallery, $linkprefix = false, $cols = 4) {
global $_EP;
$thiscol = 0;
$cols--;
$directory = $_EP['webdir']."/".$relative_dir;
if (!file_exists($directory)) {
panic("Directory ".$directory." doesn't exist");
}
$dir = opendir($directory);
if (! $dir) {
panic("Directory isn't a directory");
}
//DETABLE $output = "<table><tr>\n\t";
while($file = readdir($dir)){
if(preg_match("/.(jpg|gif|png)$/i", $file) && !preg_match("/.thumb.(jpg|gif|png)$/i", $file) && !preg_match("/^title.gif$/i", $file)){
$fn_length = strlen($file);
$fn_dot = strpos($file, ".");
$fn_name = substr ($file, 0, $fn_dot);
$fn_ext = substr ($file, ($fn_dot+1), $fn_length);
$pic_url = $relative_dir."/".$fn_name.".thumb.jpg";
$alt_pic_url = $relative_dir."/".$file.".thumb.jpg";
$pic_url = $relative_dir."/".$fn_name.".thumb.jpg";
$alt_pic_url = $relative_dir."/".$file.".thumb.jpg";
$fn_size = filesize($directory."/".$file)/102.4;
$fn_size = (int) $fn_size;
#$filetype = get_filetype($fn_ext);
$link = $gallery."/".htmlentities($file);
//DETABLE $output .= "\t<td align=\"center\">"
$output .= "\t<a href=\"".$link."\">";
$bigimage = getimagesize($directory."/".$file);
$alt = $file.", ".$bigimage[0]."*". $bigimage[1] ." <".$fn_size."k>";
if (file_exists($directory."/".$fn_name .".caption")){
$alt .= $string = strip_tags(implode("", file($directory."/".$fn_name .".caption")));
}elseif (file_exists($directory."/".$file .".caption")){
$alt .= $string = strip_tags(implode("", file($directory."/".$file .".caption")));
}
if (file_exists($_EP['webdir']."/".$pic_url)){
$image = getimagesize($_EP['webdir']."/".$pic_url);
$output .= "<img src=\"/".htmlentities($pic_url)."\" width=\"".$image[0]
."\" height=\"".$image[1]."\" class=\"thumbnail\" alt=\"$alt\" style=\"max-width: 500px\">";
}elseif (file_exists($_EP['webdir']."/".$alt_pic_url)){
$image = getimagesize($_EP['webdir']."/"