Skip to content
Snippets Groups Projects

Compare revisions

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

Source

Select target project
No results found

Target

Select target project
  • osian/sucs-site
  • kais58/sucs-site
  • imranh/sucs-site
  • foshjedi2004/sucs-site
  • gigosaurus/sucs-site
  • matstn/sucs-site
  • ripp_/sucs-site
  • eggnog/sucs-site
  • sucssite/sucs-site
  • elbows/sucs-site
  • realitykiller/sucs-site
  • crox/sucs-site
  • vectre/sucs-site
  • welshbyte/sucs-site
  • paperclipman/sucs-site
15 results
Show changes
Showing
with 1922 additions and 2285 deletions
<?php <?php
include_once("../lib/date.php"); include_once("../lib/date.php");
// Config options // Config options
$inform="treasurer@sucs.org"; $inform = "treasurer@sucs.org";
$permission="sucsstaff"; $permission = "sucsstaff";
// Enable and disable database updating // Enable and disable database updating
$enable=TRUE; $enable = TRUE;
// Set next payment date // Set next payment date
$paydate = paidUntil(time()); $paydate = paidUntil(time());
...@@ -14,135 +14,129 @@ if (isset($session->groups[$permission])) { ...@@ -14,135 +14,129 @@ if (isset($session->groups[$permission])) {
$smarty->assign("staff", TRUE); $smarty->assign("staff", TRUE);
// $sucsDB->debug = true; // $sucsDB->debug = true;
// handle updates // handle updates
if(isset($_POST['uid']) && isset($_POST['lastupdate'])){ if (isset($_POST['uid']) && isset($_POST['lastupdate'])) {
// Check data hasn't changed and that nothing is broked // Check data hasn't changed and that nothing is broked
$query = "SELECT * FROM members WHERE uid=? AND lastupdate=?"; $query = "SELECT * FROM members WHERE uid=? AND lastupdate=?";
$array = array($_POST['uid'], $_POST['lastupdate']); $array = array($_POST['uid'], $_POST['lastupdate']);
$data = $sucsDB->GetAll($query,$array); $data = $sucsDB->GetAll($query, $array);
// If there is only one record then everything is fine // If there is only one record then everything is fine
if(sizeof($data)==1){ if (sizeof($data) == 1) {
// get info on currently logged in user // get info on currently logged in user
$user = posix_getpwnam($session->username); $user = posix_getpwnam($session->username);
// Update record // Update record
$record = $data[0]; $record = $data[0];
$query = "UPDATE members"; $query = "UPDATE members";
$query .= " SET paid = ?, lastupdate = DEFAULT, lastedit = ?"; $query .= " SET paid = ?, lastupdate = DEFAULT, lastedit = ?";
$query .= " WHERE uid = ?"; $query .= " WHERE uid = ?";
$array = array($paydate,$user['uid'],$_POST['uid']); $array = array($paydate, $user['uid'], $_POST['uid']);
if($enable){ if ($enable) {
$sucsDB->query($query,$array); $sucsDB->query($query, $array);
} }
// emailing contact (tresurer) // emailing contact (tresurer)
$message = "Account renewal notification\n\n"; $message = "Account renewal notification\n\n";
$message .= "Account : ".$record['username']."\n"; $message .= "Account : " . $record['username'] . "\n";
$message .= "User Type : ".$record['type']."\n"; $message .= "User Type : " . $record['type'] . "\n";
$message .= "Renewed by: ".$user['name']."\n\n"; $message .= "Renewed by: " . $user['name'] . "\n\n";
$message .= "Regards\n eclipse's script"; $message .= "Regards\n eclipse's script";
mail($inform,"Account Renewal",$message); mail($inform, "Account Renewal", $message);
// emailing user // emailing user
$message = "Your Swansea University Computer Society (SUCS) membership has been renewed\n\n"; $message = "Your Swansea University Computer Society (SUCS) membership has been renewed\n\n";
$message .= "Username: ".$record['username']."\n"; $message .= "Username: " . $record['username'] . "\n";
$message .= "If you do not know or have forgotten your password, please email admin@sucs.org to arrange for it to be changed.\n\n"; $message .= "If you do not know or have forgotten your password, please email admin@sucs.org to arrange for it to be changed.\n\n";
$message .= "Regards\n The SUCS admin"; $message .= "Regards\n The SUCS admin";
$header = "From: admin@sucs.org\r\n"; $header = "From: admin@sucs.org\r\n";
$header .= "Reply-To: admin@sucs.org"; $header .= "Reply-To: admin@sucs.org";
// Personal account // Personal account
mail($record['email'],"SUCS account renewal",$message,$header); mail($record['email'], "SUCS account renewal", $message, $header);
// sucs account // sucs account
mail($record['username']."@sucs.org","SUCS account renewal",$message,$header); mail($record['username'] . "@sucs.org", "SUCS account renewal", $message, $header);
message_flash("Renewed account for: ".htmlentities($record['username'])); message_flash("Renewed account for: " . htmlentities($record['username']));
} } else {
else{ trigger_error("Number of recored returned: " . sizeof($data) . ". Expected: 1.", E_USER_ERROR);
trigger_error("Number of recored returned: ".sizeof($data).". Expected: 1.", E_USER_ERROR);
} }
} }
// if sort is specified in GET // if sort is specified in GET
if(isset($_GET["sort"])){ if (isset($_GET["sort"])) {
$sortoptions = array("username","sid","realname"); $sortoptions = array("username", "sid", "realname");
// and is a valid option // and is a valid option
if(in_array($_GET["sort"],$sortoptions,TRUE)){ if (in_array($_GET["sort"], $sortoptions, TRUE)) {
// use it // use it
$sort=$_GET["sort"]; $sort = $_GET["sort"];
} } // else use username
// else use username else {
else{ $sort = 'username';
$sort='username';
} }
$getsort=$sort; $getsort = $sort;
} } //else use username
//else use username else {
else{ $sort = 'username';
$sort='username';
} }
//Get members details //Get members details
$query = "SELECT * FROM members, member_type"; $query = "SELECT * FROM members, member_type";
$query .= " WHERE paid != ?"; $query .= " WHERE paid != ?";
$query .= " AND (type = 1 OR type = 2 OR type = 5)"; $query .= " AND (type = 1 OR type = 2 OR type = 5)";
$query .= " AND type=member_type.id"; $query .= " AND type=member_type.id";
$query .= " ORDER BY paid,type,".$sort; $query .= " ORDER BY paid,type," . $sort;
$array = array($paydate); $array = array($paydate);
$data = $sucsDB->GetAll($query, $array); $data = $sucsDB->GetAll($query, $array);
$smarty->assign("members", $data); $smarty->assign("members", $data);
// set refresh rate // set refresh rate
$autorefresh=$_GET["autorefresh"]; $autorefresh = $_GET["autorefresh"];
// if autorefresh is not 'n' // if autorefresh is not 'n'
if($autorefresh!="n"){ if ($autorefresh != "n") {
// and is a decimal value // and is a decimal value
if(ctype_digit($autorefresh)){ if (ctype_digit($autorefresh)) {
// use it // use it
$refreshval=$autorefresh; $refreshval = $autorefresh;
// set passthrough // set passthrough
$getrefresh=$refreshval; $getrefresh = $refreshval;
} } else {
else{ // If no valid value assigned, default to OFF
// If no valid value assigned, default to OFF $refreshval = "n";
$refreshval="n"; }
} $optrefresh = $refreshval;
$optrefresh=$refreshval; $smarty->assign("refresh", $refreshval);
$smarty->assign("refresh", $refreshval); } else {
}
else{
// set passthrough // set passthrough
$getrefresh='n'; $getrefresh = 'n';
$optrefresh='n'; $optrefresh = 'n';
} }
// compile passthrough url // compile passthrough url
// sort // sort
if(isset($getsort)){ if (isset($getsort)) {
$getout="?sort=".$getsort; $getout = "?sort=" . $getsort;
} }
// autorefresh // autorefresh
if(isset($getrefresh)){ if (isset($getrefresh)) {
if(isset($getout)){ if (isset($getout)) {
$getout .= "&amp;autorefresh=".$getrefresh; $getout .= "&amp;autorefresh=" . $getrefresh;
} } else {
else{ $getout = "?autorefresh=" . $getrefresh;
$getout = "?autorefresh=".$getrefresh;
} }
} }
// set smarty variables // set smarty variables
$smarty->assign("self",$baseurl.$path.$getout); $smarty->assign("self", $baseurl . $path . $getout);
$smarty->assign("optionrefresh",$optrefresh); $smarty->assign("optionrefresh", $optrefresh);
$smarty->assign("optionsort",$sort); $smarty->assign("optionsort", $sort);
$smarty->assign("paydate",$paydate); $smarty->assign("paydate", $paydate);
} }
$side = $smarty->fetch('membershiprenew-options.tpl'); $side = $smarty->fetch('membershiprenew-options.tpl');
$body = $smarty->fetch('membershiprenew.tpl'); $body = $smarty->fetch('membershiprenew.tpl');
$smarty->assign('secondary',$side); $smarty->assign('secondary', $side);
$smarty->assign('title', "Renew Membership"); $smarty->assign('title', "Renew Membership");
$smarty->assign('body', $body); $smarty->assign('body', $body);
?> ?>
<?php <?php
function getPageID($name) { function getPageID($name)
global $DB; {
$query=$DB->GetRow("select id from menu where title='".$name."'"); global $DB;
return (int)@$query['id']; $query = $DB->GetRow("select id from menu where title='" . $name . "'");
return (int)@$query['id'];
} }
function translate($word) { function translate($word)
global $language, $DB; {
global $language, $DB;
if ($language['code']!="en") { if ($language['code'] != "en") {
$query=$DB->GetRow("select title, title".$language['db']." from menu where title='".$word."'"); $query = $DB->GetRow("select title, title" . $language['db'] . " from menu where title='" . $word . "'");
if ($query['title'.$language['db']]!="") return $query['title'.$language['db']]; if ($query['title' . $language['db']] != "") return $query['title' . $language['db']];
else return $query['title']; else return $query['title'];
} else return $word; } else return $word;
} }
function parseMenu($res) { function parseMenu($res)
global $language; {
global $language;
$menu = array(); $menu = array();
foreach ($res as $row) { foreach ($res as $row) {
if ($language['code']!="en") { if ($language['code'] != "en") {
if ($row['title'.$language['db']]!="") $title=$row['title'.$language['db']]; if ($row['title' . $language['db']] != "") $title = $row['title' . $language['db']];
else $title=$row['title']; else $title = $row['title'];
$menu[$title] = $row['target']; $menu[$title] = $row['target'];
} else { } else {
$menu[$row['title']] = $row['target']; $menu[$row['title']] = $row['target'];
} }
} }
return $menu; return $menu;
} }
if (isset($pathlist[1])) if (isset($pathlist[1]))
$pagename = $pathlist[1]; else $pagename = ""; $pagename = $pathlist[1]; else $pagename = "";
// Menu stuff // Menu stuff
$smarty->assign("select",$pagename); $smarty->assign("select", $pagename);
if (isset($pathlist[2])) if (isset($pathlist[2]))
$smarty->assign("subselect",$pathlist[2]); $smarty->assign("subselect", $pathlist[2]);
else else
$smarty->assign("subselect",$pagename); $smarty->assign("subselect", $pagename);
$query = "select * from menu where parent is NULL and (permission is NULL"; $query = "select * from menu where parent is NULL and (permission is NULL";
// Temporary - all members should be members of the "users" group but aren't // Temporary - all members should be members of the "users" group but aren't
if ($session->loggedin) $query .= " or permission='users'"; if ($session->loggedin) $query .= " or permission='users'";
foreach ($session->groups as $group => $value) { foreach ($session->groups as $group => $value) {
$query .= " or permission='$group'"; $query .= " or permission='$group'";
} }
$query .= ") order by menuorder"; $query .= ") order by menuorder";
...@@ -62,7 +65,7 @@ $menu = parseMenu($res); ...@@ -62,7 +65,7 @@ $menu = parseMenu($res);
// this needs to choose the actual current one // this needs to choose the actual current one
// subpages/submenu items can have permissions attached to them as well! // 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 .= "'";
$query2 .= getPageID($pagename); $query2 .= getPageID($pagename);
$query2 .= "'"; $query2 .= "'";
...@@ -71,16 +74,16 @@ $query2 .= " and (permission is NULL"; ...@@ -71,16 +74,16 @@ $query2 .= " and (permission is NULL";
if ($session->loggedin) $query2 .= " or permission='users'"; if ($session->loggedin) $query2 .= " or permission='users'";
foreach ($session->groups as $group => $value) { foreach ($session->groups as $group => $value) {
$query2 .= " or permission='$group'"; $query2 .= " or permission='$group'";
} }
$query2 .= ") order by menuorder"; $query2 .= ") order by menuorder";
$res2 = $DB->GetAll($query2); $res2 = $DB->GetAll($query2);
if (count($res2)>0) { if (count($res2) > 0) {
$submenu = parseMenu($res2); $submenu = parseMenu($res2);
$menu[translate($pagename)] = $submenu; $menu[translate($pagename)] = $submenu;
} }
$smarty->assign("menu",$menu); $smarty->assign("menu", $menu);
?> ?>
<?php <?php
function parseIdleTime($idletime) { function parseIdleTime($idletime)
$idlearray = preg_split("/[hms]/",$idletime); {
if (strstr($idletime,'h')) { $idlearray = preg_split("/[hms]/", $idletime);
$hours = $idlearray[0]; if (strstr($idletime, 'h')) {
$minutes = $idlearray[1]; $hours = $idlearray[0];
$seconds = 0; $minutes = $idlearray[1];
} elseif (strstr($idletime,'m')) { $seconds = 0;
$hours = 0; } elseif (strstr($idletime, 'm')) {
$minutes = $idlearray[0]; $hours = 0;
$seconds = $idlearray[1]; $minutes = $idlearray[0];
} else { $seconds = $idlearray[1];
$hours = 0; } else {
$minutes = 0; $hours = 0;
$seconds = $idlearray[0]; $minutes = 0;
} $seconds = $idlearray[0];
}
return (intval($hours * 3600)) + (intval($minutes) * 60) + intval($seconds);
return (intval($hours * 3600)) + (intval($minutes) * 60) + intval($seconds);
} }
function compare_idletime($a, $b) { function compare_idletime($a, $b)
return strnatcmp($a['idleseconds'], $b['idleseconds']); {
return strnatcmp($a['idleseconds'], $b['idleseconds']);
} }
$mwpath = array_search("Milliways", $pathlist); $mwpath = array_search("Milliways", $pathlist);
$newpath = $baseurl; $newpath = $baseurl;
for($i=0;$i<=$mwpath;$i++) { for ($i = 0; $i <= $mwpath; $i++) {
if ($i!=0) $newpath .= "/"; if ($i != 0) $newpath .= "/";
$newpath .= $pathlist[$i]; $newpath .= $pathlist[$i];
} }
$smarty->assign("mwpath", $newpath); $smarty->assign("mwpath", $newpath);
$cal = cal_info(CAL_JULIAN); $cal = cal_info(CAL_JULIAN);
if (strtolower($pathlist[$mwpath+1]) == "uri") { if (strtolower($pathlist[$mwpath + 1]) == "uri") {
$latest = FALSE; $latest = FALSE;
$today = FALSE; $today = FALSE;
unset($search); unset($search);
if (isset($pathlist[$mwpath+2])) { if (isset($pathlist[$mwpath + 2])) {
if ($pathlist[$mwpath+2] == "search" && isset($pathlist[$mwpath+3])) { if ($pathlist[$mwpath + 2] == "search" && isset($pathlist[$mwpath + 3])) {
$search = $pathlist[$mwpath+3]; $search = $pathlist[$mwpath + 3];
} else { } else {
$today = strtotime($pathlist[$mwpath+2]); $today = strtotime($pathlist[$mwpath + 2]);
} }
} }
if ($today === FALSE && !isset($search)) { if ($today === FALSE && !isset($search)) {
$today = time(); $today = time();
$latest = TRUE; $latest = TRUE;
} }
$smarty->assign("extra_scripts", array( $smarty->assign("extra_scripts", array(
'<meta name="ROBOTS" content="NOINDEX" />', '<meta name="ROBOTS" content="NOINDEX" />',
'<meta name="ROBOTS" content="NOFOLLOW" />')); '<meta name="ROBOTS" content="NOFOLLOW" />'));
$mwdb = new PDO('sqlite:/var/lib/mw/mwuri.db'); $mwdb = new PDO('sqlite:/var/lib/mw/mwuri.db');
$res = $mwdb->prepare("select distinct strftime('%Y',added) from mwuri"); $res = $mwdb->prepare("select distinct strftime('%Y',added) from mwuri");
$res->execute(); $res->execute();
$yearlist = $res->fetchAll(PDO::FETCH_COLUMN,0); $yearlist = $res->fetchAll(PDO::FETCH_COLUMN, 0);
$smarty->assign("yearlist",$yearlist); $smarty->assign("yearlist", $yearlist);
$res= $mwdb->prepare("select distinct strftime('%m',added) from mwuri where strftime('%Y',added) = ?"); $res = $mwdb->prepare("select distinct strftime('%m',added) from mwuri where strftime('%Y',added) = ?");
$res->execute(array(date("Y",$today))); $res->execute(array(date("Y", $today)));
$mlist = $res->fetchAll(PDO::FETCH_COLUMN,0); $mlist = $res->fetchAll(PDO::FETCH_COLUMN, 0);
$monthlist = array(); $monthlist = array();
foreach( $mlist as $m) { foreach ($mlist as $m) {
$monthlist[$m] = $cal['abbrevmonths'][(int)$m]; $monthlist[$m] = $cal['abbrevmonths'][(int)$m];
} }
$smarty->assign("monthlist",$monthlist); $smarty->assign("monthlist", $monthlist);
$res= $mwdb->prepare("select distinct strftime('%d',added) from mwuri where strftime('%Y-%m',added) = ?"); $res = $mwdb->prepare("select distinct strftime('%d',added) from mwuri where strftime('%Y-%m',added) = ?");
$res->execute(array(date("Y-m",$today))); $res->execute(array(date("Y-m", $today)));
$daylist = $res->fetchAll(PDO::FETCH_COLUMN,0); $daylist = $res->fetchAll(PDO::FETCH_COLUMN, 0);
$smarty->assign("daylist",$daylist); $smarty->assign("daylist", $daylist);
if ($today === FALSE && isset($search)) { if ($today === FALSE && isset($search)) {
// do a search // do a search
$res = $mwdb->prepare("select *, time(added,'localtime') as hour, date(added,'localtime') as day from mwuri where title like ? or url like ? order by added desc"); $res = $mwdb->prepare("select *, time(added,'localtime') as hour, date(added,'localtime') as day from mwuri where title like ? or url like ? order by added desc");
$term = "%".$search."%"; $term = "%" . $search . "%";
$res->execute(array($term,$term)); $res->execute(array($term, $term));
$data = $res->fetchAll(PDO::FETCH_ASSOC); $data = $res->fetchAll(PDO::FETCH_ASSOC);
} else { } else {
//standard date based lookup //standard date based lookup
$res = $mwdb->prepare("select *, time(added,'localtime') as hour, date(added,'localtime') as day from mwuri where date(added,'localtime')=? order by added desc"); $res = $mwdb->prepare("select *, time(added,'localtime') as hour, date(added,'localtime') as day from mwuri where date(added,'localtime')=? order by added desc");
$res->execute(array(date("Y-m-d",$today))); $res->execute(array(date("Y-m-d", $today)));
$data = $res->fetchAll(PDO::FETCH_ASSOC); $data = $res->fetchAll(PDO::FETCH_ASSOC);
if ($latest && count($data == 0)) { if ($latest && count($data == 0)) {
$day = end($yearlist)."-".end($monthlist)."-".end($daylist); $day = end($yearlist) . "-" . end($monthlist) . "-" . end($daylist);
$today = strtotime($day); $today = strtotime($day);
$res->execute(array(date("Y-m-d",$today))); $res->execute(array(date("Y-m-d", $today)));
$data = $res->fetchAll(PDO::FETCH_ASSOC); $data = $res->fetchAll(PDO::FETCH_ASSOC);
} }
} }
foreach($data as $k => $row) foreach ($data as $k => $row) {
{ if ($row['tags']) {
if ($row['tags']) { $json = json_decode($row['tags'], TRUE);
$json = json_decode($row['tags'], TRUE); if (is_array($json))
if (is_array($json)) $data[$k]['taglist'] = $json[0]['top_tags'];
$data[$k]['taglist'] = $json[0]['top_tags']; }
} }
} $smarty->assign("urilist", $data);
$smarty->assign("urilist", $data);
$smarty->assign("thisyear", date("Y", $today));
$smarty->assign("thisyear", date("Y",$today)); $smarty->assign("thismonth", date("m", $today));
$smarty->assign("thismonth", date("m",$today)); $smarty->assign("thisday", date("d", $today));
$smarty->assign("thisday", date("d",$today));
$output = $smarty->fetch($base . "templates/milliways_uri.tpl");
$output = $smarty->fetch($base."templates/milliways_uri.tpl"); $smarty->assign("title", "Milliways URI");
$smarty->assign("title", "Milliways URI"); $smarty->assign("body", $output);
$smarty->assign("body", $output); $smarty->assign("extra_styles", "/css/milliways.css");
$smarty->assign("extra_styles", "/css/milliways.css"); $smarty->assign("refresh", 120);
$smarty->assign("refresh", 120); return;
return;
} }
if (strtolower($pathlist[$mwpath+1]) == "status") { if (strtolower($pathlist[$mwpath + 1]) == "status") {
$today = FALSE; $today = FALSE;
$wantuser = FALSE; $wantuser = FALSE;
if (isset($pathlist[$mwpath+2])) { if (isset($pathlist[$mwpath + 2])) {
if ($pathlist[$mwpath+2] == "user" && isset($pathlist[$mwpath+3])) if ($pathlist[$mwpath + 2] == "user" && isset($pathlist[$mwpath + 3]))
$wantuser = $pathlist[$mwpath+3]; $wantuser = $pathlist[$mwpath + 3];
else else
$today = strtotime($pathlist[$mwpath+2]); $today = strtotime($pathlist[$mwpath + 2]);
} }
if ($today === FALSE) if ($today === FALSE)
$today = time(); $today = time();
$smarty->assign("extra_scripts", array( $smarty->assign("extra_scripts", array(
'<meta name="ROBOTS" content="NOINDEX" />', '<meta name="ROBOTS" content="NOINDEX" />',
'<meta name="ROBOTS" content="NOFOLLOW" />')); '<meta name="ROBOTS" content="NOFOLLOW" />'));
$mwdb = new PDO('sqlite:/var/lib/mw/mwuri.db'); $mwdb = new PDO('sqlite:/var/lib/mw/mwuri.db');
if ($wantuser !== FALSE) { if ($wantuser !== FALSE) {
$res = $mwdb->prepare("select *, time(added,'localtime') as hour, date(added,'localtime') as day from mwdoing where user=? order by added desc"); $res = $mwdb->prepare("select *, time(added,'localtime') as hour, date(added,'localtime') as day from mwdoing where user=? order by added desc");
$res->execute(array($wantuser)); $res->execute(array($wantuser));
} else { } else {
$res = $mwdb->prepare("select *, time(added,'localtime') as hour, date(added,'localtime') as day from mwdoing where strftime('%Y-%m',added,'localtime')=? order by added desc"); $res = $mwdb->prepare("select *, time(added,'localtime') as hour, date(added,'localtime') as day from mwdoing where strftime('%Y-%m',added,'localtime')=? order by added desc");
$res->execute(array(date("Y-m",$today))); $res->execute(array(date("Y-m", $today)));
} }
//$res = $mwdb->prepare("select *, time(added,'localtime') as hour, date(added,'localtime') as day from mwdoing where date(added,'localtime')=? order by added desc"); //$res = $mwdb->prepare("select *, time(added,'localtime') as hour, date(added,'localtime') as day from mwdoing where date(added,'localtime')=? order by added desc");
//$res->execute(array(date("Y-m-d",$today))); //$res->execute(array(date("Y-m-d",$today)));
$data = $res->fetchAll(PDO::FETCH_ASSOC); $data = $res->fetchAll(PDO::FETCH_ASSOC);
$smarty->assign("statuslist", $data); $smarty->assign("statuslist", $data);
$res = $mwdb->prepare("select distinct strftime('%Y',added) from mwdoing"); $res = $mwdb->prepare("select distinct strftime('%Y',added) from mwdoing");
$res->execute(); $res->execute();
$yearlist = $res->fetchAll(PDO::FETCH_COLUMN,0); $yearlist = $res->fetchAll(PDO::FETCH_COLUMN, 0);
$smarty->assign("yearlist",$yearlist); $smarty->assign("yearlist", $yearlist);
$res= $mwdb->prepare("select distinct strftime('%m',added) from mwdoing where strftime('%Y',added) = ?"); $res = $mwdb->prepare("select distinct strftime('%m',added) from mwdoing where strftime('%Y',added) = ?");
$res->execute(array(date("Y",$today))); $res->execute(array(date("Y", $today)));
$mlist = $res->fetchAll(PDO::FETCH_COLUMN,0); $mlist = $res->fetchAll(PDO::FETCH_COLUMN, 0);
$monthlist = array(); $monthlist = array();
foreach( $mlist as $m) { foreach ($mlist as $m) {
$monthlist[$m] = $cal['abbrevmonths'][(int)$m]; $monthlist[$m] = $cal['abbrevmonths'][(int)$m];
} }
$smarty->assign("monthlist",$monthlist); $smarty->assign("monthlist", $monthlist);
$res= $mwdb->prepare("select distinct strftime('%d',added) from mwdoing where strftime('%Y-%m',added) = ?"); $res = $mwdb->prepare("select distinct strftime('%d',added) from mwdoing where strftime('%Y-%m',added) = ?");
$res->execute(array(date("Y-m",$today))); $res->execute(array(date("Y-m", $today)));
$daylist = $res->fetchAll(PDO::FETCH_COLUMN,0); $daylist = $res->fetchAll(PDO::FETCH_COLUMN, 0);
$smarty->assign("daylist",$daylist); $smarty->assign("daylist", $daylist);
$smarty->assign("thisyear", date("Y",$today)); $smarty->assign("thisyear", date("Y", $today));
$smarty->assign("thismonth", date("m",$today)); $smarty->assign("thismonth", date("m", $today));
$smarty->assign("thisday", date("d",$today)); $smarty->assign("thisday", date("d", $today));
$output = $smarty->fetch($base."templates/milliways_status.tpl"); $output = $smarty->fetch($base . "templates/milliways_status.tpl");
$smarty->assign("title", "Milliways Status"); $smarty->assign("title", "Milliways Status");
$smarty->assign("body", $output); $smarty->assign("body", $output);
$smarty->assign("extra_styles", "/css/milliways.css"); $smarty->assign("extra_styles", "/css/milliways.css");
$smarty->assign("refresh", 120); $smarty->assign("refresh", 120);
return; return;
} }
if (strtolower($pathlist[$mwpath+1]) == "tag") { if (strtolower($pathlist[$mwpath + 1]) == "tag") {
$smarty->assign("extra_scripts", array( $smarty->assign("extra_scripts", array(
'<meta name="ROBOTS" content="NOINDEX" />', '<meta name="ROBOTS" content="NOINDEX" />',
'<meta name="ROBOTS" content="NOFOLLOW" />')); '<meta name="ROBOTS" content="NOFOLLOW" />'));
$mwdb = new PDO('sqlite:/var/lib/mw/mwuri.db'); $mwdb = new PDO('sqlite:/var/lib/mw/mwuri.db');
if (isset($pathlist[$mwpath+2])) { if (isset($pathlist[$mwpath + 2])) {
$res = $mwdb->prepare("select *, date(added) as day, substr(tag,2) as name from mwtag where tag=? order by added desc"); $res = $mwdb->prepare("select *, date(added) as day, substr(tag,2) as name from mwtag where tag=? order by added desc");
$res->execute(array('#'.$pathlist[$mwpath+2])); $res->execute(array('#' . $pathlist[$mwpath + 2]));
$data = $res->fetchAll(PDO::FETCH_ASSOC); $data = $res->fetchAll(PDO::FETCH_ASSOC);
$smarty->assign("taglist", $data); $smarty->assign("taglist", $data);
$output = $smarty->fetch($base."templates/milliways_tag.tpl"); $output = $smarty->fetch($base . "templates/milliways_tag.tpl");
} else { } else {
$res = $mwdb->prepare("select distinct tag, substr(tag,2) as name, count(tag) as count from mwtag group by tag order by count(tag) desc limit 20"); $res = $mwdb->prepare("select distinct tag, substr(tag,2) as name, count(tag) as count from mwtag group by tag order by count(tag) desc limit 20");
$res->execute(); $res->execute();
$data = $res->fetchAll(PDO::FETCH_ASSOC); $data = $res->fetchAll(PDO::FETCH_ASSOC);
$smarty->assign("toplist", $data); $smarty->assign("toplist", $data);
$res = $mwdb->prepare("select distinct tag, substr(tag,2) as name, count(tag) as count, max(added) as dated, date(max(added)) as day from mwtag group by tag order by max(added) desc limit 20"); $res = $mwdb->prepare("select distinct tag, substr(tag,2) as name, count(tag) as count, max(added) as dated, date(max(added)) as day from mwtag group by tag order by max(added) desc limit 20");
$res->execute(); $res->execute();
$data = $res->fetchAll(PDO::FETCH_ASSOC); $data = $res->fetchAll(PDO::FETCH_ASSOC);
$smarty->assign("latestlist", $data); $smarty->assign("latestlist", $data);
$output = $smarty->fetch($base."templates/milliways_taglist.tpl"); $output = $smarty->fetch($base . "templates/milliways_taglist.tpl");
} }
$smarty->assign("title", "Milliways Tags"); $smarty->assign("title", "Milliways Tags");
$smarty->assign("body", $output); $smarty->assign("body", $output);
$smarty->assign("extra_styles", "/css/milliways.css"); $smarty->assign("extra_styles", "/css/milliways.css");
$smarty->assign("refresh", 120); $smarty->assign("refresh", 120);
return; return;
} }
exec("/usr/bin/mw -who", $wholist, $ret); exec("/usr/bin/mw -who", $wholist, $ret);
...@@ -214,18 +215,18 @@ $people = array(); ...@@ -214,18 +215,18 @@ $people = array();
$idlers = array(); $idlers = array();
foreach ($wholist as $person) { foreach ($wholist as $person) {
$pid = strtok($person, " "); $pid = strtok($person, " ");
if ($pid == "" || $pid == "Name" || substr($pid,0,5)=="-----") continue; if ($pid == "" || $pid == "Name" || substr($pid, 0, 5) == "-----") continue;
$person = array( $person = array(
"username" => trim(substr($person, 1, 16)), "username" => trim(substr($person, 1, 16)),
"idle" => trim(substr($person, 18, 6)), "idle" => trim(substr($person, 18, 6)),
"idleseconds" => parseIdleTime(trim(substr($person, 18, 6))), "idleseconds" => parseIdleTime(trim(substr($person, 18, 6))),
"what" => substr($person,25)); "what" => substr($person, 25));
if ($person['idleseconds'] > 10800) { if ($person['idleseconds'] > 10800) {
$idlers[] = $person; $idlers[] = $person;
} else { } else {
$people[] = $person; $people[] = $person;
} }
} }
usort($people, 'compare_idletime'); usort($people, 'compare_idletime');
...@@ -238,9 +239,9 @@ $mwdb = new PDO('sqlite:/var/lib/mw/mwuri.db'); ...@@ -238,9 +239,9 @@ $mwdb = new PDO('sqlite:/var/lib/mw/mwuri.db');
$res = $mwdb->prepare("select *, time(added,'localtime') as hour, date(added,'localtime') as day from mwuri order by added desc limit 5"); $res = $mwdb->prepare("select *, time(added,'localtime') as hour, date(added,'localtime') as day from mwuri order by added desc limit 5");
$res->execute(); $res->execute();
$urilist = $res->fetchAll(PDO::FETCH_ASSOC); $urilist = $res->fetchAll(PDO::FETCH_ASSOC);
foreach ($urilist as $k=>$v) { foreach ($urilist as $k => $v) {
if ($v['title'] == "") $urilist[$k]['title']=$v['url']; if ($v['title'] == "") $urilist[$k]['title'] = $v['url'];
$urilist[$k]['title']=filter_var(trim($urilist[$k]['title']),FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH | FILTER_FLAG_STRIP_LOW); $urilist[$k]['title'] = filter_var(trim($urilist[$k]['title']), FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH | FILTER_FLAG_STRIP_LOW);
} }
$smarty->assign("urilist", $urilist); $smarty->assign("urilist", $urilist);
...@@ -249,11 +250,11 @@ $res->execute(); ...@@ -249,11 +250,11 @@ $res->execute();
$taglist = $res->fetchAll(PDO::FETCH_ASSOC); $taglist = $res->fetchAll(PDO::FETCH_ASSOC);
$smarty->assign("taglist", $taglist); $smarty->assign("taglist", $taglist);
$smarty->assign("people",$people); $smarty->assign("people", $people);
$smarty->assign("idlers",$idlers); $smarty->assign("idlers", $idlers);
$output = $smarty->fetch($base."templates/milliways.tpl"); $output = $smarty->fetch($base . "templates/milliways.tpl");
$smarty->assign("title", "Milliways"); $smarty->assign("title", "Milliways");
$smarty->assign("body", file_get_contents($base."static/fragments/Milliways.txt")); $smarty->assign("body", file_get_contents($base . "static/fragments/Milliways.txt"));
$smarty->assign("secondary", $output); $smarty->assign("secondary", $output);
$smarty->assign("refresh", 120); $smarty->assign("refresh", 120);
?> ?>
<?php <?php
$motd_file = "/etc/motd"; $motd_file = "/etc/motd";
function decode_entities($text, $quote_style = ENT_COMPAT) { function decode_entities($text, $quote_style = ENT_COMPAT)
if (function_exists('html_entity_decode')) { {
$text = html_entity_decode($text, $quote_style, 'ISO-8859-1'); // NOTE: UTF-8 does not work! $text = html_entity_decode($text, $quote_style, 'ISO-8859-1'); // NOTE: UTF-8 does not work!
} $text = preg_replace('~&ndash\;~i', '-', $text);
else { $text = preg_replace_callback('~&#x([0-9a-f]+);~i',
$trans_tbl = get_html_translation_table(HTML_ENTITIES, $quote_style); function ($matches) {
$trans_tbl = array_flip($trans_tbl); foreach ($matches as $match) {
$text = strtr($text, $trans_tbl); return chr(hexdec($match));
} }
$text = preg_replace('~&ndash\;~i', '-', $text); },
$text = preg_replace('~&#x([0-9a-f]+);~ei', 'chr(hexdec("\\1"))', $text); $text);
$text = preg_replace('~&#([0-9]+);~e', 'chr("\\1")', $text); $text = preg_replace_callback('~&#([0-9]+);~',
return $text; function ($matches) {
foreach ($matches as $match) {
return chr($match);
}
},
$text);
return $text;
} }
//function to count and collect hyperlinks //function to count and collect hyperlinks
$links_count = 0; $links_count = 0;
function linkcounter($uri) { function linkcounter($uri)
global $links_count, $uris; {
$uris[++$links_count] = $uri; global $links_count, $uris;
return $links_count; $uris[++$links_count] = $uri;
return $links_count;
} }
$poemmode = 0; $poemmode = 0;
$news = $DB->GetAll("SELECT * FROM news WHERE sticky=true AND expiry > now() ORDER BY date DESC"); $news = $DB->GetAll("SELECT * FROM news WHERE sticky=true AND expiry > now() ORDER BY date DESC");
if (count($news)<3) { if (count($news) < 3) {
$news = $DB->GetAll("(SELECT * FROM news WHERE sticky=false AND expiry > now() ORDER by date DESC LIMIT ".(3-count($news)).") UNION SELECT * FROM news WHERE sticky=true AND expiry > now() ORDER BY date DESC"); $news = $DB->GetAll("(SELECT * FROM news WHERE sticky=false AND expiry > now() ORDER by date DESC LIMIT " . (3 - count($news)) . ") UNION SELECT * FROM news WHERE sticky=true AND expiry > now() ORDER BY date DESC");
} }
if (count($news)<1) { if (count($news) < 1) {
$news = $DB->GetAll("SELECT * FROM poems ORDER BY RANDOM() LIMIT 1"); $news = $DB->GetAll("SELECT * FROM poems ORDER BY RANDOM() LIMIT 1");
$poemmode = 1; $poemmode = 1;
} }
$motd = "----------------------------- MESSAGE OF THE DAY ------------------------------\n\n"; $motd = "----------------------------- MESSAGE OF THE DAY ------------------------------\n\n";
for ($i=count($news)-1;$i>-1;$i--) { for ($i = count($news) - 1; $i > -1; $i--) {
$nitem = str_replace("\n", "", $news[$i]); $nitem = str_replace("\n", "", $news[$i]);
$nitem = str_replace("\r", "", $nitem); $nitem = str_replace("\r", "", $nitem);
$motd .= " ".$nitem['title']."\n"; $motd .= " " . $nitem['title'] . "\n";
$body = str_replace("</p>", "\n\n ", $nitem['body']); $body = str_replace("</p>", "\n\n ", $nitem['body']);
$body = str_replace("<br />", "\n ", $body); $body = str_replace("<br />", "\n ", $body);
$body = str_replace("<li>", " * ", $body); $body = str_replace("<li>", " * ", $body);
$body = str_replace("</li>", "\n ", $body); $body = str_replace("</li>", "\n ", $body);
$body = str_replace("&nbsp;", " ", $body); $body = str_replace("&nbsp;", " ", $body);
$body = str_replace("&hellip;", "...", $body); $body = str_replace("&hellip;", "...", $body);
$body = str_replace("&apos;", "'", $body); $body = str_replace("&apos;", "'", $body);
// remove hyperlinks, collect to display later // remove hyperlinks, collect to display later
$body = preg_replace(":<a href=['\"](.+?)['\"].*?>(.*?)</a>:e", "'\\2['.linkcounter('\\1').']'", $body); $body = preg_replace_callback(":<a href=['\"](.+?)['\"].*?>(.*?)</a>:",
$body = strip_tags($body); function ($matches) {
$body = decode_entities($body); $i = linkcounter($matches[1]);
$body = wordwrap($body, 75, "\n ", 1); return $matches[0]."[".$i."]";
$body = rtrim($body); },
$motd .=" ".$body."\n"; $body);
if (isset($uris)) { $body = strip_tags($body);
$footer = "----\n"; $body = decode_entities($body);
foreach ($uris as $urinum => $uri) { $body = wordwrap($body, 75, "\n ", 1);
$footer .= " [$urinum]: $uri\n"; $body = rtrim($body);
//remove uri from list so it won't show up on the next post $motd .= " " . $body . "\n";
unset($uris[$urinum]); if (isset($uris)) {
} $footer = "----\n";
$motd .= " ".$footer; foreach ($uris as $urinum => $uri) {
} $footer .= " [$urinum]: $uri\n";
$motd .= str_pad($nitem['author'], 78, " ", STR_PAD_LEFT)."\n"; //remove uri from list so it won't show up on the next post
unset($uris[$urinum]);
}
$motd .= " " . $footer;
}
$motd .= str_pad($nitem['author'], 78, " ", STR_PAD_LEFT) . "\n";
if ($poemmode == 1 && $nitem['submitter'] != '') { if ($poemmode == 1 && $nitem['submitter'] != '') {
$motd .= str_pad("Submitted by ".$nitem['submitter'], 78, " ", STR_PAD_LEFT)."\n"; $motd .= str_pad("Submitted by " . $nitem['submitter'], 78, " ", STR_PAD_LEFT) . "\n";
} }
$motd .= "\n"; $motd .= "\n";
} }
$motd .= "---------------------------- [ http://sucs.org/ ] -----------------------------\n"; $motd .= "---------------------------- [ http://sucs.org/ ] -----------------------------\n";
//print($motd);
//if (time()-filemtime($motd_file) < 86000 && $poemmode == 1) { //86000 to allow a little slack depending on when cron runs //if (time()-filemtime($motd_file) < 86000 && $poemmode == 1) { //86000 to allow a little slack depending on when cron runs
// print "MOTD too recent to replace with a poem!\n"; // print "MOTD too recent to replace with a poem!\n";
//} else { //} else {
file_put_contents($motd_file, $motd); file_put_contents($motd_file, $motd);
//} //}
?> ?>
\ No newline at end of file
...@@ -4,11 +4,11 @@ require("/var/www/sucssite/htdocs/settings.php"); ...@@ -4,11 +4,11 @@ require("/var/www/sucssite/htdocs/settings.php");
require("/usr/share/php/adodb/adodb.inc.php"); require("/usr/share/php/adodb/adodb.inc.php");
$dbname = 'sucssite'; $dbname = 'sucssite';
$dbuser = 'apache'; $dbuser = 'sucs_site_user';
$DB = NewADOConnection('postgres8'); $DB = NewADOConnection('postgres9');
$DB->Connect('dbname='.$dbname.' user='.$dbuser); $DB->Connect('dbname=' . $dbname . ' user=' . $dbuser);
$DB->SetCharSet('utf8'); $DB->SetCharSet('utf8');
$DB->SetFetchMode(ADODB_FETCH_ASSOC); $DB->SetFetchMode(ADODB_FETCH_ASSOC);
include($base."components/motd.php"); include($base . "components/motd.php");
<? <?php
// guard against corrupt folder data // guard against corrupt folder data
define("TOOBIG",102400); define("TOOBIG", 102400);
function load_folders() function load_folders()
{ {
$f = fopen("/var/lib/mw/folders.bb", "r"); $f = fopen("/var/lib/mw/folders.bb", "r");
$folders = array(); $folders = array();
while (!feof($f) && $fol=fread($f,64)) { while (!feof($f) && $fol = fread($f, 64)) {
$data = unpack("Cstatus/A11name/A31topic/Cspare/Lfirst/Llast", $fol); $data = unpack("Cstatus/A11name/A31topic/Cspare/Lfirst/Llast", $fol);
cleanup($data['name']); cleanup($data['name']);
cleanup($data['topic']); cleanup($data['topic']);
if ($data['status'] & 0x01 && !($data['status']&0x20)) $folders[$data['name']] = $data; if ($data['status'] & 0x01 && !($data['status'] & 0x20)) $folders[$data['name']] = $data;
} }
fclose($f); fclose($f);
return $folders; return $folders;
} }
function cleanup(&$foo) function cleanup(&$foo)
{ {
$i=0; $i = 0;
$new = ""; $new = "";
while ($i < strlen($foo)) { while ($i < strlen($foo)) {
if ( ord($foo[$i]) == 0) break; if (ord($foo[$i]) == 0) break;
if (ctype_print($foo[$i])) if (ctype_print($foo[$i]))
$new .= $foo[$i]; $new .= $foo[$i];
$i++; $i++;
} }
// $foo = htmlentities($new); // $foo = htmlentities($new);
$foo = $new; $foo = $new;
} }
function load_index($folname, $getbody=FALSE) function load_index($folname, $getbody = FALSE)
{ {
$index = array(); $index = array();
$f = @fopen("/var/lib/mw/$folname.i", "r"); $f = @fopen("/var/lib/mw/$folname.i", "r");
$body = @fopen("/var/lib/mw/$folname.t", "r"); $body = @fopen("/var/lib/mw/$folname.t", "r");
if ($f === FALSE || $body === FALSE) return array(); if ($f === FALSE || $body === FALSE) return array();
while (!feof($f) && $fol=fread($f,128)) { while (!feof($f) && $fol = fread($f, 128)) {
$data = unpack("Lref/Ldate/A17from/A41to/A41subject/c1spare/Ldatafield/Lsize/Cstatus/a3spare/Lreplyto/C4spare", $fol); $data = unpack("Lref/Ldate/A17from/A41to/A41subject/c1spare/Ldatafield/Lsize/Cstatus/a3spare/Lreplyto/C4spare", $fol);
cleanup($data['subject']); cleanup($data['subject']);
cleanup($data['to']); cleanup($data['to']);
cleanup($data['from']); cleanup($data['from']);
// not deleted, has data, and want it, so load the body // not deleted, has data, and want it, so load the body
if (!( $data['status'] & 0x02)) { if (!($data['status'] & 0x02)) {
if ($getbody && $data['size']>0 && $data['size'] < TOOBIG) { if ($getbody && $data['size'] > 0 && $data['size'] < TOOBIG) {
fseek($body, $data['datafield']); fseek($body, $data['datafield']);
//$data['body'] = htmlentities(fread($body, $data['size'])); //$data['body'] = htmlentities(fread($body, $data['size']));
$data['body'] = fread($body, $data['size']); $data['body'] = fread($body, $data['size']);
} }
$index[ $data['ref'] ] = $data; $index[$data['ref']] = $data;
} }
} }
fclose($f); fclose($f);
return $index; return $index;
} }
// Count how many articles are replies to this one // Count how many articles are replies to this one
function count_sub(&$haystack, $ref) function count_sub(&$haystack, $ref)
{ {
$count = 0; $count = 0;
foreach($haystack as $k => $v) foreach ($haystack as $k => $v) {
{ if ($v['replyto'] == $ref) {
if ($v['replyto'] == $ref) { $count++;
$count++; $count += count_sub($haystack, $v['ref']);
$count += count_sub($haystack, $v['ref']); }
} }
} return $count;
return $count;
} }
function fetch_sub(&$all, $ref) function fetch_sub(&$all, $ref)
{ {
$sub = array(); $sub = array();
foreach($all as $k => $v) { foreach ($all as $k => $v) {
if ($v['replyto'] == $ref) { if ($v['replyto'] == $ref) {
$sub[$k] = $v; $sub[$k] = $v;
$sub = array_merge($sub, fetch_sub($all, $v['ref'])); $sub = array_merge($sub, fetch_sub($all, $v['ref']));
} }
} }
return $sub; return $sub;
} }
function post_article($folder, $user, $replyto) function post_article($folder, $user, $replyto)
{ {
$folder = escapeshellarg($folder); $folder = escapeshellarg($folder);
$f = popen("/usr/bin/mw -f $folder $user $replyto","w"); $f = popen("/usr/bin/mw -f $folder $user $replyto", "w");
$to = strip_tags($_POST['to']); $to = strip_tags($_POST['to']);
$subject = strip_tags($_POST['subject']); $subject = strip_tags($_POST['subject']);
$body = strip_tags( $_POST['body']); $body = strip_tags($_POST['body']);
$to = preg_replace('/[^[:alnum:][:punct:][:space:]]*/','',trim($to)); $to = preg_replace('/[^[:alnum:][:punct:][:space:]]*/', '', trim($to));
$subject = preg_replace('/[^[:alnum:][:punct:][:space:]]*/','',trim($subject)); $subject = preg_replace('/[^[:alnum:][:punct:][:space:]]*/', '', trim($subject));
$body = preg_replace("/\n\\.\n","\n .\n/",$body); $body = preg_replace("/\n\\.\n", "\n .\n/", $body);
$deb = fopen("/tmp/mwdebug.txt","w"); $deb = fopen("/tmp/mwdebug.txt", "w");
fwrite($deb, "folder: '$folder'\n"); fwrite($deb, "folder: '$folder'\n");
fwrite($deb, "user: '$user'\n"); fwrite($deb, "user: '$user'\n");
fwrite($deb, "replyto: '$replyto'\n"); fwrite($deb, "replyto: '$replyto'\n");
fwrite($deb, "to: '$to'\n"); // Send to fwrite($deb, "to: '$to'\n"); // Send to
fwrite($deb, "sub: '$subject'\n"); // subject fwrite($deb, "sub: '$subject'\n"); // subject
fwrite($deb,"body:\n$body\n.\n"); // end post fwrite($deb, "body:\n$body\n.\n"); // end post
if ($replyto == 0) { if ($replyto == 0) {
fwrite($f, "$to\n"); // Send to fwrite($f, "$to\n"); // Send to
fwrite($f, "$subject\n"); // subject fwrite($f, "$subject\n"); // subject
fwrite($f,"$body\n.\n"); // end post fwrite($f, "$body\n.\n"); // end post
} else { } else {
fwrite($f, "$subject\n"); // subject fwrite($f, "$subject\n"); // subject
fwrite($f, "$to\n"); // send to fwrite($f, "$to\n"); // send to
fwrite($f,"$body\n.\n"); // end post fwrite($f, "$body\n.\n"); // end post
} }
$ret = pclose($f); $ret = pclose($f);
fwrite($deb, "Exit = ".($ret/256)."\n"); fwrite($deb, "Exit = " . ($ret / 256) . "\n");
fclose($deb); fclose($deb);
} }
if (!$session->loggedin) { if (!$session->loggedin) {
$smarty->assign("title", "Milliways"); $smarty->assign("title", "Milliways");
$smarty->assign("body", "Sorry, you must be logged in for this feature"); $smarty->assign("body", "Sorry, you must be logged in for this feature");
return; return;
} }
$folders = load_folders(); $folders = load_folders();
...@@ -134,92 +133,92 @@ $smarty->assign("extra_styles", array("/css/forum/SUCS.css")); ...@@ -134,92 +133,92 @@ $smarty->assign("extra_styles", array("/css/forum/SUCS.css"));
unset($mode); unset($mode);
$last = end($pathlist); $last = end($pathlist);
if ($last == "new" || $last == "reply") { if ($last == "new" || $last == "reply") {
$mode = $last; $mode = $last;
array_pop($pathlist); array_pop($pathlist);
$path = implode("/",$pathlist); $path = implode("/", $pathlist);
/* $smarty->assign("extra_scripts", array( /* $smarty->assign("extra_scripts", array(
'<script language="javascript" type="text/javascript" src="/js/tinymce/jscripts/tiny_mce/tiny_mce.js"></script>', '<script language="javascript" type="text/javascript" src="/js/tinymce/jscripts/tiny_mce/tiny_mce.js"></script>',
'<script language="javascript" type="text/javascript" src="/js/tiny_mce.js"></script>' '<script language="javascript" type="text/javascript" src="/js/tiny_mce.js"></script>'
)); ));
*/ */
} }
if ($last == "post") { if ($last == "post") {
$mode = $last; $mode = $last;
array_pop($pathlist); array_pop($pathlist);
$path = implode("/",$pathlist); $path = implode("/", $pathlist);
} }
$smarty->assign("mode",$mode); $smarty->assign("mode", $mode);
$shortpathlist = $pathlist; $shortpathlist = $pathlist;
array_pop($shortpathlist); array_pop($shortpathlist);
$shortpath = implode("/",$shortpathlist); $shortpath = implode("/", $shortpathlist);
$smarty->assign("shortpath",$shortpath); $smarty->assign("shortpath", $shortpath);
if (isset($pathlist[3])) { if (isset($pathlist[3])) {
$name = $pathlist[3]; $name = $pathlist[3];
if (isset($folders[$name])) { if (isset($folders[$name])) {
$smarty->assign("folder", $folders[$name]['name']); $smarty->assign("folder", $folders[$name]['name']);
$all = load_index($name, TRUE); $all = load_index($name, TRUE);
// One specific article was mentioned // One specific article was mentioned
if (isset($pathlist[4])) { if (isset($pathlist[4])) {
$artno = (int)$pathlist[4]; $artno = (int)$pathlist[4];
if (isset($all[$artno])) { if (isset($all[$artno])) {
if ($mode == "post") { if ($mode == "post") {
post_article($name, $session->username, $artno); post_article($name, $session->username, $artno);
$all = load_index($name, TRUE); $all = load_index($name, TRUE);
} }
$smarty->assign("title", "Milliways"); $smarty->assign("title", "Milliways");
$smarty->assign_by_ref("message", $all[$artno]); $smarty->assign_by_ref("message", $all[$artno]);
$sub = fetch_sub($all, $all[$artno]['ref']); $sub = fetch_sub($all, $all[$artno]['ref']);
$smarty->assign_by_ref("articles", $sub); $smarty->assign_by_ref("articles", $sub);
$smarty->assign("howmany",count($sub)); $smarty->assign("howmany", count($sub));
$output = $smarty->fetch($base."templates/mw-article.tpl"); $output = $smarty->fetch($base . "templates/mw-article.tpl");
} }
} else { } else {
if ($mode == "post") { if ($mode == "post") {
post_article($name, $session->username, 0); post_article($name, $session->username, 0);
$all = load_index($name, TRUE); $all = load_index($name, TRUE);
} }
// list all the articles in this folder // list all the articles in this folder
$top = array(); $top = array();
foreach ($all as $k => $v) { foreach ($all as $k => $v) {
if ($v['replyto'] == 0 ) { if ($v['replyto'] == 0) {
$v['suball'] = fetch_sub($all,$v['ref']); $v['suball'] = fetch_sub($all, $v['ref']);
$v['sub'] = count($v['suball']); $v['sub'] = count($v['suball']);
$l = end($v['suball']); $l = end($v['suball']);
$v['lastpost'] = $l['date']; $v['lastpost'] = $l['date'];
$v['lastfrom'] = $l['from']; $v['lastfrom'] = $l['from'];
$top[$k]=$v; $top[$k] = $v;
} }
} }
$top = array_reverse($top); $top = array_reverse($top);
$smarty->assign("title", htmlentities("Milliways - Folder $name")); $smarty->assign("title", htmlentities("Milliways - Folder $name"));
$smarty->assign_by_ref("articles", $top); $smarty->assign_by_ref("articles", $top);
$output = $smarty->fetch($base."templates/mw-list.tpl"); $output = $smarty->fetch($base . "templates/mw-list.tpl");
} }
} else { } else {
$output = "Error, no such folder $name"; $output = "Error, no such folder $name";
} }
$smarty->assign("body", $output); $smarty->assign("body", $output);
} else { } else {
// List all the folders // List all the folders
foreach($folders as $k => $v) { foreach ($folders as $k => $v) {
$list = load_index($v['name']); $list = load_index($v['name']);
$topics = 0; $topics = 0;
foreach ($list as $art) if ($art['replyto'] == 0) $topics++; foreach ($list as $art) if ($art['replyto'] == 0) $topics++;
$folders[$k]['topics'] = $topics; $folders[$k]['topics'] = $topics;
$lastone = end($list); $lastone = end($list);
$folders[$k]['lastpost'] = $lastone['date']; $folders[$k]['lastpost'] = $lastone['date'];
} }
$smarty->assign("title", "Milliways - Topic List"); $smarty->assign("title", "Milliways - Topic List");
$output = $smarty->fetch($base."templates/mw-folders.tpl"); $output = $smarty->fetch($base . "templates/mw-folders.tpl");
$smarty->assign("body", $output); $smarty->assign("body", $output);
} }
?> ?>
<?php <?php
// Ensure we have a trailing slash so that relative links within the page work // Ensure we have a trailing slash so that relative links within the page work
if ($_SERVER['PATH_INFO']=="/News") header("Location: ".$baseurl."/News/"); if ($_SERVER['PATH_INFO'] == "/News") header("Location: " . $baseurl . "/News/");
// A user must be in the staff group in order to edit content in this component // A user must be in the staff group in order to edit content in this component
$permission = "sucsstaff"; $permission = "sucsstaff";
...@@ -8,39 +8,39 @@ $newstable = "news"; ...@@ -8,39 +8,39 @@ $newstable = "news";
if (isset($session->groups[$permission])) { if (isset($session->groups[$permission])) {
// display Edit links on page // display Edit links on page
$smarty->assign("editable", TRUE); $smarty->assign("editable", TRUE);
switch (@$_REQUEST['action']) { switch (@$_REQUEST['action']) {
case "Save": case "Save":
$record['title'] = $_REQUEST['edittitle']; $record['title'] = $_REQUEST['edittitle'];
$record['body'] = $_REQUEST['body']; $record['body'] = $_REQUEST['body'];
if (isset($_REQUEST['sticky'])) if (isset($_REQUEST['sticky']))
$record['sticky'] = 't'; $record['sticky'] = 't';
else else
$record['sticky'] = 'f'; $record['sticky'] = 'f';
if ($_REQUEST['id']=="*") { if ($_REQUEST['id'] == "*") {
$record['author'] = $session->username; $record['author'] = $session->username;
$record['date'] = "now"; $record['date'] = "now";
$DB->AutoExecute($newstable, $record, 'INSERT'); $DB->AutoExecute($newstable, $record, 'INSERT');
} else { } else {
$DB->AutoExecute($newstable, $record, 'UPDATE', "id=".$DB->qstr($_REQUEST['id'])); $DB->AutoExecute($newstable, $record, 'UPDATE', "id=" . $DB->qstr($_REQUEST['id']));
} }
include("motd.php"); include("motd.php");
break; break;
case "Delete": case "Delete":
$deleted = $DB->Execute("DELETE FROM $newstable WHERE id=?", array($_REQUEST['id'])); $deleted = $DB->Execute("DELETE FROM $newstable WHERE id=?", array($_REQUEST['id']));
include("motd.php"); include("motd.php");
break; break;
case "Expire": case "Expire":
$expired = $DB->Execute("UPDATE $newstable SET expiry=now() WHERE id=?", array($_REQUEST['id'])); $expired = $DB->Execute("UPDATE $newstable SET expiry=now() WHERE id=?", array($_REQUEST['id']));
include("motd.php"); include("motd.php");
break; break;
} }
} }
$query = "SELECT *, date_part('epoch', expiry) AS expirytime FROM news"; $query = "SELECT *, date_part('epoch', expiry) AS expirytime FROM news";
if (@$pathlist[2]!="") $query .= " WHERE title=".$DB->qstr($pathlist[2]); if (@$pathlist[2] != "") $query .= " WHERE title=" . $DB->qstr($pathlist[2]);
$query .= " ORDER BY date DESC"; $query .= " ORDER BY date DESC";
$smarty->assign("news", $DB->GetArray($query)); $smarty->assign("news", $DB->GetArray($query));
...@@ -50,25 +50,25 @@ $smarty->assign("title", "News"); ...@@ -50,25 +50,25 @@ $smarty->assign("title", "News");
if (isset($session->groups[$permission])) { if (isset($session->groups[$permission])) {
// Perform any requested actions // Perform any requested actions
switch (@$_REQUEST['action']) { switch (@$_REQUEST['action']) {
case "create": case "create":
$news = array(array("id" => "*")); $news = array(array("id" => "*"));
$smarty->assign("news", $news); $smarty->assign("news", $news);
case "edit": case "edit":
$output = $smarty->fetch("news_edit.tpl"); $output = $smarty->fetch("news_edit.tpl");
$smarty->assign("action", "edit"); $smarty->assign("action", "edit");
$smarty->assign("title", "Edit News"); $smarty->assign("title", "Edit News");
break; break;
case "delete-query": case "delete-query":
$output = $smarty->fetch('news_delete.tpl').$output; $output = $smarty->fetch('news_delete.tpl') . $output;
break; break;
case "expire-query": case "expire-query":
$output = $smarty->fetch('news_expire.tpl').$output; $output = $smarty->fetch('news_expire.tpl') . $output;
break; break;
case "Delete": case "Delete":
if ($deleted) $output = "News item deleted"; if ($deleted) $output = "News item deleted";
break; break;
} }
} }
$smarty->assign("body", $output); $smarty->assign("body", $output);
......
...@@ -5,208 +5,220 @@ require_once("../lib/validation.php"); ...@@ -5,208 +5,220 @@ require_once("../lib/validation.php");
require_once("Net/MAC.php"); require_once("Net/MAC.php");
include_once("../lib/date.php"); include_once("../lib/date.php");
// password hash, renewal functions
include_once("../lib/member_functions.php");
// Some Constants // Some Constants
// These could possibly be moved somewhere saner? // These could possibly be moved somewhere saner?
define('GUESTNET_LOW','137.44.10.130'); // These could possibly be a set of ranges or a subnet which might be saner? define('GUESTNET_LOW', '137.44.10.130'); // These could possibly be a set of ranges or a subnet which might be saner?
define('GUESTNET_HIGH','137.44.10.134'); // These could possibly be a set of ranges or a subnet which might be saner? define('GUESTNET_HIGH', '137.44.10.134'); // These could possibly be a set of ranges or a subnet which might be saner?
// Helper Functions // Helper Functions
// Could these be moved to some kind of library? // Could these be moved to some kind of library?
// Set next payment date // Set next payment date
$paydate = "Sept. ".(academicYear(time())+1); $paydate = "Sept. " . (academicYear(time()) + 1);
// function to change a user's password // function to change a user's password
function changePassword ($oldpass, $newpass1, $newpass2) { function changePassword($oldpass, $newpass1, $newpass2)
global $session; {
global $session;
if ($newpass1 !== $newpass2) {
// new passwords do not match! if ($newpass1 !== $newpass2) {
trigger_error("New passwords do not match", E_USER_WARNING); // new passwords do not match!
return FALSE; trigger_error("New passwords do not match", E_USER_WARNING);
} return FALSE;
}
$reason = weakPassword($newpass1);
if ($reason !== FALSE) { $reason = weakPassword($newpass1);
trigger_error("New password is weak: $reason", E_USER_WARNING); if ($reason !== FALSE) {
return FALSE; trigger_error("New password is weak: $reason", E_USER_WARNING);
} return FALSE;
}
if (!($ldap = @ldap_connect("ldap://localhost"))) {
trigger_error("LDAP connect failed", E_USER_ERROR); if (!($ldap = @ldap_connect("ldap://localhost"))) {
return FALSE; trigger_error("LDAP connect failed", E_USER_ERROR);
} return FALSE;
}
if (!($ldapbind = ldap_bind($ldap, "uid=".$session->username.",ou=People,dc=sucs,dc=org",$oldpass))) {
trigger_error("Existing password incorrect", E_USER_WARNING); if (!($ldapbind = ldap_bind($ldap, "uid=" . $session->username . ",ou=People,dc=sucs,dc=org", $oldpass))) {
ldap_close($ldap); trigger_error("Existing password incorrect", E_USER_WARNING);
return FALSE; ldap_close($ldap);
} return FALSE;
}
// if everything looks OK, attempt to make the change
$success = ldap_mod_replace ($ldap, "uid=".$session->username.",ou=People,dc=sucs,dc=org", // if everything looks OK, attempt to make the change
array('userpassword' => "{SHA}".base64_encode(pack("H*", sha1($newpass1))))); $success = ldap_mod_replace($ldap, "uid=" . $session->username . ",ou=People,dc=sucs,dc=org",
array('userpassword' => "{CRYPT}" . cryptPassword($newpass1)));
ldap_close($ldap);
return $success; ldap_close($ldap);
return $success;
} }
// function to update contact details // function to update contact details
function changeContactDetails($address, $phone, $externalEmail) { function changeContactDetails($address, $phone, $externalEmail)
global $sucsDB, $session, $error; {
// Do some kind of checking here global $sucsDB, $session, $error;
// Check valid email (do we have a function for this? // Do some kind of checking here
if (!validEmail($externalEmail)) // Check valid email (do we have a function for this?
return FALSE; // Valid Email handles errors itself if (!validEmail($externalEmail))
// Check valid phone number (do we have a function for this?) return FALSE; // Valid Email handles errors itself
if (empty($phone) || (strlen($phone) < 6)) { // Check valid phone number (do we have a function for this?)
trigger_error("You must have a contact phone number!", E_USER_WARNING); if (empty($phone) || (strlen($phone) < 6)) {
return FALSE; trigger_error("You must have a contact phone number!", E_USER_WARNING);
} return FALSE;
// Update }
if ($sucsDB->Execute('UPDATE members SET address = ?,phone = ?, email = ?, lastupdate = now(), lastedit = uid WHERE username = ?', // Update
array($address, $phone, $externalEmail, $session->username)) === FALSE) { if ($sucsDB->Execute('UPDATE members SET address = ?,phone = ?, email = ?, lastupdate = now(), lastedit = uid WHERE username = ?',
trigger_error("There was an error updating your contact details. Please contact admin.", E_USER_ERROR); array($address, $phone, $externalEmail, $session->username)) === FALSE
return FALSE; ) {
} trigger_error("There was an error updating your contact details. Please contact admin.", E_USER_ERROR);
return TRUE; return FALSE;
}
return TRUE;
} }
function changeGuestnetDetails($wiredMAC) { function changeGuestnetDetails($wiredMAC)
global $sucsDB, $session, $error; {
// Get UID as we don't have it yet global $sucsDB, $session, $error;
if(($uid = $sucsDB->GetOne("SELECt uid FROM members WHERE username = ?", array($session->username))) === FALSE) { // Get UID as we don't have it yet
trigger_error("There was an error updating your GuestNET MAC Address. Please contact admin. (UID)", E_USER_ERROR); if (($uid = $sucsDB->GetOne("SELECt uid FROM members WHERE username = ?", array($session->username))) === FALSE) {
return FALSE; trigger_error("There was an error updating your GuestNET MAC Address. Please contact admin. (UID)", E_USER_ERROR);
} return FALSE;
// Replace the guestnet record with the one with the new mac }
if (!$sucsDB->Replace('guestnet', array('mac' => "'$wiredMAC'", 'uid' => $uid), 'uid')) { // Replace the guestnet record with the one with the new mac
trigger_error("There was an error updating your GuestNET MAC Address. Please contact admin. (QUERY)", E_USER_ERROR); if (!$sucsDB->Replace('guestnet', array('mac' => "'$wiredMAC'", 'uid' => $uid), 'uid')) {
return FALSE; trigger_error("There was an error updating your GuestNET MAC Address. Please contact admin. (QUERY)", E_USER_ERROR);
} return FALSE;
exec('/usr/local/bin/update-dhcpd', $placeholder, $returnVar); }
exec('/usr/local/bin/update-dhcpd', $placeholder, $returnVar);
if ($returnVar == 0) {
return TRUE; if ($returnVar == 0) {
// $message[] = 'GuestNet MAC Address updated. Please wait a minute or two for the changes to take effect.'; return TRUE;
} else { // $message[] = 'GuestNet MAC Address updated. Please wait a minute or two for the changes to take effect.';
trigger_error("There was an error updating your GuestNet Mac Address. Please contact admin. (RETURNVAR)", E_USER_ERROR); } else {
return FALSE; trigger_error("There was an error updating your GuestNet Mac Address. Please contact admin. (RETURNVAR)", E_USER_ERROR);
} return FALSE;
}
} }
// Checks whether the given string mac address is valid // Checks whether the given string mac address is valid
function isValidMACAddr($mac) { function isValidMACAddr($mac)
{
if (Net_MAC::check($mac)) { if (Net_MAC::check($mac)) {
return TRUE; return TRUE;
}else{ } else {
return FALSE; return FALSE;
} }
} }
// Returns the users GuestNet MAC Address if they have one and false otherwise // Returns the users GuestNet MAC Address if they have one and false otherwise
function getGuestNetMAC() { function getGuestNetMAC()
$ip = trim($_SERVER['REMOTE_ADDR']); {
// Sanity Check ip? $ip = trim($_SERVER['REMOTE_ADDR']);
// Check we are in the correct ip range (unregistered GuestNET addresses) // Sanity Check ip?
if (ip2long($ip) && (ip2long($ip) >= ip2long(GUESTNET_LOW)) && (ip2long($ip) <= ip2long(GUESTNET_HIGH))) { // Check we are in the correct ip range (unregistered GuestNET addresses)
if (ip2long($ip) && (ip2long($ip) >= ip2long(GUESTNET_LOW)) && (ip2long($ip) <= ip2long(GUESTNET_HIGH))) {
exec("sudo /usr/local/sbin/gw-copy-arp.sh", $placeholder, $returnVar);
if ($returnVar == 0) { exec("sudo /usr/local/sbin/gw-copy-arp.sh", $placeholder, $returnVar);
$arpLines = file('/tmp/gwarp'); if ($returnVar == 0) {
foreach ($arpLines as $arpLine) { $arpLines = file('/tmp/gwarp');
$arpFields = preg_split('/[\s\t\n]+/', $arpLine); foreach ($arpLines as $arpLine) {
if ($arpFields[0] == $ip) { $arpFields = preg_split('/[\s\t\n]+/', $arpLine);
// Perhaps do some checking on the mac here? if ($arpFields[0] == $ip) {
if (isValidMACAddr($arpFields[3])) // Perhaps do some checking on the mac here?
return $arpFields[3]; if (isValidMACAddr($arpFields[3]))
else return $arpFields[3];
break; else
} break;
} }
} }
// We didn't find their mac address :\ }
trigger_error("There was an error finding your MAC Address. Please contact admin.", E_USER_ERROR); // We didn't find their mac address :\
return FALSE; trigger_error("There was an error finding your MAC Address. Please contact admin.", E_USER_ERROR);
} else { return FALSE;
return FALSE; } else {
} return FALSE;
}
} }
// Delete the user's hackergotchi file cause they've decided they're too embarrassed by it // Delete the user's hackergotchi file cause they've decided they're too embarrassed by it
function clearHackergotchi() { function clearHackergotchi()
global $session; {
$imagefilepath = hackergotchiPath($session->username); global $session;
$imagefilepath = hackergotchiPath($session->username);
if (unlink(realpath($imagefilepath))) {
return true; if (unlink(realpath($imagefilepath))) {
} else { return true;
trigger_error("Unable to remove hackergotchi file", E_USER_ERROR); } else {
return false; trigger_error("Unable to remove hackergotchi file", E_USER_ERROR);
} return false;
}
} }
// construct the filesystem path to a user's hackergotchi picture // construct the filesystem path to a user's hackergotchi picture
function hackergotchiPath($username) { function hackergotchiPath($username)
global $base; {
$path = $base."htdocs/pictures/people/".$username.".png"; global $base;
return $path; $path = $base . "htdocs/pictures/people/" . $username . ".png";
return $path;
} }
// Takes an entry from $_FILES and makes this the new hackergotchi // Takes an entry from $_FILES and makes this the new hackergotchi
function updateHackergotchi($fileDetails) { function updateHackergotchi($fileDetails)
global $session; {
if ( ((list($width, $height, $type, $attr) = @getimagesize($fileDetails['tmp_name'])) !== false)) { global $session;
if ($type != IMAGETYPE_PNG) { if (((list($width, $height, $type, $attr) = @getimagesize($fileDetails['tmp_name'])) !== false)) {
trigger_error("Uploaded hackergotchi is not in PNG format. Please convert your image to PNG and try again.", E_USER_ERROR); if ($type != IMAGETYPE_PNG) {
return FALSE; trigger_error("Uploaded hackergotchi is not in PNG format. Please convert your image to PNG and try again.", E_USER_ERROR);
} else if (($width > 128) || ($height > 128)) { return FALSE;
trigger_error("Uploaded hackergotchi is too large. Hackergotchis must be 128x128 pixels or smaller.", E_USER_ERROR); } else if (($width > 128) || ($height > 128)) {
return FALSE; trigger_error("Uploaded hackergotchi is too large. Hackergotchis must be 128x128 pixels or smaller.", E_USER_ERROR);
} return FALSE;
}
$imagefilepath = hackergotchiPath($session->username);
$imagefilepath = hackergotchiPath($session->username);
// Move uploaded hackergotchi into place
if( move_uploaded_file($fileDetails['tmp_name'], $imagefilepath) && chmod($imagefilepath, 0644) ) { // Move uploaded hackergotchi into place
return TRUE; if (move_uploaded_file($fileDetails['tmp_name'], $imagefilepath) && chmod($imagefilepath, 0644)) {
} return TRUE;
} }
// We should have returned True by now }
trigger_error("There was an error updating your hackergotchi. Please contact admin.", E_USER_ERROR); // We should have returned True by now
return FALSE; trigger_error("There was an error updating your hackergotchi. Please contact admin.", E_USER_ERROR);
return FALSE;
} }
function updateRenew() { function updateRenew()
global $sucsDB, $session, $error; {
global $paydate; global $sucsDB, $session, $error;
global $paydate;
if (!isset($_REQUEST['userid']) || !isset($_REQUEST['supass'])) {
trigger_error("Invalid renewal info", E_USER_ERROR); if (!isset($_REQUEST['userid']) || !isset($_REQUEST['supass'])) {
return FALSE; trigger_error("Invalid renewal info", E_USER_ERROR);
} return FALSE;
$userid = (int)$_REQUEST['userid']; }
$pass = $_REQUEST['supass']; $userid = (int)$_REQUEST['userid'];
$member = $sucsDB->GetRow("select * from members left join member_type on members.type=member_type.id where username='".$session->username."'"); $pass = $_REQUEST['supass'];
$member = $sucsDB->GetRow("select * from members left join member_type on members.type=member_type.id where username='" . $session->username . "'");
$signup = $sucsDB->GetRow("select * from signup where id=?", array($userid));
if (!is_array($signup) || count($signup) < 1) { $signup = $sucsDB->GetRow("select * from signup where id=?", array($userid));
trigger_error("Invalid renewal info", E_USER_ERROR); if (!is_array($signup) || count($signup) < 1) {
return FALSE; trigger_error("Invalid renewal info", E_USER_ERROR);
} return FALSE;
if ($signup['password'] != $pass) { }
trigger_error("Invalid renewal info", E_USER_ERROR); if ($signup['password'] != $pass) {
return FALSE; trigger_error("Invalid renewal info", E_USER_ERROR);
} return FALSE;
if ($signup['activated'] != NULL) { }
trigger_error("Signup slip already used", E_USER_ERROR); if ($signup['activated'] != NULL) {
return FALSE; trigger_error("Signup slip already used", E_USER_ERROR);
} return FALSE;
}
$sucsDB->Execute("update members set paid=?, lastupdate=DEFAULT, lastedit=uid where uid=?", array($paydate, $member['uid']));
$sucsDB->Execute("update signup set activated=NOW(), username=? where id=?", array($member['username'], $signup['id'])); renew_membership($member['username']);
return TRUE; $sucsDB->Execute("update signup set activated=NOW(), username=? where id=?", array($member['username'], $signup['id']));
return TRUE;
} }
// Template Setup // Template Setup
...@@ -217,69 +229,69 @@ if ($session->loggedin === TRUE) { ...@@ -217,69 +229,69 @@ if ($session->loggedin === TRUE) {
// $sucsDB->debug = true; // $sucsDB->debug = true;
$newGuestNetMAC = getGuestNetMAC(); $newGuestNetMAC = getGuestNetMAC();
// Handle Postbacks // Handle Postbacks
if (isset($_POST['action'])) { if (isset($_POST['action'])) {
switch($_POST['action']) { switch ($_POST['action']) {
case 'changepass' : case 'changepass' :
if (changePassword($_POST['oldpass'], $_POST['newpass1'], $_POST['newpass2'])) { if (changePassword($_POST['oldpass'], $_POST['newpass1'], $_POST['newpass2'])) {
message_flash('Password changed.'); message_flash('Password changed.');
} else { } else {
// Should we log something here for bug trcaking use? // Should we log something here for bug trcaking use?
trigger_error("Password change failed.", E_USER_WARNING); trigger_error("Password change failed.", E_USER_WARNING);
} }
break; break;
case 'changecontact' : case 'changecontact' :
if(changeContactDetails($_POST['address'], $_POST['phone'], $_POST['email'])) { if (changeContactDetails($_POST['address'], $_POST['phone'], $_POST['email'])) {
message_flash('Contact Details Updated.'); message_flash('Contact Details Updated.');
} }
break; break;
case 'changeguestnet' : case 'changeguestnet' :
if(changeGuestNetDetails($newGuestNetMAC)) { if (changeGuestNetDetails($newGuestNetMAC)) {
message_flash('GuestNet Details Updated!'); message_flash('GuestNet Details Updated!');
} }
break; break;
case 'updatehackergotchi' : case 'updatehackergotchi' :
if (updateHackergotchi($_FILES['hackergotchi'])) { if (updateHackergotchi($_FILES['hackergotchi'])) {
message_flash('Hackergotchi Updated'); message_flash('Hackergotchi Updated');
} }
break; break;
case 'clearhackergotchi' : case 'clearhackergotchi' :
if (clearHackergotchi()) { if (clearHackergotchi()) {
message_flash('Hackergotchi Cleared'); message_flash('Hackergotchi Cleared');
} }
break; break;
case 'renew' : case 'renew' :
if (updateRenew()) { if (updateRenew()) {
message_flash('Account renewed'); message_flash('Account renewed');
} }
break; break;
} }
} }
// Display Details // Display Details
// Some checking could be done here to ensure we have a members record. Ideally we should // Some checking could be done here to ensure we have a members record. Ideally we should
// be able to assume this though if they are logged in. // be able to assume this though if they are logged in.
if (is_file($base."htdocs/pictures/people/".$session->username.".png")) $smarty->assign('hackergotchi', TRUE); if (is_file($base . "htdocs/pictures/people/" . $session->username . ".png")) $smarty->assign('hackergotchi', TRUE);
$member = $sucsDB->GetRow("select * from members left join member_type on members.type=member_type.id where username='".$session->username."'"); $member = $sucsDB->GetRow("select * from members left join member_type on members.type=member_type.id where username='" . $session->username . "'");
$smarty->assign('paydate', $paydate); $smarty->assign('paydate', $paydate);
if(($currentGuestNetMAC = $sucsDB->GetOne('SELECT * FROM guestnet WHERE uid=?', array((int)$member['uid']))) !== FALSE) { if (($currentGuestNetMAC = $sucsDB->GetOne('SELECT * FROM guestnet WHERE uid=?', array((int)$member['uid']))) !== FALSE) {
$smarty->assign('currentGuestNetMAC', $currentGuestNetMAC); $smarty->assign('currentGuestNetMAC', $currentGuestNetMAC);
} else { } else {
$smarty->assign('currentGuestNetMAC', ''); $smarty->assign('currentGuestNetMAC', '');
} }
if (($newGuestNetMAC !== false) && ($newGuestNetMAC != $currentGuestNetMAC)) { if (($newGuestNetMAC !== false) && ($newGuestNetMAC != $currentGuestNetMAC)) {
$smarty->assign('newGuestNetMAC', $newGuestNetMAC); $smarty->assign('newGuestNetMAC', $newGuestNetMAC);
} }
$smarty->assign('member', $member); $smarty->assign('member', $member);
} }
......
<?php <?php
$permission="html"; $permission = "html";
// Only html group members can use this page - horrible emergency bodge // Only html group members can use this page - horrible emergency bodge
if (isset($session->groups[$permission])) { if (isset($session->groups[$permission])) {
...@@ -10,28 +10,28 @@ if (isset($session->groups[$permission])) { ...@@ -10,28 +10,28 @@ if (isset($session->groups[$permission])) {
unset($output); unset($output);
if (@$pathlist[3] == "Edit") { if (@$pathlist[3] == "Edit") {
if (isset($_REQUEST['mapid'])) { if (isset($_REQUEST['mapid'])) {
$id = (int)$_REQUEST['mapid']; $id = (int)$_REQUEST['mapid'];
$res = $DB->GetAll("SELECT * FROM pagemap where id=?", array($id)); $res = $DB->GetAll("SELECT * FROM pagemap where id=?", array($id));
if ($res && count($res) > 0) { if ($res && count($res) > 0) {
$smarty->assign("oldmap",$res[0]); $smarty->assign("oldmap", $res[0]);
$output = $smarty->fetch($base."templates/pagemap_edit.tpl"); $output = $smarty->fetch($base . "templates/pagemap_edit.tpl");
} else { } else {
header("Location: /Admin/Pagemap"); header("Location: /Admin/Pagemap");
exit; exit;
} }
} else { } else {
header("Location: /Admin/Pagemap"); header("Location: /Admin/Pagemap");
exit; exit;
} }
} }
} }
if (!isset($output)) { if (!isset($output)) {
$smarty->assign("map",$DB->GetAll("SELECT * FROM pagemap ORDER BY depth, path")); $smarty->assign("map", $DB->GetAll("SELECT * FROM pagemap ORDER BY depth, path"));
$output = $smarty->fetch($base."templates/pagemap.tpl"); $output = $smarty->fetch($base . "templates/pagemap.tpl");
} }
$smarty->assign("title", "Page Map"); $smarty->assign("title", "Page Map");
$smarty->assign("body", $output); $smarty->assign("body", $output);
......
...@@ -2,29 +2,29 @@ ...@@ -2,29 +2,29 @@
/** /**
* Notes : * Notes :
* % Need to either a) install Text_Highlighter as a PEAR module properly or b) alter it so * % Need to either a) install Text_Highlighter as a PEAR module properly or b) alter it so
* that it can be included properly without having a Text/ directory at the same level * that it can be included properly without having a Text/ directory at the same level
* as the index file. * as the index file.
* % Needs some form of cron job or similar to remove old entries * % Needs some form of cron job or similar to remove old entries
* * This would seem preferable to running a delete query every page view * * This would seem preferable to running a delete query every page view
* * The retain_until field is there and set by the script so * * The retain_until field is there and set by the script so
* the framework is there for removal. * the framework is there for removal.
* * Rather than using a cron job this could be done using a simple timestamp stored in a php * * Rather than using a cron job this could be done using a simple timestamp stored in a php
* file which could be included (ie $timestamp = X, then include that and * file which could be included (ie $timestamp = X, then include that and
* if($timestamp >= now()) { delete query } * if($timestamp >= now()) { delete query }
* % Preventing XSS in User input needed * % Preventing XSS in User input needed
* * Should be handled by any User Auth * * Should be handled by any User Auth
* % Needs Checking for Aeternus-Brand Stupidity * % Needs Checking for Aeternus-Brand Stupidity
* Fixed : * Fixed :
* % Problem with strtotime() not parsing PostGres timestamps * % Problem with strtotime() not parsing PostGres timestamps
* set field type to timestamp(0) to remove fractional seconds * set field type to timestamp(0) to remove fractional seconds
* % Added User Authentication using pwauth * % Added User Authentication using pwauth
* * Could still do with session handling * * Could still do with session handling
* % Frosty mentioned it wasn't using a monospace font * % Frosty mentioned it wasn't using a monospace font
* * Simply made all text within the .hl-main block use the * * Simply made all text within the .hl-main block use the
* Courier New Monospace font * Courier New Monospace font
* * Could possibly offer the user more customisation in terms of * * Could possibly offer the user more customisation in terms of
* how they want things displayed (necessary??) * how they want things displayed (necessary??)
*/ */
...@@ -34,31 +34,31 @@ ...@@ -34,31 +34,31 @@
// Config // Config
define('_LIST_LIMIT', 15); define('_LIST_LIMIT', 15);
// Defined so we can customise them to whatever we like // Defined so we can customise them to whatever we like
define('_BASE_PATH', 'https://'.$_SERVER['SERVER_NAME'].'/'); define('_BASE_PATH', 'https://' . $_SERVER['SERVER_NAME'] . '/');
define('_SCRIPT_NAME', 'PasteBin/'); define('_SCRIPT_NAME', 'PasteBin/');
define('_TABLE_NAME', 'pastebin'); define('_TABLE_NAME', 'pastebin');
$smarty->assign('urifragment', '/Tools/PasteBin/'); $smarty->assign('urifragment', '/Tools/PasteBin/');
$pburi = 'https://'.$_SERVER['SERVER_NAME'].$baseurl; $pburi = 'https://' . $_SERVER['SERVER_NAME'] . $baseurl;
$smarty->assign('uri', $pburi.'/pb/'); $smarty->assign('uri', $pburi . '/pb/');
// Init // Init
$id = ''; $id = '';
if (is_numeric($pathlist[count($pathlist) - 1])) { if (is_numeric($pathlist[count($pathlist) - 1])) {
//$id = substr($_SERVER['PATH_INFO'],1); //$id = substr($_SERVER['PATH_INFO'],1);
//$id = preg_match('/[0-9]+/', $id)?$id:''; //$id = preg_match('/[0-9]+/', $id)?$id:'';
$i = count($pathlist)-1; $i = count($pathlist) - 1;
$id = $pathlist[$i]; $id = $pathlist[$i];
$id = preg_match('/[0-9]+/', $id)?$id:''; $id = preg_match('/[0-9]+/', $id) ? $id : '';
} else if (is_numeric($pathlist[count($pathlist) - 2]) && (strtolower($pathlist[count($pathlist) - 1]) == 'plain') ) { } else if (is_numeric($pathlist[count($pathlist) - 2]) && (strtolower($pathlist[count($pathlist) - 1]) == 'plain')) {
// Plain text // Plain text
$no_template = true; $no_template = true;
$id = $pathlist[count($pathlist) - 2]; $id = $pathlist[count($pathlist) - 2];
$id = preg_match('/[0-9]+/', $id)?$id:''; $id = preg_match('/[0-9]+/', $id) ? $id : '';
$code = $DB->GetOne('SELECT code FROM ' . _TABLE_NAME . ' WHERE id = ?', array($id)); $code = $DB->GetOne('SELECT code FROM ' . _TABLE_NAME . ' WHERE id = ?', array($id));
header('Content-Type: text/plain'); header('Content-Type: text/plain');
print html_entity_decode($code, ENT_QUOTES,'UTF-8'); print html_entity_decode($code, ENT_QUOTES, 'UTF-8');
return; // Finish processing in this file return; // Finish processing in this file
} }
$code = ''; $code = '';
$pblang = ''; $pblang = '';
...@@ -75,53 +75,48 @@ require_once '../lib/ArrayRenderer.php'; ...@@ -75,53 +75,48 @@ require_once '../lib/ArrayRenderer.php';
// Grabbed from blog.lib.php // Grabbed from blog.lib.php
// Returns a textual diff between two time stamps // Returns a textual diff between two time stamps
function timeDiff($first, $second=0) function timeDiff($first, $second = 0)
{ {
if($second == 0) { if ($second == 0) {
$second = time(); $second = time();
} }
$diff = max($first, $second) - min($first, $second); $diff = max($first, $second) - min($first, $second);
if($diff>604800) { if ($diff > 604800) {
$ret = round($diff/604800); $ret = round($diff / 604800);
return $ret.(($ret>1)? _(" weeks") : _(" week")); return $ret . (($ret > 1) ? _(" weeks") : _(" week"));
} } elseif ($diff > 86400) {
elseif($diff>86400) { $ret = round($diff / 86400);
$ret = round($diff/86400); return $ret . (($ret > 1) ? _(" days") : _(" day"));
return $ret.(($ret>1)? _(" days") : _(" day")); } elseif ($diff > 3600) {
} $ret = round($diff / 3600);
elseif($diff>3600) { return $ret . (($ret > 1) ? _(" hours") : _(" hour"));
$ret = round($diff/3600); } elseif ($diff > 60) {
return $ret.(($ret>1)? _(" hours") : _(" hour")); $ret = round($diff / 60);
} return $ret . (($ret > 1) ? _(" minutes") : _(" minute"));
elseif($diff>60) { } elseif ($diff > 0) {
$ret = round($diff/60); return $diff . (($diff > 1) ? _(" seconds") : _(" second"));
return $ret.(($ret>1)? _(" minutes") : _(" minute")); } else {
} return "no time";
elseif($diff>0) { }
return $diff.(($diff>1)? _(" seconds") : _(" second"));
}
else {
return "no time";
}
} }
// Languages // Languages
$LANGUAGES = array ( $LANGUAGES = array(
'PHP' => 'PHP', 'PHP' => 'PHP',
'CPP' => 'C/C++', 'CPP' => 'C/C++',
'DIFF' => 'Diff', 'DIFF' => 'Diff',
'DTD' => 'DTD', 'DTD' => 'DTD',
'HTML' => 'HTML', 'HTML' => 'HTML',
'JAVA' => 'Java', 'JAVA' => 'Java',
'JAVASCRIPT' => 'Javascript', 'JAVASCRIPT' => 'Javascript',
'MYSQL' => 'MySQL', 'MYSQL' => 'MySQL',
'PERL' => 'Perl', 'PERL' => 'Perl',
'PYTHON' => 'Python', 'PYTHON' => 'Python',
'RUBY' => 'Ruby', 'RUBY' => 'Ruby',
'SQL' => 'SQL', 'SQL' => 'SQL',
'XML' => 'XML' 'XML' => 'XML'
); );
// Remove Old Pastebin Entries // Remove Old Pastebin Entries
...@@ -132,108 +127,111 @@ $DB->Execute('DELETE FROM ' . _TABLE_NAME . ' WHERE retain_til < now()'); ...@@ -132,108 +127,111 @@ $DB->Execute('DELETE FROM ' . _TABLE_NAME . ' WHERE retain_til < now()');
//removeMagicQuotes($_POST); //removeMagicQuotes($_POST);
if (isset($_POST['code'])) { if (isset($_POST['code'])) {
$code = htmlentities($_POST['code'], ENT_QUOTES,'UTF-8'); $code = htmlentities($_POST['code'], ENT_QUOTES, 'UTF-8');
if ( isset($_POST['language']) && isset($_POST['retain'])) { if (isset($_POST['language']) && isset($_POST['retain'])) {
// Add // Add
$pblang = strtoupper($_POST['language']); $pblang = strtoupper($_POST['language']);
if (!isset($LANGUAGES[ $pblang ])) { if (!isset($LANGUAGES[$pblang])) {
$pblang = 'NONE'; $pblang = 'NONE';
} }
switch($_POST['retain'][0]) { switch ($_POST['retain'][0]) {
case 'month' : case 'month' :
$retain = 2592000; $retain = 2592000;
$retainTil = date('Y/m/d H:i:s', time() + $retain);break; $retainTil = date('Y/m/d H:i:s', time() + $retain);
case 'week' : break;
$retain = 604800; case 'week' :
$retainTil = date('Y/m/d H:i:s', time() + $retain);break; $retain = 604800;
case 'forever' : $retainTil = date('Y/m/d H:i:s', time() + $retain);
$retain = null; break;
$retainTil = null;break; case 'forever' :
case 'day' : $retain = null;
default : $retainTil = null;
$retain = 86400; break;
$retainTil = date('Y/m/d H:i:s', time() + $retain); case 'day' :
} default :
$retain = 86400;
if (trim($code) == '') { $retainTil = date('Y/m/d H:i:s', time() + $retain);
trigger_error('No Code Given', E_USER_NOTICE); }
} else if (!$session->loggedin) {
trigger_error('You must be logged in to use this service.', E_USER_NOTICE); if (trim($code) == '') {
} else { trigger_error('No Code Given', E_USER_NOTICE);
// Additional user validation needed here } else if (!$session->loggedin) {
//$retainTil = date('Y/m/d H:i:s', time() + $retain); trigger_error('You must be logged in to use this service.', E_USER_NOTICE);
$id = $DB->GetOne("SELECT nextval('pastebin_id_seq'::regclass)"); } else {
$DB->Execute( // Additional user validation needed here
'INSERT INTO ' . _TABLE_NAME . ' ( id, code, username, retain_til, language) ' . //$retainTil = date('Y/m/d H:i:s', time() + $retain);
'VALUES (?, ?, ?, ?, ?)', $id = $DB->GetOne("SELECT nextval('pastebin_id_seq'::regclass)");
array( $id, $code, $session->username, $retainTil, $pblang)); $DB->Execute(
'INSERT INTO ' . _TABLE_NAME . ' ( id, code, username, retain_til, language) ' .
//bump user to uri of newly pasted item 'VALUES (?, ?, ?, ?, ?)',
header('Status: 303 See Other'); array($id, $code, $session->username, $retainTil, $pblang));
header("Location: $pburi/Tools/PasteBin/$id");
//bump user to uri of newly pasted item
$userInfo = 'Created By ' . $session->username . ' at ' . date('Y/m/d H:i'); header('Status: 303 See Other');
$smarty->assign('id', $id); header("Location: $pburi/Tools/PasteBin/$id");
$smarty->assign('userInfo', $userInfo);
$smarty->assign('code', $code); $userInfo = 'Created By ' . $session->username . ' at ' . date('Y/m/d H:i');
$smarty->assign('id', $id);
} $smarty->assign('userInfo', $userInfo);
} $smarty->assign('code', $code);
}
}
} }
// List All Entries in order. // List All Entries in order.
$pasteList = $DB->GetAll( $pasteList = $DB->GetAll(
'SELECT id, username AS name, created AS time_diff FROM ' . _TABLE_NAME . ' ORDER BY created DESC LIMIT ' . _LIST_LIMIT ); 'SELECT id, username AS name, created AS time_diff FROM ' . _TABLE_NAME . ' ORDER BY created DESC LIMIT ' . _LIST_LIMIT);
for($i=0;$i< count($pasteList);$i++) { for ($i = 0; $i < count($pasteList); $i++) {
$pasteList[$i]['time_diff'] = timeDiff(strtotime($pasteList[$i]['time_diff'])); $pasteList[$i]['time_diff'] = timeDiff(strtotime($pasteList[$i]['time_diff']));
} }
$smarty->assign('pasteList', $pasteList); $smarty->assign('pasteList', $pasteList);
// Check for either display or form input // Check for either display or form input
if (!empty($id) || !empty($code)) { if (!empty($id) || !empty($code)) {
// Form // Form
if (empty($code)) { if (empty($code)) {
$result = $DB->GetRow('SELECT * FROM ' . _TABLE_NAME . ' WHERE id = ?', array($id)); $result = $DB->GetRow('SELECT * FROM ' . _TABLE_NAME . ' WHERE id = ?', array($id));
//$query = db_query('SELECT * FROM ' . _TABLE_NAME . ' WHERE id = \'' . $id . '\''); //$query = db_query('SELECT * FROM ' . _TABLE_NAME . ' WHERE id = \'' . $id . '\'');
if (!empty($result) ) { if (!empty($result)) {
//$result = db_getrow($query); //$result = db_getrow($query);
$code = $result['code']; $code = $result['code'];
$userInfo = 'Created By ' . $result['username'] . ' at ' . date('Y/m/d H:i', strtotime($result['created'])); $userInfo = 'Created By ' . $result['username'] . ' at ' . date('Y/m/d H:i', strtotime($result['created']));
$pblang = $result['language']; $pblang = $result['language'];
// Smarty // Smarty
$smarty->assign('id', $id); $smarty->assign('id', $id);
$smarty->assign('code', $code); $smarty->assign('code', $code);
$smarty->assign('userInfo', $userInfo); $smarty->assign('userInfo', $userInfo);
} else { } else {
// Error // Error
trigger_error('Error - Code Piece not found for id - ' . $id, E_USER_WARNING); trigger_error('Error - Code Piece not found for id - ' . $id, E_USER_WARNING);
} }
} }
// Check there hasn't been an error // Check there hasn't been an error
// Code should have been set in the if statement above, this can not become // Code should have been set in the if statement above, this can not become
// an else // an else
if (!empty($code)) { if (!empty($code)) {
// Highlight the code // Highlight the code
if ($pblang == 'NONE') { if ($pblang == 'NONE') {
$pblang = 'HTML'; $pblang = 'HTML';
} }
$renderer = new Text_Highlighter_Renderer_Array_dez(); $renderer = new Text_Highlighter_Renderer_Array_dez();
$tmpobj = new Text_Highlighter; $tmpobj = new Text_Highlighter;
$hl =& $tmpobj->factory($pblang); $hl =& $tmpobj->factory($pblang);
$hl->setRenderer($renderer); $hl->setRenderer($renderer);
// Have to decode again here for the highlighting // Have to decode again here for the highlighting
// It might be a little better if we kept the unencoded version from above // It might be a little better if we kept the unencoded version from above
$highlightedCode = $hl->highlight(html_entity_decode($code, ENT_QUOTES,'UTF-8')); $highlightedCode = $hl->highlight(html_entity_decode($code, ENT_QUOTES, 'UTF-8'));
$smarty->assign('highlightedCode', $highlightedCode); $smarty->assign('highlightedCode', $highlightedCode);
} }
} }
// Sort Out Languages // Sort Out Languages
if(!empty($pblang) && $pblang != 'NONE') { if (!empty($pblang) && $pblang != 'NONE') {
$smarty->assign('selectedLanguage', array('key' => $pblang, 'lang' => $LANGUAGES[$pblang])); $smarty->assign('selectedLanguage', array('key' => $pblang, 'lang' => $LANGUAGES[$pblang]));
unset($LANGUAGES[$pblang]); unset($LANGUAGES[$pblang]);
} }
$smarty->assign('pasteLanguages', $LANGUAGES); $smarty->assign('pasteLanguages', $LANGUAGES);
...@@ -243,5 +241,5 @@ $result = $smarty->fetch('pastebin.tpl'); ...@@ -243,5 +241,5 @@ $result = $smarty->fetch('pastebin.tpl');
$sidebar = $smarty->fetch('pastebin-sidebar.tpl'); $sidebar = $smarty->fetch('pastebin-sidebar.tpl');
$smarty->assign('title', 'PasteBin'); $smarty->assign('title', 'PasteBin');
$smarty->assign('body', $result); $smarty->assign('body', $result);
$smarty->assign('secondary',$sidebar); $smarty->assign('secondary', $sidebar);
?> ?>
<? <?php
$res = $sucsDB->Execute("select username, sum(pages) as pages from printer where username != 'old' group by username order by sum(pages) desc"); $res = $sucsDB->Execute("select username, sum(pages) as pages from printer where username != 'old' group by username order by sum(pages) desc");
$num = $res->RecordCount(); $num = $res->RecordCount();
for ($i=0;$i<$num;$i++) { for ($i = 0; $i < $num; $i++) {
$row[$i] = $res->FetchRow(); $row[$i] = $res->FetchRow();
if ($i < 12) if ($i < 12) {
{ $item[] = $row[$i]['username'];
$item[]=$row[$i]['username']; $slice[] = $row[$i]['pages'];
$slice[]=$row[$i]['pages']; } else {
} $otherSize += $row[$i]['pages'];
else { }
$otherSize += $row[$i]['pages']; }
}
}
// $itemName[]="Other"; // $itemName[]="Other";
// $sliceSize[]=$otherSize; // $sliceSize[]=$otherSize;
$slice = array_merge(array($otherSize),$slice); $slice = array_merge(array($otherSize), $slice);
$item = array_merge(array("Other"), $item); $item = array_merge(array("Other"), $item);
/* echo "<pre>"; /* echo "<pre>";
print_r($slice); print_r($slice);
print_r($item);*/ print_r($item);*/
include("../../lib/pieChart.php"); include("../../lib/pieChart.php");
piechart("Top 12, Users of Printing", $slice, $item,0) piechart("Top 12, Users of Printing", $slice, $item, 0)
?> ?>
\ No newline at end of file
...@@ -4,39 +4,39 @@ ...@@ -4,39 +4,39 @@
* Ported from old site by tswsl1989 * Ported from old site by tswsl1989
* *
*/ */
$max=10; //Set this to number of users to display in chart $max = 10; //Set this to number of users to display in chart
$timestamp = '2014-02-05 18:29:02+00'; //display printer stats since this time $timestamp = '2014-02-05 18:29:02+00'; //display printer stats since this time
$smarty->assign('title',"Printer Statistics"); $smarty->assign('title', "Printer Statistics");
// $out="<img src=\"/images/printer.graph.php\" alt=\"pie chart of top 12 printer users\"/>"; // $out="<img src=\"/images/printer.graph.php\" alt=\"pie chart of top 12 printer users\"/>";
$table="<table border=1 cellpadding=3>\n<tr>\n<th>Username</th>\n<th>Pages</th>\n<th>Projected Monthly Usage</th>\n<th>Printed This Month</th>\n<th>What it would cost in the library</th></tr>\n"; $table = "<table border=1 cellpadding=3>\n<tr>\n<th>Username</th>\n<th>Pages</th>\n<th>Projected Monthly Usage</th>\n<th>Printed This Month</th>\n<th>What it would cost in the library</th></tr>\n";
//pull in all the current users (ie not old) who have printed stuff //pull in all the current users (ie not old) who have printed stuff
$res = $sucsDB->Execute("select username, sum(pages) as pages from printer where username != 'old' AND start > '".$timestamp."' group by username order by sum(pages) desc"); $res = $sucsDB->Execute("select username, sum(pages) as pages from printer where username != 'old' AND start > '" . $timestamp . "' group by username order by sum(pages) desc");
$num = $res->RecordCount(); $num = $res->RecordCount();
//for each row stuff the infomation into an array, then free up the database resorces //for each row stuff the infomation into an array, then free up the database resorces
for ($i=0;$i<$num;$i++) { for ($i = 0; $i < $num; $i++) {
$data[$i] = $res->FetchRow(); $data[$i] = $res->FetchRow();
$data[$i]['month'] = 0; $data[$i]['month'] = 0;
} }
$res->Close(); $res->Close();
//get the second since epoch //get the second since epoch
$thisSecond = time(); $thisSecond = time();
//for each user who has printed stuff add the first printed time (since epoch) to the array //for each user who has printed stuff add the first printed time (since epoch) to the array
for ($i=0;$i<$num;$i++) { for ($i = 0; $i < $num; $i++) {
$res = $sucsDB->Execute("select date_part('epoch',start) as first from printer where username ='".$data[$i]['username']."' order by start asc limit 1;"); $res = $sucsDB->Execute("select date_part('epoch',start) as first from printer where username ='" . $data[$i]['username'] . "' order by start asc limit 1;");
$temp = $res->FetchRow(); $temp = $res->FetchRow();
$data[$i]['first'] = $temp['first']; $data[$i]['first'] = $temp['first'];
$res->Close(); $res->Close();
} }
$res = $sucsDB->Execute("select username, pages, start from printer where username != 'old'"); $res = $sucsDB->Execute("select username, pages, start from printer where username != 'old'");
$datesnum = $res->RecordCount();//for each row stuff the infomation into an array, then free up the database resorces $datesnum = $res->RecordCount();//for each row stuff the infomation into an array, then free up the database resorces
for ($i=0;$i<$datesnum;$i++) { for ($i = 0; $i < $datesnum; $i++) {
$dates[$i] = $res->FetchRow($res, $i); $dates[$i] = $res->FetchRow($res, $i);
} }
$res->Close(); $res->Close();
...@@ -44,50 +44,47 @@ $res->Close(); ...@@ -44,50 +44,47 @@ $res->Close();
// get the current month // get the current month
$theMonth = date("m"); $theMonth = date("m");
$theYear = date("Y"); $theYear = date("Y");
for ($i=0;$i<$datesnum;$i++) { for ($i = 0; $i < $datesnum; $i++) {
$userMonth = substr($dates[$i]['start'], 5, 2); $userMonth = substr($dates[$i]['start'], 5, 2);
$userYear = substr($dates[$i]['start'], 0, 4); $userYear = substr($dates[$i]['start'], 0, 4);
if (($userMonth == $theMonth) && ($userYear == $theYear)) { if (($userMonth == $theMonth) && ($userYear == $theYear)) {
for ($j=0;$j<$num;$j++) { for ($j = 0; $j < $num; $j++) {
if ($data[$j]['username'] == $dates[$i]['username']) { if ($data[$j]['username'] == $dates[$i]['username']) {
$data[$j]['month'] += $dates[$i]['pages']; $data[$j]['month'] += $dates[$i]['pages'];
} }
} }
} }
} }
//start the total counter //start the total counter
$total = 0; $total = 0;
//for each user.. print a row in the table //for each user.. print a row in the table
for ($i=0;$i<$num;$i++) { for ($i = 0; $i < $num; $i++) {
$table.="<tr align=\"center\">\n"; $table .= "<tr align=\"center\">\n";
$table.="<td>{$data[$i]['username']}</td>\n"; $table .= "<td>{$data[$i]['username']}</td>\n";
$table.="<td>{$data[$i]['pages']}</td>\n"; $table .= "<td>{$data[$i]['pages']}</td>\n";
//avg pages per month = seconds in a month / (now - first print) * pages //avg pages per month = seconds in a month / (now - first print) * pages
$crazyGuess = round((2629743.83/($thisSecond-$data[$i]['first']))*$data[$i]['pages']); $crazyGuess = round((2629743.83 / ($thisSecond - $data[$i]['first'])) * $data[$i]['pages']);
//if the user has only started printing in the last month its not sensible to give a guess of average useage //if the user has only started printing in the last month its not sensible to give a guess of average useage
if ($thisSecond-$data[$i]['first'] <= 2629743.83) { if ($thisSecond - $data[$i]['first'] <= 2629743.83) {
$table.="<td>Not enough data</td>\n"; $table .= "<td>Not enough data</td>\n";
} } //traffic lights for pinter useage, adjust values as required
//traffic lights for pinter useage, adjust values as required elseif ($crazyGuess <= 25) {
elseif($crazyGuess <= 25) { $table .= "<td BGCOLOR=\"Green\">" . $crazyGuess . "</td>\n";
$table.="<td BGCOLOR=\"Green\">".$crazyGuess."</td>\n"; } elseif ($crazyGuess <= 33) {
} $table .= "<td BGCOLOR=\"Orange\">" . $crazyGuess . "</td>\n";
elseif($crazyGuess <= 33) { } else {
$table.="<td BGCOLOR=\"Orange\">".$crazyGuess."</td>\n"; $table .= "<td BGCOLOR=\"Red\">" . $crazyGuess . "</td>\n";
} }
else{ if ($data[$i]['month'] >= 300) {
$table.="<td BGCOLOR=\"Red\">".$crazyGuess."</td>\n"; $table .= "<td BGCOLOR=\"Red\">{$data[$i]['month']}</td>\n";
} } else {
if ($data[$i]['month'] >= 300) { $table .= "<td>{$data[$i]['month']}</td>\n";
$table.="<td BGCOLOR=\"Red\">{$data[$i]['month']}</td>\n"; }
} else { $table .= "<td>" . sprintf("£ %01.2f", round(0.05 * $data[$i]['pages'], 2)) . "</td>\n";
$table.="<td>{$data[$i]['month']}</td>\n"; //add this users useage to the total
} $total += $data[$i]['pages'];
$table.="<td>".sprintf("£ %01.2f",round(0.05*$data[$i]['pages'],2))."</td>\n"; $table .= "</tr>\n";
//add this users useage to the total
$total += $data[$i]['pages'];
$table.="</tr>\n";
} }
//get the first print date //get the first print date
...@@ -101,16 +98,16 @@ $res->Close(); ...@@ -101,16 +98,16 @@ $res->Close();
//get the number of pages printed by "old" users and add it to the total //get the number of pages printed by "old" users and add it to the total
$res = $sucsDB->Execute("select sum(pages) as pages from printer where username = 'old' group by username order by sum(pages) desc"); $res = $sucsDB->Execute("select sum(pages) as pages from printer where username = 'old' group by username order by sum(pages) desc");
$old = $res->FetchRow(); $old = $res->FetchRow();
$old = $old[0]; $old = $old['pages'];
$res->Close(); $res->Close();
$total += $old; $total += $old;
//Output two lines at the bottem of the table, one for "old" users and the other for the total //Output two lines at the bottem of the table, one for "old" users and the other for the total
$table.="<tr align=\"center\">\n\t<th>Old Users</th>\n\t<th>$old</th>\n\t<th>n/a</th>\n</tr>"; $table .= "<tr align=\"center\">\n\t<th>Old Users</th>\n\t<th>$old</th>\n\t<th>n/a</th>\n</tr>";
$table.="<tr align=\"center\">\n\t<th>Total</th>\n\t<th>$total</th>\n\t<th>".round((2629743.83/($thisSecond-$date['first'][0]))*$total)."</th>\n</tr>"; $table .= "<tr align=\"center\">\n\t<th>Total</th>\n\t<th>$total</th>\n\t<th>" . round((2629743.83 / ($thisSecond - $date['first'][0])) * $total) . "</th>\n</tr>";
$table.="</table>\n"; $table .= "</table>\n";
//output the dates of the first and last prints recorded //output the dates of the first and last prints recorded
$out.="<script type=\"text/javascript\" src=\"https://www.google.com/jsapi\"></script> $out .= "<script type=\"text/javascript\" src=\"https://www.google.com/jsapi\"></script>
<script type=\"text/javascript\"> <script type=\"text/javascript\">
google.load(\"visualization\", \"1\", {packages:[\"corechart\"]}); google.load(\"visualization\", \"1\", {packages:[\"corechart\"]});
google.setOnLoadCallback(drawChart); google.setOnLoadCallback(drawChart);
...@@ -118,35 +115,35 @@ $out.="<script type=\"text/javascript\" src=\"https://www.google.com/jsapi\"></s ...@@ -118,35 +115,35 @@ $out.="<script type=\"text/javascript\" src=\"https://www.google.com/jsapi\"></s
var data = new google.visualization.DataTable(); var data = new google.visualization.DataTable();
data.addColumn('string', 'User'); data.addColumn('string', 'User');
data.addColumn('number', 'Pages Printed'); data.addColumn('number', 'Pages Printed');
data.addRows(".($max+2).");\n"; data.addRows(" . ($max + 2) . ");\n";
for( $i=0; $i<($max+1); $i++ ){ for ($i = 0; $i < ($max + 1); $i++) {
$out.="data.setValue(".($i).", 0, '".$data[$i]['username']."');\n"; $out .= "data.setValue(" . ($i) . ", 0, '" . $data[$i]['username'] . "');\n";
$out.="data.setValue(".($i).", 1,".$data[$i]['pages'].");\n"; $out .= "data.setValue(" . ($i) . ", 1," . $data[$i]['pages'] . ");\n";
} }
$others=0; $others = 0;
for ( $i=$max; $i<count($data); $i++ ) { for ($i = $max; $i < count($data); $i++) {
$others+=$data[$i]['pages']; $others += $data[$i]['pages'];
} }
$out.="data.setValue(".($max+1).", 0, 'Others');\ndata.setValue(".($max+1).",1, $others);\n"; $out .= "data.setValue(" . ($max + 1) . ", 0, 'Others');\ndata.setValue(" . ($max + 1) . ",1, $others);\n";
$out.="\t\tvar chart = new google.visualization.PieChart(document.getElementById('chart_div')); $out .= "\t\tvar chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {width: 500, height: 360, backgroundColor: 'none', is3D: true, title: 'Printer Usage'}); chart.draw(data, {width: 500, height: 360, backgroundColor: 'none', is3D: true, title: 'Printer Usage'});
} }
</script>"; </script>";
$out.="<div id=\"chart_div\" style=\"background: none;\"></div>"; $out .= "<div id=\"chart_div\" style=\"background: none;\"></div>";
$out.="<p>First Data - ".$date['first'][weekday].", ".$date['first'][mday]." ".$date['first'][month]." ".$date['first'][year].", at ".sprintf("%02d:%02d:%02d",$date['first'][hours],$date['first'][minutes],$date['first'][seconds])."<br />"; $out .= "<p>First Data - " . $date['first'][weekday] . ", " . $date['first'][mday] . " " . $date['first'][month] . " " . $date['first'][year] . ", at " . sprintf("%02d:%02d:%02d", $date['first'][hours], $date['first'][minutes], $date['first'][seconds]) . "<br />";
$out.="Last Data - ".$date['last'][weekday].", ".$date['last'][mday]." ".$date['last'][month]." ".$date['last'][year].", at ".sprintf("%02d:%02d:%02d",$date['last'][hours],$date['last'][minutes],$date['last'][seconds])."</p>"; $out .= "Last Data - " . $date['last'][weekday] . ", " . $date['last'][mday] . " " . $date['last'][month] . " " . $date['last'][year] . ", at " . sprintf("%02d:%02d:%02d", $date['last'][hours], $date['last'][minutes], $date['last'][seconds]) . "</p>";
//do some silly maths to work out lots of silly things //do some silly maths to work out lots of silly things
$paperarea = round(0.21*0.297*$total,3); //area of paper $paperarea = round(0.21 * 0.297 * $total, 3); //area of paper
$paperweight = round($paperarea*.08, 3); //how much that would weigh $paperweight = round($paperarea * .08, 3); //how much that would weigh
$numtrees = round($paperweight/730.296, 6); //*very* roughly how many trees that would be $numtrees = round($paperweight / 730.296, 6); //*very* roughly how many trees that would be
$cost = sprintf("£%01.2f",round(0.05*$total,2)); $cost = sprintf("£%01.2f", round(0.05 * $total, 2));
$out.="<p>That's ".$paperarea."m<sup>2</sup> of paper, weighing ".$paperweight."kg!<br>\n"; $out .= "<p>That's " . $paperarea . "m<sup>2</sup> of paper, weighing " . $paperweight . "kg!<br>\n";
$out.="This is equivalent to approximately ".$numtrees." trees.<br>\n"; $out .= "This is equivalent to approximately " . $numtrees . " trees.<br>\n";
$out.="That would have cost our members a grand total of ".$cost." if it were printed in the library.. not bad for £5 each!"; $out .= "That would have cost our members a grand total of " . $cost . " if it were printed in the library.. not bad for £5 each!";
//done //done
$out.="<p>Note: The number of pages is the number spooled and may be more than the actual number printed</p>"; $out .= "<p>Note: The number of pages is the number spooled and may be more than the actual number printed</p>";
$out.=$table; $out .= $table;
$sucsDB->Close(); $sucsDB->Close();
$smarty->assign('body',$out); $smarty->assign('body', $out);
?> ?>
...@@ -4,39 +4,39 @@ $dirlist = scandir("/var/projects/trac"); ...@@ -4,39 +4,39 @@ $dirlist = scandir("/var/projects/trac");
$projects = array(); $projects = array();
foreach ($dirlist as $file) { foreach ($dirlist as $file) {
if ($file[0]!=".") { if ($file[0] != ".") {
$object=array(); $object = array();
$object['filename'] = $file; $object['filename'] = $file;
$ini_array = array(); $ini_array = array();
$filepath = "/var/projects/trac/".$file."/conf/trac.ini"; $filepath = "/var/projects/trac/" . $file . "/conf/trac.ini";
// read trac.ini for this project // read trac.ini for this project
if (is_readable($filepath) && ($ini_data = file($filepath)) != FALSE) { if (is_readable($filepath) && ($ini_data = file($filepath)) != FALSE) {
$projectsection = FALSE; $projectsection = FALSE;
foreach ($ini_data as $ini_line) { foreach ($ini_data as $ini_line) {
if (trim($ini_line) == "[project]") { if (trim($ini_line) == "[project]") {
$projectsection = TRUE; $projectsection = TRUE;
} else if ($projectsection && (1 == preg_match("/^\[.*\]$/", trim($ini_line)))) { } else if ($projectsection && (1 == preg_match("/^\[.*\]$/", trim($ini_line)))) {
$projectsection = FALSE; $projectsection = FALSE;
} else if ($projectsection) { } else if ($projectsection) {
list($key, $value) = preg_split("/=/", $ini_line); list($key, $value) = preg_split("/=/", $ini_line);
$ini_array[trim($key)] = trim($value); $ini_array[trim($key)] = trim($value);
} }
} }
// only list projects whose trac.ini sets public = true // only list projects whose trac.ini sets public = true
if (isset($ini_array['public']) && ($ini_array['public'] == "true")) { if (isset($ini_array['public']) && ($ini_array['public'] == "true")) {
$object['name'] = $ini_array['name']; $object['name'] = $ini_array['name'];
if ($object['name']=="") $object['name'] = $file; if ($object['name'] == "") $object['name'] = $file;
$object['descr'] = $ini_array['descr']; $object['descr'] = $ini_array['descr'];
$projects[$file]=$object; $projects[$file] = $object;
} }
} }
} }
} }
$smarty->assign("projects", $projects); $smarty->assign("projects", $projects);
......
<?php <?php
// Config options // Config options
$permission="sucsstaff"; $permission = "sucsstaff";
// TODO: DEV: UNSTICK THIS BEFORE DEPLOY // TODO: DEV: UNSTICK THIS BEFORE DEPLOY
if (isset($session->groups[$permission])) { if (isset($session->groups[$permission])) {
$smarty->assign("staff",TRUE); $smarty->assign("staff", TRUE);
//get unused signup slips
$query = "SELECT signup.id, signup.sid, member_type.typename, members.username, signup.card";
$query .= " FROM signup LEFT JOIN member_type ON signup.type = member_type.id LEFT JOIN members ON signup.issuedby=members.uid";
$query .= " WHERE";
$query .= " signup.activated is NULL";
$query .= " or signup.username is NULL";
$query .= " ORDER BY signup.id";
$query .= ";";
$data = $sucsDB->GetAll($query);
// process responces
if(isset($_POST['command'])){
if($_POST['command']=='update'){
$changed = 0;
$upquery = "UPDATE signup";
$upquery .= " SET sid = ?";
$upquery .= " WHERE id = ?";
$upquery .= ";";
foreach($data as $value){
if(array_key_exists('sid:'.$value['id'],$_POST) && $_POST['sid:'.$value['id']]!=$value['sid']){
$uparray = array($_POST['sid:'.$value['id']],$value['id']);
$sucsDB->query($upquery,$uparray);
$changed++;
}
}
message_flash($changed." record(s) updated");
//get unused signup slips
$query = "SELECT signup.id, signup.sid, member_type.typename, members.username, signup.card";
$query .= " FROM signup LEFT JOIN member_type ON signup.type = member_type.id LEFT JOIN members ON signup.issuedby=members.uid";
$query .= " WHERE";
$query .= " signup.activated is NULL";
$query .= " or signup.username is NULL";
$query .= " ORDER BY signup.id";
$query .= ";";
$data = $sucsDB->GetAll($query);
// process responces
if (isset($_POST['command'])) {
if ($_POST['command'] == 'update') {
$changed = 0;
$upquery = "UPDATE signup";
$upquery .= " SET sid = ?";
$upquery .= " WHERE id = ?";
$upquery .= ";";
foreach ($data as $value) {
if (array_key_exists('sid:' . $value['id'], $_POST) && $_POST['sid:' . $value['id']] != $value['sid']) {
$uparray = array($_POST['sid:' . $value['id']], $value['id']);
$sucsDB->query($upquery, $uparray);
$changed++;
} }
} }
$data = $sucsDB->GetAll($query); message_flash($changed . " record(s) updated");
//set smarty stuff
$smarty->assign("signups",$data); }
$smarty->assign("self",$baseurl.$path.$getout); }
$data = $sucsDB->GetAll($query);
//set smarty stuff
$smarty->assign("signups", $data);
$smarty->assign("self", $baseurl . $path . $getout);
} }
$body = $smarty->fetch("signup-admin.tpl"); $body = $smarty->fetch("signup-admin.tpl");
$smarty->assign('title', "Signup Slip Admin"); $smarty->assign('title', "Signup Slip Admin");
......
This diff is collapsed.
This diff is collapsed.
...@@ -10,24 +10,24 @@ $conn = ldap_connect(_LDAP_SERVER); ...@@ -10,24 +10,24 @@ $conn = ldap_connect(_LDAP_SERVER);
$search = ldap_search($conn, _BASE_DN, 'uid=*', array('uid', 'cn', 'homedirectory')); $search = ldap_search($conn, _BASE_DN, 'uid=*', array('uid', 'cn', 'homedirectory'));
// Sort By Username // Sort By Username
ldap_sort($conn, $search, 'uid'); ldap_sort($conn, $search, 'uid');
// Produce an array of usernames // Produce an array of usernames
$usernames = array(); $usernames = array();
$entryHandler = ldap_first_entry($conn, $search); $entryHandler = ldap_first_entry($conn, $search);
while($entryHandler) { while ($entryHandler) {
$username = ldap_get_values($conn, $entryHandler, 'uid'); $username = ldap_get_values($conn, $entryHandler, 'uid');
$fullname = ldap_get_values($conn, $entryHandler, 'cn'); $fullname = ldap_get_values($conn, $entryHandler, 'cn');
$homedir = ldap_get_values($conn, $entryHandler, 'homedirectory'); $homedir = ldap_get_values($conn, $entryHandler, 'homedirectory');
$homedir = $homedir[0]; $homedir = $homedir[0];
$homedirArray = explode('/', $homedir); $homedirArray = explode('/', $homedir);
if (($homedirArray[2]=="society") && file_exists( "$homedir/public_html")) { if (($homedirArray[2] == "society") && file_exists("$homedir/public_html")) {
$usernames[] = array( "username" => $username[0], "fullname" => $fullname[0]); $usernames[] = array("username" => $username[0], "fullname" => $fullname[0]);
} }
$entryHandler = ldap_next_entry($conn, $entryHandler); $entryHandler = ldap_next_entry($conn, $entryHandler);
} }
$smarty->assign("societies", $usernames); $smarty->assign("societies", $usernames);
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.