#!/usr/bin/php
<?php

/*
 * hmod IRC links. A script for generating some fancy pages of links from
 * a list of URIs in a slightly-preprocessed IRC log format.
 *
 * Copyright (c) 2007  Ted Percival <ted@midg3t.net>
 *
 * This script is free software; you can redistribute it and/or modify 
 * it under the terms of the GNU Lesser General Public License as 
 * published by the Free Software Foundation; either version 2.1 of the 
 * License, or (at your option) any later version.
 *
 * This script is provided 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 
 * Lesser General Public License for more details.
 *
 * You can receive a copy of the GNU Lesser General Public License from 
 * http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html or by writing 
 * to the Free Software Foundation, Inc., 51 Franklin Street, Fifth 
 * Floor, Boston, MA  02110-1301  USA.
 */

$textlinks "/irc-links.txt";

function 
make_irc_links($infilename$outfilename$rssfilename) {
    
$tmpfilename "$outfilename.tmp";
    
$rsstmpfilename "$rssfilename.tmp";

    
$infile fopen($infilename'r');

    
$outfile fopen($tmpfilename'w');
    
$rssfile fopen($rsstmpfilename'w');

    
$lastupd gmdate('r'filemtime($infilename));

    
fputs($outfile, <<<EOZ
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
    "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-AU">
<head>
<title>hmod IRC links</title>
<link rel="alternate" type="application/rss+xml" href="/irc-links/rss" />
<link rel="alternate" type="text/plain" href="
{$GLOBALS['textlinks']}" />
<style type="text/css">
ul  {
    list-style-type: none;
}

a   {
    color: #333AC8;
}

a img {
    border: none;
}

a:visited {
    color: #737A88;
}
body    {   
    margin-right: 5%;
    margin-left: 5%;
    border: 1px solid #D3DAE8;  
    line-height: 1.5em;
    font-family: Calibri, Arial, sans-serif;
    font-size: medium;
}

h1  {
    text-align: center;
    background: #D3DAE8;
    margin: 0;
    padding: 0.8em;
}

p {
    margin: 1em;
}

div.footer {
    border-top: 1px solid #D3DAE8;
    font-size: smaller;
    text-align: right;
}

div.footer p {
    line-height: 1;
    margin: 0.6em;
}

li  {
    line-height: 1.8em;
    text-indent: -1em;
}
li:before {
    content: "ยป "; 
    color: #9AC;
}

h2.datemarker {
    text-indent: 2em; 
    border-bottom: 1px dashed #D3DAE8;
    margin: 1.5em 1em;
    color: #679;
    font-size: inherit;
    font-weight: normal;
}
</style>
</head>

<body>

<h1><span title="#hmod on irc.enterthegame.com">hmod</span> IRC links</h1>

<p style="text-align: center;">
Possibly <acronym title="Not Safe For Work">NSFW</acronym>.
</p>

EOZ
    );

    
// Now the RSS feed
    
$lastbuilddate gmdate('r');
    
fputs($rssfile, <<<EOZ
<?xml version="1.0" encoding="utf-8" ?>
<rss version="2.0">
  <channel>
    <title>hmod IRC links</title>
    <link>http://hmodha.us/irc-links/</link>
    <description>Recent web links posted in the #hmod IRC channel</description>
    <language>en-au</language>
    <webMaster>Ted Percival &lt;te&#100;&#64;midg3t.net&gt;</webMaster>
    <ttl>240</ttl><!-- four hours -->
    <lastBuildDate>$lastbuilddate</lastBuildDate>

EOZ
    );

    
$thisday = array();
    
$guids = array();
    
$datestr '';

    while((
$line fgets($infile)) !== FALSE) {
        
$line trim($line); // remove \n
        # Based on RFC 1459 allowable nick characters
        
$line preg_replace('/<[a-zA-Z][a-zA-Z0-9-[\]\\`^{}]*>/'''$line);
        if (
strstr($line'--- Day changed') || strstr($line'--- Log opened')) {
            if (
strstr($line'--- Day changed'))
                
$line str_replace('--- Day changed '''$line);
            else 
/* Log opened, strip the time */
                
$line preg_replace(',^--- Log opened (.*) [0-2][0-9]:[0-5][0-9]:[0-5][0-9] ([0-9]*),''$1 $2'$line);

//            $line = str_replace(array('--- Day changed', '--- Log opened'), array('', ''), $line);
            
if (!strcmp($datestr$line)) /* Don't print the same date twice. */
                
continue;

            if (empty(
$thisday))
                continue; 
/* Don't print an empty section */

            
$datestr $line;

            
$line htmlspecialchars($line); // does nothing... but... in theory...
            
$line "<h2 class=\"datemarker\">$line</h2>\n<ul>\n";
            
fputs($outfile$line);
            foreach (
$thisday as $line)
                
fputs($outfile$line);
            
fputs($outfile"</ul>\n\n");
            
$thisday = array();
        } else {
            
/* Regular line */

            // RSS
            
$safeline htmlspecialchars($line);
            
//$guid = md5($line);
            
$guid $safeline;
            if (!
in_array($guid$guids)) {
                
$guids[] = $guid;
                
fputs($rssfile"    <item>\n");
                
// grab the first URI as the link and title
                
$uri strstr($line'http://') ? strstr($line'http://') : strstr($line'https://');
                
$uri strtok($uri' >');
                
$uri htmlspecialchars($uri);

                
// Parse wiki-style links for the RSS feed
                // Given:
                //   preg_match('/^([^[]*)\[([^ \]]+) ([^\]]*)](.*)$/', "[http://lwn.net/ lwn] website", $matches);
                // Will return an array containing [0] -> full match, followed by:
                //  [1]pre text [2]url [3]title [4]post text
                
if (preg_match('/^([^[]*)\[([^ \]]+) ([^\]]*)](.*)$/'$safeline$matches)) {
                    
/* Wiki-style link */
                    
$title $matches[3];
                    
//$uri  = $matches[2];
                    
$text $matches[1]. $title" &lt;$uri&gt;"$matches[4];
                    
fputs($rssfile"      <title>$uri</title>\n");
                    
fputs($rssfile"      <description>$text</description>\n");
                } else {
                    
/* Regular non-wiki link */
                    
fputs($rssfile"      <title>$uri</title>\n");
                    
fputs($rssfile"      <description>$safeline</description>\n");
                }
                
fputs($rssfile"      <link>$uri</link>\n");
                
fputs($rssfile"      <guid isPermaLink=\"false\">$guid</guid>\n");
                
fputs($rssfile"    </item>\n");
                
fputs($rssfile"\n");
            }

            
// HTML
            
$line $safeline;
            
// Square-bracket links with descriptive text, eg
            // [http://web.midg3t.net/blog/ tedp's blog]
            
$line preg_replace(',\[(https?://[^ \n]+) ([^\]]+)\],''<a href="$1">$2</a>'$line);
            
$line preg_replace(',(^|[^"])(https?://[^ \n]+),''$1<a href="$2">$2</a>'$line);
            
// Remove a possible '>' at the end of a URI for eg.
            // an original string of "<http://web.midg3t.net/blog/>"
            
$line str_replace('&gt;">http''">http'$line);
            
$line str_replace('&gt;</a>''</a>&gt;'$line);

            
$line " <li>$line</li>\n";
            
$thisday[] = $line;
        }
    }

    
// RSS
    
fputs($rssfile"  </channel>\n");
    
fputs($rssfile"</rss>\n");

    if (!empty(
$thisday)) {
        
/* The remaining items. I won't bother calculating the date. */
        
fputs($outfile" <h2 class=\"datemarker\">Older</h2>\n<ul>\n");
        foreach (
$thisday as $line)
            
fputs($outfile$line);
        
fputs($outfile"</ul>\n\n");
    }

    
fputs($outfile, <<<EOZ
<div class="footer">
<p>
Also available as an
<a href="/irc-links/rss">
 <acronym title="Really Simple Syndication">RSS</acronym> feed
 <img src="/img/feed-icon-14x14.png" style="width:14px; height:14px;" alt="" /></a>.
</p>
<p>Powered by <a href="http://hmodha.us/">hmodha.us</a>.</p>
<p>View the <a href="/irc-links/source">source</a> that generates this page.</p>
<p>Last generated $lastupd.</p>
</div>

</body>
</html>

EOZ
);

    if (
fclose($rssfile))
        
rename($rsstmpfilename$rssfilename);

    if (
fclose($outfile))
        
rename($tmpfilename$outfilename);

    return 
true;
}

$webroot '/var/www';
make_irc_links(
    
"$webroot$textlinks",
    
"$webroot/cache/hmod-irc-links.xhtml",
    
"$webroot/cache/hmod-irc-links.rss");

/* vim:ts=4:sw=4:et
 */

?>