Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • osian/sucs-site
  • kais58/sucs-site
  • imranh/sucs-site
  • foshjedi2004/sucs-site
  • gigosaurus/sucs-site
  • matstn/sucs-site
  • ripp_/sucs-site
  • eggnog/sucs-site
  • sucssite/sucs-site
  • elbows/sucs-site
  • realitykiller/sucs-site
  • crox/sucs-site
  • vectre/sucs-site
  • welshbyte/sucs-site
  • paperclipman/sucs-site
15 results
Show changes
Showing
with 1617 additions and 1698 deletions
...@@ -9,22 +9,22 @@ $cal = new vcalendar(); ...@@ -9,22 +9,22 @@ $cal = new vcalendar();
$cal->setConfig('unique_id', 'sucs.org'); $cal->setConfig('unique_id', 'sucs.org');
$cal->setProperty('method', 'PUBLISH'); $cal->setProperty('method', 'PUBLISH');
$cal->setProperty('x-wr-calname', "SUCS Events Calendar"); $cal->setProperty('x-wr-calname', "SUCS Events Calendar");
$cal->setProperty('X-WR-CALDESC', $cal->setProperty('X-WR-CALDESC',
"Upcoming events for members of the Swansea University Computer Society"); "Upcoming events for members of the Swansea University Computer Society");
$cal->setProperty('X-WR-TIMEZONE', 'Europe/London'); $cal->setProperty('X-WR-TIMEZONE', 'Europe/London');
//populate with upcoming events //populate with upcoming events
$events = $DB->GetAll("SELECT * FROM events WHERE $events = $DB->GetAll("SELECT * FROM events WHERE
date_trunc('day', whn) >= date_trunc('day', NOW()) ORDER BY whn ASC"); date_trunc('day', whn) >= date_trunc('day', NOW()) ORDER BY whn ASC");
foreach($events as $event) { foreach ($events as $event) {
$vevent = new vevent(); $vevent = new vevent();
$vevent->setProperty('dtstart', $event['whn']); $vevent->setProperty('dtstart', $event['whn']);
$vevent->setProperty('LOCATION', $event['location']); $vevent->setProperty('LOCATION', $event['location']);
$vevent->setProperty('summary', $event['name']); $vevent->setProperty('summary', $event['name']);
$vevent->setProperty('description', $event['description']); $vevent->setProperty('description', $event['description']);
$vevent->setProperty('categories', $event['category']); $vevent->setProperty('categories', $event['category']);
$cal -> setComponent($vevent); $cal->setComponent($vevent);
} }
//spit out a shiny new iCal file //spit out a shiny new iCal file
......
<?php
// Forum integration component
$punbb_base = "$base/lib/punbb";
// Attempt to divine which punbb file is wanted
$file_index = array_search("Forum", $pathlist) + 1;
if ($pathlist[$file_index] == "") {
$punbb_file = "index.php";
} else {
$punbb_file = $pathlist[$file_index];
}
// Stick relevant get parameters somewhere where the template can get them
// This is to cure problems with the login form eating essential get params
// Done here instead of site-wide to limit potential for an XSS vulnerabilityy
// (it occurs though that this could be solved using session data rather than writing GET params)
$gets = array();
if (isset($_GET['id']))
$gets['id'] = intval($_GET['id']);
if (isset($_GET['p']))
$gets['p'] = intval($_GET['p']);
$smarty->assign("gets", $gets);
// move to the punbb directory and start buffering
$oldcwd = getcwd();
chdir($punbb_base);
ob_start();
// include the wanted punbb file
try {
include($punbb_base."/".$punbb_file);
} catch (Exception $e) {
// do nothing. This is practically expected as our punbb throws exceptions when it's done rendering
// this sounds nasty, but it's better than calling exit() like the stock punbb does ;-)
}
// stop buffering, move back to where we were
$page = ob_get_contents();
ob_clean();
chdir($oldcwd);
// if this is for syndication purposes or the punbb installer, we don't want a template
if ($punbb_file == "extern.php" || $punbb_file == "install.php") {
$no_template = TRUE;
echo $page;
} else {
// make the breadcrumbs tastier
$pathlist = array_slice($pathlist, 0, $file_index);
$smarty->assign("title", "Forum");
$smarty->assign("extra_styles", "$baseurl/css/forum/SUCS.css");
$smarty->assign("rss_url", "/Community/Forum/extern.php?action=active&amp;type=rss");
$smarty->assign("body", $page);
}
?>
<?php
unset($result);
//require_once("/usr/share/adodb/adodb.inc.php");
require_once("/usr/share/php/adodb/adodb.inc.php");
$ForumDB = NewADOConnection('postgres8');
$ForumDB->Connect('dbname=punbb user=apache');
$ForumDB->SetFetchMode(ADODB_FETCH_ASSOC);
$posts = $ForumDB->GetAll('SELECT t.subject, t.last_poster, t.last_post_id FROM topics AS t INNER JOIN forums AS f ON f.id=t.forum_id LEFT JOIN forum_perms AS fp ON (fp.forum_id=f.id AND fp.group_id=4) WHERE (fp.read_forum IS NULL OR fp.read_forum=1) ORDER BY t.last_post DESC LIMIT 5');
$smarty->assign('posts', $posts);
$result = $smarty->fetch('forumposts.tpl');
?>
<?php <?php
$smarty->assign("news",$DB->GetArray("(SELECT * FROM news WHERE expiry > now() ORDER BY date DESC LIMIT 3) UNION SELECT * FROM news WHERE sticky=true and expiry > now() ORDER BY date DESC")); $smarty->assign("news", $DB->GetArray("(SELECT * FROM news WHERE expiry > now() ORDER BY date DESC LIMIT 3) UNION SELECT * FROM news WHERE sticky=true and expiry > now() ORDER BY date DESC"));
$output = $smarty->fetch("front.tpl"); $output = $smarty->fetch("front.tpl");
$smarty->assign("title", "Home"); $smarty->assign("title", "Home");
$smarty->assign("body", $output); $smarty->assign("body", $output);
if (!$session->loggedin) { if (!$session->loggedin) {
$output = file_get_contents("../static/fragments/Join.txt"); $output = file_get_contents("../static/fragments/Join.txt");
} else { } else {
// $output = "<div class=\"cbb\"><h3>You are logged in</h3><p>If you would like to contribute to the site or report a bug, please contact chckens or dez.</p></div>"; $output = "<div class=\"cbb\"><h3>You are logged in</h3><p>If you would like to contribute to the site or report a bug, please contact imranh.</p></div>";
$output = "<div class=\"cbb\"><h3>You are logged in</h3><p style=\"text-align: center;\">Why not join our <a href=\"#\" onclick=\"window.open('/mw/','Milliways','height=600,width=800,menubar=no,resizable=yes,location=no,directories=no,scrollbars=yes,status=no,toolbar=no')\" style=\"font-size: 150%; font-weight: bold; color: #ffc62b;\">Live Chat</a>?</p></div>"; $output = "<div class=\"cbb\"><h3>You are logged in</h3><p style=\"text-align: center;\">Why not join our <a href=\"https://chat.sucs.org\" target=\"_blank\">Live Chat</a>?</p></div>";
//include('users.php'); //include('users.php');
//$output .= $result; //$output .= $result;
include('electionreminder.php'); include('electionreminder.php');
$output .= $result; $output .= $result;
include('planetposts.php');
$output .= $result;
include('forumposts.php');
$output .= $result;
} }
$output .= "<div class=\"cbb\"><h3>SUCS Tools</h3><p>Download the SUCS Tools to make it easier to access SUCS services from your computer.</p><ul><li><a href=\"/files/sucstools-latest.exe\">SUCS Tools for Windows</a></li><li><a href=\"/files/SUCS-latest.dmg\">SUCS Tools for Mac OS X</a></li></ul><p>More information about the tools is available in \"<a href=\"/Knowledge/Help/SUCS%20Services/Using%20the%20SUCS%20Tools\">Using the SUCS Tools</a>\".</p></div>"; $output .= "<div class=\"cbb\"><h3>SUCS Tools</h3><p>Download the SUCS Tools to make it easier to access SUCS services from your computer.</p><ul><li><a href=\"/files/sucstools-latest.exe\">SUCS Tools for Windows</a></li><li><a href=\"/files/SUCS-latest.dmg\">SUCS Tools for Mac OS X</a></li></ul><p>More information about the tools is available in \"<a href=\"/Knowledge/Help/SUCS%20Services/Using%20the%20SUCS%20Tools\">Using the SUCS Tools</a>\".</p></div>";
$smarty->assign("secondary",$output); $smarty->assign("secondary", $output);
?> ?>
...@@ -9,5 +9,5 @@ $smarty->assign("title", "Games"); ...@@ -9,5 +9,5 @@ $smarty->assign("title", "Games");
$smarty->assign("body", $output); $smarty->assign("body", $output);
$output = file_get_contents("../static/fragments/Games-secondary.txt"); $output = file_get_contents("../static/fragments/Games-secondary.txt");
$smarty->assign("secondary",$output); $smarty->assign("secondary", $output);
?> ?>
<? <?php
$out = exec("/usr/bin/id"); $out = exec("/usr/bin/id");
$smarty->assign("body",$out); $smarty->assign("body", $out);
?> ?>
...@@ -4,196 +4,187 @@ ...@@ -4,196 +4,187 @@
$mode = "list"; $mode = "list";
$admin = false; $admin = false;
$admin_group="sucsstaff"; $admin_group = "sucsstaff";
// who's notified of items being requested? // who's notified of items being requested?
$junk_contact="admin@sucs.org"; $junk_contact = "admin@sucs.org";
$admin = isset($session->groups[$admin_group]); $admin = isset($session->groups[$admin_group]);
// If you're an admin and the path ends in Edit/ then a number put it into edit mode // If you're an admin and the path ends in Edit/ then a number put it into edit mode
// create canedit rules // create canedit rules
$canedit=isset($pathlist[($component[depth]/2)+1]); $canedit = isset($pathlist[($component[depth] / 2) + 1]);
$canedit=$canedit && isset($pathlist[($component[depth]/2)+2]); $canedit = $canedit && isset($pathlist[($component[depth] / 2) + 2]);
$canedit=$canedit && $pathlist[($component[depth]/2)+1]=='Edit'; $canedit = $canedit && $pathlist[($component[depth] / 2) + 1] == 'Edit';
$canedit=$canedit && is_numeric($pathlist[($component[depth]/2)+2]); $canedit = $canedit && is_numeric($pathlist[($component[depth] / 2) + 2]);
$canedit=$canedit && $admin; $canedit = $canedit && $admin;
// Apply canedit rules // Apply canedit rules
if ($canedit){ if ($canedit) {
$id = $pathlist[($component[depth]/2)+2]; $id = $pathlist[($component[depth] / 2) + 2];
$items = $DB->GetAll("SELECT id, title, category, description, donated_by, status FROM inventory WHERE id=? AND requested_by IS NULL",$id); $items = $DB->GetAll("SELECT id, title, category, description, donated_by, status FROM inventory WHERE id=? AND requested_by IS NULL", $id);
if(sizeof($items) === 1){ if (sizeof($items) === 1) {
$item = $items[0]; $item = $items[0];
$smarty->assign("item", $item); $smarty->assign("item", $item);
$mode = "edit"; $mode = "edit";
} }
} }
// If you're an admin and the path ends in Add put it into add mode // If you're an admin and the path ends in Add put it into add mode
// create canadd rules // create canadd rules
$canadd=isset($pathlist[($component[depth]/2)+1]); $canadd = isset($pathlist[($component[depth] / 2) + 1]);
$canadd=$canadd && $pathlist[($component[depth]/2)+1]=='Add'; $canadd = $canadd && $pathlist[($component[depth] / 2) + 1] == 'Add';
$canadd=$canadd && $admin; $canadd = $canadd && $admin;
// Apply canadd rules // Apply canadd rules
if ($canadd){$mode = "add";} if ($canadd) {
$mode = "add";
}
// Process actions before retrieving the data // Process actions before retrieving the data
// List request data // List request data
if ($session->loggedin && isset($_REQUEST['action'])) { if ($session->loggedin && isset($_REQUEST['action'])) {
// Junk Requests // Junk Requests
if ($_REQUEST['action'] == "Request") { if ($_REQUEST['action'] == "Request") {
// Request Item if its available // Request Item if its available
$query = "UPDATE inventory SET requested_by=?, requested_on=now() WHERE id=? AND requested_by IS NULL"; $query = "UPDATE inventory SET requested_by=?, requested_on=now() WHERE id=? AND requested_by IS NULL";
$DB->Query($query, array($session->username, $_REQUEST['item'])); $DB->Query($query, array($session->username, $_REQUEST['item']));
// mail someone so we know that this has been requested // mail someone so we know that this has been requested
$iteminfo = $DB->GetRow("SELECT title, description FROM inventory WHERE id=?", array($_REQUEST['item'])); $iteminfo = $DB->GetRow("SELECT title, description FROM inventory WHERE id=?", array($_REQUEST['item']));
$msgbody = "User {$session->username} has requested the junk item:\n\n"; $msgbody = "User {$session->username} has requested the junk item:\n\n";
$msgbody .= "{$iteminfo['title']}: {$iteminfo['description']}\n\n"; $msgbody .= "{$iteminfo['title']}: {$iteminfo['description']}\n\n";
$msgbody .= "Please ensure this is taken away and never brought back."; $msgbody .= "Please ensure this is taken away and never brought back.";
mail($junk_contact,"Junk item requested",$msgbody); mail($junk_contact, "Junk item requested", $msgbody);
} elseif ($_REQUEST['action'] == "Un-Request") {
// Un-Request Item
if ($admin) {
// if you're admin just do it
$query = "UPDATE inventory SET requested_by=null, requested_on=null WHERE id=?";
$array = array($_REQUEST['item']);
} else {
// if not admin check if you requested it first
$query = "UPDATE inventory SET requested_by=null, requested_on=null WHERE id=? AND requested_by=?";
$array = array($_REQUEST['item'], $session->username);
}
$DB->Query($query, $array);
} elseif ($_REQUEST['action'] == "Take" && $admin) {
// Take item, if you're admin
$query = "UPDATE inventory SET taken_on=now() WHERE id=? AND requested_by IS NOT NULL";
$DB->Query($query, $_REQUEST['item']);
} elseif ($_REQUEST['action'] == "Remove" && $admin) {
// Remove item, if you're admin
$query = "DELETE FROM inventory WHERE id=?";
if ($DB->Query($query, $_REQUEST['item'])) {
message_flash("Item removed");
} else {
trigger_error("Failed to remove item");
} }
elseif ($_REQUEST['action'] == "Un-Request") { } elseif ($_REQUEST['action'] == "Not Junk" && $admin) {
// Un-Request Item // Mark item as not junk if it's not been requested and you're admin
if ($admin){ $query = "UPDATE inventory SET status='unknown' WHERE id=? AND requested_by IS NULL";
// if you're admin just do it $DB->Query($query, $_REQUEST['item']);
$query = "UPDATE inventory SET requested_by=null, requested_on=null WHERE id=?"; } elseif ($_REQUEST['action'] == "Junk" && $admin) {
$array = array($_REQUEST['item']); // Mark item as junk, if you're admin
} $query = "UPDATE inventory SET status='junk' WHERE id=?";
else{ $DB->Query($query, $_REQUEST['item']);
// if not admin check if you requested it first }
$query = "UPDATE inventory SET requested_by=null, requested_on=null WHERE id=? AND requested_by=?";
$array = array($_REQUEST['item'], $session->username);
}
$DB->Query($query, $array);
}
elseif ($_REQUEST['action'] == "Take" && $admin){
// Take item, if you're admin
$query = "UPDATE inventory SET taken_on=now() WHERE id=? AND requested_by IS NOT NULL";
$DB->Query($query, $_REQUEST['item']);
}
elseif ($_REQUEST['action'] == "Remove" && $admin){
// Remove item, if you're admin
$query = "DELETE FROM inventory WHERE id=?";
if ($DB->Query($query, $_REQUEST['item'])) {
message_flash("Item removed");
} else {
trigger_error("Failed to remove item");
}
}
elseif ($_REQUEST['action'] == "Not Junk" && $admin){
// Mark item as not junk if it's not been requested and you're admin
$query = "UPDATE inventory SET status='unknown' WHERE id=? AND requested_by IS NULL";
$DB->Query($query, $_REQUEST['item']);
}
elseif ($_REQUEST['action'] =="Junk" && $admin){
// Mark item as junk, if you're admin
$query = "UPDATE inventory SET status='junk' WHERE id=?";
$DB->Query($query, $_REQUEST['item']);
}
} }
// Update/Add item // Update/Add item
if ($session->loggedin && $admin && (isset($_REQUEST['update']) || isset($_REQUEST['add']))) { if ($session->loggedin && $admin && (isset($_REQUEST['update']) || isset($_REQUEST['add']))) {
// try to guess which category field the user meant us to see // try to guess which category field the user meant us to see
// ideally we'd use an html combo box, but since they don't exist... // ideally we'd use an html combo box, but since they don't exist...
if ($_REQUEST['categorymenu'] == "") { if ($_REQUEST['categorymenu'] == "") {
$category = $_REQUEST['category']; $category = $_REQUEST['category'];
} else { } else {
$category = $_REQUEST['categorymenu']; $category = $_REQUEST['categorymenu'];
} }
// Update/Add item if title and category are filled in else error // Update/Add item if title and category are filled in else error
if ($_REQUEST['title'] != "" && $category != "") { if ($_REQUEST['title'] != "" && $category != "") {
// if the description is blank, return null // if the description is blank, return null
if ($_REQUEST['description'] == ""){ if ($_REQUEST['description'] == "") {
$description = null; $description = null;
} } else {
else{ $description = $_REQUEST['description'];
$description = $_REQUEST['description']; }
} // if the donated_by is blank, return null
// if the donated_by is blank, return null if ($_REQUEST['donated_by'] == "") {
if ($_REQUEST['donated_by'] == ""){ $donated_by = null;
$donated_by = null; } else {
} $donated_by = $_REQUEST['donated_by'];
else{ }
$donated_by = $_REQUEST['donated_by']; // run the query
} if (isset($_REQUEST['update'])) {
// run the query $query = "UPDATE inventory SET title=?, category=?, description=?, donated_by=?, status=? WHERE id=?";
if(isset($_REQUEST['update'])){ $array = array($_REQUEST['title'], $category, $description, $donated_by, $_REQUEST['status'], $_REQUEST['id']);
$query = "UPDATE inventory SET title=?, category=?, description=?, donated_by=?, status=? WHERE id=?"; if ($DB->Query($query, $array)) {
$array = array($_REQUEST['title'], $category, $description, $donated_by, $_REQUEST['status'], $_REQUEST['id']); message_flash("Item Updated");
if ($DB->Query($query, $array)) { } else {
message_flash("Item Updated"); trigger_error("Item update failed :-(", E_USER_ERROR);
} else { }
trigger_error("Item update failed :-(", E_USER_ERROR); } elseif (isset($_REQUEST['add'])) {
} $query = "INSERT INTO inventory (title, category, description, donated_by, status) VALUES (?, ?, ?, ?, ?)";
} $array = array($_REQUEST['title'], $category, $description, $donated_by, $_REQUEST['status']);
elseif(isset($_REQUEST['add'])){ if ($DB->Query($query, $array)) {
$query = "INSERT INTO inventory (title, category, description, donated_by, status) VALUES (?, ?, ?, ?, ?)"; message_flash("Item Added");
$array = array($_REQUEST['title'], $category, $description, $donated_by, $_REQUEST['status']); } else {
if ($DB->Query($query, $array)) { trigger_error("Adding item failed :-( - " . $DB->ErrorMsg(), E_USER_ERROR);
message_flash("Item Added"); }
} else { }
trigger_error("Adding item failed :-( - ".$DB->ErrorMsg(), E_USER_ERROR); } else {
} trigger_error("Required field(s) missing", E_USER_WARNING);
} }
}
else{
trigger_error("Required field(s) missing", E_USER_WARNING);
}
} }
// Remove old taken junk // Remove old taken junk
$DB->Query("DELETE FROM inventory WHERE (taken_on + interval'7 days') < now()"); $DB->Query("DELETE FROM inventory WHERE (taken_on + interval'7 days') < now()");
if ($mode == 'list'){ if ($mode == 'list') {
// Get junk from database, and give admin the full list // Get junk from database, and give admin the full list
if ($admin == true){ if ($admin == true) {
$junk = $DB->GetAll("SELECT * FROM inventory ORDER BY category, title, id"); $junk = $DB->GetAll("SELECT * FROM inventory ORDER BY category, title, id");
} } else {
else{ $junk = $DB->GetAll("SELECT * FROM inventory WHERE status = 'junk' ORDER BY category, title, id");
$junk = $DB->GetAll("SELECT * FROM inventory WHERE status = 'junk' ORDER BY category, title, id"); }
} //
// // Check there is some junk
// Check there is some junk if (sizeof($junk) < 1) {
if (sizeof($junk) < 1) { $mode = "nojunk";
$mode = "nojunk"; } else {
} else {
// group the junk by status then by category
// group the junk by status then by category foreach ($junk as $junkitem) {
foreach($junk as $junkitem) { if ($junkitem['status'] != 'junk') {
if ($junkitem['status'] != 'junk') { $status = "unknown";
$status = "unknown"; } else if ($junkitem['requested_by'] == null) {
} else if ($junkitem['requested_by'] == null) { $status = "available";
$status = "available"; } else if ($junkitem['taken_on'] == null) {
} else if ($junkitem['taken_on'] == null) { $status = "requested";
$status = "requested"; } else {
} else { $status = "taken";
$status = "taken"; }
}
$sortedjunk[$status][$junkitem['category']][] = $junkitem;
$sortedjunk[$status][$junkitem['category']][] = $junkitem; }
} $smarty->assign("junk", $sortedjunk);
$smarty->assign("junk", $sortedjunk); }
}
} else { } else {
$categories = $DB->GetCol("SELECT DISTINCT category FROM inventory ORDER BY category ASC"); $categories = $DB->GetCol("SELECT DISTINCT category FROM inventory ORDER BY category ASC");
$smarty->assign("categories", $categories); $smarty->assign("categories", $categories);
} }
// Generate output // Generate output
$smarty->assign("statuses",array("unknown", "in use", "wanted", "junk")); $smarty->assign("statuses", array("unknown", "in use", "wanted", "junk"));
$smarty->assign("componentpath", $baseurl . $component[path]); $smarty->assign("componentpath", $baseurl . $component[path]);
$smarty->assign("mode", $mode); $smarty->assign("mode", $mode);
$smarty->assign("admin", $admin); $smarty->assign("admin", $admin);
$output = $smarty->fetch("junk.tpl"); $output = $smarty->fetch("junk.tpl");
$smarty->assign("title", "Junk List"); $smarty->assign("title", "Junk List");
$smarty->assign("body", $output); $smarty->assign("body", $output);
......
...@@ -9,171 +9,178 @@ $librarian_mail = "librarian@sucs.org"; ...@@ -9,171 +9,178 @@ $librarian_mail = "librarian@sucs.org";
// don't try to convert existing html entities // don't try to convert existing html entities
// this could be broken out someplace else // this could be broken out someplace else
function htmlentities2($myHTML) { function htmlentities2($myHTML)
$translation_table=get_html_translation_table (HTML_ENTITIES,ENT_QUOTES); {
$translation_table[chr(38)] = '&'; $translation_table = get_html_translation_table(HTML_ENTITIES, ENT_QUOTES);
return preg_replace("/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/","&amp;" , strtr($myHTML, $translation_table)); $translation_table[chr(38)] = '&';
return preg_replace("/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/", "&amp;", strtr($myHTML, $translation_table));
} }
$library_index = array_search("Library", $pathlist); $library_index = array_search("Library", $pathlist);
if (isset($session->groups[$permission])) { if (isset($session->groups[$permission])) {
$smarty->assign("librarian", TRUE); $smarty->assign("librarian", TRUE);
} }
// Default to browsing, empty search box, generic title // Default to browsing, empty search box, generic title
$mode = "browse"; $mode = "browse";
$search = ""; $search = "";
$smarty->assign("title","Library"); $smarty->assign("title", "Library");
$output2 = $smarty->fetch("library-search.tpl"); $output2 = $smarty->fetch("library-search.tpl");
$smarty->assign("secondary", $output2); $smarty->assign("secondary", $output2);
if (isset($_REQUEST['search']) && (trim($_REQUEST['search']) != "")) { if (isset($_REQUEST['search']) && (trim($_REQUEST['search']) != "")) {
// Pass the template some search results // Pass the template some search results
$mode = "search"; $mode = "search";
} elseif (isset($pathlist[$library_index +1]) && ($pathlist[$library_index + 1] == "Tags")) { } elseif (isset($pathlist[$library_index + 1]) && ($pathlist[$library_index + 1] == "Tags")) {
if (isset($pathlist[$library_index + 2])) { if (isset($pathlist[$library_index + 2])) {
$tag = $pathlist[$library_index + 2]; $tag = $pathlist[$library_index + 2];
// we're displaying books with a specific tag // we're displaying books with a specific tag
$categories = $DB->GetOne("SELECT count(name) FROM bookcategories WHERE name=?", array($tag)); //The following line doesn't do what I think you think it does.
if ($categories['count'] == 1) { //It will return a string if the tag exists, "1" and "0" when a tag doesn't exist
$mode = "tagdisplay"; $categories = $DB->GetOne("SELECT count(name) FROM bookcategories WHERE name=?", array($tag));
$query = "SELECT b.id, b.title FROM books AS b JOIN booktags AS bt ON b.id= bt.bookid"; //debug stuff, LOOK IT'S A STRING
$query .= " JOIN bookcategories AS bc ON bc.id = bt.tag WHERE bc.name=?"; //var_dump($categories);
$smarty->assign("results", $DB->GetAll($query, array($tag))); //if ($categories['count'] == 1) {
} else { //$categories is not an aray, it's a string, yeah i know == != good_programing
// this tag doesn't exist... if ($categories == 1) {
$mode = "tagerror"; $mode = "tagdisplay";
} $query = "SELECT b.id, b.title FROM books AS b JOIN booktags AS bt ON b.id= bt.bookid";
} else { $query .= " JOIN bookcategories AS bc ON bc.id = bt.tag WHERE bc.name=?";
$mode = "taglist"; $smarty->assign("results", $DB->GetAll($query, array($tag)));
$smarty->assign("tags", $DB->GetAll("SELECT name FROM bookcategories")); } else {
} // this tag doesn't exist...
$mode = "tagerror";
}
} else {
$mode = "taglist";
$smarty->assign("tags", $DB->GetAll("SELECT name FROM bookcategories"));
}
} elseif (isset($pathlist[$library_index + 1]) && is_numeric($pathlist[$library_index + 1])) { } elseif (isset($pathlist[$library_index + 1]) && is_numeric($pathlist[$library_index + 1])) {
// We're displaying a specific book // We're displaying a specific book
$mode = "display"; $mode = "display";
$checkout_request = false; $checkout_request = false;
$book_index = intval($pathlist[$library_index + 1]); $book_index = intval($pathlist[$library_index + 1]);
if (isset($session->groups[$permission])) $smarty->assign('editable', true); if (isset($session->groups[$permission])) $smarty->assign('editable', true);
// Check this book actually exists // Check this book actually exists
$loans = $DB->GetAll("SELECT onloan FROM books WHERE id=? LIMIT 1", array($book_index)); $loans = $DB->GetAll("SELECT onloan FROM books WHERE id=? LIMIT 1", array($book_index));
if (sizeof($loans) != 1) { if (sizeof($loans) != 1) {
$mode = "bookerror"; $mode = "bookerror";
} else { } else {
// See if we're supposed to be loaning/returning/editing/saving this book // See if we're supposed to be loaning/returning/editing/saving this book
if ($session->loggedin && isset($_REQUEST['action'])) { if ($session->loggedin && isset($_REQUEST['action'])) {
if ($_REQUEST['action'] == "loan") { if ($_REQUEST['action'] == "loan") {
if (isset($session->groups[$permission])) { if (isset($session->groups[$permission])) {
// update DB // update DB
$query = "UPDATE books SET onloan='t', loandate=now(), loanwho=? WHERE id=?"; $query = "UPDATE books SET onloan='t', loandate=now(), loanwho=? WHERE id=?";
$DB->Query($query, array($_REQUEST['member'], $book_index)); $DB->Query($query, array($_REQUEST['member'], $book_index));
} else { } else {
// send mail to librarians // send mail to librarians
// do this in a moment when we have more details about the book // do this in a moment when we have more details about the book
$checkout_request = true; $checkout_request = true;
} }
} elseif (($_REQUEST['action'] == "return") && isset($session->groups[$permission])) { } elseif (($_REQUEST['action'] == "return") && isset($session->groups[$permission])) {
// update DB // update DB
$DB->Query("UPDATE books SET onloan='f', loandate=NULL WHERE id=?", array($book_index)); $DB->Query("UPDATE books SET onloan='f', loandate=NULL WHERE id=?", array($book_index));
} elseif (($_REQUEST['action'] == "edit") && isset($session->groups[$permission])) { } elseif (($_REQUEST['action'] == "edit") && isset($session->groups[$permission])) {
// we're an editor and want to edit this book // we're an editor and want to edit this book
$smarty->assign("editing", true); $smarty->assign("editing", true);
} elseif (($_REQUEST['action'] == "save") && isset($session->groups[$permission])) { } elseif (($_REQUEST['action'] == "save") && isset($session->groups[$permission])) {
// save edited book // save edited book
$book['title'] = $_REQUEST['title']; $book['title'] = $_REQUEST['title'];
$book['author'] = $_REQUEST['author']; $book['author'] = $_REQUEST['author'];
$book['publisher'] = $_REQUEST['publisher']; $book['publisher'] = $_REQUEST['publisher'];
$book['description'] = $_REQUEST['description']; $book['description'] = $_REQUEST['description'];
if ($DB->AutoExecute('books', $book, 'UPDATE', "id=".$DB->qstr($book_index))) { if ($DB->AutoExecute('books', $book, 'UPDATE', "id=" . $DB->qstr($book_index))) {
message_flash_postponed("Book Updated!"); message_flash_postponed("Book Updated!");
//redirect to prevent form resubmission //redirect to prevent form resubmission
header('HTTP/1.1 303 See Other'); header('HTTP/1.1 303 See Other');
header("Location: $baseurl$path"); header("Location: $baseurl$path");
} else { } else {
trigger_error("Error updating book: ".$DB->ErrorMsg(), E_USER_WARNING); trigger_error("Error updating book: " . $DB->ErrorMsg(), E_USER_WARNING);
} }
} }
} }
$results = $DB->GetAll("SELECT * FROM books WHERE id=? LIMIT 1", array($book_index)); $results = $DB->GetAll("SELECT * FROM books WHERE id=? LIMIT 1", array($book_index));
$book = $results[0]; $book = $results[0];
if ($checkout_request) { if ($checkout_request) {
// someone wants to check out this book // someone wants to check out this book
$msgbody = "User {$session->username} would like to take out"; $msgbody = "User {$session->username} would like to take out";
$msgbody .= " {$book['title']} by {$book['author']} from the library.\n\n"; $msgbody .= " {$book['title']} by {$book['author']} from the library.\n\n";
$msgbody .= "Visit https://$preferred_hostname$path to process this request."; $msgbody .= "Visit https://$preferred_hostname$path to process this request.";
mail($librarian_mail, "Book Request", $msgbody); mail($librarian_mail, "Book Request", $msgbody);
$smarty->assign("checkout_request", true); $smarty->assign("checkout_request", true);
} }
// Clean up ready for output // Clean up ready for output
$book['title'] = htmlentities2($book['title']); $book['title'] = htmlentities2($book['title']);
$book['author'] = htmlentities2($book['author']); $book['author'] = htmlentities2($book['author']);
$book['onloan'] = ($book['onloan'] == 't') ? true : false; $book['onloan'] = ($book['onloan'] == 't') ? true : false;
if (!isset($book['description'])) {
if (!isset($book['description'])) { // no book description in the database, try using Amazon data
// no book description in the database, try using Amazon data
// Extract amazon data (maybe this should be stored in separate fields in the db?)
// Extract amazon data (maybe this should be stored in separate fields in the db?) $simple_xml = simplexml_load_string($book['amazon_data']);
$simple_xml = simplexml_load_string($book['amazon_data']);
$book['description'] = @$simple_xml->Items->Item->EditorialReviews->EditorialReview->Content;
$book['description'] = @$simple_xml->Items->Item->EditorialReviews->EditorialReview->Content; if (isset($book['description'])) {
if (isset($book['description'])) { // tidy description markup
// tidy description markup $tidy_config['doctype'] = 'omit';
$tidy_config['doctype'] = 'omit'; $tidy_config['output-xhtml'] = true;
$tidy_config['output-xhtml'] = true; $tidy_config['show-body-only'] = true;
$tidy_config['show-body-only'] = true; $tidy_config['logical-emphasis'] = true;
$tidy_config['logical-emphasis'] = true; $book['description'] = tidy_repair_string($book['description'], $tidy_config);
$book['description'] = tidy_repair_string($book['description'], $tidy_config);
// Commented out by ~imranh
// update db so we don't have to do this next time // update db so we don't have to do this next time
$DB->Execute("UPDATE books SET description=? WHERE id=?", array($book['description'],$book['id'])); //$DB->Execute("UPDATE books SET description=? WHERE id=?", array($book['description'],$book['id']));
} }
} }
$smarty->assign("book", $book); $smarty->assign("book", $book);
// Add loan interface to sidebar if we're logged in // Add loan interface to sidebar if we're logged in
if ($session->loggedin) { if ($session->loggedin) {
$members = new Members; $members = new Members;
$smarty->assign("memberlist", $members->getMemberList()); $smarty->assign("memberlist", $members->getMemberList());
$secondary = $smarty->get_template_vars("secondary"); $secondary = $smarty->getTemplateVars("secondary");
$secondary .= $smarty->fetch('library-loan.tpl'); $secondary .= $smarty->fetch('library-loan.tpl');
$smarty->assign("secondary", $secondary); $smarty->assign("secondary", $secondary);
} }
// Edit the path list to make the breadcrumbs tastier // Edit the path list to make the breadcrumbs tastier
$pathlist[$library_index + 1] = $results[0]['title']; $pathlist[$library_index + 1] = $results[0]['title'];
} }
} else { } else {
//Nothing being requested, just find some random books to put on main page //Nothing being requested, just find some random books to put on main page
$smarty->assign("tags", $DB->GetAll("SELECT name FROM bookcategories")); $smarty->assign("tags", $DB->GetAll("SELECT name FROM bookcategories"));
$smarty->assign("randoms", $DB->GetAll("SELECT * FROM books WHERE image_url IS NOT NULL ORDER BY random() LIMIT 4")); $smarty->assign("randoms", $DB->GetAll("SELECT * FROM books WHERE image_url IS NOT NULL ORDER BY random() LIMIT 4"));
} }
if ($mode == "search") { if ($mode == "search") {
$search = $_REQUEST['search']; $search = $_REQUEST['search'];
$query = "SELECT id, title, onloan FROM books WHERE (title || ' ' || author || ' ' || keywords) ~* ? ORDER BY title ASC"; $query = "SELECT id, title, onloan FROM books WHERE (title || ' ' || author || ' ' || keywords) ~* ? ORDER BY title ASC";
$results = $DB->GetAll($query,array($search)); $results = $DB->GetAll($query, array($search));
foreach ($results as &$result) { foreach ($results as &$result) {
$result['title'] = htmlentities2($result['title']); $result['title'] = htmlentities2($result['title']);
$result['onloan'] = ($result['onloan'] == 't') ? true : false; $result['onloan'] = ($result['onloan'] == 't') ? true : false;
} }
$pathlist[] = "Search"; $pathlist[] = "Search";
$smarty->assign("results", $results); $smarty->assign("results", $results);
} elseif ($mode == "display") { } elseif ($mode == "display") {
...@@ -183,6 +190,6 @@ $smarty->assign("mode", $mode); ...@@ -183,6 +190,6 @@ $smarty->assign("mode", $mode);
$smarty->assign("search", $search); $smarty->assign("search", $search);
$smarty->assign("pathlist", $pathlist); $smarty->assign("pathlist", $pathlist);
$output = $smarty->fetch("library.tpl"); $output = $smarty->fetch("library.tpl");
$smarty->assign("body",$output); $smarty->assign("body", $output);
?> ?>
<?php <?php
// you gotta be this high to enter // you gotta be this high to enter
$permission="librarian"; $permission = "librarian";
//include ISBN validation library //include ISBN validation library
require_once('../lib/Validate/ISPN.php'); require_once('../lib/Validate/ISPN.php');
$error = array(); $error = array();
function fetch_isbndb_data($isbn) { function fetch_isbndb_data($isbn)
{
$url1 = "http://isbndb.com/api/books.xml?access_key=I6AH5WJI&index1=isbn&value1="; $url1 = "http://isbndb.com/api/books.xml?access_key=I6AH5WJI&index1=isbn&value1=";
return file_get_contents($url1.$isbn); return file_get_contents($url1 . $isbn);
} }
function valid_isbn($isbn) { function valid_isbn($isbn)
{
return Validate_ISPN::isbn($isbn); return (new Validate_ISPN)->isbn($isbn);
} }
if ($session->groups[$permission]) { if ($session->groups[$permission]) {
if ($_REQUEST['action'] == "search") { if ($_REQUEST['action'] == "search") {
$isbn = $_REQUEST['isbn']; $isbn = $_REQUEST['isbn'];
$isbn = str_replace(array('ISBN', '-', ' ', "\t", "\n"), '', $isbn); $isbn = str_replace(array('ISBN', '-', ' ', "\t", "\n"), '', $isbn);
if (valid_isbn($isbn)) { if (valid_isbn($isbn)) {
$xmlresult = fetch_isbndb_data($isbn); $xmlresult = fetch_isbndb_data($isbn);
$simple_xml = simplexml_load_string($xmlresult); $simple_xml = simplexml_load_string($xmlresult);
$book['isbn'] = $isbn; $book['isbn'] = $isbn;
$book['title'] = $simple_xml->BookList->BookData->Title; $book['title'] = $simple_xml->BookList->BookData->Title;
$book['author'] = $simple_xml->BookList->BookData->AuthorsText; $book['author'] = $simple_xml->BookList->BookData->AuthorsText;
if (substr(trim($book['author']),-1)==',') {$book['author']=substr(trim($book['author']),0,-1);} if (substr(trim($book['author']), -1) == ',') {
$book['publisher'] = $simple_xml->BookList->BookData->PublisherText; $book['author'] = substr(trim($book['author']), 0, -1);
$book['image_url'] = ""; }
$smarty->assign("book", $book); $book['publisher'] = $simple_xml->BookList->BookData->PublisherText;
} else { $book['image_url'] = "";
// invalid isbn entered $smarty->assign("book", $book);
trigger_error("invalid ISBN number entered", E_USER_WARNING); } else {
} // invalid isbn entered
trigger_error("invalid ISBN number entered", E_USER_WARNING);
}
} elseif ($_REQUEST['action'] == "add") {
$book = array();
$book['isbn'] = $_REQUEST['isbn']; } elseif ($_REQUEST['action'] == "add") {
$book['title'] = $_REQUEST['title']; $book = array();
$book['author'] = $_REQUEST['author']; $book['isbn'] = $_REQUEST['isbn'];
$book['publisher'] = $_REQUEST['publisher']; $book['title'] = $_REQUEST['title'];
$book['image_url'] = $_REQUEST['image_url']; $book['author'] = $_REQUEST['author'];
$book['publisher'] = $_REQUEST['publisher'];
// Validate that we have enough info to add $book['image_url'] = $_REQUEST['image_url'];
if (($book['isbn'] != "") && (!valid_isbn($book['isbn']))) {
trigger_error("invalid ISBN", E_USER_WARNING); // Validate that we have enough info to add
} elseif (trim($book['title']) == "") { if (($book['isbn'] != "") && (!valid_isbn($book['isbn']))) {
trigger_error("you must supply a title", E_USER_WARNING); trigger_error("invalid ISBN", E_USER_WARNING);
} elseif (trim($book['author']) == "") { } elseif (trim($book['title']) == "") {
trigger_error("you must supply an author"); trigger_error("you must supply a title", E_USER_WARNING);
} else { } elseif (trim($book['author']) == "") {
$insertdata = array($book['title'], $book['author'], $book['publisher']); trigger_error("you must supply an author");
if (valid_isbn($book['isbn'])) { } else {
$book['amazon_data'] = fetch_isbndb_data($book['isbn']); $insertdata = array($book['title'], $book['author'], $book['publisher']);
$newinsertdata = array($book['isbn'], $book['image_url'], $book['amazon_data']); if (valid_isbn($book['isbn'])) {
$insertdata = array_merge($insertdata, $newinsertdata); $book['amazon_data'] = fetch_isbndb_data($book['isbn']);
$DB->Query("INSERT INTO books (title, author, publisher, isbn, image_url, amazon_data) VALUES (?,?,?,?,?,?)", $insertdata); $newinsertdata = array($book['isbn'], $book['image_url'], $book['amazon_data']);
} else { $insertdata = array_merge($insertdata, $newinsertdata);
$DB->Query("INSERT INTO books (title, author, publisher) VALUES (?,?,?)", $insertdata); $DB->Query("INSERT INTO books (title, author, publisher, isbn, image_url, amazon_data) VALUES (?,?,?,?,?,?)", $insertdata);
} } else {
} $DB->Query("INSERT INTO books (title, author, publisher) VALUES (?,?,?)", $insertdata);
}
} }
$result = $smarty->fetch("library-addbook.tpl");
}
$result = $smarty->fetch("library-addbook.tpl");
} }
$smarty->assign("title", "Library Admin"); $smarty->assign("title", "Library Admin");
......
...@@ -5,160 +5,151 @@ include_once("../lib/date.php"); ...@@ -5,160 +5,151 @@ include_once("../lib/date.php");
$members = new Members; $members = new Members;
if ($session->loggedin) { if ($session->loggedin) {
$usernames = $members->getMemberList(); $usernames = $members->getMemberList();
$smarty->assign('members', $usernames); $smarty->assign('members', $usernames);
$sidebar = $smarty->fetch('members-search.tpl'); $sidebar = $smarty->fetch('members-search.tpl');
$smarty->assign('secondary', $sidebar); $smarty->assign('secondary', $sidebar);
// Show Searched for users depending on the method provided // Show Searched for users depending on the method provided
$value = ''; $value = '';
$uid = false; $uid = false;
$pathCount = count($pathlist) -1; $pathCount = count($pathlist) - 1;
if ( isset($_POST['search']) ) { if (isset($_POST['search'])) {
$value = $_POST['search']; $value = $_POST['search'];
$uid = true; $uid = true;
$usernames = $members->memberSearch($value); $usernames = $members->memberSearch($value);
} else if ( isset($_POST['member']) ) { } else if (isset($_POST['member'])) {
$value = $_POST['member']; $value = $_POST['member'];
$uid = true; $uid = true;
$usernames = $members->memberView($value); $usernames = $members->memberView($value);
} else if ( $component['path'] != $path ) { } else if ($component['path'] != $path) {
$value = $pathlist[$pathCount]; $value = $pathlist[$pathCount];
$usernames = $members->memberView($value); $usernames = $members->memberView($value);
} }
if (!empty($value) ) { if (!empty($value)) {
// Redirect if we have found a valid single user // Redirect if we have found a valid single user
if (count($usernames) == 1) { if (count($usernames) == 1) {
$smarty->assign('who', $usernames[0]['uid']); $smarty->assign('who', $usernames[0]['uid']);
// Add banana widget to the sidebar // Add banana widget to the sidebar
$who = $usernames[0]['uid']; $who = $usernames[0]['uid'];
include("../lib/banana-admin.php"); //Tell the banana library that we're dealing with a real member
// Needs Redirection $isnonmember = false;
if ($uid) { include("../lib/banana-admin.php");
header('Location: ' . $component['path'] . '/' . $usernames[0]['uid']); // Needs Redirection
} else { if ($uid) {
// Pictures header('Location: ' . $component['path'] . '/' . $usernames[0]['uid']);
if (file_exists('pictures/people/' . $usernames[0]['uid'] . '.png')) { } else {
$usernames[0]['picture'] = '/pictures/people/' . $usernames[0]['uid'] . '.png'; // Pictures
} if (file_exists('pictures/people/' . $usernames[0]['uid'] . '.png')) {
// Account type $usernames[0]['picture'] = '/pictures/people/' . $usernames[0]['uid'] . '.png';
$homedir = explode('/', $usernames[0]['homedir']);
$usernames[0]['acctype'] = ucfirst($homedir[2]);
// Project
if (file_exists( $usernames[0]['homedir'] . '/.project')) {
$usernames[0]['project'] = file_get_contents($usernames[0]['homedir'] . '/.project');
}
// Plan
if (file_exists( $usernames[0]['homedir'] . '/.plan')) {
$usernames[0]['plan'] = file_get_contents($usernames[0]['homedir'] . '/.plan');
}
// Website
if ( file_exists( $usernames[0]['homedir'] . '/public_html') &&
!file_exists( $usernames[0]['homedir'] . '/public_html/robots.txt')) {
$usernames[0]['website'] = true;
}
// Blog
require_once("/usr/share/php/adodb/adodb.inc.php");
$BlogDB = NewADOConnection('postgres8');
$BlogDB->Connect('dbname=blogs user=apache');
$BlogDB->SetFetchMode(ADODB_FETCH_ASSOC);
require_once('../lib/blog/validation.lib.php');
if (blogger($usernames[0]['uid'])) {
$usernames[0]['blog'] = $BlogDB->GetOne("select title from users where username='".$usernames[0]['uid']."'");
}
// Bananas stuff
$bananasql = "SELECT *, date_trunc('second', whn) FROM awards ";
$bananasql .= "WHERE username ~* ? ORDER BY WHN DESC";
$awards = $DB->GetAll($bananasql, array("^".$usernames[0]['uid']."$"));
// arrange by academic year, calculate sums as we go
foreach ($awards as $award) {
$acyear = academicYear(strtotime($award['whn']));
$awards_by_year[$acyear]['awards'][] = $award;
$awards_by_year[$acyear]['sum'] += $award['score'];
$bananasum += $award['score'];
}
$usernames[0]['awardsbyyear'] = &$awards_by_year;
$usernames[0]['bananascore'] = $bananasum;
}
}
$smarty->assign('results', $usernames);
} else {
// generate fun data to put on index page
// top 5
$stats['top'] = $DB->GetAll("SELECT username, sum(score) as sum FROM awards GROUP BY username ORDER BY sum DESC LIMIT 5");
// top 5 (this academic year)
$yeartop_sql = "SELECT username, sum(score) as sum FROM awards ";
$yeartop_sql .= "WHERE whn > date(?) GROUP BY username ORDER BY sum DESC LIMIT 5";
$stats['yeartop'] = $DB->GetAll($yeartop_sql, array(academicYear(time())."-09-01"));
// bottom 5
$stats['bottom'] = $DB->GetAll("SELECT username, sum(score) as sum FROM awards GROUP BY username ORDER BY sum ASC LIMIT 5");
// recent awards
// today's definition of "recent" is all awards within three days of the newest award and a minimum of five...
// if this seems like a dumb method then try something else :-)
$recentAwards_sql = "(SELECT * FROM awards WHERE whn > (SELECT whn - interval '3 days' FROM awards ORDER BY whn DESC LIMIT 1))";
$recentAwards_sql .= " UNION (SELECT * FROM awards ORDER BY whn DESC LIMIT 5) ORDER BY 4 DESC";
$stats['recent'] = $DB->GetAll($recentAwards_sql);
// retrieve the usernames for top stats, bottom stats, and all users - so we can filter out who's a user and who's not
foreach ($usernames as $i => $value) {
$realUsers[] = $usernames[$i]['uid'];
} }
foreach ($stats['yeartop'] as $i => $value) { // Account type
if (in_array(strtolower($stats['yeartop'][$i]['username']), $realUsers)) { $homedir = explode('/', $usernames[0]['homedir']);
$stats['yeartop'][$i]['real'] = TRUE; $usernames[0]['acctype'] = ucfirst($homedir[2]);
} else { // Project
$stats['yeartop'][$i]['real'] = FALSE; if (file_exists($usernames[0]['homedir'] . '/.project') && ! is_link($usernames[0]['homedir'] . '/.project')) {
} $usernames[0]['project'] = file_get_contents($usernames[0]['homedir'] . '/.project');
} }
foreach ($stats['top'] as $i => $value) { // Plan
if (in_array(strtolower($stats['top'][$i]['username']), $realUsers)) { if (file_exists($usernames[0]['homedir'] . '/.plan') && ! is_link($usernames[0]['homedir'] . '/.plan')) {
$stats['top'][$i]['real'] = TRUE; $usernames[0]['plan'] = file_get_contents($usernames[0]['homedir'] . '/.plan');
} else {
$stats['top'][$i]['real'] = FALSE;
}
} }
foreach ($stats['bottom'] as $i => $value) { // Website
if (in_array(strtolower($stats['bottom'][$i]['username']), $realUsers)) { if (file_exists($usernames[0]['homedir'] . '/public_html')) {
$stats['bottom'][$i]['real'] = TRUE; $usernames[0]['website'] = true;
} else {
$stats['bottom'][$i]['real'] = FALSE;
}
} }
foreach ($stats['recent'] as $i => $value) { // Bananas stuff
if (in_array(strtolower($stats['recent'][$i]['username']), $realUsers)) { $bananasql = "SELECT *, date_trunc('second', whn) FROM awards ";
$stats['recent'][$i]['real'] = TRUE; $bananasql .= "WHERE username ~* ? ORDER BY WHN DESC";
} else { $awards = $DB->GetAll($bananasql, array("^" . $usernames[0]['uid'] . "$"));
$stats['recent'][$i]['real'] = FALSE;
} // arrange by academic year, calculate sums as we go
foreach ($awards as $award) {
$acyear = academicYear(strtotime($award['whn']));
$awards_by_year[$acyear]['awards'][] = $award;
$awards_by_year[$acyear]['sum'] += $award['score'];
$bananasum += $award['score'];
} }
$smarty->assign("stats", $stats);
$secondary = $smarty->get_template_vars("secondary");
$secondary .= $smarty->fetch("banana-leaders.tpl");
$smarty->assign("secondary", $secondary);
} $usernames[0]['awardsbyyear'] = &$awards_by_year;
$usernames[0]['bananascore'] = $bananasum;
}
}
$smarty->assign('results', $usernames);
} else {
// generate fun data to put on index page
// top 5
$stats['top'] = $DB->GetAll("SELECT username, sum(score) as sum FROM awards GROUP BY username ORDER BY sum DESC LIMIT 5");
// top 5 (this academic year)
$yeartop_sql = "SELECT username, sum(score) as sum FROM awards ";
$yeartop_sql .= "WHERE whn > date(?) GROUP BY username ORDER BY sum DESC LIMIT 5";
$stats['yeartop'] = $DB->GetAll($yeartop_sql, array(academicYear(time()) . "-09-01"));
// bottom 5
// exclude sambws and frostys allways decresing banana that scres up the result
$stats['bottom'] = $DB->GetAll("SELECT username, sum(score) as sum FROM awards WHERE id!=685 and id!=393 GROUP BY username ORDER BY sum ASC LIMIT 5");
// recent awards
// today's definition of "recent" is all awards within three days of the newest award and a minimum of five...
// if this seems like a dumb method then try something else :-)
$recentAwards_sql = "(SELECT * FROM awards WHERE whn > (SELECT whn - interval '3 days' FROM awards ORDER BY whn DESC LIMIT 1))";
$recentAwards_sql .= " UNION (SELECT * FROM awards ORDER BY whn DESC LIMIT 5) ORDER BY 4 DESC";
$stats['recent'] = $DB->GetAll($recentAwards_sql);
// retrieve the usernames for top stats, bottom stats, and all users - so we can filter out who's a user and who's not
foreach ($usernames as $i => $value) {
$realUsers[] = $usernames[$i]['uid'];
}
foreach ($stats['yeartop'] as $i => $value) {
if (in_array(strtolower($stats['yeartop'][$i]['username']), $realUsers)) {
$stats['yeartop'][$i]['real'] = TRUE;
} else {
$stats['yeartop'][$i]['real'] = FALSE;
}
}
foreach ($stats['top'] as $i => $value) {
if (in_array(strtolower($stats['top'][$i]['username']), $realUsers)) {
$stats['top'][$i]['real'] = TRUE;
} else {
$stats['top'][$i]['real'] = FALSE;
}
}
foreach ($stats['bottom'] as $i => $value) {
if (in_array(strtolower($stats['bottom'][$i]['username']), $realUsers)) {
$stats['bottom'][$i]['real'] = TRUE;
} else {
$stats['bottom'][$i]['real'] = FALSE;
}
}
foreach ($stats['recent'] as $i => $value) {
if (in_array(strtolower($stats['recent'][$i]['username']), $realUsers)) {
$stats['recent'][$i]['real'] = TRUE;
} else {
$stats['recent'][$i]['real'] = FALSE;
}
}
$smarty->assign("stats", $stats);
$secondary = $smarty->getTemplateVars("secondary");
$secondary .= $smarty->fetch("banana-leaders.tpl");
$smarty->assign("secondary", $secondary);
}
} else { } else {
// not logged in. Show a list of members with websites // not logged in. Show a list of members with websites
$usernames = $members->getMemberList(); $usernames = $members->getMemberList();
foreach ($usernames as $user) { foreach ($usernames as $user) {
if ( file_exists( $user['homedir'] . '/public_html') && if (file_exists($user['homedir'] . '/public_html')) {
!file_exists( $user['homedir'] . '/public_html/robots.txt')) { $public_usernames[] = $user;
$public_usernames[] = $user; }
} }
} $smarty->assign("public_members", $public_usernames);
$smarty->assign("public_members", $public_usernames);
} }
$smarty->assign('url', $component['path']); $smarty->assign('url', $component['path']);
$smarty->assign('extra_styles', "/css/members.css"); $smarty->assign('extra_styles', "/css/members.css");
......
<?php <?php
include_once("../lib/date.php"); include_once("../lib/date.php");
// Config options // Config options
$inform="treasurer@sucs.org"; $inform = "treasurer@sucs.org";
$permission="sucsstaff"; $permission = "sucsstaff";
// Enable and disable database updating // Enable and disable database updating
$enable=TRUE; $enable = TRUE;
// Set next payment date // Set next payment date
$paydate = paidUntil(time()); $paydate = paidUntil(time());
...@@ -12,141 +12,131 @@ $paydate = paidUntil(time()); ...@@ -12,141 +12,131 @@ $paydate = paidUntil(time());
// Only staff can use this page // Only staff can use this page
if (isset($session->groups[$permission])) { if (isset($session->groups[$permission])) {
$smarty->assign("staff", TRUE); $smarty->assign("staff", TRUE);
// connect to sucs database
$sucsDB = NewADOConnection('postgres8');
$sucsDB->Connect('dbname=sucs user=apache');
$sucsDB->SetFetchMode(ADODB_FETCH_ASSOC);
// $sucsDB->debug = true; // $sucsDB->debug = true;
// handle updates // handle updates
if(isset($_POST['uid']) && isset($_POST['lastupdate'])){ if (isset($_POST['uid']) && isset($_POST['lastupdate'])) {
// Check data hasn't changed and that nothing is broked // Check data hasn't changed and that nothing is broked
$query = "SELECT * FROM members WHERE uid=? AND lastupdate=?"; $query = "SELECT * FROM members WHERE uid=? AND lastupdate=?";
$array = array($_POST['uid'], $_POST['lastupdate']); $array = array($_POST['uid'], $_POST['lastupdate']);
$data = $sucsDB->GetAll($query,$array); $data = $sucsDB->GetAll($query, $array);
// If there is only one record then everything is fine // If there is only one record then everything is fine
if(sizeof($data)==1){ if (sizeof($data) == 1) {
// get info on currently logged in user // get info on currently logged in user
$user = posix_getpwnam($session->username); $user = posix_getpwnam($session->username);
// Update record // Update record
$record = $data[0]; $record = $data[0];
$query = "UPDATE members"; $query = "UPDATE members";
$query .= " SET paid = ?, lastupdate = DEFAULT, lastedit = ?"; $query .= " SET paid = ?, lastupdate = DEFAULT, lastedit = ?";
$query .= " WHERE uid = ?"; $query .= " WHERE uid = ?";
$array = array($paydate,$user['uid'],$_POST['uid']); $array = array($paydate, $user['uid'], $_POST['uid']);
if($enable){ if ($enable) {
$sucsDB->query($query,$array); $sucsDB->query($query, $array);
} }
// emailing contact (tresurer) // emailing contact (tresurer)
$message = "Account renewal notification\n\n"; $message = "Account renewal notification\n\n";
$message .= "Account : ".$record['username']."\n"; $message .= "Account : " . $record['username'] . "\n";
$message .= "User Type : ".$record['type']."\n"; $message .= "User Type : " . $record['type'] . "\n";
$message .= "Renewed by: ".$user[name]."\n\n"; $message .= "Renewed by: " . $user['name'] . "\n\n";
$message .= "Regards\n eclipse's script"; $message .= "Regards\n eclipse's script";
mail($inform,"Account Renewal",$message); mail($inform, "Account Renewal", $message);
// emailing user // emailing user
$message = "Your Swansea University Computer Society (SUCS) membership has been renewed\n\n"; $message = "Your Swansea University Computer Society (SUCS) membership has been renewed\n\n";
$message .= "Username: ".$record['username']."\n"; $message .= "Username: " . $record['username'] . "\n";
$message .= "If you do not know or have forgotten your password, please email admin@sucs.org to arrange for it to be changed.\n\n"; $message .= "If you do not know or have forgotten your password, please email admin@sucs.org to arrange for it to be changed.\n\n";
$message .= "Regards\n The SUCS admin"; $message .= "Regards\n The SUCS admin";
$header = "From: admin@sucs.org\r\n"; $header = "From: admin@sucs.org\r\n";
$header .= "Reply-To: admin@sucs.org"; $header .= "Reply-To: admin@sucs.org";
// Personal account // Personal account
mail($record['email'],"SUCS account renewal",$message,$header); mail($record['email'], "SUCS account renewal", $message, $header);
// sucs account // sucs account
mail($record['username']."@sucs.org","SUCS account renewal",$message,$header); mail($record['username'] . "@sucs.org", "SUCS account renewal", $message, $header);
message_flash("Renewed account for: ".htmlentities($record['username'])); message_flash("Renewed account for: " . htmlentities($record['username']));
} } else {
else{ trigger_error("Number of recored returned: " . sizeof($data) . ". Expected: 1.", E_USER_ERROR);
trigger_error("Number of recored returned: ".sizeof($data).". Expected: 1.", E_USER_ERROR);
} }
} }
// if sort is specified in GET // if sort is specified in GET
if(isset($_GET["sort"])){ if (isset($_GET["sort"])) {
$sortoptions = array("username","sid","realname"); $sortoptions = array("username", "sid", "realname");
// and is a valid option // and is a valid option
if(in_array($_GET["sort"],$sortoptions,TRUE)){ if (in_array($_GET["sort"], $sortoptions, TRUE)) {
// use it // use it
$sort=$_GET["sort"]; $sort = $_GET["sort"];
} // else use username
else {
$sort = 'username';
} }
// else use username $getsort = $sort;
else{ } //else use username
$sort='username'; else {
} $sort = 'username';
$getsort=$sort;
}
//else use username
else{
$sort='username';
} }
//Get members details //Get members details
$query = "SELECT * FROM members, member_type"; $query = "SELECT * FROM members, member_type";
$query .= " WHERE paid != ?"; $query .= " WHERE paid != ?";
$query .= " AND (type = 1 OR type = 2 OR type = 5)"; $query .= " AND (type = 1 OR type = 2 OR type = 5)";
$query .= " AND type=member_type.id"; $query .= " AND type=member_type.id";
$query .= " ORDER BY paid,type,".$sort; $query .= " ORDER BY paid,type," . $sort;
$array = array($paydate); $array = array($paydate);
$data = $sucsDB->GetAll($query, $array); $data = $sucsDB->GetAll($query, $array);
$smarty->assign("members", $data); $smarty->assign("members", $data);
// set refresh rate // set refresh rate
$autorefresh=$_GET["autorefresh"]; $autorefresh = $_GET["autorefresh"];
// if autorefresh is not 'n' // if autorefresh is not 'n'
if($autorefresh!="n"){ if ($autorefresh != "n") {
// and is a decimal value // and is a decimal value
if(ctype_digit($autorefresh)){ if (ctype_digit($autorefresh)) {
// use it // use it
$refreshval=$autorefresh; $refreshval = $autorefresh;
// set passthrough // set passthrough
$getrefresh=$refreshval; $getrefresh = $refreshval;
} } else {
else{ // If no valid value assigned, default to OFF
// If no valid value assigned, default to OFF $refreshval = "n";
$refreshval="n"; }
} $optrefresh = $refreshval;
$optrefresh=$refreshval; $smarty->assign("refresh", $refreshval);
$smarty->assign("refresh", $refreshval); } else {
}
else{
// set passthrough // set passthrough
$getrefresh='n'; $getrefresh = 'n';
$optrefresh='n'; $optrefresh = 'n';
} }
// compile passthrough url // compile passthrough url
// sort // sort
if(isset($getsort)){ if (isset($getsort)) {
$getout="?sort=".$getsort; $getout = "?sort=" . $getsort;
} }
// autorefresh // autorefresh
if(isset($getrefresh)){ if (isset($getrefresh)) {
if(isset($getout)){ if (isset($getout)) {
$getout .= "&amp;autorefresh=".$getrefresh; $getout .= "&amp;autorefresh=" . $getrefresh;
} } else {
else{ $getout = "?autorefresh=" . $getrefresh;
$getout = "?autorefresh=".$getrefresh;
} }
} }
// set smarty variables // set smarty variables
$smarty->assign("self",$baseurl.$path.$getout); $smarty->assign("self", $baseurl . $path . $getout);
$smarty->assign("optionrefresh",$optrefresh); $smarty->assign("optionrefresh", $optrefresh);
$smarty->assign("optionsort",$sort); $smarty->assign("optionsort", $sort);
$smarty->assign("paydate",$paydate); $smarty->assign("paydate", $paydate);
} }
$side = $smarty->fetch('membershiprenew-options.tpl'); $side = $smarty->fetch('membershiprenew-options.tpl');
$body = $smarty->fetch('membershiprenew.tpl'); $body = $smarty->fetch('membershiprenew.tpl');
$smarty->assign('secondary',$side); $smarty->assign('secondary', $side);
$smarty->assign('title', "Renew Membership"); $smarty->assign('title', "Renew Membership");
$smarty->assign('body', $body); $smarty->assign('body', $body);
?> ?>
<?php <?php
function getPageID($name) { function getPageID($name)
global $DB; {
$query=$DB->GetRow("select id from menu where title='".$name."'"); global $DB;
return (int)@$query['id']; $query = $DB->GetRow("select id from menu where title='" . $name . "'");
return (int)@$query['id'];
} }
function translate($word) { function translate($word)
global $language, $DB; {
global $language, $DB;
if ($language['code']!="en") {
$query=$DB->GetRow("select title, title".$language['db']." from menu where title='".$word."'"); if ($language['code'] != "en") {
if ($query['title'.$language['db']]!="") return $query['title'.$language['db']]; $query = $DB->GetRow("select title, title" . $language['db'] . " from menu where title='" . $word . "'");
else return $query['title']; if ($query['title' . $language['db']] != "") return $query['title' . $language['db']];
} else return $word; else return $query['title'];
} else return $word;
} }
function parseMenu($res) { function parseMenu($res)
global $language; {
global $language;
$menu = array(); $menu = array();
foreach ($res as $row) { foreach ($res as $row) {
if ($language['code']!="en") { if ($language['code'] != "en") {
if ($row['title'.$language['db']]!="") $title=$row['title'.$language['db']]; if ($row['title' . $language['db']] != "") $title = $row['title' . $language['db']];
else $title=$row['title']; else $title = $row['title'];
$menu[$title] = $row['target']; $menu[$title] = $row['target'];
} else { } else {
$menu[$row['title']] = $row['target']; $menu[$row['title']] = $row['target'];
} }
} }
return $menu; return $menu;
} }
if (isset($pathlist[1])) if (isset($pathlist[1]))
$pagename = $pathlist[1]; else $pagename = ""; $pagename = $pathlist[1]; else $pagename = "";
// Menu stuff // Menu stuff
$smarty->assign("select",$pagename); $smarty->assign("select", $pagename);
if (isset($pathlist[2])) if (isset($pathlist[2]))
$smarty->assign("subselect",$pathlist[2]); $smarty->assign("subselect", $pathlist[2]);
else else
$smarty->assign("subselect",$pagename); $smarty->assign("subselect", $pagename);
$query = "select * from menu where parent is NULL and (permission is NULL"; $query = "select * from menu where parent is NULL and (permission is NULL";
// Temporary - all members should be members of the "users" group but aren't // Temporary - all members should be members of the "users" group but aren't
if ($session->loggedin) $query .= " or permission='users'"; if ($session->loggedin) $query .= " or permission='users'";
foreach ($session->groups as $group => $value) { foreach ($session->groups as $group => $value) {
$query .= " or permission='$group'"; $query .= " or permission='$group'";
} }
$query .= ") order by menuorder"; $query .= ") order by menuorder";
...@@ -60,11 +63,27 @@ $res = $DB->GetAll($query); ...@@ -60,11 +63,27 @@ $res = $DB->GetAll($query);
$menu = parseMenu($res); $menu = parseMenu($res);
// this needs to choose the actual current one // this needs to choose the actual current one
$res = $DB->GetAll("select * from menu where parent=".getPageID($pagename)." order by menuorder"); // subpages/submenu items can have permissions attached to them as well!
if (count($res)>0) {
$submenu = parseMenu($res); $query2 = "select * from menu where parent=";
$menu[translate($pagename)] = $submenu; $query2 .= "'";
$query2 .= getPageID($pagename);
$query2 .= "'";
$query2 .= " and (permission is NULL";
if ($session->loggedin) $query2 .= " or permission='users'";
foreach ($session->groups as $group => $value) {
$query2 .= " or permission='$group'";
}
$query2 .= ") order by menuorder";
$res2 = $DB->GetAll($query2);
if (count($res2) > 0) {
$submenu = parseMenu($res2);
$menu[translate($pagename)] = $submenu;
} }
$smarty->assign("menu",$menu); $smarty->assign("menu", $menu);
?> ?>
<?php <?php
function parseIdleTime($idletime) { function parseIdleTime($idletime)
$idlearray = preg_split("/[hms]/",$idletime); {
if (strstr($idletime,'h')) { $idlearray = preg_split("/[hms]/", $idletime);
$hours = $idlearray[0]; if (strstr($idletime, 'h')) {
$minutes = $idlearray[1]; $hours = $idlearray[0];
$seconds = 0; $minutes = $idlearray[1];
} elseif (strstr($idletime,'m')) { $seconds = 0;
$hours = 0; } elseif (strstr($idletime, 'm')) {
$minutes = $idlearray[0]; $hours = 0;
$seconds = $idlearray[1]; $minutes = $idlearray[0];
} else { $seconds = $idlearray[1];
$hours = 0; } else {
$minutes = 0; $hours = 0;
$seconds = $idlearray[0]; $minutes = 0;
} $seconds = $idlearray[0];
}
return (intval($hours * 3600)) + (intval($minutes) * 60) + intval($seconds);
return (intval($hours * 3600)) + (intval($minutes) * 60) + intval($seconds);
} }
function compare_idletime($a, $b) { function compare_idletime($a, $b)
return strnatcmp($a['idleseconds'], $b['idleseconds']); {
return strnatcmp($a['idleseconds'], $b['idleseconds']);
} }
$mwpath = array_search("Milliways", $pathlist); $mwpath = array_search("Milliways", $pathlist);
$newpath = $baseurl; $newpath = $baseurl;
for($i=0;$i<=$mwpath;$i++) { for ($i = 0; $i <= $mwpath; $i++) {
if ($i!=0) $newpath .= "/"; if ($i != 0) $newpath .= "/";
$newpath .= $pathlist[$i]; $newpath .= $pathlist[$i];
} }
$smarty->assign("mwpath", $newpath); $smarty->assign("mwpath", $newpath);
$cal = cal_info(CAL_JULIAN); $cal = cal_info(CAL_JULIAN);
if (strtolower($pathlist[$mwpath+1]) == "uri") { if (strtolower($pathlist[$mwpath + 1]) == "uri") {
$latest = FALSE; $latest = FALSE;
$today = FALSE; $today = FALSE;
unset($search); unset($search);
if (isset($pathlist[$mwpath+2])) { if (isset($pathlist[$mwpath + 2])) {
if ($pathlist[$mwpath+2] == "search" && isset($pathlist[$mwpath+3])) { if ($pathlist[$mwpath + 2] == "search" && isset($pathlist[$mwpath + 3])) {
$search = $pathlist[$mwpath+3]; $search = $pathlist[$mwpath + 3];
} else { } else {
$today = strtotime($pathlist[$mwpath+2]); $today = strtotime($pathlist[$mwpath + 2]);
} }
} }
if ($today === FALSE && !isset($search)) { if ($today === FALSE && !isset($search)) {
$today = time(); $today = time();
$latest = TRUE; $latest = TRUE;
} }
$smarty->assign("extra_scripts", array( $smarty->assign("extra_scripts", array(
'<meta name="ROBOTS" content="NOINDEX" />', '<meta name="ROBOTS" content="NOINDEX" />',
'<meta name="ROBOTS" content="NOFOLLOW" />')); '<meta name="ROBOTS" content="NOFOLLOW" />'));
$mwdb = new PDO('sqlite:/var/lib/mw/mwuri.db'); $mwdb = new PDO('sqlite:/var/lib/mw/mwuri.db');
$res = $mwdb->prepare("select distinct strftime('%Y',added) from mwuri"); $res = $mwdb->prepare("select distinct strftime('%Y',added) from mwuri");
$res->execute(); $res->execute();
$yearlist = $res->fetchAll(PDO::FETCH_COLUMN,0); $yearlist = $res->fetchAll(PDO::FETCH_COLUMN, 0);
$smarty->assign("yearlist",$yearlist); $smarty->assign("yearlist", $yearlist);
$res= $mwdb->prepare("select distinct strftime('%m',added) from mwuri where strftime('%Y',added) = ?"); $res = $mwdb->prepare("select distinct strftime('%m',added) from mwuri where strftime('%Y',added) = ?");
$res->execute(array(date("Y",$today))); $res->execute(array(date("Y", $today)));
$mlist = $res->fetchAll(PDO::FETCH_COLUMN,0); $mlist = $res->fetchAll(PDO::FETCH_COLUMN, 0);
$monthlist = array(); $monthlist = array();
foreach( $mlist as $m) { foreach ($mlist as $m) {
$monthlist[$m] = $cal['abbrevmonths'][(int)$m]; $monthlist[$m] = $cal['abbrevmonths'][(int)$m];
} }
$smarty->assign("monthlist",$monthlist); $smarty->assign("monthlist", $monthlist);
$res= $mwdb->prepare("select distinct strftime('%d',added) from mwuri where strftime('%Y-%m',added) = ?"); $res = $mwdb->prepare("select distinct strftime('%d',added) from mwuri where strftime('%Y-%m',added) = ?");
$res->execute(array(date("Y-m",$today))); $res->execute(array(date("Y-m", $today)));
$daylist = $res->fetchAll(PDO::FETCH_COLUMN,0); $daylist = $res->fetchAll(PDO::FETCH_COLUMN, 0);
$smarty->assign("daylist",$daylist); $smarty->assign("daylist", $daylist);
if ($today === FALSE && isset($search)) { if ($today === FALSE && isset($search)) {
// do a search // do a search
$res = $mwdb->prepare("select *, time(added,'localtime') as hour, date(added,'localtime') as day from mwuri where title like ? or url like ? order by added desc"); $res = $mwdb->prepare("select *, time(added,'localtime') as hour, date(added,'localtime') as day from mwuri where title like ? or url like ? order by added desc");
$term = "%".$search."%"; $term = "%" . $search . "%";
$res->execute(array($term,$term)); $res->execute(array($term, $term));
$data = $res->fetchAll(PDO::FETCH_ASSOC); $data = $res->fetchAll(PDO::FETCH_ASSOC);
} else { } else {
//standard date based lookup //standard date based lookup
$res = $mwdb->prepare("select *, time(added,'localtime') as hour, date(added,'localtime') as day from mwuri where date(added,'localtime')=? order by added desc"); $res = $mwdb->prepare("select *, time(added,'localtime') as hour, date(added,'localtime') as day from mwuri where date(added,'localtime')=? order by added desc");
$res->execute(array(date("Y-m-d",$today))); $res->execute(array(date("Y-m-d", $today)));
$data = $res->fetchAll(PDO::FETCH_ASSOC); $data = $res->fetchAll(PDO::FETCH_ASSOC);
if ($latest && count($data == 0)) { if ($latest && count($data == 0)) {
$day = end($yearlist)."-".end($monthlist)."-".end($daylist); $day = end($yearlist) . "-" . end($monthlist) . "-" . end($daylist);
$today = strtotime($day); $today = strtotime($day);
$res->execute(array(date("Y-m-d",$today))); $res->execute(array(date("Y-m-d", $today)));
$data = $res->fetchAll(PDO::FETCH_ASSOC); $data = $res->fetchAll(PDO::FETCH_ASSOC);
} }
} }
foreach($data as $k => $row) foreach ($data as $k => $row) {
{ if ($row['tags']) {
if ($row['tags']) { $json = json_decode($row['tags'], TRUE);
$json = json_decode($row['tags'], TRUE); if (is_array($json))
if (is_array($json)) $data[$k]['taglist'] = $json[0]['top_tags'];
$data[$k]['taglist'] = $json[0]['top_tags']; }
} }
} $smarty->assign("urilist", $data);
$smarty->assign("urilist", $data);
$smarty->assign("thisyear", date("Y", $today));
$smarty->assign("thisyear", date("Y",$today)); $smarty->assign("thismonth", date("m", $today));
$smarty->assign("thismonth", date("m",$today)); $smarty->assign("thisday", date("d", $today));
$smarty->assign("thisday", date("d",$today));
$output = $smarty->fetch($base . "templates/milliways_uri.tpl");
$output = $smarty->fetch($base."templates/milliways_uri.tpl"); $smarty->assign("title", "Milliways URI");
$smarty->assign("title", "Milliways URI"); $smarty->assign("body", $output);
$smarty->assign("body", $output); $smarty->assign("extra_styles", "/css/milliways.css");
$smarty->assign("extra_styles", "/css/milliways.css"); $smarty->assign("refresh", 120);
$smarty->assign("refresh", 120); return;
return;
} }
if (strtolower($pathlist[$mwpath+1]) == "status") { if (strtolower($pathlist[$mwpath + 1]) == "status") {
$today = FALSE; $today = FALSE;
$wantuser = FALSE; $wantuser = FALSE;
if (isset($pathlist[$mwpath+2])) { if (isset($pathlist[$mwpath + 2])) {
if ($pathlist[$mwpath+2] == "user" && isset($pathlist[$mwpath+3])) if ($pathlist[$mwpath + 2] == "user" && isset($pathlist[$mwpath + 3]))
$wantuser = $pathlist[$mwpath+3]; $wantuser = $pathlist[$mwpath + 3];
else else
$today = strtotime($pathlist[$mwpath+2]); $today = strtotime($pathlist[$mwpath + 2]);
} }
if ($today === FALSE) if ($today === FALSE)
$today = time(); $today = time();
$smarty->assign("extra_scripts", array( $smarty->assign("extra_scripts", array(
'<meta name="ROBOTS" content="NOINDEX" />', '<meta name="ROBOTS" content="NOINDEX" />',
'<meta name="ROBOTS" content="NOFOLLOW" />')); '<meta name="ROBOTS" content="NOFOLLOW" />'));
$mwdb = new PDO('sqlite:/var/lib/mw/mwuri.db'); $mwdb = new PDO('sqlite:/var/lib/mw/mwuri.db');
if ($wantuser !== FALSE) { if ($wantuser !== FALSE) {
$res = $mwdb->prepare("select *, time(added,'localtime') as hour, date(added,'localtime') as day from mwdoing where user=? order by added desc"); $res = $mwdb->prepare("select *, time(added,'localtime') as hour, date(added,'localtime') as day from mwdoing where user=? order by added desc");
$res->execute(array($wantuser)); $res->execute(array($wantuser));
} else { } else {
$res = $mwdb->prepare("select *, time(added,'localtime') as hour, date(added,'localtime') as day from mwdoing where strftime('%Y-%m',added,'localtime')=? order by added desc"); $res = $mwdb->prepare("select *, time(added,'localtime') as hour, date(added,'localtime') as day from mwdoing where strftime('%Y-%m',added,'localtime')=? order by added desc");
$res->execute(array(date("Y-m",$today))); $res->execute(array(date("Y-m", $today)));
} }
//$res = $mwdb->prepare("select *, time(added,'localtime') as hour, date(added,'localtime') as day from mwdoing where date(added,'localtime')=? order by added desc"); //$res = $mwdb->prepare("select *, time(added,'localtime') as hour, date(added,'localtime') as day from mwdoing where date(added,'localtime')=? order by added desc");
//$res->execute(array(date("Y-m-d",$today))); //$res->execute(array(date("Y-m-d",$today)));
$data = $res->fetchAll(PDO::FETCH_ASSOC); $data = $res->fetchAll(PDO::FETCH_ASSOC);
$smarty->assign("statuslist", $data); $smarty->assign("statuslist", $data);
$res = $mwdb->prepare("select distinct strftime('%Y',added) from mwdoing"); $res = $mwdb->prepare("select distinct strftime('%Y',added) from mwdoing");
$res->execute(); $res->execute();
$yearlist = $res->fetchAll(PDO::FETCH_COLUMN,0); $yearlist = $res->fetchAll(PDO::FETCH_COLUMN, 0);
$smarty->assign("yearlist",$yearlist); $smarty->assign("yearlist", $yearlist);
$res= $mwdb->prepare("select distinct strftime('%m',added) from mwdoing where strftime('%Y',added) = ?"); $res = $mwdb->prepare("select distinct strftime('%m',added) from mwdoing where strftime('%Y',added) = ?");
$res->execute(array(date("Y",$today))); $res->execute(array(date("Y", $today)));
$mlist = $res->fetchAll(PDO::FETCH_COLUMN,0); $mlist = $res->fetchAll(PDO::FETCH_COLUMN, 0);
$monthlist = array(); $monthlist = array();
foreach( $mlist as $m) { foreach ($mlist as $m) {
$monthlist[$m] = $cal['abbrevmonths'][(int)$m]; $monthlist[$m] = $cal['abbrevmonths'][(int)$m];
} }
$smarty->assign("monthlist",$monthlist); $smarty->assign("monthlist", $monthlist);
$res= $mwdb->prepare("select distinct strftime('%d',added) from mwdoing where strftime('%Y-%m',added) = ?"); $res = $mwdb->prepare("select distinct strftime('%d',added) from mwdoing where strftime('%Y-%m',added) = ?");
$res->execute(array(date("Y-m",$today))); $res->execute(array(date("Y-m", $today)));
$daylist = $res->fetchAll(PDO::FETCH_COLUMN,0); $daylist = $res->fetchAll(PDO::FETCH_COLUMN, 0);
$smarty->assign("daylist",$daylist); $smarty->assign("daylist", $daylist);
$smarty->assign("thisyear", date("Y",$today)); $smarty->assign("thisyear", date("Y", $today));
$smarty->assign("thismonth", date("m",$today)); $smarty->assign("thismonth", date("m", $today));
$smarty->assign("thisday", date("d",$today)); $smarty->assign("thisday", date("d", $today));
$output = $smarty->fetch($base."templates/milliways_status.tpl"); $output = $smarty->fetch($base . "templates/milliways_status.tpl");
$smarty->assign("title", "Milliways Status"); $smarty->assign("title", "Milliways Status");
$smarty->assign("body", $output); $smarty->assign("body", $output);
$smarty->assign("extra_styles", "/css/milliways.css"); $smarty->assign("extra_styles", "/css/milliways.css");
$smarty->assign("refresh", 120); $smarty->assign("refresh", 120);
return; return;
} }
if (strtolower($pathlist[$mwpath+1]) == "tag") { if (strtolower($pathlist[$mwpath + 1]) == "tag") {
$smarty->assign("extra_scripts", array( $smarty->assign("extra_scripts", array(
'<meta name="ROBOTS" content="NOINDEX" />', '<meta name="ROBOTS" content="NOINDEX" />',
'<meta name="ROBOTS" content="NOFOLLOW" />')); '<meta name="ROBOTS" content="NOFOLLOW" />'));
$mwdb = new PDO('sqlite:/var/lib/mw/mwuri.db'); $mwdb = new PDO('sqlite:/var/lib/mw/mwuri.db');
if (isset($pathlist[$mwpath+2])) { if (isset($pathlist[$mwpath + 2])) {
$res = $mwdb->prepare("select *, date(added) as day, substr(tag,2) as name from mwtag where tag=? order by added desc"); $res = $mwdb->prepare("select *, date(added) as day, substr(tag,2) as name from mwtag where tag=? order by added desc");
$res->execute(array('#'.$pathlist[$mwpath+2])); $res->execute(array('#' . $pathlist[$mwpath + 2]));
$data = $res->fetchAll(PDO::FETCH_ASSOC); $data = $res->fetchAll(PDO::FETCH_ASSOC);
$smarty->assign("taglist", $data); $smarty->assign("taglist", $data);
$output = $smarty->fetch($base."templates/milliways_tag.tpl"); $output = $smarty->fetch($base . "templates/milliways_tag.tpl");
} else { } else {
$res = $mwdb->prepare("select distinct tag, substr(tag,2) as name, count(tag) as count from mwtag group by tag order by count(tag) desc limit 20"); $res = $mwdb->prepare("select distinct tag, substr(tag,2) as name, count(tag) as count from mwtag group by tag order by count(tag) desc limit 20");
$res->execute(); $res->execute();
$data = $res->fetchAll(PDO::FETCH_ASSOC); $data = $res->fetchAll(PDO::FETCH_ASSOC);
$smarty->assign("toplist", $data); $smarty->assign("toplist", $data);
$res = $mwdb->prepare("select distinct tag, substr(tag,2) as name, count(tag) as count, max(added) as dated, date(max(added)) as day from mwtag group by tag order by max(added) desc limit 20"); $res = $mwdb->prepare("select distinct tag, substr(tag,2) as name, count(tag) as count, max(added) as dated, date(max(added)) as day from mwtag group by tag order by max(added) desc limit 20");
$res->execute(); $res->execute();
$data = $res->fetchAll(PDO::FETCH_ASSOC); $data = $res->fetchAll(PDO::FETCH_ASSOC);
$smarty->assign("latestlist", $data); $smarty->assign("latestlist", $data);
$output = $smarty->fetch($base."templates/milliways_taglist.tpl"); $output = $smarty->fetch($base . "templates/milliways_taglist.tpl");
} }
$smarty->assign("title", "Milliways Tags"); $smarty->assign("title", "Milliways Tags");
$smarty->assign("body", $output); $smarty->assign("body", $output);
$smarty->assign("extra_styles", "/css/milliways.css"); $smarty->assign("extra_styles", "/css/milliways.css");
$smarty->assign("refresh", 120); $smarty->assign("refresh", 120);
return; return;
} }
exec("/usr/bin/mw -who", $wholist, $ret); exec("/usr/bin/mw -who", $wholist, $ret);
...@@ -214,18 +215,18 @@ $people = array(); ...@@ -214,18 +215,18 @@ $people = array();
$idlers = array(); $idlers = array();
foreach ($wholist as $person) { foreach ($wholist as $person) {
$pid = strtok($person, " "); $pid = strtok($person, " ");
if ($pid == "" || $pid == "Name" || substr($pid,0,5)=="-----") continue; if ($pid == "" || $pid == "Name" || substr($pid, 0, 5) == "-----") continue;
$person = array( $person = array(
"username" => trim(substr($person, 1, 16)), "username" => trim(substr($person, 1, 16)),
"idle" => trim(substr($person, 18, 6)), "idle" => trim(substr($person, 18, 6)),
"idleseconds" => parseIdleTime(trim(substr($person, 18, 6))), "idleseconds" => parseIdleTime(trim(substr($person, 18, 6))),
"what" => substr($person,25)); "what" => substr($person, 25));
if ($person['idleseconds'] > 10800) { if ($person['idleseconds'] > 10800) {
$idlers[] = $person; $idlers[] = $person;
} else { } else {
$people[] = $person; $people[] = $person;
} }
} }
usort($people, 'compare_idletime'); usort($people, 'compare_idletime');
...@@ -238,9 +239,9 @@ $mwdb = new PDO('sqlite:/var/lib/mw/mwuri.db'); ...@@ -238,9 +239,9 @@ $mwdb = new PDO('sqlite:/var/lib/mw/mwuri.db');
$res = $mwdb->prepare("select *, time(added,'localtime') as hour, date(added,'localtime') as day from mwuri order by added desc limit 5"); $res = $mwdb->prepare("select *, time(added,'localtime') as hour, date(added,'localtime') as day from mwuri order by added desc limit 5");
$res->execute(); $res->execute();
$urilist = $res->fetchAll(PDO::FETCH_ASSOC); $urilist = $res->fetchAll(PDO::FETCH_ASSOC);
foreach ($urilist as $k=>$v) { foreach ($urilist as $k => $v) {
if ($v['title'] == "") $urilist[$k]['title']=$v['url']; if ($v['title'] == "") $urilist[$k]['title'] = $v['url'];
$urilist[$k]['title']=filter_var(trim($urilist[$k]['title']),FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH | FILTER_FLAG_STRIP_LOW); $urilist[$k]['title'] = filter_var(trim($urilist[$k]['title']), FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH | FILTER_FLAG_STRIP_LOW);
} }
$smarty->assign("urilist", $urilist); $smarty->assign("urilist", $urilist);
...@@ -249,11 +250,11 @@ $res->execute(); ...@@ -249,11 +250,11 @@ $res->execute();
$taglist = $res->fetchAll(PDO::FETCH_ASSOC); $taglist = $res->fetchAll(PDO::FETCH_ASSOC);
$smarty->assign("taglist", $taglist); $smarty->assign("taglist", $taglist);
$smarty->assign("people",$people); $smarty->assign("people", $people);
$smarty->assign("idlers",$idlers); $smarty->assign("idlers", $idlers);
$output = $smarty->fetch($base."templates/milliways.tpl"); $output = $smarty->fetch($base . "templates/milliways.tpl");
$smarty->assign("title", "Milliways"); $smarty->assign("title", "Milliways");
$smarty->assign("body", file_get_contents($base."static/fragments/Milliways.txt")); $smarty->assign("body", file_get_contents($base . "static/fragments/Milliways.txt"));
$smarty->assign("secondary", $output); $smarty->assign("secondary", $output);
$smarty->assign("refresh", 120); $smarty->assign("refresh", 120);
?> ?>
<?php <?php
$motd_file = "/etc/motd"; $motd_file = "/etc/motd";
function decode_entities($text, $quote_style = ENT_COMPAT) { function decode_entities($text, $quote_style = ENT_COMPAT)
if (function_exists('html_entity_decode')) { {
$text = html_entity_decode($text, $quote_style, 'ISO-8859-1'); // NOTE: UTF-8 does not work! $text = html_entity_decode($text, $quote_style, 'ISO-8859-1'); // NOTE: UTF-8 does not work!
} $text = preg_replace('~&ndash\;~i', '-', $text);
else { $text = preg_replace_callback('~&#x([0-9a-f]+);~i',
$trans_tbl = get_html_translation_table(HTML_ENTITIES, $quote_style); function ($matches) {
$trans_tbl = array_flip($trans_tbl); foreach ($matches as $match) {
$text = strtr($text, $trans_tbl); return chr(hexdec($match));
} }
$text = preg_replace('~&ndash\;~i', '-', $text); },
$text = preg_replace('~&#x([0-9a-f]+);~ei', 'chr(hexdec("\\1"))', $text); $text);
$text = preg_replace('~&#([0-9]+);~e', 'chr("\\1")', $text); $text = preg_replace_callback('~&#([0-9]+);~',
return $text; function ($matches) {
foreach ($matches as $match) {
return chr($match);
}
},
$text);
return $text;
} }
//function to count and collect hyperlinks //function to count and collect hyperlinks
$links_count = 0; $links_count = 0;
function linkcounter($uri) { function linkcounter($uri)
global $links_count, $uris; {
$uris[++$links_count] = $uri; global $links_count, $uris;
return $links_count; $uris[++$links_count] = $uri;
return $links_count;
} }
$poemmode = 0;
$news = $DB->GetAll("SELECT * FROM news WHERE sticky=true AND expiry > now() ORDER BY date DESC"); $news = $DB->GetAll("SELECT * FROM news WHERE sticky=true AND expiry > now() ORDER BY date DESC");
if (count($news)<3) {
$news = $DB->GetAll("(SELECT * FROM news WHERE sticky=false AND expiry > now() ORDER by date DESC LIMIT ".(3-count($news)).") UNION SELECT * FROM news WHERE sticky=true AND expiry > now() ORDER BY date DESC"); if (count($news) < 3) {
$news = $DB->GetAll("(SELECT * FROM news WHERE sticky=false AND expiry > now() ORDER by date DESC LIMIT " . (3 - count($news)) . ") UNION SELECT * FROM news WHERE sticky=true AND expiry > now() ORDER BY date DESC");
}
if (count($news) < 1) {
$news = $DB->GetAll("SELECT * FROM poems ORDER BY RANDOM() LIMIT 1");
$poemmode = 1;
} }
$motd = "----------------------------- MESSAGE OF THE DAY ------------------------------\n\n"; $motd = "----------------------------- MESSAGE OF THE DAY ------------------------------\n\n";
for ($i=count($news)-1;$i>-1;$i--) { for ($i = count($news) - 1; $i > -1; $i--) {
$nitem = str_replace("\n", "", $news[$i]); $nitem = str_replace("\n", "", $news[$i]);
$nitem = str_replace("\r", "", $nitem); $nitem = str_replace("\r", "", $nitem);
$motd .= " ".$nitem['title']."\n"; $motd .= " " . $nitem['title'] . "\n";
$body = str_replace("</p>", "\n\n ", $nitem['body']); $body = str_replace("</p>", "\n\n ", $nitem['body']);
$body = str_replace("<br />", "\n ", $body); $body = str_replace("<br />", "\n ", $body);
$body = str_replace("<li>", " * ", $body); $body = str_replace("<li>", " * ", $body);
$body = str_replace("</li>", "\n ", $body); $body = str_replace("</li>", "\n ", $body);
$body = str_replace("&nbsp;", " ", $body); $body = str_replace("&nbsp;", " ", $body);
$body = str_replace("&hellip;", "...", $body); $body = str_replace("&hellip;", "...", $body);
$body = str_replace("&apos;", "'", $body);
// remove hyperlinks, collect to display later // remove hyperlinks, collect to display later
$body = preg_replace(":<a href=['\"](.+?)['\"].*?>(.*?)</a>:e", "'\\2['.linkcounter('\\1').']'", $body); $body = preg_replace_callback(":<a href=['\"](.+?)['\"].*?>(.*?)</a>:",
$body = strip_tags($body); function ($matches) {
$body = decode_entities($body); $i = linkcounter($matches[1]);
$body = wordwrap($body, 75, "\n ", 1); return $matches[0]."[".$i."]";
$body = rtrim($body); },
$motd .=" ".$body."\n"; $body);
if (isset($uris)) { $body = strip_tags($body);
$footer = "----\n"; $body = decode_entities($body);
foreach ($uris as $urinum => $uri) { $body = wordwrap($body, 75, "\n ", 1);
$footer .= " [$urinum]: $uri\n"; $body = rtrim($body);
//remove uri from list so it won't show up on the next post $motd .= " " . $body . "\n";
unset($uris[$urinum]); if (isset($uris)) {
} $footer = "----\n";
$motd .= " ".$footer; foreach ($uris as $urinum => $uri) {
} $footer .= " [$urinum]: $uri\n";
$motd .= str_pad($nitem['author'], 78, " ", STR_PAD_LEFT)."\n\n"; //remove uri from list so it won't show up on the next post
unset($uris[$urinum]);
}
$motd .= " " . $footer;
}
$motd .= str_pad($nitem['author'], 78, " ", STR_PAD_LEFT) . "\n";
if ($poemmode == 1 && $nitem['submitter'] != '') {
$motd .= str_pad("Submitted by " . $nitem['submitter'], 78, " ", STR_PAD_LEFT) . "\n";
}
$motd .= "\n";
} }
$motd .= "---------------------------- [ http://sucs.org/ ] -----------------------------\n"; $motd .= "---------------------------- [ http://sucs.org/ ] -----------------------------\n";
//print($motd);
//if (time()-filemtime($motd_file) < 86000 && $poemmode == 1) { //86000 to allow a little slack depending on when cron runs
// print "MOTD too recent to replace with a poem!\n";
//} else {
file_put_contents($motd_file, $motd); file_put_contents($motd_file, $motd);
?> //}
?>
\ No newline at end of file
<?PHP
require("/var/www/sucssite/htdocs/settings.php");
require("/usr/share/php/adodb/adodb.inc.php");
$dbname = 'sucssite';
$dbuser = 'sucs_site_user';
$DB = NewADOConnection('postgres9');
$DB->Connect('dbname=' . $dbname . ' user=' . $dbuser);
$DB->SetCharSet('utf8');
$DB->SetFetchMode(ADODB_FETCH_ASSOC);
include($base . "components/motd.php");
<? <?php
// guard against corrupt folder data // guard against corrupt folder data
define("TOOBIG",102400); define("TOOBIG", 102400);
function load_folders() function load_folders()
{ {
$f = fopen("/var/lib/mw/folders.bb", "r"); $f = fopen("/var/lib/mw/folders.bb", "r");
$folders = array(); $folders = array();
while (!feof($f) && $fol=fread($f,64)) { while (!feof($f) && $fol = fread($f, 64)) {
$data = unpack("Cstatus/A11name/A31topic/Cspare/Lfirst/Llast", $fol); $data = unpack("Cstatus/A11name/A31topic/Cspare/Lfirst/Llast", $fol);
cleanup($data['name']); cleanup($data['name']);
cleanup($data['topic']); cleanup($data['topic']);
if ($data['status'] & 0x01 && !($data['status']&0x20)) $folders[$data['name']] = $data; if ($data['status'] & 0x01 && !($data['status'] & 0x20)) $folders[$data['name']] = $data;
} }
fclose($f); fclose($f);
return $folders; return $folders;
} }
function cleanup(&$foo) function cleanup(&$foo)
{ {
$i=0; $i = 0;
$new = ""; $new = "";
while ($i < strlen($foo)) { while ($i < strlen($foo)) {
if ( ord($foo[$i]) == 0) break; if (ord($foo[$i]) == 0) break;
if (ctype_print($foo[$i])) if (ctype_print($foo[$i]))
$new .= $foo[$i]; $new .= $foo[$i];
$i++; $i++;
} }
// $foo = htmlentities($new); // $foo = htmlentities($new);
$foo = $new; $foo = $new;
} }
function load_index($folname, $getbody=FALSE) function load_index($folname, $getbody = FALSE)
{ {
$index = array(); $index = array();
$f = @fopen("/var/lib/mw/$folname.i", "r"); $f = @fopen("/var/lib/mw/$folname.i", "r");
$body = @fopen("/var/lib/mw/$folname.t", "r"); $body = @fopen("/var/lib/mw/$folname.t", "r");
if ($f === FALSE || $body === FALSE) return array(); if ($f === FALSE || $body === FALSE) return array();
while (!feof($f) && $fol=fread($f,128)) { while (!feof($f) && $fol = fread($f, 128)) {
$data = unpack("Lref/Ldate/A17from/A41to/A41subject/c1spare/Ldatafield/Lsize/Cstatus/a3spare/Lreplyto/C4spare", $fol); $data = unpack("Lref/Ldate/A17from/A41to/A41subject/c1spare/Ldatafield/Lsize/Cstatus/a3spare/Lreplyto/C4spare", $fol);
cleanup($data['subject']); cleanup($data['subject']);
cleanup($data['to']); cleanup($data['to']);
cleanup($data['from']); cleanup($data['from']);
// not deleted, has data, and want it, so load the body // not deleted, has data, and want it, so load the body
if (!( $data['status'] & 0x02)) { if (!($data['status'] & 0x02)) {
if ($getbody && $data['size']>0 && $data['size'] < TOOBIG) { if ($getbody && $data['size'] > 0 && $data['size'] < TOOBIG) {
fseek($body, $data['datafield']); fseek($body, $data['datafield']);
//$data['body'] = htmlentities(fread($body, $data['size'])); //$data['body'] = htmlentities(fread($body, $data['size']));
$data['body'] = fread($body, $data['size']); $data['body'] = fread($body, $data['size']);
} }
$index[ $data['ref'] ] = $data; $index[$data['ref']] = $data;
} }
} }
fclose($f); fclose($f);
return $index; return $index;
} }
// Count how many articles are replies to this one // Count how many articles are replies to this one
function count_sub(&$haystack, $ref) function count_sub(&$haystack, $ref)
{ {
$count = 0; $count = 0;
foreach($haystack as $k => $v) foreach ($haystack as $k => $v) {
{ if ($v['replyto'] == $ref) {
if ($v['replyto'] == $ref) { $count++;
$count++; $count += count_sub($haystack, $v['ref']);
$count += count_sub($haystack, $v['ref']); }
} }
} return $count;
return $count;
} }
function fetch_sub(&$all, $ref) function fetch_sub(&$all, $ref)
{ {
$sub = array(); $sub = array();
foreach($all as $k => $v) { foreach ($all as $k => $v) {
if ($v['replyto'] == $ref) { if ($v['replyto'] == $ref) {
$sub[$k] = $v; $sub[$k] = $v;
$sub = array_merge($sub, fetch_sub($all, $v['ref'])); $sub = array_merge($sub, fetch_sub($all, $v['ref']));
} }
} }
return $sub; return $sub;
} }
function post_article($folder, $user, $replyto) function post_article($folder, $user, $replyto)
{ {
$folder = escapeshellarg($folder); $folder = escapeshellarg($folder);
$f = popen("/usr/bin/mw -f $folder $user $replyto","w"); $f = popen("/usr/bin/mw -f $folder $user $replyto", "w");
$to = strip_tags($_POST['to']); $to = strip_tags($_POST['to']);
$subject = strip_tags($_POST['subject']); $subject = strip_tags($_POST['subject']);
$body = strip_tags( $_POST['body']); $body = strip_tags($_POST['body']);
$to = preg_replace('/[^[:alnum:][:punct:][:space:]]*/','',trim($to)); $to = preg_replace('/[^[:alnum:][:punct:][:space:]]*/', '', trim($to));
$subject = preg_replace('/[^[:alnum:][:punct:][:space:]]*/','',trim($subject)); $subject = preg_replace('/[^[:alnum:][:punct:][:space:]]*/', '', trim($subject));
$body = preg_replace("/\n\\.\n","\n .\n/",$body); $body = preg_replace("/\n\\.\n", "\n .\n/", $body);
$deb = fopen("/tmp/mwdebug.txt","w"); $deb = fopen("/tmp/mwdebug.txt", "w");
fwrite($deb, "folder: '$folder'\n"); fwrite($deb, "folder: '$folder'\n");
fwrite($deb, "user: '$user'\n"); fwrite($deb, "user: '$user'\n");
fwrite($deb, "replyto: '$replyto'\n"); fwrite($deb, "replyto: '$replyto'\n");
fwrite($deb, "to: '$to'\n"); // Send to fwrite($deb, "to: '$to'\n"); // Send to
fwrite($deb, "sub: '$subject'\n"); // subject fwrite($deb, "sub: '$subject'\n"); // subject
fwrite($deb,"body:\n$body\n.\n"); // end post fwrite($deb, "body:\n$body\n.\n"); // end post
if ($replyto == 0) { if ($replyto == 0) {
fwrite($f, "$to\n"); // Send to fwrite($f, "$to\n"); // Send to
fwrite($f, "$subject\n"); // subject fwrite($f, "$subject\n"); // subject
fwrite($f,"$body\n.\n"); // end post fwrite($f, "$body\n.\n"); // end post
} else { } else {
fwrite($f, "$subject\n"); // subject fwrite($f, "$subject\n"); // subject
fwrite($f, "$to\n"); // send to fwrite($f, "$to\n"); // send to
fwrite($f,"$body\n.\n"); // end post fwrite($f, "$body\n.\n"); // end post
} }
$ret = pclose($f); $ret = pclose($f);
fwrite($deb, "Exit = ".($ret/256)."\n"); fwrite($deb, "Exit = " . ($ret / 256) . "\n");
fclose($deb); fclose($deb);
} }
if (!$session->loggedin) { if (!$session->loggedin) {
$smarty->assign("title", "Milliways"); $smarty->assign("title", "Milliways");
$smarty->assign("body", "Sorry, you must be logged in for this feature"); $smarty->assign("body", "Sorry, you must be logged in for this feature");
return; return;
} }
$folders = load_folders(); $folders = load_folders();
$smarty->assign_by_ref("folders", $folders); $smarty->assignByRef("folders", $folders);
$smarty->assign("extra_styles", array("/css/forum/SUCS.css")); $smarty->assign("extra_styles", array("/css/forum/SUCS.css"));
unset($mode); unset($mode);
$last = end($pathlist); $last = end($pathlist);
if ($last == "new" || $last == "reply") { if ($last == "new" || $last == "reply") {
$mode = $last; $mode = $last;
array_pop($pathlist); array_pop($pathlist);
$path = implode("/",$pathlist); $path = implode("/", $pathlist);
/* $smarty->assign("extra_scripts", array( /* $smarty->assign("extra_scripts", array(
'<script language="javascript" type="text/javascript" src="/js/tinymce/jscripts/tiny_mce/tiny_mce.js"></script>', '<script language="javascript" type="text/javascript" src="/js/tinymce/jscripts/tiny_mce/tiny_mce.js"></script>',
'<script language="javascript" type="text/javascript" src="/js/tiny_mce.js"></script>' '<script language="javascript" type="text/javascript" src="/js/tiny_mce.js"></script>'
)); ));
*/ */
} }
if ($last == "post") { if ($last == "post") {
$mode = $last; $mode = $last;
array_pop($pathlist); array_pop($pathlist);
$path = implode("/",$pathlist); $path = implode("/", $pathlist);
} }
$smarty->assign("mode",$mode); $smarty->assign("mode", $mode);
$shortpathlist = $pathlist; $shortpathlist = $pathlist;
array_pop($shortpathlist); array_pop($shortpathlist);
$shortpath = implode("/",$shortpathlist); $shortpath = implode("/", $shortpathlist);
$smarty->assign("shortpath",$shortpath); $smarty->assign("shortpath", $shortpath);
if (isset($pathlist[3])) { if (isset($pathlist[3])) {
$name = $pathlist[3]; $name = $pathlist[3];
if (isset($folders[$name])) { if (isset($folders[$name])) {
$smarty->assign("folder", $folders[$name]['name']); $smarty->assign("folder", $folders[$name]['name']);
$all = load_index($name, TRUE); $all = load_index($name, TRUE);
// One specific article was mentioned // One specific article was mentioned
if (isset($pathlist[4])) { if (isset($pathlist[4])) {
$artno = (int)$pathlist[4]; $artno = (int)$pathlist[4];
if (isset($all[$artno])) { if (isset($all[$artno])) {
if ($mode == "post") { if ($mode == "post") {
post_article($name, $session->username, $artno); post_article($name, $session->username, $artno);
$all = load_index($name, TRUE); $all = load_index($name, TRUE);
} }
$smarty->assign("title", "Milliways"); $smarty->assign("title", "Milliways");
$smarty->assign_by_ref("message", $all[$artno]); $smarty->assign_by_ref("message", $all[$artno]);
$sub = fetch_sub($all, $all[$artno]['ref']); $sub = fetch_sub($all, $all[$artno]['ref']);
$smarty->assign_by_ref("articles", $sub); $smarty->assign_by_ref("articles", $sub);
$smarty->assign("howmany",count($sub)); $smarty->assign("howmany", count($sub));
$output = $smarty->fetch($base."templates/mw-article.tpl"); $output = $smarty->fetch($base . "templates/mw-article.tpl");
} }
} else { } else {
if ($mode == "post") { if ($mode == "post") {
post_article($name, $session->username, 0); post_article($name, $session->username, 0);
$all = load_index($name, TRUE); $all = load_index($name, TRUE);
} }
// list all the articles in this folder // list all the articles in this folder
$top = array(); $top = array();
foreach ($all as $k => $v) { foreach ($all as $k => $v) {
if ($v['replyto'] == 0 ) { if ($v['replyto'] == 0) {
$v['suball'] = fetch_sub($all,$v['ref']); $v['suball'] = fetch_sub($all, $v['ref']);
$v['sub'] = count($v['suball']); $v['sub'] = count($v['suball']);
$l = end($v['suball']); $l = end($v['suball']);
$v['lastpost'] = $l['date']; $v['lastpost'] = $l['date'];
$v['lastfrom'] = $l['from']; $v['lastfrom'] = $l['from'];
$top[$k]=$v; $top[$k] = $v;
} }
} }
$top = array_reverse($top); $top = array_reverse($top);
$smarty->assign("title", htmlentities("Milliways - Folder $name")); $smarty->assign("title", htmlentities("Milliways - Folder $name"));
$smarty->assign_by_ref("articles", $top); $smarty->assign_by_ref("articles", $top);
$output = $smarty->fetch($base."templates/mw-list.tpl"); $output = $smarty->fetch($base . "templates/mw-list.tpl");
} }
} else { } else {
$output = "Error, no such folder $name"; $output = "Error, no such folder $name";
} }
$smarty->assign("body", $output); $smarty->assign("body", $output);
} else { } else {
// List all the folders // List all the folders
foreach($folders as $k => $v) { foreach ($folders as $k => $v) {
$list = load_index($v['name']); $list = load_index($v['name']);
$topics = 0; $topics = 0;
foreach ($list as $art) if ($art['replyto'] == 0) $topics++; foreach ($list as $art) if ($art['replyto'] == 0) $topics++;
$folders[$k]['topics'] = $topics; $folders[$k]['topics'] = $topics;
$lastone = end($list); $lastone = end($list);
$folders[$k]['lastpost'] = $lastone['date']; $folders[$k]['lastpost'] = $lastone['date'];
} }
$smarty->assign("title", "Milliways - Topic List"); $smarty->assign("title", "Milliways - Topic List");
$output = $smarty->fetch($base."templates/mw-folders.tpl"); $output = $smarty->fetch($base . "templates/mw-folders.tpl");
$smarty->assign("body", $output); $smarty->assign("body", $output);
} }
?> ?>
<?php <?php
// Ensure we have a trailing slash so that relative links within the page work // Ensure we have a trailing slash so that relative links within the page work
if ($_SERVER['PATH_INFO']=="/News") header("Location: ".$baseurl."/News/"); if ($_SERVER['PATH_INFO'] == "/News") header("Location: " . $baseurl . "/News/");
// A user must be in the staff group in order to edit content in this component // A user must be in the staff group in order to edit content in this component
$permission = "sucsstaff"; $permission = "sucsstaff";
...@@ -8,39 +8,39 @@ $newstable = "news"; ...@@ -8,39 +8,39 @@ $newstable = "news";
if (isset($session->groups[$permission])) { if (isset($session->groups[$permission])) {
// display Edit links on page // display Edit links on page
$smarty->assign("editable", TRUE); $smarty->assign("editable", TRUE);
switch (@$_REQUEST['action']) { switch (@$_REQUEST['action']) {
case "Save": case "Save":
$record['title'] = $_REQUEST['edittitle']; $record['title'] = $_REQUEST['edittitle'];
$record['body'] = $_REQUEST['body']; $record['body'] = $_REQUEST['body'];
if (isset($_REQUEST['sticky'])) if (isset($_REQUEST['sticky']))
$record['sticky'] = 't'; $record['sticky'] = 't';
else else
$record['sticky'] = 'f'; $record['sticky'] = 'f';
if ($_REQUEST['id']=="*") { if ($_REQUEST['id'] == "*") {
$record['author'] = $session->username; $record['author'] = $session->username;
$record['date'] = "now"; $record['date'] = "now";
$DB->AutoExecute($newstable, $record, 'INSERT'); $DB->AutoExecute($newstable, $record, 'INSERT');
} else { } else {
$DB->AutoExecute($newstable, $record, 'UPDATE', "id=".$DB->qstr($_REQUEST['id'])); $DB->AutoExecute($newstable, $record, 'UPDATE', "id=" . $DB->qstr($_REQUEST['id']));
} }
include("motd.php"); include("motd.php");
break; break;
case "Delete": case "Delete":
$deleted = $DB->Execute("DELETE FROM $newstable WHERE id=?", array($_REQUEST['id'])); $deleted = $DB->Execute("DELETE FROM $newstable WHERE id=?", array($_REQUEST['id']));
include("motd.php"); include("motd.php");
break; break;
case "Expire": case "Expire":
$expired = $DB->Execute("UPDATE $newstable SET expiry=now() WHERE id=?", array($_REQUEST['id'])); $expired = $DB->Execute("UPDATE $newstable SET expiry=now() WHERE id=?", array($_REQUEST['id']));
include("motd.php"); include("motd.php");
break; break;
} }
} }
$query = "SELECT *, date_part('epoch', expiry) AS expirytime FROM news"; $query = "SELECT *, date_part('epoch', expiry) AS expirytime FROM news";
if (@$pathlist[2]!="") $query .= " WHERE title=".$DB->qstr($pathlist[2]); if (@$pathlist[2] != "") $query .= " WHERE title=" . $DB->qstr($pathlist[2]);
$query .= " ORDER BY date DESC"; $query .= " ORDER BY date DESC";
$smarty->assign("news", $DB->GetArray($query)); $smarty->assign("news", $DB->GetArray($query));
...@@ -50,25 +50,25 @@ $smarty->assign("title", "News"); ...@@ -50,25 +50,25 @@ $smarty->assign("title", "News");
if (isset($session->groups[$permission])) { if (isset($session->groups[$permission])) {
// Perform any requested actions // Perform any requested actions
switch (@$_REQUEST['action']) { switch (@$_REQUEST['action']) {
case "create": case "create":
$news = array(array("id" => "*")); $news = array(array("id" => "*"));
$smarty->assign("news", $news); $smarty->assign("news", $news);
case "edit": case "edit":
$output = $smarty->fetch("news_edit.tpl"); $output = $smarty->fetch("news_edit.tpl");
$smarty->assign("action", "edit"); $smarty->assign("action", "edit");
$smarty->assign("title", "Edit News"); $smarty->assign("title", "Edit News");
break; break;
case "delete-query": case "delete-query":
$output = $smarty->fetch('news_delete.tpl').$output; $output = $smarty->fetch('news_delete.tpl') . $output;
break; break;
case "expire-query": case "expire-query":
$output = $smarty->fetch('news_expire.tpl').$output; $output = $smarty->fetch('news_expire.tpl') . $output;
break; break;
case "Delete": case "Delete":
if ($deleted) $output = "News item deleted"; if ($deleted) $output = "News item deleted";
break; break;
} }
} }
$smarty->assign("body", $output); $smarty->assign("body", $output);
......
This diff is collapsed.
<?php <?php
$permission="html"; $permission = "html";
// Only html group members can use this page - horrible emergency bodge // Only html group members can use this page - horrible emergency bodge
if (isset($session->groups[$permission])) { if (isset($session->groups[$permission])) {
...@@ -10,28 +10,28 @@ if (isset($session->groups[$permission])) { ...@@ -10,28 +10,28 @@ if (isset($session->groups[$permission])) {
unset($output); unset($output);
if (@$pathlist[3] == "Edit") { if (@$pathlist[3] == "Edit") {
if (isset($_REQUEST['mapid'])) { if (isset($_REQUEST['mapid'])) {
$id = (int)$_REQUEST['mapid']; $id = (int)$_REQUEST['mapid'];
$res = $DB->GetAll("SELECT * FROM pagemap where id=?", array($id)); $res = $DB->GetAll("SELECT * FROM pagemap where id=?", array($id));
if ($res && count($res) > 0) { if ($res && count($res) > 0) {
$smarty->assign("oldmap",$res[0]); $smarty->assign("oldmap", $res[0]);
$output = $smarty->fetch($base."templates/pagemap_edit.tpl"); $output = $smarty->fetch($base . "templates/pagemap_edit.tpl");
} else { } else {
header("Location: /Admin/Pagemap"); header("Location: /Admin/Pagemap");
exit; exit;
} }
} else { } else {
header("Location: /Admin/Pagemap"); header("Location: /Admin/Pagemap");
exit; exit;
} }
} }
} }
if (!isset($output)) { if (!isset($output)) {
$smarty->assign("map",$DB->GetAll("SELECT * FROM pagemap ORDER BY depth, path")); $smarty->assign("map", $DB->GetAll("SELECT * FROM pagemap ORDER BY depth, path"));
$output = $smarty->fetch($base."templates/pagemap.tpl"); $output = $smarty->fetch($base . "templates/pagemap.tpl");
} }
$smarty->assign("title", "Page Map"); $smarty->assign("title", "Page Map");
$smarty->assign("body", $output); $smarty->assign("body", $output);
......
This diff is collapsed.