Commit 1704da03 authored by Imran Hussain's avatar Imran Hussain
Browse files

Run a code reformatting tool against the sucsite php code.

parent e2bf8da2
......@@ -8,34 +8,34 @@ $members = new Members;
$banana_index = array_search("Bananas", $pathlist);
if ((sizeof($pathlist) > $banana_index + 1) && (trim($pathlist[$banana_index + 1]) != "")) {
$mode = "detail";
$who = $pathlist[$banana_index + 1];
$mode = "detail";
$who = $pathlist[$banana_index + 1];
} else {
// User wasn't looking for anything in particular, so bump them to the Members page
header("HTTP/1.1 301 Moved Permanently");
header("Location: https://$preferred_hostname$baseurl/Community/Members/");
// User wasn't looking for anything in particular, so bump them to the Members page
header("HTTP/1.1 301 Moved Permanently");
header("Location: https://$preferred_hostname$baseurl/Community/Members/");
}
/* redirect requests for members' bananas to Members component. Only serve banana info for non-members (e.g. LIS ;-)) */
if (count($members->memberView($who)) > 0) {
// this is actually a real member, so serve a redirect and let Members handle it
header("HTTP/1.1 301 Moved Permanently");
header("Location: https://$preferred_hostname$baseurl/Community/Members/$who");
// this is actually a real member, so serve a redirect and let Members handle it
header("HTTP/1.1 301 Moved Permanently");
header("Location: https://$preferred_hostname$baseurl/Community/Members/$who");
} else {
// banana admin bits
if ($mode == "detail") {
if ($session->loggedin) {
include("../lib/banana-admin.php");
}
}
// attempt to find some bananas for this name in the database
$smarty->assign("awards",$DB->GetAll("SELECT *, date_trunc('second', whn) FROM awards WHERE username=? ORDER BY whn DESC", array($who)));
// banana admin bits
if ($mode == "detail") {
if ($session->loggedin) {
include("../lib/banana-admin.php");
}
}
// attempt to find some bananas for this name in the database
$smarty->assign("awards", $DB->GetAll("SELECT *, date_trunc('second', whn) FROM awards WHERE username=? ORDER BY whn DESC", array($who)));
}
if (isset($who))
$smarty->assign('who', "$who");
$smarty->assign('who', "$who");
$smarty->assign('mode', "$mode");
......@@ -46,5 +46,4 @@ $smarty->assign('title', "Banana Awards");
$smarty->assign('body', $result);
?>
<?php
function listdir($mypath, $recurse, $summaries) {
global $DB, $base;
function listdir($mypath, $recurse, $summaries)
{
global $DB, $base;
$dirlist = @scandir($base."static".$mypath);
$output = array();
if (is_array($dirlist)) foreach($dirlist as $file) {
// Hide files starting with a .
if ($file[0]!=".") {
$element = array();
if (!is_dir($base."static".$mypath."/".$file)) {
$pagename = preg_replace("/\.txt/", "", $file);
if ($summaries) $element['summary'] = $DB->GetOne("select summary from static where path=?", array($mypath."/".$pagename));
if ($pagename!=@$lastdir) $output[$pagename]=str_replace("_", " ", $element);
} else {
if ($recurse) $element['file']=listdir($mypath."/".$file, $recurse, $summaries);
if ($summaries) $element['summary'] = $DB->GetOne("select summary from static where path=?", array($mypath."/".$file));
$output[$file]=$element;
$lastdir=$file;
}
}
}
return $output;
$dirlist = @scandir($base . "static" . $mypath);
$output = array();
if (is_array($dirlist)) foreach ($dirlist as $file) {
// Hide files starting with a .
if ($file[0] != ".") {
$element = array();
if (!is_dir($base . "static" . $mypath . "/" . $file)) {
$pagename = preg_replace("/\.txt/", "", $file);
if ($summaries) $element['summary'] = $DB->GetOne("select summary from static where path=?", array($mypath . "/" . $pagename));
if ($pagename != @$lastdir) $output[$pagename] = str_replace("_", " ", $element);
} else {
if ($recurse) $element['file'] = listdir($mypath . "/" . $file, $recurse, $summaries);
if ($summaries) $element['summary'] = $DB->GetOne("select summary from static where path=?", array($mypath . "/" . $file));
$output[$file] = $element;
$lastdir = $file;
}
}
}
return $output;
}
if ($path==$component['path']) {
$dirlist = listdir($component['path'], TRUE, TRUE);
if ($path == $component['path']) {
$dirlist = listdir($component['path'], TRUE, TRUE);
$smarty->assign('rootnode', $component['path']);
$smarty->assign('dirlist', $dirlist);
$output = $smarty->fetch('contents.tpl');
$smarty->assign('title', $pathlist[1]);
$smarty->assign('body', $output);
$smarty->assign('rootnode', $component['path']);
$smarty->assign('dirlist', $dirlist);
$output = $smarty->fetch('contents.tpl');
$smarty->assign('title', $pathlist[1]);
$smarty->assign('body', $output);
} else {
include("static.php");
include("static.php");
if ($title!="File not found") {
if (!is_dir($base."static".$path)) {
$pos = strrpos($path, "/");
$path = substr($path, 0, $pos);
}
if ($title != "File not found") {
if (!is_dir($base . "static" . $path)) {
$pos = strrpos($path, "/");
$path = substr($path, 0, $pos);
}
$dirlist = listdir($path, FALSE, FALSE);
$smarty->assign('rootnode', $path);
$smarty->assign('data', $dirlist);
$smarty->assign('level', 0);
if (!isset($_REQUEST['action'])) {
$output = $smarty->fetch('contents-loop.tpl');
$smarty->assign("secondary", "<div class=\"cbb\"><h3>In this section</h3>".$output."</div>");
}
}
$dirlist = listdir($path, FALSE, FALSE);
$smarty->assign('rootnode', $path);
$smarty->assign('data', $dirlist);
$smarty->assign('level', 0);
if (!isset($_REQUEST['action'])) {
$output = $smarty->fetch('contents-loop.tpl');
$smarty->assign("secondary", "<div class=\"cbb\"><h3>In this section</h3>" . $output . "</div>");
}
}
}
?>
<?php
$output = "<pre>".print_r($session, true)."</pre>";
$output = "<pre>" . print_r($session, true) . "</pre>";
$smarty->assign("title", "Debug");
$smarty->assign("body", $output);
?>
<?
exec("/usr/local/bin/shame.py -a", $Shame);
for ( $i=1 ; $i < (count($Shame) - 1); $i++)
{
list($space, $place, $user, $size) = preg_split("/ +/", $Shame[$i]);
if ($i <= 12)
{
$item[]=$user;
$slice[]=preg_replace('/M/', '', ${size});
}
else {
$otherSize += preg_replace('/M/', '', ${size});
}
}
exec("/usr/local/bin/shame.py -a", $Shame);
for ($i = 1; $i < (count($Shame) - 1); $i++) {
list($space, $place, $user, $size) = preg_split("/ +/", $Shame[$i]);
if ($i <= 12) {
$item[] = $user;
$slice[] = preg_replace('/M/', '', ${size});
} else {
$otherSize += preg_replace('/M/', '', ${size});
}
}
// $itemName[]="Other";
// $sliceSize[]=$otherSize;
$slice = array_merge(array($otherSize),$slice);
$item = array_merge(array("Other"), $item);
$slice = array_merge(array($otherSize), $slice);
$item = array_merge(array("Other"), $item);
/* echo "<pre>";
print_r($slice);
print_r($item);*/
include("../../lib/pieChart.php");
piechart("Top 12 Users of disk space", $slice, $item, 1)
include("../../lib/pieChart.php");
piechart("Top 12 Users of disk space", $slice, $item, 1)
?>
<? exec("/usr/local/bin/shame.py -a", $Shame);
$max=10; //SET to number of users to display
$smarty->assign('title',"The SUCS Hall of Shame");
<? exec("/usr/local/bin/shame.py -a", $Shame);
$max = 10; //SET to number of users to display
$smarty->assign('title', "The SUCS Hall of Shame");
//$o="<div style='text-align: center;'><img src=\"/images/disk.graph.php\" alt=\"pie chart of top 12 disk users\"/></div>";
$o.="<table align=\"center\">\n";
$o.="\t<tr><th align=\"center\">User</th><th align=\"center\">Home Directory Size</th></tr>\n";
for ( $i=1 ; $i < 13 /*(count($Shame) - 1)*/; $i++)
{
list($space, $place, $user, $size) = preg_split("/ +/", $Shame[$i]);
if ($size > 0)
$o.="\t<tr><td align=\"center\">$user</td><td align=\"center\">${size}B</td></tr>\n";
}
exec("df -m /home",$dfraw);
$dfout = preg_split('/[ ]+/', $dfraw[1]);
$o.="\t<tr><td align=\"center\" colspan=\"2\">".floor($dfout[2]/1024)."GB used of ".floor($dfout[1]/1024). "GB (".floor($dfout[3]/1024)."GB available)</td></tr>\n";
$o.="</table>\n";
$o.=$Shame[count($Shame) - 1];
$o.="<br />\n";
//readfile("tail.html");
$out="<script type=\"text/javascript\" src=\"https://www.google.com/jsapi\"></script>
$o .= "<table align=\"center\">\n";
$o .= "\t<tr><th align=\"center\">User</th><th align=\"center\">Home Directory Size</th></tr>\n";
for ($i = 1; $i < 13 /*(count($Shame) - 1)*/; $i++) {
list($space, $place, $user, $size) = preg_split("/ +/", $Shame[$i]);
if ($size > 0)
$o .= "\t<tr><td align=\"center\">$user</td><td align=\"center\">${size}B</td></tr>\n";
}
exec("df -m /home", $dfraw);
$dfout = preg_split('/[ ]+/', $dfraw[1]);
$o .= "\t<tr><td align=\"center\" colspan=\"2\">" . floor($dfout[2] / 1024) . "GB used of " . floor($dfout[1] / 1024) . "GB (" . floor($dfout[3] / 1024) . "GB available)</td></tr>\n";
$o .= "</table>\n";
$o .= $Shame[count($Shame) - 1];
$o .= "<br />\n";
//readfile("tail.html");
$out = "<script type=\"text/javascript\" src=\"https://www.google.com/jsapi\"></script>
<script type=\"text/javascript\">
google.load(\"visualization\", \"1\", {packages:[\"corechart\"]});
google.setOnLoadCallback(drawChart);
......@@ -26,26 +25,28 @@
var data = new google.visualization.DataTable();
data.addColumn('string', 'User');
data.addColumn('number', 'Megabytes in use');
data.addRows(".(count($Shame) - 1).");\n";
for( $i=0; $i<(count($Shame) - 3); $i++ ){
list($u,$d)=parseLine($Shame[$i+1]);
$out.="data.setValue(".($i+1).", 0, '".$u."');\n";
$out.="data.setValue(".($i+1).", 1,".$d.");\n";
}
$others=0;
for ( $i=$max; $i<count($data); $i++ ) {
list($u,$d)=parseLine($Shame[$i+1]);
$others+=$d;
}
$out.="data.setValue(0, 0, 'Free Space');\ndata.setValue(0,1,".$dfout[3]." );\n";
$out.="\t\tvar chart = new google.visualization.PieChart(document.getElementById('chart_div'));
data.addRows(" . (count($Shame) - 1) . ");\n";
for ($i = 0; $i < (count($Shame) - 3); $i++) {
list($u, $d) = parseLine($Shame[$i + 1]);
$out .= "data.setValue(" . ($i + 1) . ", 0, '" . $u . "');\n";
$out .= "data.setValue(" . ($i + 1) . ", 1," . $d . ");\n";
}
$others = 0;
for ($i = $max; $i < count($data); $i++) {
list($u, $d) = parseLine($Shame[$i + 1]);
$others += $d;
}
$out .= "data.setValue(0, 0, 'Free Space');\ndata.setValue(0,1," . $dfout[3] . " );\n";
$out .= "\t\tvar chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {width: 500, height: 360, backgroundColor: 'none', is3D: true, title: 'Disk Usage',sliceVisibilityThreshold: 1/180});
}
</script>";
$out.="<div id='chart_div' align='center'></div>";
$smarty->assign('body', ($out.$o));
function parseLine($l){
$fields=explode("|",preg_filter("/[ ]+/","|",$l));
return array(trim($fields[2]),trim(str_replace("M","",$fields[3])));
$out .= "<div id='chart_div' align='center'></div>";
$smarty->assign('body', ($out . $o));
function parseLine($l)
{
$fields = explode("|", preg_filter("/[ ]+/", "|", $l));
return array(trim($fields[2]), trim(str_replace("M", "", $fields[3])));
}
?>
<?php
<?php
$smarty->assign("election_year", ELECTION_YEAR);
$smarty->assign("title", "Executive Election ".ELECTION_YEAR);
function display_ballot() {
global $DB, $smarty, $output;
require_once("../lib/members.php");
$members = new Members;
$role = $DB->GetAll("SELECT post FROM election_candidates GROUP BY post");
foreach ($role as $post) {
$candidate[$post['post']] = $DB->GetAll("SELECT username, manifesto_link FROM election_candidates WHERE post=? ORDER BY username ASC", $post['post']);
$i=0;
foreach ($candidate[$post['post']] as $person) {
$details = $members->memberView($person['username']);
$candidate[$post['post']][$i]['realname'] = $details[0]['cn'];
if (empty($person['manifesto_link'])) $candidate[$post['post']][$i]['manifesto_link'] = ELECTION_NO_MANIFESTO;
$i++;
}
}
$smarty->assign("candidate", $candidate);
$output = $smarty->fetch('election-vote.tpl');
$smarty->assign("title", "Executive Election " . ELECTION_YEAR);
function display_ballot()
{
global $DB, $smarty, $output;
require_once("../lib/members.php");
$members = new Members;
$role = $DB->GetAll("SELECT post FROM election_candidates GROUP BY post");
foreach ($role as $post) {
$candidate[$post['post']] = $DB->GetAll("SELECT username, manifesto_link FROM election_candidates WHERE post=? ORDER BY username ASC", $post['post']);
$i = 0;
foreach ($candidate[$post['post']] as $person) {
$details = $members->memberView($person['username']);
$candidate[$post['post']][$i]['realname'] = $details[0]['cn'];
if (empty($person['manifesto_link'])) $candidate[$post['post']][$i]['manifesto_link'] = ELECTION_NO_MANIFESTO;
$i++;
}
}
$smarty->assign("candidate", $candidate);
$output = $smarty->fetch('election-vote.tpl');
}
if (!$session->loggedin) {
# You can't vote if you're not logged in!
trigger_error("You are not logged in.", E_USER_WARNING);
# You can't vote if you're not logged in!
trigger_error("You are not logged in.", E_USER_WARNING);
} else {
# The election hasn't started yet
if (strtotime('now') < strtotime(ELECTION_START)) trigger_error("The polling station is not yet open. Voting begins on ".date('l jS F, Y \a\t H:i', strtotime(ELECTION_START)).".");
# The election is over - display the results
else if (strtotime('now') > strtotime(ELECTION_END)) {
require_once("../lib/members.php");
$members = new Members;
$role = $DB->GetAll("SELECT post FROM election_candidates GROUP BY post");
foreach ($role as $post) {
$candidate[$post['post']] = $DB->GetAll("SELECT username, manifesto_link FROM election_candidates WHERE post=?", $post['post']);
$i=0;
foreach ($candidate[$post['post']] as $person) {
$details = $members->memberView($person['username']);
$candidate[$post['post']][$i]['realname'] = $details[0]['cn'];
if (empty($person['manifesto_link'])) $candidate[$post['post']][$i]['manifesto_link'] = ELECTION_NO_MANIFESTO;
$candidate[$post['post']][$i]['votes'] = $DB->GetOne("SELECT count(username) FROM election_votes WHERE ".$post['post']."=?", array($person['username']));
$i++;
}
}
$smarty->assign("candidate", $candidate);
$output = $smarty->fetch('election-results.tpl');
} else {
# It's election time
# Check the user hasn't already voted
$vote_details = $DB->GetRow("SELECT time, ipaddress FROM election_votes WHERE username=?", $session->username);
if (count($vote_details)>0) {
trigger_error("You already voted on ".date('l jS F, Y \a\t H:i', strtotime($vote_details['time']))." from IP address ".$vote_details['ipaddress'].".", E_USER_WARNING);
$output = "<p>Please email the Returning Officer at <a href=\"mailto:vote@sucs.org\">vote@sucs.org</a> with any queries.</p>\n<p>Once polling has closed on ".date('l jS F, Y \a\t H:i', strtotime(ELECTION_END)).", the election results will be available on this page.</p>";
} else {
if ($_POST['submit']=="Cast Votes") {
# We have a ballot paper to process
$output = "<h2>Thank you for your vote</h2>\n<p>You will shortly receive an email confirming your vote.</p>\n<p>Once polling has closed on ".date('l jS F, Y \a\t H:i', strtotime(ELECTION_END)).", the election results will be available on this page.</p>";
# Establish which positions are contested
$role = $DB->GetCol("SELECT post FROM election_candidates GROUP BY post HAVING count(username) > 1");
$fail = FALSE;
$invalid_candidate = FALSE;
$abstain_count = 0;
foreach ($role as $post) {
if ($_POST[$post] == "abstain") $abstain_count++;
# check that we have a valid option selected
if (!($DB->GetOne("SELECT username FROM election_candidates WHERE post=? AND username=?", array($post, $_POST[$post])) || $_POST[$post]=="abstain")) $fail = TRUE;
}
# Check their password first
if ($session->check_pass($session->username, $_POST['vote_passwd'])) {
if ($fail) {
# Either no option or an invalid candidate was supplied
trigger_error("An invalid option was selected in at least one ballot. Please try again.", E_USER_WARNING);
display_ballot();
} else {
# User has abstained in all votes
if ($abstain_count == count($role)) {
trigger_error("You have not selected any candidates in any ballots.", E_USER_WARNING);
display_ballot();
} else {
# The input is valid - record the vote
$vote = array(
'username' => $session->username,
'time' => 'now',
'ipaddress' => $_SERVER['REMOTE_ADDR']);
# Email the Returning Officer
$ro_message = "User: ".$vote['username']."\nIP: ".$vote['ipaddress']."\n\n";
# Email the voter with confirmation
$voter_message = "Thank you for voting in the SUCS election this year. Here are the votes you cast:\n\n";
foreach ($role as $post) {
# Don't add votes up as we go
# $DB->Execute("UPDATE election_candidates SET votes=votes+1 WHERE post=? AND username=?", array($post, $_POST[$post]));
$vote[$post] = $_POST[$post];
$ro_message .= ucfirst($post).": ".$_POST[$post]."\n";
$voter_message .= ucfirst($post).": ".$_POST[$post]."\n";
}
$voter_message .= "\nResults of the election will be announced on ".date('l jS F, Y \a\t H:i', strtotime(ELECTION_END))." at http://sucs.org/Vote\n";
$DB->AutoExecute("election_votes", $vote, 'INSERT');
mail("SUCS Returning Officer <vote@sucs.org>", "[SUCS Election] Vote received from ".$vote['username'], $ro_message, "From: SUCS Election ".ELECTION_YEAR." <vote@sucs.org>");
mail($session->fullname." <".$session->username."@sucs.org>", "[SUCS Election] Thanks For Voting", $voter_message, "From: SUCS Election ".ELECTION_YEAR." <vote@sucs.org>");
}
}
} else {
display_ballot();
}
} else {
# Display the ballot paper
display_ballot();
}
}
}
# The election hasn't started yet
if (strtotime('now') < strtotime(ELECTION_START)) trigger_error("The polling station is not yet open. Voting begins on " . date('l jS F, Y \a\t H:i', strtotime(ELECTION_START)) . ".");
# The election is over - display the results
else if (strtotime('now') > strtotime(ELECTION_END)) {
require_once("../lib/members.php");
$members = new Members;
$role = $DB->GetAll("SELECT post FROM election_candidates GROUP BY post");
foreach ($role as $post) {
$candidate[$post['post']] = $DB->GetAll("SELECT username, manifesto_link FROM election_candidates WHERE post=?", $post['post']);
$i = 0;
foreach ($candidate[$post['post']] as $person) {
$details = $members->memberView($person['username']);
$candidate[$post['post']][$i]['realname'] = $details[0]['cn'];
if (empty($person['manifesto_link'])) $candidate[$post['post']][$i]['manifesto_link'] = ELECTION_NO_MANIFESTO;
$candidate[$post['post']][$i]['votes'] = $DB->GetOne("SELECT count(username) FROM election_votes WHERE " . $post['post'] . "=?", array($person['username']));
$i++;
}
}
$smarty->assign("candidate", $candidate);
$output = $smarty->fetch('election-results.tpl');
} else {
# It's election time
# Check the user hasn't already voted
$vote_details = $DB->GetRow("SELECT time, ipaddress FROM election_votes WHERE username=?", $session->username);
if (count($vote_details) > 0) {
trigger_error("You already voted on " . date('l jS F, Y \a\t H:i', strtotime($vote_details['time'])) . " from IP address " . $vote_details['ipaddress'] . ".", E_USER_WARNING);
$output = "<p>Please email the Returning Officer at <a href=\"mailto:vote@sucs.org\">vote@sucs.org</a> with any queries.</p>\n<p>Once polling has closed on " . date('l jS F, Y \a\t H:i', strtotime(ELECTION_END)) . ", the election results will be available on this page.</p>";
} else {
if ($_POST['submit'] == "Cast Votes") {
# We have a ballot paper to process
$output = "<h2>Thank you for your vote</h2>\n<p>You will shortly receive an email confirming your vote.</p>\n<p>Once polling has closed on " . date('l jS F, Y \a\t H:i', strtotime(ELECTION_END)) . ", the election results will be available on this page.</p>";
# Establish which positions are contested
$role = $DB->GetCol("SELECT post FROM election_candidates GROUP BY post HAVING count(username) > 1");
$fail = FALSE;
$invalid_candidate = FALSE;
$abstain_count = 0;
foreach ($role as $post) {
if ($_POST[$post] == "abstain") $abstain_count++;
# check that we have a valid option selected
if (!($DB->GetOne("SELECT username FROM election_candidates WHERE post=? AND username=?", array($post, $_POST[$post])) || $_POST[$post] == "abstain")) $fail = TRUE;
}
# Check their password first
if ($session->check_pass($session->username, $_POST['vote_passwd'])) {
if ($fail) {
# Either no option or an invalid candidate was supplied
trigger_error("An invalid option was selected in at least one ballot. Please try again.", E_USER_WARNING);
display_ballot();
} else {
# User has abstained in all votes
if ($abstain_count == count($role)) {
trigger_error("You have not selected any candidates in any ballots.", E_USER_WARNING);
display_ballot();
} else {
# The input is valid - record the vote
$vote = array(
'username' => $session->username,
'time' => 'now',
'ipaddress' => $_SERVER['REMOTE_ADDR']);
# Email the Returning Officer
$ro_message = "User: " . $vote['username'] . "\nIP: " . $vote['ipaddress'] . "\n\n";
# Email the voter with confirmation
$voter_message = "Thank you for voting in the SUCS election this year. Here are the votes you cast:\n\n";
foreach ($role as $post) {
# Don't add votes up as we go
# $DB->Execute("UPDATE election_candidates SET votes=votes+1 WHERE post=? AND username=?", array($post, $_POST[$post]));
$vote[$post] = $_POST[$post];
$ro_message .= ucfirst($post) . ": " . $_POST[$post] . "\n";
$voter_message .= ucfirst($post) . ": " . $_POST[$post] . "\n";
}
$voter_message .= "\nResults of the election will be announced on " . date('l jS F, Y \a\t H:i', strtotime(ELECTION_END)) . " at http://sucs.org/Vote\n";
$DB->AutoExecute("election_votes", $vote, 'INSERT');
mail("SUCS Returning Officer <vote@sucs.org>", "[SUCS Election] Vote received from " . $vote['username'], $ro_message, "From: SUCS Election " . ELECTION_YEAR . " <vote@sucs.org>");
mail($session->fullname . " <" . $session->username . "@sucs.org>", "[SUCS Election] Thanks For Voting", $voter_message, "From: SUCS Election " . ELECTION_YEAR . " <vote@sucs.org>");
}
}
} else {
display_ballot();
}
} else {
# Display the ballot paper
display_ballot();
}
}
}
}
$smarty->assign("body", $output);
......
<?php
if (strtotime('now') > strtotime(ELECTION_START) && strtotime('now') < strtotime(ELECTION_END) && !$DB->GetOne("SELECT username FROM election_votes where username=?", $session->username)) {
$messages['info'][] = "<strong>You haven't voted yet</strong><br />\nThe SUCS Executive Election is in progress. <a href=\"/Vote\">Vote now!</a>\n";
$messages['info'][] = "<strong>You haven't voted yet</strong><br />\nThe SUCS Executive Election is in progress. <a href=\"/Vote\">Vote now!</a>\n";
}
......
......@@ -2,56 +2,56 @@
$body = "";
$email_to = "joinus@sucs.org";
$_REQUEST['email'] = str_replace("\n", "", $_REQUEST['email']);
$headers = "From: ".$_REQUEST['email']."\n"."Reply-to: ".$_REQUEST['email'];
$subject = "Join request for user ".$_REQUEST['uname'];
$headers = "From: " . $_REQUEST['email'] . "\n" . "Reply-to: " . $_REQUEST['email'];
$subject = "Join request for user " . $_REQUEST['uname'];
// Perform data integrity checks
// Full name
if (preg_match("/[^\p{L}- ]/iu", $_REQUEST['realname'])) {
$body .= "<p>That's a suspiciously unusual-looking name, <strong>" . htmlentities($_REQUEST['realname']) . "</strong>.</p>\n";
$body .= "<p>Please click <em>Back</em> and correct it.</p>\n";
$body .= "<p>That's a suspiciously unusual-looking name, <strong>" . htmlentities($_REQUEST['realname']) . "</strong>.</p>\n";
$body .= "<p>Please click <em>Back</em> and correct it.</p>\n";
} else {
// Student number
if (!is_numeric($_REQUEST['student_number']) || strlen($_REQUEST['student_number']) <> 6) {
$body .= "<p>The student number <strong>" . htmlentities($_REQUEST['student_number']) . "</strong> appears not to be valid.</p>\n";
$body .= "<p>Please click <em>Back</em> and correct it.</p>\n";
} else {
if (!is_numeric($_REQUEST['student_number']) || strlen($_REQUEST['student_number']) <> 6) {
$body .= "<p>The student number <strong>" . htmlentities($_REQUEST['student_number']) . "</strong> appears not to be valid.</p>\n";
$body .= "<p>Please click <em>Back</em> and correct it.</p>\n";
} else {
// Email address
list($username, $maildomain) = preg_split("/@/", $_REQUEST['email']);
if (!checkdnsrr($maildomain, "MX") && !checkdnsrr($maildomain)) {
$body .= "<p>The email address <strong>" . htmlentities($_REQUEST['email']) . "</strong> appears not to be valid.</p>\n";
$body .= "<p>Please click <em>Back</em> and correct it.</p>\n";
} else {
list($username, $maildomain) = preg_split("/@/", $_REQUEST['email']);
if (!checkdnsrr($maildomain, "MX") && !checkdnsrr($maildomain)) {
$body .= "<p>The email address <strong>" . htmlentities($_REQUEST['email']) . "</strong> appears not to be valid.</p>\n";
$body .= "<p>Please click <em>Back</em> and correct it.</p>\n";
} else {
// Username
// This test is rather inadequate. Needs improving
if (!preg_match("/^[a-z0-9_]*$/i", $_REQUEST['uname'])) {
$body .= "<p>Usernames can only contain letters, numbers and underscores(_).</p>\n";
$body .= "<p>Please click <em>Back</em> and choose a different one.</p>\n";
} else {
// This test is rather inadequate. Needs improving
if (!preg_match("/^[a-z0-9_]*$/i", $_REQUEST['uname'])) {
$body .= "<p>Usernames can only contain letters, numbers and underscores(_).</p>\n";
$body .= "<p>Please click <em>Back</em> and choose a different one.</p>\n";
} else {
// We're good to go
$address = "http";
if ($_SERVER['HTTPS']) $address .= "s";
$address .= "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ;
$email_body = "This email was automatically created by the SUCS Website.\n\n";
$email_body .= "It was created by " . $address . "\n";
$email_body .= "from IP " . $_SERVER['REMOTE_ADDR'] . " on " . date("r") . "\n\n";
$email_body .= "The details of the request are as follows:\n\n";
$email_body .= " Real name ............ {$_REQUEST['realname']}\n";
$email_body .= " Student number ....... {$_REQUEST['student_number']}\n";
$email_body .= " Email address ........ {$_REQUEST['email']}\n";
$email_body .= " Requested username ... {$_REQUEST['uname']}\n\n";
$email_body .= "Please reply to this email, providing the user with details of\n";
$email_body .= "how to join.\n\n";
$email_body .= "-- \nSUCS Website\n";
$address = "http";
if ($_SERVER['HTTPS']) $address .= "s";
$address .= "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$email_body = "This email was automatically created by the SUCS Website.\n\n";
$email_body .= "It was created by " . $address . "\n";
$email_body .= "from IP " . $_SERVER['REMOTE_ADDR'] . " on " . date("r") . "\n\n";
$email_body .= "The details of the request are as follows:\n\n";
$email_body .= " Real name ............ {$_REQUEST['realname']}\n";
$email_body .= " Student number ....... {$_REQUEST['student_number']}\n";
$email_body .= " Email address ........ {$_REQUEST['email']}\n";
$email_body .= " Requested username ... {$_REQUEST['uname']}\n\n";
$email_body .= "Please reply to this email, providing the user with details of\n";
$email_body .= "how to join.\n\n";
$email_body .= "-- \nSUCS Website\n";
mail($email_to, $subject, $email_body, $headers);
mail($email_to, $subject, $email_body, $headers);
$body .= "<p>Thank you for your request to join SUCS.</p>";
$body .= "<p>Someone from our admin team will email you shortly.</p>";
} // username
} // email
} // student number
$body .= "<p>Thank you for your request to join SUCS.</p>";
$body .= "<p>Someone from our admin team will email you shortly.</p>";
} // username
} // email
} // student number
} // full name
$smarty->assign("body", $body);
......
......@@ -6,97 +6,97 @@
$permission = "sucsstaff";
$eventtable = "events";
$eventcategories = array("Technical","Talks","Gaming","Social","Misc");
$eventcategories = array("Technical", "Talks", "Gaming", "Social", "Misc");
$smarty->assign("event_categories", $eventcategories);
$events_index = array_search("Events", $pathlist);
if (isset($pathlist[$events_index + 1])) {
list($eventcat, $eventid) = preg_split("/_/", $pathlist[$events_index + 1]);
if (!in_array($eventcat, $eventcategories)) {
trigger_error("Invalid category specified", E_USER_ERROR);
unset($eventcat, $eventid);
} elseif (!ctype_digit($eventid)) {
trigger_error("Invalid event specified", E_USER_ERROR);
print_r($eventid);
unset($eventcat, $eventid);
}
list($eventcat, $eventid) = preg_split("/_/", $pathlist[$events_index + 1]);
if (!in_array($eventcat, $eventcategories)) {
trigger_error("Invalid category specified", E_USER_ERROR);
unset($eventcat, $eventid);
} elseif (!ctype_digit($eventid)) {
trigger_error("Invalid event specified", E_USER_ERROR);
print_r($eventid);
unset($eventcat, $eventid);
}
}
if (isset($session->groups[$permission])) {
$smarty->assign("editable", true);
$action = @$_REQUEST['action'];
// process form actions with side-effects first
switch ($action) {
case "save":
$record['name'] = $_REQUEST['name'];
$record['description'] = $_REQUEST['description'];
$record['location'] = $_REQUEST['location'];
// reconstruct date/time
$datetime = $_REQUEST['Date_Year'];
$datetime .= str_pad((int) $_REQUEST['Date_Month'],2,'0',STR_PAD_LEFT);
$datetime .= str_pad((int) $_REQUEST['Date_Day'],2,'0',STR_PAD_LEFT);
$datetime .= " ".$_REQUEST['Time_Hour'];
$datetime .= ":".$_REQUEST['Time_Minute'];
$record['whn'] = $datetime;
$record['category'] = $_REQUEST['category'];
$id = @$_REQUEST['id'];
// this may be an existing event which needs to be updated
if (ctype_digit($id)) {
$DB->AutoExecute($eventtable, $record, 'UPDATE', "id=".$id);
} else {
$DB->AutoExecute($eventtable, $record, 'INSERT');
}
unset($action);
break;
$smarty->assign("editable", true);
$action = @$_REQUEST['action'];
// process form actions with side-effects first
switch ($action) {
case "save":
$record['name'] = $_REQUEST['name'];
$record['description'] = $_REQUEST['description'];
$record['location'] = $_REQUEST['location'];
// reconstruct date/time
$datetime = $_REQUEST['Date_Year'];
$datetime .= str_pad((int)$_REQUEST['Date_Month'], 2, '0', STR_PAD_LEFT);
$datetime .= str_pad((int)$_REQUEST['Date_Day'], 2, '0', STR_PAD_LEFT);
$datetime .= " " . $_REQUEST['Time_Hour'];
$datetime .= ":" . $_REQUEST['Time_Minute'];
$record['whn'] = $datetime;
$record['category'] = $_REQUEST['category'];
$id = @$_REQUEST['id'];
// this may be an existing event which needs to be updated
if (ctype_digit($id)) {
$DB->AutoExecute($eventtable, $record, 'UPDATE', "id=" . $id);
} else {
$DB->AutoExecute($eventtable, $record, 'INSERT');
}
unset($action);
break;
}
}
if (isset($session->groups[$permission]) && isset($action)) {
switch($action) {
case "create":
$event = array("id" => "*");
$body = $smarty->fetch("event_edit.tpl");
break;
case "edit":
if (isset($eventcat) && isset($eventid)) {
$event = $DB->GetRow("SELECT * FROM $eventtable WHERE id=?", array($eventid));
//make tastier breadcrumbs
$pathlist[$events_index + 1] = $event['name'];
$smarty->assign("event", $event);
$body = $smarty->fetch("event_edit.tpl");
}
break;
}
switch ($action) {
case "create":
$event = array("id" => "*");
$body = $smarty->fetch("event_edit.tpl");
break;
case "edit":
if (isset($eventcat) && isset($eventid)) {
$event = $DB->GetRow("SELECT * FROM $eventtable WHERE id=?", array($eventid));
//make tastier breadcrumbs
$pathlist[$events_index + 1] = $event['name'];
$smarty->assign("event", $event);
$body = $smarty->fetch("event_edit.tpl");
}
break;
}
} else {
// not logged in, or no special action required
if (isset($eventcat) && isset($eventid)) {
$event = $DB->GetRow("SELECT * FROM $eventtable WHERE id=?", array($eventid));
// not logged in, or no special action required
if (isset($eventcat) && isset($eventid)) {
$event = $DB->GetRow("SELECT * FROM $eventtable WHERE id=?", array($eventid));
//make tastier breadcrumbs
$pathlist[$events_index + 1] = $event['name'];
//make tastier breadcrumbs
$pathlist[$events_index + 1] = $event['name'];
$smarty->assign("event", $event);
$body = $smarty->fetch("event.tpl");
} else {
$events = $DB->GetAll("SELECT *,date_part('epoch', whn) as whn_timestamp
$smarty->assign("event", $event);
$body = $smarty->fetch("event.tpl");
} else {
$events = $DB->GetAll("SELECT *,date_part('epoch', whn) as whn_timestamp
FROM $eventtable WHERE date_trunc('day', whn) >= date_trunc('day',NOW()) ORDER BY whn ASC");
$oldevents = $DB->GetAll("SELECT *,date_part('epoch', whn) as whn_timestamp
$oldevents = $DB->GetAll("SELECT *,date_part('epoch', whn) as whn_timestamp
FROM $eventtable WHERE date_trunc('day', whn) < date_trunc('day', NOW()) ORDER BY whn DESC LIMIT 3");
$smarty->assign("events", $events);
$smarty->assign("oldevents", $oldevents);
$body = $smarty->fetch("events.tpl");
}
$smarty->assign("events", $events);
$smarty->assign("oldevents", $oldevents);
$body = $smarty->fetch("events.tpl");
}
}
$smarty->assign("body", $body);
......
......@@ -9,22 +9,22 @@ $cal = new vcalendar();
$cal->setConfig('unique_id', 'sucs.org');
$cal->setProperty('method', 'PUBLISH');
$cal->setProperty('x-wr-calname', "SUCS Events Calendar");
$cal->setProperty('X-WR-CALDESC',
"Upcoming events for members of the Swansea University Computer Society");
$cal->setProperty('X-WR-CALDESC',
"Upcoming events for members of the Swansea University Computer Society");
$cal->setProperty('X-WR-TIMEZONE', 'Europe/London');
//populate with upcoming events
$events = $DB->GetAll("SELECT * FROM events WHERE
date_trunc('day', whn) >= date_trunc('day', NOW()) ORDER BY whn ASC");
foreach($events as $event) {
$vevent = new vevent();
$vevent->setProperty('dtstart', $event['whn']);
$vevent->setProperty('LOCATION', $event['location']);
$vevent->setProperty('summary', $event['name']);
$vevent->setProperty('description', $event['description']);
$vevent->setProperty('categories', $event['category']);
$cal -> setComponent($vevent);
foreach ($events as $event) {
$vevent = new vevent();
$vevent->setProperty('dtstart', $event['whn']);
$vevent->setProperty('LOCATION', $event['location']);
$vevent->setProperty('summary', $event['name']);
$vevent->setProperty('description', $event['description']);
$vevent->setProperty('categories', $event['category']);
$cal->setComponent($vevent);
}
//spit out a shiny new iCal file
......
<?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");
$smarty->assign("title", "Home");
$smarty->assign("body", $output);
if (!$session->loggedin) {
$output = file_get_contents("../static/fragments/Join.txt");
$output = file_get_contents("../static/fragments/Join.txt");
} 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 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>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>";
//include('users.php');
//$output .= $result;
include('electionreminder.php');
$output .= $result;
include('electionreminder.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>";
$smarty->assign("secondary",$output);
$smarty->assign("secondary", $output);
?>
......@@ -9,5 +9,5 @@ $smarty->assign("title", "Games");
$smarty->assign("body", $output);
$output = file_get_contents("../static/fragments/Games-secondary.txt");
$smarty->assign("secondary",$output);
$smarty->assign("secondary", $output);
?>
<?
$out = exec("/usr/bin/id");
$smarty->assign("body",$out);
$out = exec("/usr/bin/id");
$smarty->assign("body", $out);
?>
......@@ -4,196 +4,187 @@
$mode = "list";
$admin = false;
$admin_group="sucsstaff";
$admin_group = "sucsstaff";
// who's notified of items being requested?
$junk_contact="admin@sucs.org";
$junk_contact = "admin@sucs.org";
$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
// create canedit rules
$canedit=isset($pathlist[($component[depth]/2)+1]);
$canedit=$canedit && isset($pathlist[($component[depth]/2)+2]);
$canedit=$canedit && $pathlist[($component[depth]/2)+1]=='Edit';
$canedit=$canedit && is_numeric($pathlist[($component[depth]/2)+2]);
$canedit=$canedit && $admin;
$canedit = isset($pathlist[($component[depth] / 2) + 1]);
$canedit = $canedit && isset($pathlist[($component[depth] / 2) + 2]);
$canedit = $canedit && $pathlist[($component[depth] / 2) + 1] == 'Edit';
$canedit = $canedit && is_numeric($pathlist[($component[depth] / 2) + 2]);
$canedit = $canedit && $admin;
// Apply canedit rules
if ($canedit){
$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);
if(sizeof($items) === 1){
$item = $items[0];
$smarty->assign("item", $item);
$mode = "edit";
}
if ($canedit) {
$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);
if (sizeof($items) === 1) {
$item = $items[0];
$smarty->assign("item", $item);
$mode = "edit";
}
}
// If you're an admin and the path ends in Add put it into add mode
// create canadd rules
$canadd=isset($pathlist[($component[depth]/2)+1]);
$canadd=$canadd && $pathlist[($component[depth]/2)+1]=='Add';
$canadd=$canadd && $admin;
$canadd = isset($pathlist[($component[depth] / 2) + 1]);
$canadd = $canadd && $pathlist[($component[depth] / 2) + 1] == 'Add';
$canadd = $canadd && $admin;
// Apply canadd rules
if ($canadd){$mode = "add";}
if ($canadd) {
$mode = "add";
}
// Process actions before retrieving the data
// List request data
if ($session->loggedin && isset($_REQUEST['action'])) {
// Junk Requests
if ($_REQUEST['action'] == "Request") {
// Request Item if its available
$query = "UPDATE inventory SET requested_by=?, requested_on=now() WHERE id=? AND requested_by IS NULL";
$DB->Query($query, array($session->username, $_REQUEST['item']));
// mail someone so we know that this has been requested
$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 .= "{$iteminfo['title']}: {$iteminfo['description']}\n\n";
$msgbody .= "Please ensure this is taken away and never brought back.";
mail($junk_contact,"Junk item requested",$msgbody);
// Junk Requests
if ($_REQUEST['action'] == "Request") {
// Request Item if its available
$query = "UPDATE inventory SET requested_by=?, requested_on=now() WHERE id=? AND requested_by IS NULL";
$DB->Query($query, array($session->username, $_REQUEST['item']));
// mail someone so we know that this has been requested
$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 .= "{$iteminfo['title']}: {$iteminfo['description']}\n\n";
$msgbody .= "Please ensure this is taken away and never brought back.";
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") {
// 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'] == "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']);
}
} 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
if ($session->loggedin && $admin && (isset($_REQUEST['update']) || isset($_REQUEST['add']))) {
// 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...
if ($_REQUEST['categorymenu'] == "") {
$category = $_REQUEST['category'];
} else {
$category = $_REQUEST['categorymenu'];
}
// Update/Add item if title and category are filled in else error
if ($_REQUEST['title'] != "" && $category != "") {
// if the description is blank, return null
if ($_REQUEST['description'] == ""){
$description = null;
}
else{
$description = $_REQUEST['description'];
}
// if the donated_by is blank, return null
if ($_REQUEST['donated_by'] == ""){
$donated_by = null;
}
else{
$donated_by = $_REQUEST['donated_by'];
}
// run the query
if(isset($_REQUEST['update'])){
$query = "UPDATE inventory SET title=?, category=?, description=?, donated_by=?, status=? WHERE id=?";
$array = array($_REQUEST['title'], $category, $description, $donated_by, $_REQUEST['status'], $_REQUEST['id']);
if ($DB->Query($query, $array)) {
message_flash("Item Updated");
} 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']);
if ($DB->Query($query, $array)) {
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);
}
// 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...
if ($_REQUEST['categorymenu'] == "") {
$category = $_REQUEST['category'];
} else {
$category = $_REQUEST['categorymenu'];
}
// Update/Add item if title and category are filled in else error
if ($_REQUEST['title'] != "" && $category != "") {
// if the description is blank, return null
if ($_REQUEST['description'] == "") {
$description = null;
} else {
$description = $_REQUEST['description'];
}
// if the donated_by is blank, return null
if ($_REQUEST['donated_by'] == "") {
$donated_by = null;
} else {
$donated_by = $_REQUEST['donated_by'];
}
// run the query
if (isset($_REQUEST['update'])) {
$query = "UPDATE inventory SET title=?, category=?, description=?, donated_by=?, status=? WHERE id=?";
$array = array($_REQUEST['title'], $category, $description, $donated_by, $_REQUEST['status'], $_REQUEST['id']);
if ($DB->Query($query, $array)) {
message_flash("Item Updated");
} 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']);
if ($DB->Query($query, $array)) {
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);
}
}
// Remove old taken junk
$DB->Query("DELETE FROM inventory WHERE (taken_on + interval'7 days') < now()");
if ($mode == 'list'){
// Get junk from database, and give admin the full list
if ($admin == true){
$junk = $DB->GetAll("SELECT * FROM inventory ORDER BY category, title, id");
}
else{
$junk = $DB->GetAll("SELECT * FROM inventory WHERE status = 'junk' ORDER BY category, title, id");
}
//
// Check there is some junk
if (sizeof($junk) < 1) {
$mode = "nojunk";
} else {
// group the junk by status then by category
foreach($junk as $junkitem) {
if ($junkitem['status'] != 'junk') {
$status = "unknown";
} else if ($junkitem['requested_by'] == null) {
$status = "available";
} else if ($junkitem['taken_on'] == null) {
$status = "requested";
} else {
$status = "taken";
}
$sortedjunk[$status][$junkitem['category']][] = $junkitem;
}
$smarty->assign("junk", $sortedjunk);
}
if ($mode == 'list') {
// Get junk from database, and give admin the full list
if ($admin == true) {
$junk = $DB->GetAll("SELECT * FROM inventory ORDER BY category, title, id");
} else {
$junk = $DB->GetAll("SELECT * FROM inventory WHERE status = 'junk' ORDER BY category, title, id");
}
//
// Check there is some junk
if (sizeof($junk) < 1) {
$mode = "nojunk";
} else {
// group the junk by status then by category
foreach ($junk as $junkitem) {
if ($junkitem['status'] != 'junk') {
$status = "unknown";
} else if ($junkitem['requested_by'] == null) {
$status = "available";
} else if ($junkitem['taken_on'] == null) {
$status = "requested";
} else {
$status = "taken";
}
$sortedjunk[$status][$junkitem['category']][] = $junkitem;
}
$smarty->assign("junk", $sortedjunk);
}
} else {
$categories = $DB->GetCol("SELECT DISTINCT category FROM inventory ORDER BY category ASC");
$smarty->assign("categories", $categories);
$categories = $DB->GetCol("SELECT DISTINCT category FROM inventory ORDER BY category ASC");
$smarty->assign("categories", $categories);
}
// 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("mode", $mode);
$smarty->assign("admin", $admin);
$output = $smarty->fetch("junk.tpl");
$output = $smarty->fetch("junk.tpl");
$smarty->assign("title", "Junk List");
$smarty->assign("body", $output);
......
......@@ -9,177 +9,178 @@ $librarian_mail = "librarian@sucs.org";
// don't try to convert existing html entities
// this could be broken out someplace else
function htmlentities2($myHTML) {
$translation_table=get_html_translation_table (HTML_ENTITIES,ENT_QUOTES);
$translation_table[chr(38)] = '&';
return preg_replace("/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/","&amp;" , strtr($myHTML, $translation_table));
function htmlentities2($myHTML)
{
$translation_table = get_html_translation_table(HTML_ENTITIES, ENT_QUOTES);
$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);
if (isset($session->groups[$permission])) {
$smarty->assign("librarian", TRUE);
$smarty->assign("librarian", TRUE);
}
// Default to browsing, empty search box, generic title
$mode = "browse";
$search = "";
$smarty->assign("title","Library");
$smarty->assign("title", "Library");
$output2 = $smarty->fetch("library-search.tpl");
$smarty->assign("secondary", $output2);
if (isset($_REQUEST['search']) && (trim($_REQUEST['search']) != "")) {
// Pass the template some search results
$mode = "search";
} elseif (isset($pathlist[$library_index +1]) && ($pathlist[$library_index + 1] == "Tags")) {
if (isset($pathlist[$library_index + 2])) {
$tag = $pathlist[$library_index + 2];
// we're displaying books with a specific tag
//The following line doesn't do what I think you think it does.
//It will return a string if the tag exists, "1" and "0" when a tag doesn't exist
$categories = $DB->GetOne("SELECT count(name) FROM bookcategories WHERE name=?", array($tag));
//debug stuff, LOOK IT'S A STRING
//var_dump($categories);
//if ($categories['count'] == 1) {
//$categories is not an aray, it's a string, yeah i know == != good_programing
if ($categories == 1) {
$mode = "tagdisplay";
$query = "SELECT b.id, b.title FROM books AS b JOIN booktags AS bt ON b.id= bt.bookid";
$query .= " JOIN bookcategories AS bc ON bc.id = bt.tag WHERE bc.name=?";
$smarty->assign("results", $DB->GetAll($query, array($tag)));
} else {
// this tag doesn't exist...
$mode = "tagerror";
}
} else {
$mode = "taglist";
$smarty->assign("tags", $DB->GetAll("SELECT name FROM bookcategories"));
}
$mode = "search";
} elseif (isset($pathlist[$library_index + 1]) && ($pathlist[$library_index + 1] == "Tags")) {
if (isset($pathlist[$library_index + 2])) {
$tag = $pathlist[$library_index + 2];
// we're displaying books with a specific tag
//The following line doesn't do what I think you think it does.
//It will return a string if the tag exists, "1" and "0" when a tag doesn't exist
$categories = $DB->GetOne("SELECT count(name) FROM bookcategories WHERE name=?", array($tag));
//debug stuff, LOOK IT'S A STRING
//var_dump($categories);
//if ($categories['count'] == 1) {
//$categories is not an aray, it's a string, yeah i know == != good_programing
if ($categories == 1) {
$mode = "tagdisplay";
$query = "SELECT b.id, b.title FROM books AS b JOIN booktags AS bt ON b.id= bt.bookid";
$query .= " JOIN bookcategories AS bc ON bc.id = bt.tag WHERE bc.name=?";
$smarty->assign("results", $DB->GetAll($query, array($tag)));
} 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])) {
// We're displaying a specific book
$mode = "display";
$checkout_request = false;
$book_index = intval($pathlist[$library_index + 1]);
if (isset($session->groups[$permission])) $smarty->assign('editable', true);
$mode = "display";
$checkout_request = false;
$book_index = intval($pathlist[$library_index + 1]);
if (isset($session->groups[$permission])) $smarty->assign('editable', true);
// Check this book actually exists
$loans = $DB->GetAll("SELECT onloan FROM books WHERE id=? LIMIT 1", array($book_index));
if (sizeof($loans) != 1) {
$mode = "bookerror";
} else {
// See if we're supposed to be loaning/returning/editing/saving this book
if ($session->loggedin && isset($_REQUEST['action'])) {
if ($_REQUEST['action'] == "loan") {
if (isset($session->groups[$permission])) {
// update DB
$query = "UPDATE books SET onloan='t', loandate=now(), loanwho=? WHERE id=?";
$DB->Query($query, array($_REQUEST['member'], $book_index));
} else {
// send mail to librarians
// do this in a moment when we have more details about the book
$checkout_request = true;
}
} elseif (($_REQUEST['action'] == "return") && isset($session->groups[$permission])) {
// update DB
$DB->Query("UPDATE books SET onloan='f', loandate=NULL WHERE id=?", array($book_index));
} elseif (($_REQUEST['action'] == "edit") && isset($session->groups[$permission])) {
// we're an editor and want to edit this book
$smarty->assign("editing", true);
} elseif (($_REQUEST['action'] == "save") && isset($session->groups[$permission])) {
// save edited book
$book['title'] = $_REQUEST['title'];
$book['author'] = $_REQUEST['author'];
$book['publisher'] = $_REQUEST['publisher'];
$book['description'] = $_REQUEST['description'];
if ($DB->AutoExecute('books', $book, 'UPDATE', "id=".$DB->qstr($book_index))) {
message_flash_postponed("Book Updated!");
//redirect to prevent form resubmission
header('HTTP/1.1 303 See Other');
header("Location: $baseurl$path");
} else {
trigger_error("Error updating book: ".$DB->ErrorMsg(), E_USER_WARNING);
}
}
}
$results = $DB->GetAll("SELECT * FROM books WHERE id=? LIMIT 1", array($book_index));
$book = $results[0];
if ($checkout_request) {
// someone wants to check out this book
$msgbody = "User {$session->username} would like to take out";
$msgbody .= " {$book['title']} by {$book['author']} from the library.\n\n";
$msgbody .= "Visit https://$preferred_hostname$path to process this request.";
mail($librarian_mail, "Book Request", $msgbody);
$smarty->assign("checkout_request", true);
}
// Clean up ready for output
$book['title'] = htmlentities2($book['title']);
$book['author'] = htmlentities2($book['author']);
$book['onloan'] = ($book['onloan'] == 't') ? true : false;
if (!isset($book['description'])) {
// no book description in the database, try using Amazon data
// Extract amazon data (maybe this should be stored in separate fields in the db?)
$simple_xml = simplexml_load_string($book['amazon_data']);
$book['description'] = @$simple_xml->Items->Item->EditorialReviews->EditorialReview->Content;
if (isset($book['description'])) {
// tidy description markup
$tidy_config['doctype'] = 'omit';
$tidy_config['output-xhtml'] = true;
$tidy_config['show-body-only'] = true;
$tidy_config['logical-emphasis'] = true;
$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
//$DB->Execute("UPDATE books SET description=? WHERE id=?", array($book['description'],$book['id']));
}
}
$smarty->assign("book", $book);
// Add loan interface to sidebar if we're logged in
if ($session->loggedin) {
$members = new Members;
$smarty->assign("memberlist", $members->getMemberList());
$secondary = $smarty->getTemplateVars("secondary");
$secondary .= $smarty->fetch('library-loan.tpl');
$smarty->assign("secondary", $secondary);
}
// Edit the path list to make the breadcrumbs tastier
$pathlist[$library_index + 1] = $results[0]['title'];
}
$loans = $DB->GetAll("SELECT onloan FROM books WHERE id=? LIMIT 1", array($book_index));
if (sizeof($loans) != 1) {
$mode = "bookerror";
} else {
// See if we're supposed to be loaning/returning/editing/saving this book
if ($session->loggedin && isset($_REQUEST['action'])) {
if ($_REQUEST['action'] == "loan") {
if (isset($session->groups[$permission])) {
// update DB
$query = "UPDATE books SET onloan='t', loandate=now(), loanwho=? WHERE id=?";
$DB->Query($query, array($_REQUEST['member'], $book_index));
} else {
// send mail to librarians
// do this in a moment when we have more details about the book
$checkout_request = true;
}
} elseif (($_REQUEST['action'] == "return") && isset($session->groups[$permission])) {
// update DB
$DB->Query("UPDATE books SET onloan='f', loandate=NULL WHERE id=?", array($book_index));
} elseif (($_REQUEST['action'] == "edit") && isset($session->groups[$permission])) {
// we're an editor and want to edit this book
$smarty->assign("editing", true);
} elseif (($_REQUEST['action'] == "save") && isset($session->groups[$permission])) {
// save edited book
$book['title'] = $_REQUEST['title'];
$book['author'] = $_REQUEST['author'];
$book['publisher'] = $_REQUEST['publisher'];
$book['description'] = $_REQUEST['description'];
if ($DB->AutoExecute('books', $book, 'UPDATE', "id=" . $DB->qstr($book_index))) {
message_flash_postponed("Book Updated!");
//redirect to prevent form resubmission
header('HTTP/1.1 303 See Other');
header("Location: $baseurl$path");
} else {
trigger_error("Error updating book: " . $DB->ErrorMsg(), E_USER_WARNING);
}
}
}
$results = $DB->GetAll("SELECT * FROM books WHERE id=? LIMIT 1", array($book_index));
$book = $results[0];
if ($checkout_request) {
// someone wants to check out this book
$msgbody = "User {$session->username} would like to take out";
$msgbody .= " {$book['title']} by {$book['author']} from the library.\n\n";
$msgbody .= "Visit https://$preferred_hostname$path to process this request.";
mail($librarian_mail, "Book Request", $msgbody);
$smarty->assign("checkout_request", true);
}
// Clean up ready for output
$book['title'] = htmlentities2($book['title']);
$book['author'] = htmlentities2($book['author']);
$book['onloan'] = ($book['onloan'] == 't') ? true : false;
if (!isset($book['description'])) {
// no book description in the database, try using Amazon data
// Extract amazon data (maybe this should be stored in separate fields in the db?)
$simple_xml = simplexml_load_string($book['amazon_data']);
$book['description'] = @$simple_xml->Items->Item->EditorialReviews->EditorialReview->Content;
if (isset($book['description'])) {
// tidy description markup
$tidy_config['doctype'] = 'omit';
$tidy_config['output-xhtml'] = true;
$tidy_config['show-body-only'] = true;
$tidy_config['logical-emphasis'] = true;
$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
//$DB->Execute("UPDATE books SET description=? WHERE id=?", array($book['description'],$book['id']));
}
}
$smarty->assign("book", $book);
// Add loan interface to sidebar if we're logged in
if ($session->loggedin) {
$members = new Members;
$smarty->assign("memberlist", $members->getMemberList());
$secondary = $smarty->getTemplateVars("secondary");
$secondary .= $smarty->fetch('library-loan.tpl');
$smarty->assign("secondary", $secondary);
}
// Edit the path list to make the breadcrumbs tastier
$pathlist[$library_index + 1] = $results[0]['title'];
}
} else {
//Nothing being requested, just find some random books to put on main page
$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("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"));
}
if ($mode == "search") {
$search = $_REQUEST['search'];
$query = "SELECT id, title, onloan FROM books WHERE (title || ' ' || author || ' ' || keywords) ~* ? ORDER BY title ASC";
$results = $DB->GetAll($query,array($search));
foreach ($results as &$result) {
$result['title'] = htmlentities2($result['title']);
$result['onloan'] = ($result['onloan'] == 't') ? true : false;
}
$pathlist[] = "Search";
$smarty->assign("results", $results);
$search = $_REQUEST['search'];
$query = "SELECT id, title, onloan FROM books WHERE (title || ' ' || author || ' ' || keywords) ~* ? ORDER BY title ASC";
$results = $DB->GetAll($query, array($search));
foreach ($results as &$result) {
$result['title'] = htmlentities2($result['title']);
$result['onloan'] = ($result['onloan'] == 't') ? true : false;
}
$pathlist[] = "Search";
$smarty->assign("results", $results);
} elseif ($mode == "display") {
......@@ -189,6 +190,6 @@ $smarty->assign("mode", $mode);
$smarty->assign("search", $search);
$smarty->assign("pathlist", $pathlist);
$output = $smarty->fetch("library.tpl");
$smarty->assign("body",$output);
$smarty->assign("body", $output);
?>
<?php
// you gotta be this high to enter
$permission="librarian";
$permission = "librarian";
//include ISBN validation library
require_once('../lib/Validate/ISPN.php');
$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 (new Validate_ISPN)->isbn($isbn);
return (new Validate_ISPN)->isbn($isbn);
}
if ($session->groups[$permission]) {
if ($_REQUEST['action'] == "search") {
$isbn = $_REQUEST['isbn'];
$isbn = str_replace(array('ISBN', '-', ' ', "\t", "\n"), '', $isbn);
if (valid_isbn($isbn)) {
$xmlresult = fetch_isbndb_data($isbn);
$simple_xml = simplexml_load_string($xmlresult);
$book['isbn'] = $isbn;
$book['title'] = $simple_xml->BookList->BookData->Title;
$book['author'] = $simple_xml->BookList->BookData->AuthorsText;
if (substr(trim($book['author']),-1)==',') {$book['author']=substr(trim($book['author']),0,-1);}
$book['publisher'] = $simple_xml->BookList->BookData->PublisherText;
$book['image_url'] = "";
$smarty->assign("book", $book);
} else {
// invalid isbn entered
trigger_error("invalid ISBN number entered", E_USER_WARNING);
}
} elseif ($_REQUEST['action'] == "add") {
$book = array();
$book['isbn'] = $_REQUEST['isbn'];
$book['title'] = $_REQUEST['title'];
$book['author'] = $_REQUEST['author'];
$book['publisher'] = $_REQUEST['publisher'];
$book['image_url'] = $_REQUEST['image_url'];
// Validate that we have enough info to add
if (($book['isbn'] != "") && (!valid_isbn($book['isbn']))) {
trigger_error("invalid ISBN", E_USER_WARNING);
} elseif (trim($book['title']) == "") {
trigger_error("you must supply a title", E_USER_WARNING);
} elseif (trim($book['author']) == "") {
trigger_error("you must supply an author");
} else {
$insertdata = array($book['title'], $book['author'], $book['publisher']);
if (valid_isbn($book['isbn'])) {
$book['amazon_data'] = fetch_isbndb_data($book['isbn']);
$newinsertdata = array($book['isbn'], $book['image_url'], $book['amazon_data']);
$insertdata = array_merge($insertdata, $newinsertdata);
$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");
if ($_REQUEST['action'] == "search") {
$isbn = $_REQUEST['isbn'];
$isbn = str_replace(array('ISBN', '-', ' ', "\t", "\n"), '', $isbn);
if (valid_isbn($isbn)) {
$xmlresult = fetch_isbndb_data($isbn);
$simple_xml = simplexml_load_string($xmlresult);
$book['isbn'] = $isbn;
$book['title'] = $simple_xml->BookList->BookData->Title;
$book['author'] = $simple_xml->BookList->BookData->AuthorsText;
if (substr(trim($book['author']), -1) == ',') {
$book['author'] = substr(trim($book['author']), 0, -1);
}
$book['publisher'] = $simple_xml->BookList->BookData->PublisherText;
$book['image_url'] = "";
$smarty->assign("book", $book);
} else {
// invalid isbn entered
trigger_error("invalid ISBN number entered", E_USER_WARNING);
}
} elseif ($_REQUEST['action'] == "add") {
$book = array();
$book['isbn'] = $_REQUEST['isbn'];
$book['title'] = $_REQUEST['title'];
$book['author'] = $_REQUEST['author'];
$book['publisher'] = $_REQUEST['publisher'];
$book['image_url'] = $_REQUEST['image_url'];
// Validate that we have enough info to add
if (($book['isbn'] != "") && (!valid_isbn($book['isbn']))) {
trigger_error("invalid ISBN", E_USER_WARNING);
} elseif (trim($book['title']) == "") {
trigger_error("you must supply a title", E_USER_WARNING);
} elseif (trim($book['author']) == "") {
trigger_error("you must supply an author");
} else {
$insertdata = array($book['title'], $book['author'], $book['publisher']);
if (valid_isbn($book['isbn'])) {
$book['amazon_data'] = fetch_isbndb_data($book['isbn']);
$newinsertdata = array($book['isbn'], $book['image_url'], $book['amazon_data']);
$insertdata = array_merge($insertdata, $newinsertdata);
$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");
}
$smarty->assign("title", "Library Admin");
......
......@@ -5,148 +5,148 @@ include_once("../lib/date.php");
$members = new Members;
if ($session->loggedin) {
$usernames = $members->getMemberList();
$smarty->assign('members', $usernames);
$sidebar = $smarty->fetch('members-search.tpl');
$smarty->assign('secondary', $sidebar);
// Show Searched for users depending on the method provided
$value = '';
$uid = false;
$pathCount = count($pathlist) -1;
if ( isset($_POST['search']) ) {
$value = $_POST['search'];
$uid = true;
$usernames = $members->memberSearch($value);
} else if ( isset($_POST['member']) ) {
$value = $_POST['member'];
$uid = true;
$usernames = $members->memberView($value);
} else if ( $component['path'] != $path ) {
$value = $pathlist[$pathCount];
$usernames = $members->memberView($value);
}
if (!empty($value) ) {
// Redirect if we have found a valid single user
if (count($usernames) == 1) {
$smarty->assign('who', $usernames[0]['uid']);
// Add banana widget to the sidebar
$who = $usernames[0]['uid'];
include("../lib/banana-admin.php");
// Needs Redirection
if ($uid) {
header('Location: ' . $component['path'] . '/' . $usernames[0]['uid']);
} else {
// Pictures
if (file_exists('pictures/people/' . $usernames[0]['uid'] . '.png')) {
$usernames[0]['picture'] = '/pictures/people/' . $usernames[0]['uid'] . '.png';
}
// Account type
$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')) {
$usernames[0]['website'] = true;
}
// 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
// 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'];
$usernames = $members->getMemberList();
$smarty->assign('members', $usernames);
$sidebar = $smarty->fetch('members-search.tpl');
$smarty->assign('secondary', $sidebar);
// Show Searched for users depending on the method provided
$value = '';
$uid = false;
$pathCount = count($pathlist) - 1;
if (isset($_POST['search'])) {
$value = $_POST['search'];
$uid = true;
$usernames = $members->memberSearch($value);
} else if (isset($_POST['member'])) {
$value = $_POST['member'];
$uid = true;
$usernames = $members->memberView($value);
} else if ($component['path'] != $path) {
$value = $pathlist[$pathCount];
$usernames = $members->memberView($value);
}
if (!empty($value)) {
// Redirect if we have found a valid single user
if (count($usernames) == 1) {
$smarty->assign('who', $usernames[0]['uid']);
// Add banana widget to the sidebar
$who = $usernames[0]['uid'];
include("../lib/banana-admin.php");
// Needs Redirection
if ($uid) {
header('Location: ' . $component['path'] . '/' . $usernames[0]['uid']);
} else {
// Pictures
if (file_exists('pictures/people/' . $usernames[0]['uid'] . '.png')) {
$usernames[0]['picture'] = '/pictures/people/' . $usernames[0]['uid'] . '.png';
}
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;
}
// Account type
$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');
}
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;
}
// Plan
if (file_exists($usernames[0]['homedir'] . '/.plan')) {
$usernames[0]['plan'] = file_get_contents($usernames[0]['homedir'] . '/.plan');
}
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;
}
// Website
if (file_exists($usernames[0]['homedir'] . '/public_html')) {
$usernames[0]['website'] = true;
}
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;
}
// 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'];
}
$smarty->assign("stats", $stats);
$secondary = $smarty->getTemplateVars("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 {
// not logged in. Show a list of members with websites
$usernames = $members->getMemberList();
foreach ($usernames as $user) {
if ( file_exists( $user['homedir'] . '/public_html')) {
$public_usernames[] = $user;
}
}
$smarty->assign("public_members", $public_usernames);
// not logged in. Show a list of members with websites
$usernames = $members->getMemberList();
foreach ($usernames as $user) {
if (file_exists($user['homedir'] . '/public_html')) {
$public_usernames[] = $user;
}
}
$smarty->assign("public_members", $public_usernames);
}
$smarty->assign('url', $component['path']);
......
<?php
include_once("../lib/date.php");
// Config options
$inform="treasurer@sucs.org";
$permission="sucsstaff";
$inform = "treasurer@sucs.org";
$permission = "sucsstaff";
// Enable and disable database updating
$enable=TRUE;
$enable = TRUE;
// Set next payment date
$paydate = paidUntil(time());
......@@ -14,135 +14,129 @@ if (isset($session->groups[$permission])) {
$smarty->assign("staff", TRUE);
// $sucsDB->debug = true;
// handle updates
if(isset($_POST['uid']) && isset($_POST['lastupdate'])){
// handle updates
if (isset($_POST['uid']) && isset($_POST['lastupdate'])) {
// Check data hasn't changed and that nothing is broked
$query = "SELECT * FROM members WHERE uid=? AND 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(sizeof($data)==1){
if (sizeof($data) == 1) {
// get info on currently logged in user
$user = posix_getpwnam($session->username);
// Update record
$record = $data[0];
$query = "UPDATE members";
$query .= " SET paid = ?, lastupdate = DEFAULT, lastedit = ?";
$query .= " WHERE uid = ?";
$array = array($paydate,$user['uid'],$_POST['uid']);
if($enable){
$sucsDB->query($query,$array);
$query .= " SET paid = ?, lastupdate = DEFAULT, lastedit = ?";
$query .= " WHERE uid = ?";
$array = array($paydate, $user['uid'], $_POST['uid']);
if ($enable) {
$sucsDB->query($query, $array);
}
// emailing contact (tresurer)
$message = "Account renewal notification\n\n";
$message .= "Account : ".$record['username']."\n";
$message .= "User Type : ".$record['type']."\n";
$message .= "Renewed by: ".$user['name']."\n\n";
$message .= "Regards\n eclipse's script";
mail($inform,"Account Renewal",$message);
// emailing user
$message = "Your Swansea University Computer Society (SUCS) membership has been renewed\n\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 .= "Regards\n The SUCS admin";
$header = "From: admin@sucs.org\r\n";
$header .= "Reply-To: admin@sucs.org";
// Personal account
mail($record['email'],"SUCS account renewal",$message,$header);
// sucs account
mail($record['username']."@sucs.org","SUCS account renewal",$message,$header);
message_flash("Renewed account for: ".htmlentities($record['username']));
}
else{
trigger_error("Number of recored returned: ".sizeof($data).". Expected: 1.", E_USER_ERROR);
$message = "Account renewal notification\n\n";
$message .= "Account : " . $record['username'] . "\n";
$message .= "User Type : " . $record['type'] . "\n";
$message .= "Renewed by: " . $user['name'] . "\n\n";
$message .= "Regards\n eclipse's script";
mail($inform, "Account Renewal", $message);
// emailing user
$message = "Your Swansea University Computer Society (SUCS) membership has been renewed\n\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 .= "Regards\n The SUCS admin";
$header = "From: admin@sucs.org\r\n";
$header .= "Reply-To: admin@sucs.org";
// Personal account
mail($record['email'], "SUCS account renewal", $message, $header);
// sucs account
mail($record['username'] . "@sucs.org", "SUCS account renewal", $message, $header);
message_flash("Renewed account for: " . htmlentities($record['username']));
} else {
trigger_error("Number of recored returned: " . sizeof($data) . ". Expected: 1.", E_USER_ERROR);
}
}
// if sort is specified in GET
if(isset($_GET["sort"])){
$sortoptions = array("username","sid","realname");
if (isset($_GET["sort"])) {
$sortoptions = array("username", "sid", "realname");
// and is a valid option
if(in_array($_GET["sort"],$sortoptions,TRUE)){
if (in_array($_GET["sort"], $sortoptions, TRUE)) {
// use it
$sort=$_GET["sort"];
}
// else use username
else{
$sort='username';
$sort = $_GET["sort"];
} // else use username
else {
$sort = 'username';
}
$getsort=$sort;
}
//else use username
else{
$sort='username';
$getsort = $sort;
} //else use username
else {
$sort = 'username';
}
//Get members details
$query = "SELECT * FROM members, member_type";
$query .= " WHERE paid != ?";
$query .= " AND (type = 1 OR type = 2 OR type = 5)";
$query .= " AND type=member_type.id";
$query .= " ORDER BY paid,type,".$sort;
$array = array($paydate);
$data = $sucsDB->GetAll($query, $array);
$query .= " WHERE paid != ?";
$query .= " AND (type = 1 OR type = 2 OR type = 5)";
$query .= " AND type=member_type.id";
$query .= " ORDER BY paid,type," . $sort;
$array = array($paydate);
$data = $sucsDB->GetAll($query, $array);
$smarty->assign("members", $data);
// set refresh rate
$autorefresh=$_GET["autorefresh"];
// if autorefresh is not 'n'
if($autorefresh!="n"){
$autorefresh = $_GET["autorefresh"];
// if autorefresh is not 'n'
if ($autorefresh != "n") {
// and is a decimal value
if(ctype_digit($autorefresh)){
// use it
$refreshval=$autorefresh;
if (ctype_digit($autorefresh)) {
// use it
$refreshval = $autorefresh;
// set passthrough
$getrefresh=$refreshval;
}
else{
// If no valid value assigned, default to OFF
$refreshval="n";
}
$optrefresh=$refreshval;
$smarty->assign("refresh", $refreshval);
}
else{
$getrefresh = $refreshval;
} else {
// If no valid value assigned, default to OFF
$refreshval = "n";
}
$optrefresh = $refreshval;
$smarty->assign("refresh", $refreshval);
} else {
// set passthrough
$getrefresh='n';
$optrefresh='n';
$getrefresh = 'n';
$optrefresh = 'n';
}
// compile passthrough url
// sort
if(isset($getsort)){
$getout="?sort=".$getsort;
if (isset($getsort)) {
$getout = "?sort=" . $getsort;
}
// autorefresh
if(isset($getrefresh)){
if(isset($getout)){
$getout .= "&amp;autorefresh=".$getrefresh;
}
else{
$getout = "?autorefresh=".$getrefresh;
if (isset($getrefresh)) {
if (isset($getout)) {
$getout .= "&amp;autorefresh=" . $getrefresh;
} else {
$getout = "?autorefresh=" . $getrefresh;
}
}
// set smarty variables
$smarty->assign("self",$baseurl.$path.$getout);
$smarty->assign("optionrefresh",$optrefresh);
$smarty->assign("optionsort",$sort);
$smarty->assign("paydate",$paydate);
$smarty->assign("self", $baseurl . $path . $getout);
$smarty->assign("optionrefresh", $optrefresh);
$smarty->assign("optionsort", $sort);
$smarty->assign("paydate", $paydate);
}
$side = $smarty->fetch('membershiprenew-options.tpl');
$body = $smarty->fetch('membershiprenew.tpl');
$smarty->assign('secondary',$side);
$smarty->assign('secondary', $side);
$smarty->assign('title', "Renew Membership");
$smarty->assign('body', $body);
?>
<?php
function getPageID($name) {
global $DB;
$query=$DB->GetRow("select id from menu where title='".$name."'");
return (int)@$query['id'];
function getPageID($name)
{
global $DB;
$query = $DB->GetRow("select id from menu where title='" . $name . "'");
return (int)@$query['id'];
}
function translate($word) {
global $language, $DB;
function translate($word)
{
global $language, $DB;
if ($language['code']!="en") {
$query=$DB->GetRow("select title, title".$language['db']." from menu where title='".$word."'");
if ($query['title'.$language['db']]!="") return $query['title'.$language['db']];
else return $query['title'];
} else return $word;
if ($language['code'] != "en") {
$query = $DB->GetRow("select title, title" . $language['db'] . " from menu where title='" . $word . "'");
if ($query['title' . $language['db']] != "") return $query['title' . $language['db']];
else return $query['title'];
} else return $word;
}
function parseMenu($res) {
global $language;
function parseMenu($res)
{
global $language;
$menu = array();
$menu = array();
foreach ($res as $row) {
if ($language['code']!="en") {
if ($row['title'.$language['db']]!="") $title=$row['title'.$language['db']];
else $title=$row['title'];
$menu[$title] = $row['target'];
} else {
$menu[$row['title']] = $row['target'];
}
}
foreach ($res as $row) {
if ($language['code'] != "en") {
if ($row['title' . $language['db']] != "") $title = $row['title' . $language['db']];
else $title = $row['title'];
$menu[$title] = $row['target'];
} else {
$menu[$row['title']] = $row['target'];
}
}
return $menu;
return $menu;
}
if (isset($pathlist[1]))
$pagename = $pathlist[1]; else $pagename = "";
$pagename = $pathlist[1]; else $pagename = "";
// Menu stuff
$smarty->assign("select",$pagename);
$smarty->assign("select", $pagename);
if (isset($pathlist[2]))
$smarty->assign("subselect",$pathlist[2]);
$smarty->assign("subselect", $pathlist[2]);
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
if ($session->loggedin) $query .= " or permission='users'";
foreach ($session->groups as $group => $value) {
$query .= " or permission='$group'";
$query .= " or permission='$group'";
}
$query .= ") order by menuorder";
......@@ -62,7 +65,7 @@ $menu = parseMenu($res);
// this needs to choose the actual current one
// subpages/submenu items can have permissions attached to them as well!
$query2 = "select * from menu where parent=";
$query2 = "select * from menu where parent=";
$query2 .= "'";
$query2 .= getPageID($pagename);
$query2 .= "'";
......@@ -71,16 +74,16 @@ $query2 .= " and (permission is NULL";
if ($session->loggedin) $query2 .= " or permission='users'";
foreach ($session->groups as $group => $value) {
$query2 .= " or permission='$group'";
}
$query2 .= " or permission='$group'";
}
$query2 .= ") order by menuorder";
$res2 = $DB->GetAll($query2);
if (count($res2)>0) {
$submenu = parseMenu($res2);
$menu[translate($pagename)] = $submenu;
if (count($res2) > 0) {
$submenu = parseMenu($res2);
$menu[translate($pagename)] = $submenu;
}
$smarty->assign("menu",$menu);
$smarty->assign("menu", $menu);
?>
<?php
function parseIdleTime($idletime) {
$idlearray = preg_split("/[hms]/",$idletime);
if (strstr($idletime,'h')) {
$hours = $idlearray[0];
$minutes = $idlearray[1];
$seconds = 0;
} elseif (strstr($idletime,'m')) {
$hours = 0;
$minutes = $idlearray[0];
$seconds = $idlearray[1];
} else {
$hours = 0;
$minutes = 0;
$seconds = $idlearray[0];
}
return (intval($hours * 3600)) + (intval($minutes) * 60) + intval($seconds);
function parseIdleTime($idletime)
{
$idlearray = preg_split("/[hms]/", $idletime);
if (strstr($idletime, 'h')) {
$hours = $idlearray[0];
$minutes = $idlearray[1];
$seconds = 0;
} elseif (strstr($idletime, 'm')) {
$hours = 0;
$minutes = $idlearray[0];
$seconds = $idlearray[1];
} else {
$hours = 0;
$minutes = 0;
$seconds = $idlearray[0];
}
return (intval($hours * 3600)) + (intval($minutes) * 60) + intval($seconds);
}
function compare_idletime($a, $b) {
return strnatcmp($a['idleseconds'], $b['idleseconds']);
function compare_idletime($a, $b)
{
return strnatcmp($a['idleseconds'], $b['idleseconds']);
}
$mwpath = array_search("Milliways", $pathlist);
$newpath = $baseurl;
for($i=0;$i<=$mwpath;$i++) {
if ($i!=0) $newpath .= "/";
$newpath .= $pathlist[$i];
for ($i = 0; $i <= $mwpath; $i++) {
if ($i != 0) $newpath .= "/";
$newpath .= $pathlist[$i];
}
$smarty->assign("mwpath", $newpath);
$cal = cal_info(CAL_JULIAN);
if (strtolower($pathlist[$mwpath+1]) == "uri") {
$latest = FALSE;
$today = FALSE;
unset($search);
if (isset($pathlist[$mwpath+2])) {
if ($pathlist[$mwpath+2] == "search" && isset($pathlist[$mwpath+3])) {
$search = $pathlist[$mwpath+3];
} else {
$today = strtotime($pathlist[$mwpath+2]);
}
}
if ($today === FALSE && !isset($search)) {
$today = time();
$latest = TRUE;
}
$smarty->assign("extra_scripts", array(
'<meta name="ROBOTS" content="NOINDEX" />',
'<meta name="ROBOTS" content="NOFOLLOW" />'));
$mwdb = new PDO('sqlite:/var/lib/mw/mwuri.db');
$res = $mwdb->prepare("select distinct strftime('%Y',added) from mwuri");
$res->execute();
$yearlist = $res->fetchAll(PDO::FETCH_COLUMN,0);
$smarty->assign("yearlist",$yearlist);
$res= $mwdb->prepare("select distinct strftime('%m',added) from mwuri where strftime('%Y',added) = ?");
$res->execute(array(date("Y",$today)));
$mlist = $res->fetchAll(PDO::FETCH_COLUMN,0);
$monthlist = array();
foreach( $mlist as $m) {
$monthlist[$m] = $cal['abbrevmonths'][(int)$m];
}
$smarty->assign("monthlist",$monthlist);
$res= $mwdb->prepare("select distinct strftime('%d',added) from mwuri where strftime('%Y-%m',added) = ?");
$res->execute(array(date("Y-m",$today)));
$daylist = $res->fetchAll(PDO::FETCH_COLUMN,0);
$smarty->assign("daylist",$daylist);
if ($today === FALSE && isset($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");
$term = "%".$search."%";
$res->execute(array($term,$term));
$data = $res->fetchAll(PDO::FETCH_ASSOC);
} else {
//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->execute(array(date("Y-m-d",$today)));
$data = $res->fetchAll(PDO::FETCH_ASSOC);
if ($latest && count($data == 0)) {
$day = end($yearlist)."-".end($monthlist)."-".end($daylist);
$today = strtotime($day);
$res->execute(array(date("Y-m-d",$today)));
$data = $res->fetchAll(PDO::FETCH_ASSOC);
}
}
foreach($data as $k => $row)
{
if ($row['tags']) {
$json = json_decode($row['tags'], TRUE);
if (is_array($json))
$data[$k]['taglist'] = $json[0]['top_tags'];
}
}
$smarty->assign("urilist", $data);
$smarty->assign("thisyear", date("Y",$today));
$smarty->assign("thismonth", date("m",$today));
$smarty->assign("thisday", date("d",$today));
$output = $smarty->fetch($base."templates/milliways_uri.tpl");
$smarty->assign("title", "Milliways URI");
$smarty->assign("body", $output);
$smarty->assign("extra_styles", "/css/milliways.css");
$smarty->assign("refresh", 120);
return;
if (strtolower($pathlist[$mwpath + 1]) == "uri") {
$latest = FALSE;
$today = FALSE;
unset($search);
if (isset($pathlist[$mwpath + 2])) {
if ($pathlist[$mwpath + 2] == "search" && isset($pathlist[$mwpath + 3])) {
$search = $pathlist[$mwpath + 3];
} else {
$today = strtotime($pathlist[$mwpath + 2]);
}
}
if ($today === FALSE && !isset($search)) {
$today = time();
$latest = TRUE;
}
$smarty->assign("extra_scripts", array(
'<meta name="ROBOTS" content="NOINDEX" />',
'<meta name="ROBOTS" content="NOFOLLOW" />'));
$mwdb = new PDO('sqlite:/var/lib/mw/mwuri.db');
$res = $mwdb->prepare("select distinct strftime('%Y',added) from mwuri");
$res->execute();
$yearlist = $res->fetchAll(PDO::FETCH_COLUMN, 0);
$smarty->assign("yearlist", $yearlist);
$res = $mwdb->prepare("select distinct strftime('%m',added) from mwuri where strftime('%Y',added) = ?");
$res->execute(array(date("Y", $today)));
$mlist = $res->fetchAll(PDO::FETCH_COLUMN, 0);
$monthlist = array();
foreach ($mlist as $m) {
$monthlist[$m] = $cal['abbrevmonths'][(int)$m];
}
$smarty->assign("monthlist", $monthlist);
$res = $mwdb->prepare("select distinct strftime('%d',added) from mwuri where strftime('%Y-%m',added) = ?");
$res->execute(array(date("Y-m", $today)));
$daylist = $res->fetchAll(PDO::FETCH_COLUMN, 0);
$smarty->assign("daylist", $daylist);
if ($today === FALSE && isset($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");
$term = "%" . $search . "%";
$res->execute(array($term, $term));
$data = $res->fetchAll(PDO::FETCH_ASSOC);
} else {
//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->execute(array(date("Y-m-d", $today)));
$data = $res->fetchAll(PDO::FETCH_ASSOC);
if ($latest && count($data == 0)) {
$day = end($yearlist) . "-" . end($monthlist) . "-" . end($daylist);
$today = strtotime($day);
$res->execute(array(date("Y-m-d", $today)));
$data = $res->fetchAll(PDO::FETCH_ASSOC);
}
}
foreach ($data as $k => $row) {
if ($row['tags']) {
$json = json_decode($row['tags'], TRUE);
if (is_array($json))
$data[$k]['taglist'] = $json[0]['top_tags'];
}
}
$smarty->assign("urilist", $data);
$smarty->assign("thisyear", date("Y", $today));
$smarty->assign("thismonth", date("m", $today));
$smarty->assign("thisday", date("d", $today));
$output = $smarty->fetch($base . "templates/milliways_uri.tpl");
$smarty->assign("title", "Milliways URI");
$smarty->assign("body", $output);
$smarty->assign("extra_styles", "/css/milliways.css");
$smarty->assign("refresh", 120);
return;
}
if (strtolower($pathlist[$mwpath+1]) == "status") {
$today = FALSE;
$wantuser = FALSE;
if (isset($pathlist[$mwpath+2])) {
if ($pathlist[$mwpath+2] == "user" && isset($pathlist[$mwpath+3]))
$wantuser = $pathlist[$mwpath+3];
else
$today = strtotime($pathlist[$mwpath+2]);
}
if ($today === FALSE)
$today = time();
$smarty->assign("extra_scripts", array(
'<meta name="ROBOTS" content="NOINDEX" />',
'<meta name="ROBOTS" content="NOFOLLOW" />'));
$mwdb = new PDO('sqlite:/var/lib/mw/mwuri.db');
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->execute(array($wantuser));
} 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->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->execute(array(date("Y-m-d",$today)));
$data = $res->fetchAll(PDO::FETCH_ASSOC);
$smarty->assign("statuslist", $data);
$res = $mwdb->prepare("select distinct strftime('%Y',added) from mwdoing");
$res->execute();
$yearlist = $res->fetchAll(PDO::FETCH_COLUMN,0);
$smarty->assign("yearlist",$yearlist);
$res= $mwdb->prepare("select distinct strftime('%m',added) from mwdoing where strftime('%Y',added) = ?");
$res->execute(array(date("Y",$today)));
$mlist = $res->fetchAll(PDO::FETCH_COLUMN,0);
$monthlist = array();
foreach( $mlist as $m) {
$monthlist[$m] = $cal['abbrevmonths'][(int)$m];
}
$smarty->assign("monthlist",$monthlist);
$res= $mwdb->prepare("select distinct strftime('%d',added) from mwdoing where strftime('%Y-%m',added) = ?");
$res->execute(array(date("Y-m",$today)));
$daylist = $res->fetchAll(PDO::FETCH_COLUMN,0);
$smarty->assign("daylist",$daylist);
$smarty->assign("thisyear", date("Y",$today));
$smarty->assign("thismonth", date("m",$today));
$smarty->assign("thisday", date("d",$today));
$output = $smarty->fetch($base."templates/milliways_status.tpl");
$smarty->assign("title", "Milliways Status");
$smarty->assign("body", $output);
$smarty->assign("extra_styles", "/css/milliways.css");
$smarty->assign("refresh", 120);
return;
if (strtolower($pathlist[$mwpath + 1]) == "status") {
$today = FALSE;
$wantuser = FALSE;
if (isset($pathlist[$mwpath + 2])) {
if ($pathlist[$mwpath + 2] == "user" && isset($pathlist[$mwpath + 3]))
$wantuser = $pathlist[$mwpath + 3];
else
$today = strtotime($pathlist[$mwpath + 2]);
}
if ($today === FALSE)
$today = time();
$smarty->assign("extra_scripts", array(
'<meta name="ROBOTS" content="NOINDEX" />',
'<meta name="ROBOTS" content="NOFOLLOW" />'));
$mwdb = new PDO('sqlite:/var/lib/mw/mwuri.db');
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->execute(array($wantuser));
} 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->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->execute(array(date("Y-m-d",$today)));
$data = $res->fetchAll(PDO::FETCH_ASSOC);
$smarty->assign("statuslist", $data);
$res = $mwdb->prepare("select distinct strftime('%Y',added) from mwdoing");
$res->execute();
$yearlist = $res->fetchAll(PDO::FETCH_COLUMN, 0);
$smarty->assign("yearlist", $yearlist);
$res = $mwdb->prepare("select distinct strftime('%m',added) from mwdoing where strftime('%Y',added) = ?");
$res->execute(array(date("Y", $today)));
$mlist = $res->fetchAll(PDO::FETCH_COLUMN, 0);
$monthlist = array();
foreach ($mlist as $m) {
$monthlist[$m] = $cal['abbrevmonths'][(int)$m];
}
$smarty->assign("monthlist", $monthlist);
$res = $mwdb->prepare("select distinct strftime('%d',added) from mwdoing where strftime('%Y-%m',added) = ?");
$res->execute(array(date("Y-m", $today)));
$daylist = $res->fetchAll(PDO::FETCH_COLUMN, 0);
$smarty->assign("daylist", $daylist);
$smarty->assign("thisyear", date("Y", $today));
$smarty->assign("thismonth", date("m", $today));
$smarty->assign("thisday", date("d", $today));
$output = $smarty->fetch($base . "templates/milliways_status.tpl");
$smarty->assign("title", "Milliways Status");
$smarty->assign("body", $output);
$smarty->assign("extra_styles", "/css/milliways.css");
$smarty->assign("refresh", 120);
return;
}
if (strtolower($pathlist[$mwpath+1]) == "tag") {
$smarty->assign("extra_scripts", array(
'<meta name="ROBOTS" content="NOINDEX" />',
'<meta name="ROBOTS" content="NOFOLLOW" />'));
$mwdb = new PDO('sqlite:/var/lib/mw/mwuri.db');
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->execute(array('#'.$pathlist[$mwpath+2]));
$data = $res->fetchAll(PDO::FETCH_ASSOC);
$smarty->assign("taglist", $data);
$output = $smarty->fetch($base."templates/milliways_tag.tpl");
} 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->execute();
$data = $res->fetchAll(PDO::FETCH_ASSOC);
$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->execute();
$data = $res->fetchAll(PDO::FETCH_ASSOC);
$smarty->assign("latestlist", $data);
$output = $smarty->fetch($base."templates/milliways_taglist.tpl");
}
$smarty->assign("title", "Milliways Tags");
$smarty->assign("body", $output);
$smarty->assign("extra_styles", "/css/milliways.css");
$smarty->assign("refresh", 120);
return;
if (strtolower($pathlist[$mwpath + 1]) == "tag") {
$smarty->assign("extra_scripts", array(
'<meta name="ROBOTS" content="NOINDEX" />',
'<meta name="ROBOTS" content="NOFOLLOW" />'));
$mwdb = new PDO('sqlite:/var/lib/mw/mwuri.db');
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->execute(array('#' . $pathlist[$mwpath + 2]));
$data = $res->fetchAll(PDO::FETCH_ASSOC);
$smarty->assign("taglist", $data);
$output = $smarty->fetch($base . "templates/milliways_tag.tpl");
} 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->execute();
$data = $res->fetchAll(PDO::FETCH_ASSOC);
$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->execute();
$data = $res->fetchAll(PDO::FETCH_ASSOC);
$smarty->assign("latestlist", $data);
$output = $smarty->fetch($base . "templates/milliways_taglist.tpl");
}
$smarty->assign("title", "Milliways Tags");
$smarty->assign("body", $output);
$smarty->assign("extra_styles", "/css/milliways.css");
$smarty->assign("refresh", 120);
return;
}
exec("/usr/bin/mw -who", $wholist, $ret);
......@@ -214,18 +215,18 @@ $people = array();
$idlers = array();
foreach ($wholist as $person) {
$pid = strtok($person, " ");
if ($pid == "" || $pid == "Name" || substr($pid,0,5)=="-----") continue;
if ($pid == "" || $pid == "Name" || substr($pid, 0, 5) == "-----") continue;
$person = array(
"username" => trim(substr($person, 1, 16)),
"idle" => trim(substr($person, 18, 6)),
"idleseconds" => parseIdleTime(trim(substr($person, 18, 6))),
"what" => substr($person,25));
if ($person['idleseconds'] > 10800) {
$idlers[] = $person;
} else {
$people[] = $person;
}
"username" => trim(substr($person, 1, 16)),
"idle" => trim(substr($person, 18, 6)),
"idleseconds" => parseIdleTime(trim(substr($person, 18, 6))),
"what" => substr($person, 25));
if ($person['idleseconds'] > 10800) {
$idlers[] = $person;
} else {
$people[] = $person;
}
}
usort($people, 'compare_idletime');
......@@ -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->execute();
$urilist = $res->fetchAll(PDO::FETCH_ASSOC);
foreach ($urilist as $k=>$v) {
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);
foreach ($urilist as $k => $v) {
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);
}
$smarty->assign("urilist", $urilist);
......@@ -249,11 +250,11 @@ $res->execute();
$taglist = $res->fetchAll(PDO::FETCH_ASSOC);
$smarty->assign("taglist", $taglist);
$smarty->assign("people",$people);
$smarty->assign("idlers",$idlers);
$output = $smarty->fetch($base."templates/milliways.tpl");
$smarty->assign("people", $people);
$smarty->assign("idlers", $idlers);
$output = $smarty->fetch($base . "templates/milliways.tpl");
$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("refresh", 120);
?>
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment