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 8100 additions and 11626 deletions
......@@ -4,10 +4,14 @@
// Requires $who variable to be initialised before including
if (!isset($who)) {
echo "Error: I don't know who to award bananas to";
$who = "nobody";
echo "Error: I don't know who to award bananas to";
$who = "nobody";
}
// Adding variable to limit maximum bananas awarded at once?
$maxbanana = 3;
// what permission does a user need to be able to award bananas?
$permission = "bananas";
......@@ -16,35 +20,47 @@ $contact = "bananas@sucs.org";
// banana admin bits
if (isset($session->groups[$permission])) {
$smarty->assign("banana_admin", TRUE);
if ($_REQUEST['action'] == "award") {
if (trim ($_POST['why']) !== "") {
$number = intval($_POST['number']);
$why = $_POST['why'];
$DB->Query("INSERT INTO awards (username, score, whn, who, why) VALUES (?,?,NOW(),?,?)", array($who, $number, $session->username, $why));
header("Location: " . $_SERVER['PHP_SELF']);
} else {
trigger_error("No reason entered for the awarding of bananas.", E_USER_WARNING);
}
}
$smarty->assign("banana_admin", TRUE);
if ($_REQUEST['action'] == "award") {
if (trim($_REQUEST['why']) !== "") {
$number = intval($_REQUEST['number']);
$why = $_REQUEST['why'];
if ((abs($number) <= $maxbanana) && $number) {
$DB->Query("INSERT INTO awards (username, score, whn, who, why) VALUES (?,?,NOW(),?,?)", array($who, $number, $session->username, $why));
header("Location: " . $_SERVER['PHP_SELF']);
} // Checks for a nonzero banana and denies awarding if it's zero
elseif ($number == 0) {
trigger_error("Come on " . $session->username . ", enter a nonzero value please");
} else {
trigger_error("Nice try " . $session->username . "! You've submitted a request with too many bananas");
}
} else {
trigger_error("No reason entered for the awarding of bananas.", E_USER_WARNING);
}
}
} elseif ($session->loggedin) {
if ($_REQUEST['action'] == "award") {
$number = intval($_POST['number']);
$why = $_POST['why'];
if ($_REQUEST['action'] == "award") {
$number = intval($_REQUEST['number']);
$why = $_REQUEST['why'];
// Send a mail to someone about them bananas
$msgbody = $session->username." thinks $who deserves $number bananas:\r\n";
$msgbody .= "\"$why\"\r\n\r\nVisit https://sucs.org/Community/Members/$who if you want to make an award.";
mail($contact, "Banana Award Nomination", $msgbody, $msgheaders);
$smarty->assign("awarded", TRUE);
// Send a mail to someone about them bananas
$msgbody = $session->username . " thinks $who deserves $number bananas:\r\n";
//Make sure we send out the right link depending on whether they are a member or not
$msgbody .= "\"$why\"\r\n\r\nVisit https://sucs.org/Community/" . ($isnonmember ? 'Bananas' : 'Members') . "/$who if you want to make an award.";
mail($contact, "Banana Award Nomination", $msgbody, $msgheaders);
$smarty->assign("awarded", TRUE);
}
}
}
$secondary = $smarty->get_template_vars("secondary");
$secondary = $smarty->getTemplateVars("secondary");
$secondary .= $smarty->fetch('banana-award.tpl');
$smarty->assign('secondary', $secondary);
......
<?php
/*
* blogs class - provides functions for blogs
*/
// Some useful validation functions
require_once("validation.lib.php");
// random other functions that aren't validation or db related
require_once("miscfunctions.lib.php");
//stuff from blog.lib will be useful
require_once("blog.lib.php");
//Our Blogs Class
class admin {
//Blog ID
var $id;
//Blogger's Details
var $userName;
var $realName;
//Errors
var $error;
//Date formats
var $shortDateFormat;
var $longDateFormat;
//Paths
var $httpPath;
var $adminPath;
var $blogPath;
var $basePath;
//[temporary] holder for instance of blog class
var $blog;
//Constructor - checks we've been given a valid username, and pulls in generic blog info
function admin()
{
global $session, $BlogDB, $baseurl;
//set the error string first, so we dont wipe out any errors
$this->error = '';
//set the locale
setlocale(LC_ALL, 'en_GB');
//pull in the session stuff
$this->startSession();
//setup our environment
$this->userName = $session->username;
$this->realName = $session->fullname;
$this->id = $BlogDB->GetOne("select id from users where username='".$this->userName."'");
$this->shortDateFormat = "Y-m-d";
$this->longDateFormat = "r";
$this->httpPath = $baseurl."/Blogs/";
$this->adminPath = $this->httpPath."Admin/";
$this->basePath = $baseurl."/Blogs/";
if($this->httpPath[strlen($this->httpPath)-1]!="/") {
$this->httpPath .= "/";
}
//if we are logged in start a blog instance, and setup the blog path
if ($this->userName) {
$this->blog = new blogs($this->userName);
$this->blogPath = $this->basePath.$this->userName."/";
}
}
//start / check our session
function startSession()
{
//set the session time out in seconds
$maxSessionAge = 10800; //1 hour
//setup the session stuff
session_name("BlogSession");
session_set_cookie_params($maxSessionAge,dirname($_SERVER['SCRIPT_NAME'])."/");
session_start();
//if we dont have a session, start one
if (!$_SESSION[time]) {
$_SESSION[time] = time();
}
//close the session if its too old
elseif ((time()-$_SESSION[time]) > $maxSessionAge) {
session_unset();
$this->error =_("Session Expired");
$this->startSession();
}
//else we are happy, and we just update the session time
else {
$_SESSION[oldTime] = $_SESSION[time];
$_SESSION[time] = time();
}
}
//logs people in
function login()
{
global $BlogDB, $smarty;
$username = "";
$password = "";
//sanitise username
if (isset($_POST['username']) && trim($_POST['username']) != "" && safeuname(trim($_POST['username']))) {
$username = trim($_POST['username']);
}
else {
$this->error = _("Please check the username field");
}
//sanitise password
if (isset($_POST['password']) && trim($_POST['password']) != "") {
$password = trim($_POST['password']);
}
else {
$this->error = _("Please check the password field");
}
//no errors?
if(!$this->error)
{
//try to pull in the users details
$sqlRow = $BlogDB->GetRow("SELECT id, name, password from users where enabled = true and username = '".$username."' limit 1;");
//check we returned a user
if (!$sqlRow) {
$this->error =_("Invalid Username or Password");
}
else {
//check the password the user gave us agaisnt the one in the database
if ($sqlRow['password']!=crypt($password, $sqlRow['password'])) {
$this->error =_("Invalid Username or Password");
}
else {
//if everything matches dump some persistant details into the session
$_SESSION['id'] = $sqlRow['id'];
$_SESSION['userName'] = $username;
$_SESSION['realName'] = $sqlRow['name'];
$this->id = $_SESSION['id'];
$this->userName = $_SESSION['userName'];
$this->realName = $_SESSION['realName'];
}
}
}
//return a state to indicate wether login was successful
if ($this->error) {
return false;
}
else {
return true;
}
}
//admin menu
function menu() {
global $BlogDB, $smarty, $session;
$submenu = array();
if (blogger($session->username)) {
$submenu[_("My blog")] = $this->blogPath;
$submenu[_("Write new entry")] = $this->adminPath."newentry";
$submenu[_("Edit entries")] = $this->adminPath."showentries";
$submenu[_("Settings")] = $this->adminPath."Settings";
$comments = _("Comments");
$result = $BlogDB->GetOne("SELECT count(comments.id) from comments join entries on comments.post = entries.id where moderated = false and entries.user_id = ".$this->id.";");
if($result){
$comments .= " (".$result.")";
}
$submenu[$comments] = $this->adminPath."moderatecomments";
} else {
$submenu[_("Start a Blog")] = $this->adminPath."signup";
}
$menu = $smarty->get_template_vars("menu");
$menu[Blogs] = $submenu;
$smarty->assign("menu", $menu);
}
//destroys the session
function logout ()
{
session_unset();
header("Location: ".$this->blogPath);
}
//prints a login form
function printLoginForm()
{
echo "The Login Form display function has been called. This should not happen.";
}
// post an entry to the db
function postEntry()
{
global $BlogDB;
$category = '';
$subject = '';
$body = '';
//sanitise category (make sure it IS a number!)
if (isset($_POST['category']) && (int)$_POST['category'] != "" && (int)$_POST['category'] != 0) {
$category = (int)$_POST['category'];
} else {
$this->error = _("Undefined Category!");
}
//sanitise subject
if (isset($_POST['subject']) && trim($_POST['subject']) != "") {
//complain if the subject contains html or html like things rather than dumping it without warning
if (strip_tags($_POST['subject']) != $_POST['subject']) {
$this->error = _("HTML is not allowed in the subject!");
}
else {
$subject = addslashes(trim($_POST['subject']));
}
} else {
$this->error = _("No entry subject!");
}
//sanitise body
if (isset($_POST['body']) && trim($_POST['body']) != "") {
$body = trim($_POST['body']);
//we dont want to use nl2br if peeps are useing tinymce
if (!$this->blog->editor) {
$body = nl2br($body);
}
$body = addslashes($body);
} else {
$this->error = _("No entry body!");
}
//no errors, so continue..
if (!$this->error) {
//first we make our short subject
$shortsubject = $this->blog->makeCleanString($subject,true);
//need to check if there are any short titles like this one already
$sql = $BlogDB->GetAll("SELECT shortsubject FROM entries WHERE user_id = {$this->id} AND shortsubject ~ '{$shortsubject}(_[0-9]{1,3}$|$)' ORDER BY char_length(shortsubject) DESC, shortsubject DESC LIMIT 1;");
//if so we grab the last one, and add 1 to it..
if (count($sql) != 0) {
$sqlRow = array_shift($sql);
// Put the matched _number into $matches[0] if there is one
if (preg_match("/\_[0-9]{1,3}$/",$sqlRow['shortsubject'],$matches)) {
// Remove the _ to get the number, add 1 and append
$shortsubject .= '_' . ((int)substr($matches[0],1) + 1);
} else {
$shortsubject .= '_1';
}
}
//shortsubject is now safe..
//insert our new entry
$sql = $BlogDB->Execute("INSERT INTO entries (category, subject, body, user_id, shortsubject) VALUES ({$category},'{$subject}','{$body}','{$this->id}','{$shortsubject}')");
if (!$sql) {
error(2,_("Database commit failed")." - ".$BlogDB->ErrorMsg());
}
else {
// $row = db_last($sql, "entries");
$row = $BlogDB->GetRow("SELECT * FROM entries WHERE user_id = {$this->id} AND shortsubject='".$shortsubject."'");
$this->blog->printEntry($row,false,false);
}
}
//re-display entry form if there are errors
else {
$this->printEntryForm($_POST,true);
}
}
//update an entry in the db
function updateEntry($shortSubject)
{
global $BlogDB;
$category = '';
$subject = '';
$body = '';
//sanitise and check for existance of a short subject
$shortSubject = $this->blog->makeCleanString($shortSubject);
if (!$shortSubject) {
error(4,_("If you dont give me a post how do you expect me to update it"));
}
//sanitise category (make sure it IS a number!)
if (isset($_POST['category']) && (int)$_POST['category'] != "" && (int)$_POST['category'] != 0) {
$category = (int)$_POST['category'];
} else {
$this->error = _("Undefined Category!");
}
//sanitise subject
if (isset($_POST['subject']) && trim($_POST['subject']) != "") {
//complain if the subject contains html or html like things rather than dumping it without warning
if (strip_tags($_POST['subject']) != $_POST['subject']) {
$this->error = _("HTML is not allowed in the subject!");
}
else {
$subject = addslashes(trim($_POST['subject']));
}
} else {
$this->error = _("No entry subject!");
}
//sanitise body
if (isset($_POST['body']) && trim($_POST['body']) != "") {
$body = trim($_POST['body']);
//we dont want to use nl2br if peeps are useing tinymce
if (!$this->blog->editor) {
$body = nl2br($body);
}
$body = addslashes($body);
} else {
$this->error = _("No entry body!");
}
//no errors, so continue..
if (!$this->error) {
//check to see this post exists
$sql = $BlogDB->GetRow("SELECT id from entries where shortsubject = '".$shortSubject."' AND user_id='".$this->id."';");
//yes?, we can update it then..
if ($sql) {
$sql = $BlogDB->Execute("UPDATE entries SET category = {$category}, subject = '{$subject}', body = '{$body}' WHERE shortsubject = '{$shortSubject}' AND user_id = '".$this->id."';");
if (!$sql) {
error(2,_("Database commit failed - ").$BlogDB->ErrorMsg());
}
else {
echo "<div class=\"updateinfo\">"._("Updated!")."</div>\n";
$this->updateForm($shortSubject);
}
}
//cant update non-existant entrys
else {
error(2,_("Cannot update entry, as it does not exist.".$BlogDB->ErrorMsg()));
}
}
//redisplay entry form if there are errors
else {
$this->updateForm($shortSubject);
}
}
//update form
function updateForm($shortSubject)
{
global $BlogDB;
//sanitise and check the short subject
$shortSubject = $this->blog->makeCleanString($shortSubject);
if (!$shortSubject) {
error(4,_("If you dont give me a post how do you expect me to decide which one you want to edit?"));
}
//try to grab the post
$row = $BlogDB->GetRow("SELECT subject, category, body, shortsubject from entries where shortsubject = '".$shortSubject."' AND user_id = '".$this->id."';");
//if it exists we can do stuff with it
if ($row) {
$this->printEntryForm($row,true,true);
}
//else give an error
else {
error(2, _("Could not find the requested entry."));
}
}
/* currently not used.. if we dont want to bring back the delete link in printEntry from blog.lib we can get rid of this entirely
//delete an entry
function deleteEntry($shortSubject)
{
//sanitise the short subject
$shortSubject = $this->blog->makeCleanString($shortSubject);
if (!$shortSubject) {
error(4,_("If you dont give me a post how do you expect me to delete it"));
}
//check to see this post exists
$sql = db_query("SELECT id from entries where shortsubject = '".$shortSubject."' AND user_id='".$this->id."';");
$sqlNum = db_num_rows($sql);
//yes?, we can delete it then..
if ($sqlNum == 1) {
db_query("DELETE FROM entries WHERE shortsubject = '{$shortSubject}' AND user_id = '".$this->id."';");
echo "<p>"._("Entry deleted.")."</p>";
}
//can't delete non-existant entries
else {
error(2,_("Cannot delete entry, as it does not exist.".db_error()));
}
}
*/
//update settings
function updateSettings()
{
global $BlogDB;
$name = '';
$title = '';
$description = '';
$css = 'blog.css';
$password = "";
//sanitise name
if (isset($_POST['name']) && trim($_POST['name']) != "") {
$name = addslashes(trim(strip_tags($_POST['name'])));
}
else {
$this->error = _("Bad Input - Realname");
}
//sanitise title
if (isset($_POST['btitle']) && trim($_POST['btitle']) != "") {
//complain if the title contains html or html like things rather than dumping it without warning
if (strip_tags($_POST['btitle']) != $_POST['btitle']) {
$this->error = _("HTML is not allowed in the title!");
}
else {
$title = addslashes(trim($_POST['btitle']));
}
}
else {
$this->error = _("Bad Input - Title");
}
//sanitise description
if (isset($_POST['description']) && trim($_POST['description']) != "") {
//complain if the description contains html or html like things rather than dumping it without warning
if (strip_tags($_POST['description']) != $_POST['description']) {
$this->error = _("HTML is not allowed in the description!");
}
else {
$description = addslashes(trim($_POST['description']));
}
}
else {
$this->error = _("Bad Input - Description");
}
//sanitise css
if (isset($_POST['css'])) { // if its not set its defaulted...
// It's no use checking if the css file exists in this version at present
// if (trim($_POST['css']) != "" && is_file($_POST['css'])) {
if (trim($_POST['css']) != "") {
$css = $_POST['css'];
}
else {
$this->error = _("Bad Input - CSS location");
}
}
//sanitise password and encrypt
if ($_POST['pass1']) {
if ((isset($_POST['pass1']) && trim($_POST['pass1']) != "") && ($_POST['pass1']==$_POST['pass2'])) {
$password = crypt($_POST['pass1']);
}
else {
$this->error = _("Bad Input - Password");
}
}
// checkbox for comment moderation, either is or isnt
if ($_POST['moderate'] != "") {
$moderate = "true";
}
else {
$moderate = "false";
}
// checkbox for editor, either is or isnt
if ($_POST['editor'] != "") {
$editor = "true";
}
else {
$editor = "false";
}
//if there are no errors
if (!$this->error) {
//construct the query
$query = "UPDATE USERS SET name='{$name}', title='{$title}', description='{$description}', css='{$css}', moderate={$moderate}, editor={$editor}";
//if the password is set add that too
if ($password) {
$query .= ", password='{$password}'";
}
$query .= " WHERE username='{$this->userName}';";
//execute query
if (!$BlogDB->Execute($query)) {
error(2,_("Database Insertion failed."));
}
//it it worked report sucsess
else {
echo "<div class=\"updateinfo\">"._("Blog settings updated.")."</div>\n";
}
}
//return the form, this also returns the errors if they exist
$this->printSettingsForm();
}
//print the blog Entry form...
//used for both new and edit
function printEntryForm($row='',$show=false,$edit=false)
{
global $BlogDB;
echo "<div class=\"entry\">\n";
if ($this->error) {
echo "<div class=\"errorinfo\">Error : " . $this->error . "</div>\n";
}
echo "<h2>".((!$edit) ?_("Write Entry") : _("Edit Entry"))."</h2>\n";
echo "<form action=\"".$this->adminPath.((!$edit) ? "postentry" : "postupdate/{$row['shortsubject']}")."\" method=\"post\" id=\"entryform\">\n";
echo "<div class=\"row\">\n";
echo "<label for=\"subject\">"._(Subject)."</label>\n";
echo "<span class=\"textinput\"><input type=\"text\" name=\"subject\" id=\"subject\" value=\"" . (($show) ? htmlentities(strip_tags(trim($row['subject']))) : "") . "\" style=\"width: 100%;\" maxlength=\"100\" tabindex=\"1\" /></span>\n";
echo "</div>\n";
echo "<div class=\"row\">\n";
echo "<label for=\"category\">"._("Category")."</label>\n";
echo "<span class=\"textinput\"><select name=\"category\" id=\"category\" tabindex=\"2\">";
//pull in the list of catogories from the database
$sql = $BlogDB->GetAll("SELECT id, name FROM categories ORDER BY name ASC;");
while ($sqlRow = array_shift($sql)) {
echo "<option value=\"{$sqlRow['id']}\"".(((int)$row['category'] == $sqlRow['id']) ? " selected=\"selected\"" : "").">{$sqlRow['name']}</option>\n";
}
echo "</select></span>\n";
echo "</div>\n";
echo "<div class=\"row\">\n";
echo "<label for=\"body\">Body</label>\n";
echo "<span class=\"textinput\"><textarea name=\"body\" id=\"body\" tabindex=\"3\" style=\"width: 100%; height: 30em;\">";
if ($show) {
//we dont want to use br2nl if peeps are using tinymce
if (!$this->blog->editor) {
echo "<![CDATA[".br2nl($row['body'])."]]>";
}
else {
echo htmlentities($row['body'], ENT_QUOTES, "UTF-8");
}
}
echo "</textarea></span>\n";
echo "</div>\n";
echo "<div class=\"row\">\n";
echo "<span class=\"textinput\"><input name=\"submit\" type=\"submit\" id=\"submit\" tabindex=\"4\" value=\"Submit Entry\" /></span>\n";
echo "</div>\n<div class=\"clear\"></div>\n";
echo "</form>\n";
echo "</div>\n";
}
//print the blog settings form...
function printSettingsForm()
{
global $BlogDB;
//pull in user's current settings from the database
$settings = $BlogDB->GetRow("SELECT name, title, description, css, moderate, editor FROM users WHERE username='" . $this->userName . "'");
echo "<div class=\"entry\">\n";
if ($this->error) {
echo "<div class=\"errorinfo\">Error : " . $this->error . "</div>\n";
}
echo "<h2>"._("Blog Settings")."</h2>\n";
echo "<form action=\"".$this->adminPath."Settings\" method=\"post\" id=\"settingsform\">\n";
echo "<div class=\"row\">\n";
echo "<label for=\"name\">"._("Real name")."</label>\n";
echo "<span class=\"textinput\"><input type=\"text\" name=\"name\" id=\"name\" value=\"" . $settings['name'] . "\" size=\"30\" maxlength=\"60\" tabindex=\"1\" /></span>\n";
echo "</div>\n";
echo "<div class=\"row\">\n";
echo "<label for=\"btitle\">"._("Title")."</label>\n";
echo "<span class=\"textinput\"><input type=\"text\" name=\"btitle\" id=\"btitle\" value=\"" . $settings['title'] . "\" size=\"30\" maxlength=\"60\" tabindex=\"2\" /></span>\n";
echo "</div>\n";
echo "<div class=\"row\">\n";
echo "<label for=\"description\">"._("Description")."</label>\n";
echo "<span class=\"textinput\"><input type=\"text\" name=\"description\" id=\"description\" value=\"" . $settings['description'] . "\" size=\"30\" maxlength=\"60\" tabindex=\"3\" /></span>\n";
echo "</div>\n";
echo "<div class=\"row\">\n";
echo "<label for=\"css\">"._("CSS")."</label>\n";
echo "<span class=\"textinput\"><input type=\"text\" name=\"css\" id=\"css\" value=\"" . $settings['css'] . "\" size=\"30\" maxlength=\"255\" tabindex=\"4\" /></span>\n";
echo "</div>\n";
echo "<div class=\"row\">\n";
echo "<label for=\"moderate\">"._("Moderate new comments")."</label>\n";
echo "<span class=\"textinput\"><input type=\"checkbox\" name=\"moderate\" id=\"moderate\" ".(($settings['moderate']=="t") ? "checked=\"checked\"" : "")." /></span>\n";
echo "</div>\n";
echo "<div class=\"row\">\n";
echo "<label for=\"editor\">"._("Enable HTML editor")."</label>\n";
echo "<span class=\"textinput\"><input type=\"checkbox\" name=\"editor\" id=\"editor\" ".(($settings['editor']=="t") ? "checked=\"checked\"" : "")." /></span>\n";
echo "</div>\n";
/* echo "<div class=\"row\">\n";
echo "<label for=\"pass1\">"._("Password")."</label>\n";
echo "<span class=\"textinput\"><input type=\"password\" name=\"pass1\" id=\"pass1\" value=\"\" size=\"15\" maxlength=\"16\" tabindex=\"5\" /></span>\n";
echo "</div>\n";
echo "<div class=\"row\">\n";
echo "<label for=\"pass2\">"._("Again")."</label>\n";
echo "<span class=\"textinput\"><input type=\"password\" name=\"pass2\" id=\"pass2\" value=\"\" size=\"15\" maxlength=\"16\" tabindex=\"6\" /></span>\n";
echo "</div>\n"; */
echo "<div class=\"row\">\n";
echo "<span class=\"textinput\"><input name=\"submit\" type=\"submit\" id=\"submit\" tabindex=\"4\" value=\"Save Settings\" /></span>\n";
echo "</div>\n";
echo "<div class=\"clear\"></div>\n";
echo "</form>\n";
echo "</div>\n";
}
//shows unmoderated comments
function printComments() {
global $BlogDB;
//grab all unmoderated comments
$result = $BlogDB->GetAll("SELECT comments.*, entries.shortsubject from comments join entries on comments.post = entries.id where moderated = false and entries.user_id = ".$this->id." ORDER BY entries.subject ASC;");
if(count($result)==0) {
return;
}
echo "<div class=\"entry\">\n";
echo "<h2>Comments Pending Approval</h2>\n";
echo "<p>The comments in red are probably spam. They are premarked to be deleted for your convience.</p>\n";
echo "<form action=\"{$this->adminPath}updatecomments/\" method=\"post\">\n";
echo "<table class=\"td\">\n";
$post = '';
$count = 0;
//for each comment
while($r = array_shift($result)) {
//if the post has changed
if ($post != $r['shortsubject']) {
//grab the post, display it and the subject then some headers
$internalR = $BlogDB->GetRow("SELECT subject, body from entries where shortsubject = '".$r['shortsubject']."' and user_id = ".$this->id." limit 1;");
echo "\t<tr>\n";
echo "\t\t<th colspan=\"4\"><a href=\"{$this->blogPath}entry/{$r['shortsubject']}\">". htmlentities($internalR['subject']) ."</a></th>\n";
echo "\t</tr>\n";
echo "\t<tr>\n";
echo "\t\t<td colspan=\"4\">{$internalR['body']}</td>\n";
echo "\t</tr>\n";
echo "\t<tr>\n";
echo "\t\t<th>Author</th>\n";
echo "\t\t<th>Body</th>\n";
echo "\t\t<th>Approve</th>\n";
echo "\t\t<th>Delete</th>\n";
echo "\t</tr>\n";
$post = $r['shortsubject'];
}
//how display each of the comments
if ($r['spam'] == 't') {
echo "\t<tr class=\"errorinfo\">\n";
} else {
echo "\t<tr>\n";
}
echo "\t\t<td><a href=\"mailto:{$r['email']}\" title=\"IP: {$r['host']}\">{$r['name']}</a></td>\n";
echo "\t\t<td>{$r['body']}</td>\n";
echo "\t\t<td><input type=\"radio\" name=\"group[$count]\" value=\"a:{$r['id']}\" /></td>\n";
if ($r['spam'] == 't') {
echo "\t\t<td><input type=\"radio\" name=\"group[".$count++."]\" value=\"d:{$r['id']}\" checked=\"checked\"/></td>\n";
} else {
echo "\t\t<td><input type=\"radio\" name=\"group[".$count++."]\" value=\"d:{$r['id']}\" /></td>\n";
}
echo "\t</tr>\n";
}
echo "\t<tr>\n\t\t<td></td>\n\t\t<td></td>\n\t\t<td></td>\n\t\t<td colspan=\"2\"><input type=\"submit\" value=\"Commit\" name=\"submit\" /></td>\n\t</tr>\n";
echo "</table>\n";
echo "</form>\n";
echo "</div>\n";
}
// approve or delete comments
function updateComments() {
global $BlogDB;
if (count($_POST['group'])==0) {
error(2, _("No comments selected for approval/deletion."));
return;
}
$check = "";
$approved = "";
$acount = 0;
$deleted = "";
$dcount = 0;
//get the comment numbers and requested actions.
foreach($_POST['group'] as $comment) {
$c = explode(":", $comment);
if ($c[0] == "a") {
$approved .= (int)$c[1].", ";
$acount++;
} elseif ($c[0] == "d") {
$deleted .= (int)$c[1].", ";
$dcount++;
} else {
error(1, _("Malformed input."));
return;
}
}
$approved = substr($approved, 0, -2);
$deleted = substr($deleted, 0, -2);
//construct a list of comments to check
if ($approved and $deleted) {
$check = $deleted.", ".$approved;
} else {
$check = $deleted.$approved;
}
//check the comments exist and blong to the user
$result = $BlogDB->GetRow("SELECT count(comments.id) from comments join entries on comments.post = entries.id where entries.user_id = ".$this->id." and comments.id IN($check);");
if($result[count] != ($acount + $dcount)) {
error(1,_("Cant find the requested comments, maybe they have already been deleted."));
return;
}
//delete comments
if($deleted!="") {
$BlogDB->Execute("DELETE FROM comments WHERE id IN ($deleted);");
}
//set moderated flag on comments
if($approved!="") {
$BlogDB->Execute("UPDATE comments SET moderated=true WHERE id IN ($approved);");
}
//reprint the form
echo "<div class=\"updateinfo\">$acount "._("comments approved").", $dcount "._("comments deleted").".</div>\n";
$this->printComments();
$this->printAuthorisedUsers();
}
//Delete moderated comments from (a single post)
function deleteComments($entry) {
global $BlogDB;
if(isset($_POST['submit'])) {
if(count($_POST['comment'])==0){
error(5, _("No comments selected for deletion."));
echo "<a href=\"{$this->blogPath}entry/$entry\">"._("Return to blog entry")."</a>\n";
} else {
$del = "(";
foreach($_POST['comment'] as $c) {
$del .= "comments.id = ".(int)$c." OR ";
}
$del = substr($del, 0, -4).")";
//check the comments exist and blong to the user
$result = $BlogDB->GetOne("SELECT count(comments.id) from comments join entries on comments.post = entries.id where entries.user_id = ".$this->id." and $del;");
if($result[0] != count($_POST['comment'])) {
error(1,_("Cant find the requested comments, maybe they have already been deleted."));
return;
}
//delete the comments
$sql = "DELETE FROM comments WHERE $del";
if(!$BlogDB->Execute($sql)) {
error(2, _("Database commit error."));
} else {
echo "<div class=\"updateinfo\">".count($_POST['comment'])._(" comment(s) deleted.")."</div>\n";
echo "<a href=\"{$this->blogPath}entry/$entry\">"._("Return to blog entry")."</a>\n";
}
}
}
}
//prints a form populated with email addresses that can avoid moderation on comments
function printAuthorisedUsers() {
global $BlogDB;
echo "<div class=\"entry\">\n";
echo "<a name=\"emails\"></a>\n";
echo "<h2>"._("Known Users")."</h2>\n";
//if comment moderation is off tell the user its a bit daft
if(!$this->blog->comment_moderation) {
echo "<p>"._("Comment moderation is turned off on your blog - anyone can post comments. To turn comment moderation on, visit the")." <a href=\"".$this->adminPath."Settings\">"._("settings page")."</a>.</p>\n";
echo "</div>";
return;
}
echo "<p>"._("Comments posted to your blog with an e-mail address that appears in the list below avoid the moderation queue and appear on your blog immediately.")."</p>\n";
echo "<p>"._("To turn off comment moderation, visit the")." <a href=\"{$this->adminPath}Settings\">"._("settings page")."</a>.</p>\n";
echo "<form name=\"emailform\" id=\"emailform\" action=\"".$this->adminPath."updateauthusers\" method=\"post\">\n";
echo "<select multiple=\"multiple\" name=\"emaillist[]\" size=\"10\">\n";
$result = $BlogDB->GetAll("SELECT name,email FROM authorised_emails WHERE user_id=".$this->id." ORDER BY email ASC");
while($r = array_shift($result)) {
echo "\t<option value=\"{$r['email']}\">{$r['email']} ({$r['name']})</option>\n";
}
echo "</select><br />\n";
echo "<input type=\"submit\" name=\"delete\" value=\"Delete selected\" />\n";
echo "</form>\n";
//close and start a new form, so pressing enter in the 2nd bit of the form submits with addnew rather than delete
echo "<form name=\"emailform\" id=\"emailform\" action=\"".$this->adminPath."updateauthusers\" method=\"post\">\n";
echo "<h3>"._("Add Address")."</h3>\n";
echo "<div class=\"row\">\n";
echo "<label for=\"name\"> "._("Name (not displayed anywhere but here)")."</label>\n";
echo "<span class=\"textinput\"><input type=\"text\" name=\"name\" id=\"name\" /></span>\n";
echo "</div>\n";
echo "<div class=\"row\">\n";
echo "<label for=\"email\"> "._("E-mail address")."</label>\n";
echo "<span class=\"textinput\"><input type=\"text\" name=\"email\" id=\"email\" /></span>\n";
echo "</div>\n";
echo "<div class=\"row\">\n";
echo "<span class=\"textinput\"><input type=\"submit\" name=\"addnew\" value=\"Add address\" /></span>\n";
echo "</div>\n<div class=\"clear\"></div>\n";
echo "</form>\n";
echo "</div>\n";
}
//udates the list of authorised users.
function updateAuthorisedUsers($quiet=FALSE) {
global $BlogDB;
//hack so we get error returned from validEmail
global $error;
//if we have a delete action
if(isset($_POST['delete'])) {
if (count($_POST['emaillist'])==0) {
error(5,_("No addresses selected for deletion."));
} else {
$del = "(";
foreach($_POST['emaillist'] as $addr) {
if(validEmail($addr)) {
$del .= "email='$addr' OR ";
} else {
error(2,_("Invalid email address : ".$error));
return;
}
}
$del = substr($del, 0, -4).")";
$sql = "DELETE FROM authorised_emails WHERE $del AND user_id={$this->id}";
$ret = $BlogDB->Execute($sql);
if(!$ret) {
error(2, _("Database commit error: ").$BlogDB->ErrorMsg());
} else {
echo "<div class=\"updateinfo\">"._("Address(es) deleted")."</div>\n";
}
}
}
//if we have an add action
elseif(isset($_POST['addnew'])) {
if(trim($_POST['name'])=="" or !eregi("^([a-z0-9]+([:space:][a-z0-9]*))$",trim($_POST['name']))) {
$this->error = _("Check name");
}
if(!validEmail($_POST['email'])) {
$this->error = _("Invalid e-mail address : ".$error);
}
if($this->error==""){
$name = addslashes(trim($_POST['name']));
$email = addslashes(trim($_POST['email']));
$ret = $BlogDB->Execute("INSERT INTO authorised_emails (user_id, name, email) VALUES ('{$this->id}', '{$name}', '{$email}');");
if(!$ret){
error(2, $BlogDB->ErrorMsg());
} else {
echo "<div class=\"updateinfo\">"._("Address added")."</div>\n";
}
}
else {
error(3,$this->error);
}
}
if(!$quiet){
$this->printComments();
$this->printAuthorisedUsers();
}
}
//prints a list of entries for the admin front page.
function printEntries($amount=0, $title=TRUE) {
global $BlogDB;
$limit = ($amount > 0) ? " LIMIT $amount" : "";
$result = $BlogDB->GetAll("SELECT shortsubject,timestamp,subject FROM entries WHERE user_id = '".$this->id."' ORDER BY timestamp DESC $limit;");
if(count($result)==0){
error(5, _("No entries found."));
} else {
if($title){
echo "<div class=\"entry\"><h2>"._("Edit Entries")."</h2>\n";
}
echo "<form action=\"{$this->adminPath}confirmdeleteentries/\" method=\"post\">\n<table class=\"td\">\n\t<tr>\n\t\t<th width=\"38%\">Date</th>\n\t\t<th>Title</th>\n\t\t<th width=\"5%\">Delete</th>\n\t</tr>\n";
$rownum = 0;
while($row = array_shift($result)){
echo "\t<tr>\n";
echo "\t\t<td>".strftime($this->blog->longDateFormat, strtotime($row['timestamp']))."</td>\n";
echo "\t\t<td><a href=\"".$this->adminPath."update/".$row['shortsubject']."\">".htmlentities($row['subject'])."</a></td>\n";
echo "\t\t<td><input type=\"checkbox\" name=\"entry[".$rownum++."]\" value=\"{$row['shortsubject']}\" /></td>\n";
echo "\t</tr>\n";
}
echo "\t<tr>\n";
echo "\t\t<td colspan=\"3\" align=\"right\"><input type=\"submit\" name=\"submit\" value=\""._("Delete Selected")."\" /></td>\n";
echo "\t</tr>\n";
echo "</table>\n";
echo "</form>\n";
if($title) {
echo "</div>\n";
}
}
}
//confirm entry deletion
function confirmDeleteEntries() {
echo "<form action=\"{$this->adminPath}deleteentries/\" method=\"post\">\n";
echo "<p>"._("Are you sure you want to delete the following entries?")."</p>\n<ul>\n";
$rownum = 0;
foreach ($_REQUEST[entry] as $entry) {
$entry = $this->blog->makeCleanString($entry);
echo "<input type=\"hidden\" name=\"entry[".$rownum++."]\" value=\"{$entry}\" />";
echo "<li>".$entry."</li>\n";
}
echo "</ul>\n";
echo "<p><input type=\"submit\" name=\"submit\" value=\""._("Yes")."\" />\n<input type=\"submit\" name=\"submit\" value=\""._("No")."\" /></p>\n";
echo "</form>\n";
}
//deletes entries
function deleteEntries() {
global $BlogDB;
if (count($_POST['entry'])==0) {
error(4, _("No entries marked for deletion."));
} else {
if ($_REQUEST[submit]==_("Yes")) {
$sql = "DELETE FROM entries WHERE (";
foreach($_POST['entry'] as $id) {
$sql .= "shortsubject = '".$this->blog->makeCleanString($id)."' OR ";
}
$sql = substr($sql, 0, -4);
$sql .= ") AND user_id = {$this->id};";
$BlogDB->Execute($sql);
echo $BlogDB->Affected_Rows()._(" post(s) deleted");
} else {
error(4, _("Entries not deleted."));
}
}
}
//constructs the main page
function mainPage() {
//Should display blog entries here
echo "<div class=\"entry\">\n";
echo "<h2>"._("Blog Management")."</h2>\n";
echo "<div class=\"td\">\n";
echo "<p>"._("Use the links on the left to manage your blog, or choose a recent entry to edit:")."</p>\n";
$this->printEntries(5, FALSE);
echo "<a href=\"".$this->adminPath."showentries\">show all entries...</a></div>\n";
echo "</div>\n";
}
//adds a user
function addUser() {
global $BlogDB, $session;
$username = '';
$password = makePassword();
$name = '';
$title = '';
$description = '';
//sanitise username
if (trim($session->username) != "") {
if (safeuname($session->username)) {
$username = $session->username;
} else {
$this->error = _("Invalid Username Provided");
}
} else {
$this->error = _("No Username Provided");
}
//sanitise name, perhaps a bit too strict?
if (trim($session->fullname)) {
// if (eregi("^([a-z]+([:space:][a-z]*))$",trim($session->fullname))) {
// Not working, so changed to something that does work
if (isset($session->fullname)) {
$name = trim($session->fullname);
}
else {
$this->error = _("Invalid Name Provided");
}
} else {
$this->error = _("No Real Name Provided");
}
//sanitise title, regexp? ^([a-z0-9]+([:space:][a-z0-9]*))$ as a base form and '\', '-', '.', ',', ':', ';', '?', '!'
if (isset($_POST['btitle']) && trim($_POST['btitle']) != "") {
$title = addslashes(trim(strip_tags($_POST['btitle'])));
} else {
$this->error = _("No Title Provided");
}
//sanitise description, same check as title gets
if (isset($_POST['description']) && trim($_POST['description']) != "") {
$description = addslashes(trim(strip_tags($_POST['description'])));
} else {
$this->error = _("No Description Provided");
}
//check the user doesn't already exist
$sql = $BlogDB->GetAll("SELECT username from users where username = '".$username."';");
if (count($sql) != 0) {
$this->error = _("Username already in use!");
}
//check there is a system user with this name (ie if they are a sucs member)
if(!posix_getpwnam($username)) {
$this->error = _("You need to be a SUCS member to sign up for a blog here!");
} else {
//check the user is a member of the users, staff or societies groups
$posixInfo = posix_getpwnam($username);
if ($posixInfo[gid] != 100 && $posixInfo[gid] != 106 && $posixInfo[gid] != 113) {
$this->error = _("Err, no, you're not really a system user now are you?");
}
}
//if we dont have any errors
if (!$this->error) {
//encrypt the password
$cryptPassword = crypt($password);
//add to the database
$sql = ("INSERT into USERS (username,password,name,title,description) VALUES ('{$username}','{$cryptPassword}','{$name}','{$title}','{$description}');");
//error if that failed
if (!$BlogDB->Execute($sql)) {
error(2,_("Database Insertion failed - ").$BlogDB->ErrorMsg());
} else {
//else mail the password to the user and report sucsess
mail(
"{$username}@sucs.org",
_("Blog Password"),
_("Welcome to SUCS Blogs")."\n\n"._("The multi-user web log system created by SUCS members for SUCS members.")."\n\n"._("You Blog Password is : ").$password."\n"._("Please login and change it at ")."http://".$_SERVER["SERVER_NAME"].$this->adminPath,
"From: \"Blog Admin\" <blogadmin@sucs.org>"
);
echo _("Account Added!<br />Your password has been sent to your SUCS email account");
//bodge it so the username is filled in
$session->username = $username;
}
} else {
//return to the form
$this->addUserForm();
}
}
//this should take all the input and post it to addUser, passing in the current user and stuff... i think...
function addUserForm() {
global $session;
echo "<div class=\"entry\">\n";
if ($this->error != "") {
echo "<div class=\"errorinfo\">"._("Error")." : " . $this->error . "</div>\n";
}
echo "<h2>"._("Register for a Blog")."</h2>\n";
echo "<div class=\"td\">\n";
echo "<form action=\"".$this->adminPath."adduser\" method=\"post\" id=\"adduserform\">\n";
echo "<div class=\"row\">\n";
echo "<label for=\"username\">"._("Username")."</label>\n";
// echo "<span class=\"textinput\"><input type=\"text\" name=\"username\" id=\"username\" value=\"" . (($this->error != "") ? strip_tags(trim($_POST['username'])) : "") . "\" size=\"30\" maxlength=\"60\" tabindex=\"1\" /></span>\n";
echo "<span class=\"textinput\">{$session->username}</span>\n";
echo "</div>\n";
echo "<div class=\"row\">\n";
echo "<label for=\"name\">"._("Real name")."</label>\n";
// echo "<span class=\"textinput\"><input type=\"text\" name=\"name\" id=\"name\" value=\"" . (($this->error != "") ? strip_tags(trim($_POST['name'])) : "") . "\" size=\"30\" maxlength=\"60\" tabindex=\"2\" /></span>\n";
echo "<span class=\"textinput\">{$session->fullname}</span>\n";
echo "</div>\n";
echo "<div class=\"row\">\n";
echo "<label for=\"btitle\">"._("Title")."</label>\n";
echo "<span class=\"textinput\"><input type=\"text\" name=\"btitle\" id=\"btitle\" value=\"" . (($this->error != "") ? strip_tags(trim($_POST['btitle'])) : "") . "\" size=\"30\" maxlength=\"60\" tabindex=\"3\" /></span>\n";
echo "</div>\n";
echo "<div class=\"row\">\n";
echo "<label for=\"title\">"._("Description")."</label>\n";
echo "<span class=\"textinput\"><input type=\"text\" name=\"description\" id=\"description\" value=\"" . (($this->error != "") ? strip_tags(trim($_POST['description'])) : "") . "\" size=\"30\" maxlength=\"60\" tabindex=\"4\" /></span>\n";
echo "</div>\n";
echo "<div class=\"row\">\n";
echo "<span class=\"textinput\"><input name=\"submit\" type=\"submit\" id=\"submit\" tabindex=\"4\" value=\""._("Sign Up")."\" /></span>\n";
echo "</div>\n<div class=\"clear\"></div>\n";
echo "</form>\n";
echo "<p>"._("You need to be a member of ")."<a href=\"http://sucs.org/\">SUCS</a>"._(" to register")."<br />"._("The normal ")."<a href=\"http://sucs.org/About/Conditions\">"._("Terms and Conditions")."</a>"._(" apply")."</p>\n";
echo "</div>\n";
echo "</div>\n";
}
}
<?php
/* vim: set tabstop=4: */
/*
* blogs class - provides functions for blogs
*/
// PHP Notices are fun, but we don't really want to see them right now
error_reporting(E_ALL ^ E_NOTICE);
// Initialise the database
require_once("/usr/share/php/adodb/adodb.inc.php");
$BlogDB = NewADOConnection('postgres8');
$BlogDB->Connect('dbname=blogs user=apache');
$BlogDB->SetFetchMode(ADODB_FETCH_ASSOC);
// Some useful validation functions
require_once("validation.lib.php");
// Some useful miscellaneous functions
require_once("miscfunctions.lib.php");
/* a stub of an error handler
scale of 1-5, 5 being warnings, 1 being fatal errors?
1 : fatal
2 : dberror
3
4 : bad input
5 : not found/doesnt exist etc
*/
function error($level, $error) {
echo("<p class=\"errorinfo\">"._("Level ").$level._(" error - ").$error."</p>");
}
//A bit of a nicer error handler, to allow errors encounterd in the construction phase to be displayed in the 'correct' place
function error_exc($e) {
if (!isset($e->error) || !isset($e->errormsg)) {
echo("<p class=\"errorinfo\">"._("Level 0 error - no error message available")."</p>");
} else {
echo("<p class=\"errorinfo\">"._("Level ").$e->error._(" error - ").$e->errormsg."</p>");
}
}
//Our Blogs Class
class blogs {
//Blog ID
var $id;
//Blogger's Details
var $userName;
var $realName;
//Blog Details
var $title;
var $description;
var $cssFile;
//Date formats
var $shortDateFormat;
var $longDateFormat;
//Paths
var $httpPath;
var $blogPath;
var $basePath;
var $adminPath;
//bools
var $comment_moderation;
var $editor; //surely this should be in admin.lib? it doesnt seem to be used in blog.lib
var $currentEntry;
//Errors
var $error;
var $errormsg;
//SVN Revision... the closest thing we've got to a version number
var $svnRevision;
//Constructor - checks we've been given a valid username, and pulls in generic blog info
function blogs($user) {
global $BlogDB;
//set the error string first, so we dont wipe out any errors
$this->error = null;
$this->errormsg = null;
//set the locale
setlocale(LC_ALL, 'en_GB');
//check the username
if(!safeuname($user)) {
$this->error = 1;
$this->errormsg = "No such user";
return;
} else {
//check to see if the user has a blog
$sql = $BlogDB->GetRow("SELECT id, name, title, description, css, moderate, editor from users where username = '".$user."' and enabled = true;");
if (!$sql) {
$this->error = 1;
$this->errormsg = "No such user";
return;
} else {
//pull in the blog details
$this->id = $sql['id'];
$this->userName = $user;
$this->realName = $sql['name'];
$this->title = $sql['title'];
$this->description = $sql['description'];
$this->cssFile = $sql['css'];
$this->shortDateFormat = "%x %X";
$this->longDateFormat = "%c";
//set path for all http stuff.. ie images, css and so on
$this->httpPath = "/Blogs/";
//make the httpPath work nicely if we're not in a subdir
//if(substr($this->httpPath, -1)!="/") {
// $this->httpPath .= "/";
//}
//path for the blog viewer with no user
$this->basePath = "/Blogs/";
//path to this blog
$this->blogPath = $this->basePath.$this->userName."/";
//path to the admin bits
$this->adminPath = $this->httpPath."Admin/";
$this->comment_moderation = ($sql['moderate']=='t') ? TRUE : FALSE;
$this->editor = ($sql['editor']=='t') ? TRUE : FALSE;
$this->currentEntry = "";
$this->svnRevision = getSVNRevision();
//setup the session
session_name("BlogSession");
session_start();
}
}
}
// print a blog entry, when provided with a database $row containing one.
function printEntry($row, $commentLink = true, $titleLink = true) {
global $pathlist;
echo "<div class=\"box\">\n";
echo "<div class=\"boxhead\"><h2>";
if ($titleLink) {
echo "<a href=\"{$this->blogPath}entry/". htmlentities($row['shortsubject']) ."\">". htmlentities($row['subject']) ."</a>";
} else {
echo htmlentities($row['subject']);
}
if ($pathlist[3]=="entry") {
// If we're displaying a single entry, hack the pathlist into shape
$pathlist[3]=$row['subject'];
unset($pathlist[4]);
}
echo "</h2></div>\n";
echo "<div class=\"boxcontent\">\n";
echo $row['body'] . "\n";
echo "</div>\n";
echo "<div class=\"boxfoot\"><p>[ Entry posted at: ".strftime($this->longDateFormat,strtotime($row['timestamp']));
if ($commentLink) {
echo " | <a href=\"".$this->blogPath."entry/{$row['shortsubject']}\">Comments</a>: ".$this->commentCount($row['id']);
} else {
echo " | ".$this->commentCount($row['id'])." comment(s)...";
}
echo " | Cat: <a href=\"".$this->blogPath."category/{$row['category']}\">".$this->categoryName($row['category'])."</a> ";
if($this->checkSessionOwner()){
echo "| <a href=\"".$this->adminPath."update/{$row['shortsubject']}\">"._("Edit")."</a> ";
//delete link, disabled for now
//echo "| <a href=\"".$this->adminPath."deleteentry/{$row['shortsubject']}\">"._("Delete")."</a>";
}
echo " ]</p></div>\n";
echo "</div>\n";
}
// print lots of blog entries
function printEntries($offset=0, $limit=15, $constraint='') {
global $BlogDB;
//get the entries from the database
$sql = $BlogDB->GetAll("SELECT id, category, subject, body, timestamp, shortsubject from entries where user_id = '".$this->id."' ".$constraint." order by timestamp desc limit ".$limit." offset ".$offset.";");
//return an error if we cant find any
if (count($sql) < 1) {
error(5,"No relevant posts");
} else {
//print each entry
while ($sqlRow = array_shift($sql)) {
$this->printEntry($sqlRow);
}
//archive link
echo "<div class=\"archivelink\"><a href=\"{$this->blogPath}Archive/\">"._("archived posts...")."</a></div>";
}
}
// print old entries sorted by either date (default), subject or category
function printArchive($request) {
switch(trim($request[0])) {
case 'category' :
array_shift($request);
$this->printArchiveByCategory($request);
break;
case 'subject' :
array_shift($request);
$this->printArchiveBySubject($request);
break;
case 'date' :
array_shift($request);
$this->printArchiveByDate($request);
break;
default :
$this->printArchiveByDate($request);
}
}
// print a list of entries by date
function printArchiveByDate($request)
{
global $BlogDB;
$request = preg_grep('/.+/', $request); // Remove any additional silly extra elements due to additional /'s
//get the refinements if set
$year = (isset($request[0]) && is_numeric($request[0])) ? $request[0] : "";
$month = (isset($request[1]) && is_numeric($request[1])) ? $request[1] : "";
$day = (isset($request[2]) && is_numeric($request[2]) ) ? $request[2] : "";
// Get the last request option (sort order) after the date
$lastIndex = count($request) - 1;
$order = strtoupper($request[$lastIndex]);
//this ensures order is sane
switch($order) {
case 'ASC' :
$strOppositeOrder = 'Descending';
$oppositeOrder = 'DESC';
$strOrder = 'Ascending';
break;
case 'DESC' :
default :
$strOppositeOrder = 'Ascending';
$oppositeOrder = 'ASC';
$strOrder = 'Descending';
$order = 'DESC';
}
if($month=="" && $day=="") {
$enddate = $year+1;
} elseif($month != "" && $day=="") {
$enddate = $year.(sprintf("%02d", $month+1));
} else {
$enddate = $year.$month.(sprintf("%02d", $day+1));
}
$sql = "SELECT shortsubject,subject,timestamp FROM entries WHERE ".((!$year)? "" : "timestamp >= $year$month$day AND timestamp < $enddate AND ") .
"user_id = '".$this->id."' ORDER BY timestamp " . $order;
$result = $BlogDB->GetAll($sql);
$requestPath = (count($request) > 0)?implode ( $request, '/' ) . '/':'';
$curyear = "";
$curmonth = "";
$curday = "";
echo "<div class=\"td\"><h2>Sorted By <a href=\"" . $this->blogPath . "Archive/date/\">Date</a> (" . $strOrder . ")</h2><a href=\"" . $this->blogPath .
"Archive/date/" . $requestPath . "" . $oppositeOrder . "\"> Sort " . $strOppositeOrder .
"</a> || Sort By <a href=\"" . $this->blogPath . "Archive/category\">Category</a> | <a href=\"" .
$this->blogPath . "Archive/subject\"> Subject </a><br />";
if ( count($result) >= 1 ) {
while($row = array_shift($result)){
if($curyear!=date("Y", strtotime($row['timestamp']))) {
$curyear = date("Y", strtotime($row['timestamp']));
echo "<h1><a href=\"".$this->blogPath."Archive/$curyear\">$curyear</a></h1>";
}
if($curmonth!=date("F", strtotime($row['timestamp']))) {
$curmonth = date("F", strtotime($row['timestamp']));
echo "<h2><a href=\"".$this->blogPath."Archive/".date("Y/m", strtotime($row['timestamp']))."\">$curmonth</a></h2>\n";
}
if($curday!=date("l jS", strtotime($row['timestamp']))) {
$curday = date("l jS", strtotime($row['timestamp']));
echo "<h3><a href=\"".$this->blogPath."Archive/".date("Y/m/d", strtotime($row['timestamp']))."\">$curday</a></h3>\n";
}
echo date("g:ia", strtotime($row['timestamp']))." - <a href=\"{$this->blogPath}entry/{$row['shortsubject']}\">". htmlentities($row['subject']) ."</a><br />\n";
}
} else {
error(5,"No Entries Available" . ($allentries ? '' : " for $year" . ($month != '' ? "/$month":'') . ($day != '' ? "/$day":'')));
}
echo "</div>";
}
//print a list of entries by category
function printArchiveByCategory($request)
{
global $BlogDB;
// Check for a category id
// There must be a better way to check that it isn't $order
$request = preg_grep('/.+/', $request); // Remove any additional silly extra elements due to additional /'s
if (isset($request[0]) && (strtoupper($request[0]) != 'ASC') && (strtoupper($request[0]) != 'DESC')) {
$category = $this->makeCleanString($request[0]);
if (strlen($category) < 3)
$allentries = true;
} else {
$allentries = true;
}
$lastIndex = count($request) - 1; // Get the last request option after the date
$order = 'ASC';
if (isset($request[$lastIndex]) && (($lastIndex > 0) || isset($allentries)) &&
(strlen($request[$lastIndex]) > 2)) {
$order = strtoupper($request[$lastIndex]);
array_pop($request);
}
switch($order) {
case 'DESC' :
$strOppositeOrder = 'Ascending';
$oppositeOrder = 'ASC';
$strOrder = 'Descending';
break;
case 'ASC' :
default :
$strOppositeOrder = 'Descending';
$oppositeOrder = 'DESC';
$strOrder = 'Ascending';
$order = 'ASC';
}
$sql = "SELECT shortsubject,subject,timestamp, name FROM entries AS e,categories AS c WHERE " .
($allentries ? "" : " lower(c.name) = '" . $category . "' AND ") .
"e.user_id = '".$this->id."' AND e.category = c.id ORDER BY " . ($allentries? "name " . $order . " ,timestamp ASC" : "timestamp " . $order );
$result = $BlogDB->GetAll($sql);
$requestPath = (count($request) > 0)?implode ( $request, '/' ) . '/':'';
$dbCategory = '';
echo "<div class=\"td\"><h2>Sorted By <a href=\"" . $this->blogPath . "Archive/category/\">Category</a> (" . $strOrder . ")</h2><a href=\"" . $this->blogPath .
"Archive/category/" . $requestPath . "" . $oppositeOrder . "\"> Sort " . $strOppositeOrder .
"</a> || Sort By <a href=\"" . $this->blogPath . "Archive/date\">Date</a> | <a href=\"" .
$this->blogPath . "Archive/subject\"> Subject </a><br />";
if ( count($result) >= 1 ) {
while($row = array_shift($result)){
if($dbCategory != $row['name']) {
$dbCategory = $row['name'];
echo "<h1><a href=\"".$this->blogPath."Archive/category/$dbCategory\">$dbCategory</a></h1>";
}
echo date("d/m/Y", strtotime($row['timestamp'])) . " - <a href=\"{$this->blogPath}entry/{$row['shortsubject']}\">". htmlentities($row['subject']) ."</a><br />\n";
}
echo "</div>";
} else {
error(5,"No Entries Available" . (isset($category) ? " in $category":''));
}
}
//print a list of entries by title
function printArchiveBySubject ($request)
{
global $BlogDB;
// Look for a single character to show subjects by
$request = preg_grep('/.+/', $request); // Remove any additional silly extra elements due to additional /'s
if (isset($request[0]) && (preg_match('/^[a-z]$/i', $request[0]))) {
$letter = strtolower($request[0]);
} else {
$allentries = true;
}
// Get whether it is Ascending or Descending
$lastIndex = count($request) - 1; // Get the last request option after the date
$order = 'ASC';
if (isset($request[$lastIndex]) && !is_numeric($request[$lastIndex])) {
$order = strtoupper($request[$lastIndex]);
array_pop($request);
}
switch($order) {
case 'DESC' :
$strOppositeOrder = 'Ascending';
$oppositeOrder = 'ASC';
$strOrder = 'Descending';
break;
case 'ASC' :
default :
$strOppositeOrder = 'Descending';
$oppositeOrder = 'DESC';
$strOrder = 'Ascending';
$order = 'ASC';
}
$requestPath = (count($request) > 0)?implode ( $request, '/' ) . '/':'';
// lower() exists in PG and MySQL, but given that db abstraction is wanted, is it part of the SQL standard?
// Should a better method be used?
$sql = "SELECT shortsubject,subject,timestamp FROM entries WHERE ".(($allentries)? "" : "lower(subject) LIKE '" . $letter . "%' AND ") .
"user_id = '".$this->id."' ORDER BY subject " . $order;
$result = $BlogDB->GetAll($sql);
echo "<div class=\"td\"><h2>Sorted By <a href=\"" . $this->blogPath . "Archive/subject/\">Subject</a> (" . $strOrder . ")</h2><a href=\"" . $this->blogPath .
"Archive/subject/" . $requestPath . "" . $oppositeOrder . "\"> Sort " . $strOppositeOrder .
"</a> || Sort By <a href=\"" . $this->blogPath . "Archive/date\">Date</a> | <a href=\"" .
$this->blogPath . "Archive/category\"> Category </a><br /><a href=\"" . $this->blogPath .
"Archive/subject/a/$order\">a</a> | <a href=\"" . $this->blogPath .
"Archive/subject/b/$order\">b</a> | <a href=\"" . $this->blogPath .
"Archive/subject/c/$order\">c</a> | <a href=\"" . $this->blogPath .
"Archive/subject/d/$order\">d</a> | <a href=\"" . $this->blogPath .
"Archive/subject/e/$order\">e</a> | <a href=\"" . $this->blogPath .
"Archive/subject/f/$order\">f</a> | <a href=\"" . $this->blogPath .
"Archive/subject/g/$order\">g</a> | <a href=\"" . $this->blogPath .
"Archive/subject/h/$order\">h</a> | <a href=\"" . $this->blogPath .
"Archive/subject/i/$order\">i</a> | <a href=\"" . $this->blogPath .
"Archive/subject/j/$order\">j</a> | <a href=\"" . $this->blogPath .
"Archive/subject/k/$order\">k</a> | <a href=\"" . $this->blogPath .
"Archive/subject/l/$order\">l</a> | <a href=\"" . $this->blogPath .
"Archive/subject/m/$order\">m</a> | <a href=\"" . $this->blogPath .
"Archive/subject/n/$order\">n</a> | <a href=\"" . $this->blogPath .
"Archive/subject/o/$order\">o</a> | <a href=\"" . $this->blogPath .
"Archive/subject/p/$order\">p</a> | <a href=\"" . $this->blogPath .
"Archive/subject/q/$order\">q</a> | <a href=\"" . $this->blogPath .
"Archive/subject/r/$order\">r</a> | <a href=\"" . $this->blogPath .
"Archive/subject/s/$order\">s</a> | <a href=\"" . $this->blogPath .
"Archive/subject/t/$order\">t</a> | <a href=\"" . $this->blogPath .
"Archive/subject/u/$order\">u</a> | <a href=\"" . $this->blogPath .
"Archive/subject/v/$order\">v</a> | <a href=\"" . $this->blogPath .
"Archive/subject/w/$order\">w</a> | <a href=\"" . $this->blogPath .
"Archive/subject/x/$order\">x</a> | <a href=\"" . $this->blogPath .
"Archive/subject/y/$order\">y</a> | <a href=\"" . $this->blogPath .
"Archive/subject/z/$order\">z</a><br />";
if ( count($result) >= 1 ) {
while($row = array_shift($result)){
echo date("d/m/Y", strtotime($row['timestamp'])) . " - <a href=\"{$this->blogPath}entry/{$row['shortsubject']}\">". htmlentities($row['subject']) ."</a><br />\n";
}
} else {
error(5, "No Entries Available" . ($allentries ? '' : " beginning with '$letter'"));
}
echo "</div>";
}
//print Prev/Next nav bar
function printNavigationBar($id) {
global $BlogDB;
$sql = $BlogDB->GetRow("SELECT timestamp from entries WHERE id='".$id."'");
$prev = $BlogDB->GetAll("SELECT id, shortsubject, subject FROM entries WHERE timestamp < '".$sql['timestamp']."' AND user_id = '".$this->id."' ORDER BY timestamp DESC LIMIT 1");
$next = $BlogDB->GetAll("SELECT id, shortsubject, subject FROM entries WHERE timestamp > '".$sql['timestamp']."' AND user_id = '".$this->id."' ORDER BY timestamp ASC LIMIT 1;");
if (count($prev)>0) $prevRow=array_shift($prev);
if (count($next)>0) $nextRow=array_shift($next);
echo "<div class=\"navbar\"><div><div><div>\n";
echo "<ul class=\"blognav\">";
if ($prevRow['shortsubject']!="") echo "<li class=\"prev\"><a href=\"{$this->blogPath}entry/{$prevRow['shortsubject']}\">&lt; ".htmlentities($prevRow['subject'])."</a></li>";
if ($nextRow['shortsubject']!="") echo "<li class=\"next\"><a href=\"{$this->blogPath}entry/{$nextRow['shortsubject']}\">".htmlentities($nextRow['subject'])." &gt;</a></li>";
echo "</ul>\n";
echo "<br style=\"clear: both:\" /></div></div></div></div>\n";
}
//print one entry and its comments
function printEntryAndComments($shortsubject)
{
global $BlogDB;
$shortsubject = $this->makeCleanString($shortsubject);
$sql = $BlogDB->GetRow("SELECT id, category, subject, body, timestamp, shortsubject from entries where shortsubject='".$shortsubject."' and user_id = ".$this->id." LIMIT 1;");
if (!$sql) {
error(5,"No relevant posts");
}
else {
$this->currentEntry = $sql['shortsubject'];
$this->printNavigationBar($sql['id']);
$this->printEntry($sql, false, false);
$this->printComments($sql['id']);
$this->printCommentForm($sql['id']);
}
}
//print lots of comments
function printComments($postid, $offset=0, $limit=15)
{
global $BlogDB;
$sql = $BlogDB->GetAll("SELECT timestamp, name, email, body, host, id FROM comments WHERE post = ".$postid." and moderated = true ORDER BY timestamp ASC limit ".$limit." OFFSET ".$offset.";");
echo "<div id=\"comments\">\n";
if (count($sql) > 0) {
$blogOwner = $this->checkSessionOwner();
if($blogOwner) {
echo "<form name=\"deletecomments\" id=\"deletecomments\" method=\"post\" action=\"{$this->adminPath}deletecomments/{$this->currentEntry}\">\n";
}
$count=0;
while ($sqlRow = array_shift($sql)) {
$this->printComment($sqlRow, $blogOwner, $count++);
}
if($blogOwner) {
echo "<div style=\"width: 100%; text-align: right\">\n";
echo "<input type=\"submit\" name=\"submit\" value=\"Delete Comments\" />\n";
echo "</div>\n";
echo "</form>\n";
}
}
echo "</div>\n";
}
//print a comment
function printComment($row, $printCheckBox=FALSE, $checkBoxNum=0)
{
echo "<div class=\"box\">\n";
echo "<div class=\"boxhead\"><h3>" . htmlentities($row['name']) . " writes:</h3></div>";
echo "<div class=\"boxcontent\"><p>" . nl2br(htmlentities(br2nl($row['body']))) . "</p></div>\n";
echo "<div class=\"boxfoot\"><p>[ " .strftime($this->longDateFormat,strtotime($row['timestamp']));
if($printCheckBox){
echo " | <input class=\"smallcheckbox\" type=\"checkbox\" id=\"comment{$checkBoxNum}\" name=\"comment[{$checkBoxNum}]\" value=\"{$row['id']}\" />\n";
echo "<label for=\"comment{$checkBoxNum}\">Delete</label>\n";
}
echo " ]</p></div>\n";
echo "</div>\n";
}
//counts the number of comments
function commentCount($entry) {
global $BlogDB;
$sql = $BlogDB->GetCol("SELECT count(id) from comments where post = ".$entry." and moderated = true;");
return $sql[0];
}
//returns a category name
function categoryName($category) {
global $BlogDB;
$sql = $BlogDB->GetCol("SELECT name from categories where id = ".$category.";");
return $sql[0];
}
//prints a form so people can comment
function printCommentForm($id)
{
echo "<div class=\"entry\">\n";
echo "<h2>Add Comment<a id=\"cmt\"></a></h2>\n";
echo "<div class=\"td\">\n";
if ($this->commentError != "") {
echo "<p class=\"invalid\">*** " . $this->commentError . " ***</p>\n";
}
elseif (isset($_POST['submit'])) {
echo "<p>Thank you for your comment</p>\n";
}
// try to work out the viewer's name + email
//seems a bit silly to check for the existance of the session stuff in two places, its probably fair to assume if one is set, the other will be too
//these need the same validation checks as when we put things into the db, else people can inject what ever html they like into our pages
if(isset($_SESSION['realName'])) {
$name = $_SESSION['realName'];
} elseif(isset($_COOKIE['Blog_CommentRealName'])) {
$name = $_COOKIE['Blog_CommentRealName'];
} else {
$name = "";
}
if(isset($_SESSION['userName'])) {
$email = $_SESSION['userName']."@sucs.org";
} elseif(isset($_COOKIE['Blog_CommentEmailAddress'])) {
$email = $_COOKIE['Blog_CommentEmailAddress'];
} else {
$email = "";
}
echo "<form onsubmit=\"return postcomment('".$this->httpPath."', '".$this->userName."', '".$id."')\" action=\"".$this->blogPath."postcomment/".$id."\" method=\"post\" id=\"commentform\">\n";
echo "<div class=\"row\">\n";
echo "<label for=\"author\">Name (required)</label>\n";
echo "<span class=\"textinput\"><input type=\"text\" name=\"author\" id=\"author\" value=\"$name\" size=\"40\" maxlength=\"50\" tabindex=\"1\" /></span>\n";
echo "</div>\n";
echo "<div class=\"row\">\n";
echo "<span class=\"textinput\"><input type=\"text\" name=\"email\" id=\"email\" value=\"$email\" size=\"40\" maxlength=\"70\" tabindex=\"2\" /></span>\n";
echo "<label for=\"email\">E-mail (required, not displayed)</label>\n";
echo "</div>\n";
echo "<div class=\"row\">\n";
echo "<span class=\"textinput\"><textarea name=\"comment\" id=\"comment\" cols=\"50\" rows=\"10\" tabindex=\"3\">" . (($this->commentError != "") ? strip_tags($_POST['comment']) : "") . "</textarea></span>\n";
echo "</div>\n";
echo "<div class=\"row\">\n";
echo "<span class=\"textinput\"><input name=\"submit\" type=\"submit\" id=\"submit\" tabindex=\"4\" value=\"Submit Comment\" /></span>";
echo "<img src=\"".$this->httpPath."img/spinner.gif\" alt=\"\" id=\"spinner\"/>\n";
echo "<label class=\"invalid\" for=\"submit\" id=\"errors\"></label>\n";
echo "</div>\n<div class=\"clear\"></div>";
echo "</form>\n";
echo "</div>\n";
echo "</div>\n";
}
//takes a string and strips it, making it safe to put in a URL
function makeCleanString($string,$externalSource=false)
{
//externalSource meaning directly inputed by a user, in most cases this should be false.. appart from starting a new post
$string = strtolower($string);
$string = preg_replace("/[^a-z0-9\- _]/i", "", $string);
$string = str_replace(" ", "-",trim($string));
if ($externalSource) {
$string = str_replace("_", "-",$string);
}
$string = urlencode($string);
return $string;
}
//handles posting of comments
function newComment($id, $printentry=TRUE)
{
global $BlogDB;
$author = "";
$email = "";
$comment = "";
//check the post exists, and is part of this blog
$row = $BlogDB->GetRow("SELECT subject, id from entries where user_id = ".$this->id." and id = '".$id."';");
if (!$row) {
error(1,_("Invalid blog entry, This entry may have been removed..?"));
return;
}
//pull in the unadulterated subject for later on
$subject = $row['subject'];
$postid = $row['id'];
//set hostname
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$host = addslashes($_SERVER['HTTP_X_FORWARDED_FOR']) . " : " . addslashes($_SERVER['REMOTE_ADDR']);
}
else {
$host = addslashes($_SERVER['REMOTE_ADDR']);
}
//sanitise comment
if (isset($_POST['comment']) && trim($_POST['comment']) != "") {
if(strip_tags($_POST['comment']) == $_POST['comment']) {
$comment = addslashes(nl2br(trim($_POST['comment'])));
} else {
$this->commentError = _("HTML within comments is not allowed, Please remove all html tags and try again");
$element = "comment";
}
} else {
$this->commentError = _("Please check the comment field");
$element = "comment";
}
//decided if the comment is likly to be spam
if (checkSpam($host,$_POST['comment'])) {
$spam = true;
//force this comment though moderation
$this->comment_moderation = true;
} else {
$spam = false;
}
//sanitise email
if (isset($_POST['email']) && trim($_POST['email']) != "" && validEmail(trim($_POST['email']))) {
$email = addslashes(trim($_POST['email']));
} else {
$this->commentError = _("Check email address, it does not apear to be valid.");
$element = "email";
}
//sanitse author
if (isset($_POST['author']) && trim($_POST['author']) != "") {
if(eregi("^([a-z0-9]+ *)+$", $_POST['author'])) {
$author = addslashes(nl2br(trim(strip_tags($_POST['author']))));
} else {
$this->commentError = _("Invalid name. We only allow alphanumeric names!");
$element = "author";
}
}
else {
$this->commentError = _("Please give us your name.");
$element = "author";
}
//if no errors have been raised so far commit to the db
if ($this->commentError == "") {
// do we need to set the moderated flag on this comment?
if(!$this->comment_moderation) {
$moderated = TRUE;
} else {
//check the list of 'authorised' commentors
if(count($BlogDB->GetAll("SELECT name FROM authorised_emails WHERE user_id={$this->id} AND email='{$email}'"))>0) {
$moderated = TRUE;
} else {
$moderated = FALSE;
}
}
//actualy insert the new comment and check it worked
$query = "INSERT INTO comments (post, name, email, body, host, moderated, spam) VALUES ('{$postid}','{$author}','{$email}','{$comment}','{$host}', ".(($moderated) ? "true" : "false").", ".(($spam) ? "true" : "false").")";
if(!$BlogDB->Execute($query)) {
error(2,_("Database commit failed -").$BlogDB->ErrorMsg());
}
//send out an notificaiton email if we have succeeded unless we think its spam or moderation has been bypassed
else {
if(!$spam or !$moderated)
mail($this->userName . "@sucs.org", "Blog comment on \"".$subject."\"", "You've received a comment from ".$author." on your blog post \"".$subject.". The comment is:\n==========\n".$comment.(($moderated) ? "" : "\n==========\nPlease login to your blog admin page to approve or delete this comment."), "From: Your Blog <noreply@sucs.org>");
//inform the commentor if the message has been tagged for modderation
if(!$moderated) {
echo "<p class=\"updateinfo\">"._("Your comment has been added, but before it appears here it must be accepted by the blog owner.")."</p>";
}
//or pass out the comment useing the standard form
elseif(!$printentry) {
$time = strftime($this->longDateFormat, time());
$this->printComment(array('name'=>$author, 'body'=>$comment, 'timestamp'=>$time));
}
//reprint the entire entry (for the case where we're not useing the ajax goodness)
if($printentry) {
$this->printEntryAndComments($shortSubject);
}
//if we dont have a valid session store the name & email in there own cookies
if(!isset($_SESSION['realName'])) {
setcookie("Blog_CommentRealName", $author, time()+604800);
setcookie("Blog_CommentEmailAddress", $email, time()+604800);
}
ob_end_flush();
return array(TRUE);
}
//else return our error and the status gumf for the benifit of the ajax goodness
} else {
echo $this->commentError;
return array(FALSE, $element);
}
}
//reutrns the id of the message assosiated with a short subject
function shortSubjectToID($shortsubject)
{
global $BlogDB;
$sql = $BlogDB->GetRow("SELECT id from entries where user_id = ".$this->id." and shortsubject = '".$shortsubject."';");
if ($sql) {
return $sql['id'];
}
else {
error(3,"No such post");
}
}
//reutrns the short subject of the message given message
function IDToShortSubject($id)
{
global $BlogDB;
$sql = $BlogDB->GetRow("SELECT shortsubject from entries where user_id = ".$this->id." and id = '".$id."';");
if ($sql) {
return $sql['shortsubject'];
}
else {
error(3,"No such post");
}
}
// Blog menu
function menu()
{
global $smarty, $session;
$submenu = array();
if ($session->loggedin && blogger($session->username)) $submenu[_("My Blog")] = "{$this->httpPath}{$session->username}";
if ($session->username != $this->userName) $userblog = $this->userName._("'s Blog");
$submenu[$userblog] = $this->blogPath;
if ($session->username == $this->userName) $archiveblog = _("My Archive");
else $archiveblog = $this->userName._("'s Archive");
$submenu[$archiveblog] = "{$this->blogPath}Archive/";
if ($this->checkSessionOwner() && blogger($session->username)){
$submenu[_("Blog admin")] = "{$this->adminPath}";
}
$menu = $smarty->get_template_vars("menu");
$menu[Blogs] = $submenu;
$smarty->assign("menu", $menu);
}
// Check the session to see if the user is browsing her own blog
function checkSessionOwner()
{
global $session;
$maxSessionAge = 3600;
// if the session's expired then nuke it
if ($session->username != $this->userName) {
return FALSE;
} else {
// the time's not up and the usernames match so it's probably the right user.
return TRUE;
}
}
}
// a pseudo-class to list all blog users
class bloglist {
var $title;
var $description;
var $httpPath;
var $listPath;
var $adminPath;
var $cssFile;
var $svnRevision; // the SVN revision number of the currently running blog
// don't do anything apart from setting up default variables
function bloglist()
{
$this->title = _("Blogs");
$this->description = _("Swansea University Computer Society member web logs");
$this->httpPath = "/Blogs/";
//if(substr($this->httpPath, -1)!="/") {
// $this->httpPath .= "/";
//}
$this->basePath = "/Blogs/";
$this->adminPath = $this->httpPath."Admin/";
$this->cssFile = "blog.css";
$this->svnRevision = getSVNRevision();
// setup the session purely so we get the debug bits..
session_name("BlogSession");
session_start();
}
// print a nice list of blog users and when they last updated
function listBlogs()
{
global $BlogDB, $session;
$sql = $BlogDB->GetAll("SELECT max(entries.timestamp) AS ts, users.username, users.description, users.name, users.title FROM entries LEFT JOIN users ON entries.user_id = users.id GROUP BY users.username, users.name, users.title, users.description ORDER BY ts DESC;");
if (count($sql) > 0) {
echo "<div class=\"td\">\n";
echo "<p>"._("Welcome to SUCS Blogs - The multi-user web log system created by SUCS members for SUCS members.")."</p>\n";
echo "<p>"._("Browse the blogs below or use the links on the left to navigate the site. Happy blogging!")."</p>\n";
if ($session->loggedin && !blogger($session->username)) echo "<p>"._("Want to join the ranks of SUCS bloggers? - ")."<a href=\"{$this->adminPath}signup\">"._("Start a Blog!")."</a></p>\n";
echo "</div>\n";
echo "<div id=\"listofblogs\">\n";
echo "<table class=\"border\">\n";
echo "<tr><th class=\"bname\">"._("Name")."</th><th class=\"btitle\">"._("Blog")."</th><th class=\"bupdated\">"._("Last Updated")."</th></tr>";
while($row = array_shift($sql)) {
echo "<tr>\n";
echo " <td>".$row['name']."</td>\n";
echo " <td><a href=\"".$this->basePath.$row['username']."\" title=\"".$row['description']."\">".$row['title']."</a></td>\n";
echo " <td>".$this->timeDiff(strtotime($row['ts']))." ago</td>\n";
echo "</tr>\n";
}
echo "</table>\n";
echo "</div>\n";
}
else {
error(3,_("No blogs"));
}
}
//Returns a textual diff between two time stamps
function timeDiff($first, $second=0)
{
if($second == 0) {
$second = time();
}
$diff = max($first, $second) - min($first, $second);
if($diff>604800) {
$ret = round($diff/604800);
return $ret.(($ret>1)? _(" weeks") : _(" week"));
}
elseif($diff>86400) {
$ret = round($diff/86400);
return $ret.(($ret>1)? _(" days") : _(" day"));
}
elseif($diff>3600) {
$ret = round($diff/3600);
return $ret.(($ret>1)? _(" hours") : _(" hour"));
}
elseif($diff>60) {
$ret = round($diff/60);
return $ret.(($ret>1)? _(" minutes") : _(" minute"));
}
else {
return $diff.(($diff>1)? _(" seconds") : _(" second"));
}
}
// Blog menu - links displayed when the blog list is displayed
function menu() {
global $smarty, $session;
if ($session->loggedin) {
$submenu = array();
if (blogger($session->username)) {
$submenu[_("My Blog")] = "{$this->httpPath}{$session->username}";
$submenu[_("Blog admin")] = "{$this->adminPath}";
} else {
$submenu[_("Start a Blog")] = "{$this->adminPath}signup";
}
$menu = $smarty->get_template_vars("menu");
$menu[Blogs] = $submenu;
$smarty->assign("menu", $menu);
}
}
}
<?php
// does the opposite of PHP's nl2br()
function br2nl($string) {
$string = preg_replace("/(\r\n|\n|\r)/", "", $string);
$string = preg_replace("/<br *\/?>/i", "\n", $string);
return $string;
}
// generate a pseudo-word random password
function makePassword($length=8)
{
$password = "";
$vowels = "aeiouy";
$consonants = "bcdfghjklmnprst";
$cn = strlen($consonants)-1;
$vn = strlen($vowels)-1;
// Start on cons or vowel
$alt = mt_rand(0, 1);
// How many numbers
$len = mt_rand($length-3,$length);
//add the letters
for ($i = 0; $i < $len; $i++)
{
if ($alt == 1) {
$password .= $consonants[ mt_rand(0,$cn) ];
$alt = 0;
}
else {
$password .= $vowels[ mt_rand(0,$vn) ];
$alt = 1;
}
}
//add the numbers
for ($i = 0; $i < $length-$len; $i++)
{
$password .= mt_rand(0,9);
}
return $password;
}
$revision = "unknown";
function startElement($parser, $name, $attrs)
{
global $revision;
if($name=="ENTRY" && $attrs['NAME']=="") {
$revision = $attrs['REVISION'];
}
}
function endElement($parser, $name){}
function getSVNRevision()
{
global $revision;
$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startElement", "endElement");
if (!($fp = fopen(".svn/entries", "r"))) {
return "unknown - couldn't open SVN XML file.";
}
while(($data = fread($fp, 1024)) && $revision=="unknown") {
if (!xml_parse($xml_parser, $data, feof($fp))) {
return "unknown - couldn't parse SVN XML file";
}
}
xml_parser_free($xml_parser);
return $revision;
}
/*
*
* Spam Checks
*
*/
//Check the Spam URI Realtime Blocklist
function checkSpamURLs($text) {
$spam = false;
//find urls, ugly but works
while (ereg("http://[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}",$text,$match)) {
$matches[] = $match[0];
$text = ereg_replace($match[0],"",$text);
}
//pull in list of two level tlds, make an array from them. from http://spamcheck.freeapp.net/two-level-tlds
$twoLevelTLD = file("/var/www/sucssite/lib/blog/two-level-tlds");
foreach($twoLevelTLD as $TLD) {
$two_level_tlds[trim($TLD)] = true;
}
if (!$matches)
return;
//for each url
foreach ($matches as $url) {
//break it down
$urlBits = explode(".",substr($url, 7));
//reverse the oder
$bitsURL = array_reverse($urlBits);
//if its a two level tld, we want the first 3 bits of the url.. if not just the first 2
if ($two_level_tlds[($bitsURL[1].".".$bitsURL[0])]) {
$URLstoTest[] = ($bitsURL[2].".".$bitsURL[1].".".$bitsURL[0]);
} else {
$URLstoTest[] = ($bitsURL[1].".".$bitsURL[0]);
}
}
if (!$URLstoTest)
return;
//actualy test each of he domains against the surbl
foreach($URLstoTest as $url) {
$result = gethostbyname($url.'.multi.surbl.org');
if ($result != $url.'.multi.surbl.org') {
$spam = true;
}
elseif ($url == "blogspot.com") {
$spam = true;
}
}
return $spam;
}
//feeds a message body though LinkSleeve (http://www.linksleeve.org/) which at the time of testing seems quite good.
function checkSpamLinkSleeve ($text) {
// Include the Pear XML-RPC Client Package
require_once 'XML/RPC.php';
// Build the XML-RPC message
$params = array(new XML_RPC_Value($text, 'string'));
$msg = new XML_RPC_Message('slv', $params);
//Send the XML-RPC message
$cli = new XML_RPC_Client('/slv.php', 'http://www.linksleeve.org');
$resp = $cli->send($msg);
//Check for a responce
if (!$resp) {
echo 'Communication error: ' . $cli->errstr;
return false;
}
//spam?
if (!$resp->faultCode()) {
$val = $resp->value();
if($val->scalarval()=='1') {
$spam = false;
}
else {
$spam = true;
}
}
//Handle Errors
else {
echo 'Fault Code: ' . $resp->faultCode() . "\n";
echo 'Fault Reason: ' . $resp->faultString() . "\n";
}
return $spam;
}
//checks an ip in several blacklists returns true if its present
function checkSpamIP($ip) {
$spam = false;
//reverse the ip
$ip = implode('.',array_reverse(explode('.',$ip)));
//look up in various rbls
$rbl = gethostbyname($ip.'.rbl-plus.mail-abuse.ja.net');
$scbl = gethostbynamel($ip.'.bl.spamcop.net');
$sorbs = gethostbynamel($ip.'.dnsbl.sorbs.net');
$sbl = gethostbynamel($ip.'.sbl.spamhaus.org');
$njabl = gethostbynamel($ip.'.dnsbl.njabl.org');
$opm = gethostbyname($ip.'.opm.blitzed.org');
$cbl = gethostbynamel($ip.'.cbl.abuseat.org');
//CBL
if ($cbl) {
$spam = true;
}
//OPM
if ($opm != $ip.".opm.blitzed.org") {
//this bl uses a decimal to represent one catagory of spam source
$code = decbin(ip2long($opm));
//check for WinGate
if ($code[30])
$spam = true;
//check for SOCKS
if ($code[29])
$spam = true;
//check for HTTP CONNECT
if ($code[28])
$spam = true;
//check for Router
if ($code[27])
$spam = true;
//check for HTTP POST
if ($code[26])
$spam = true;
}
//RBL+
if ($rbl != $ip.".rbl-plus.mail-abuse.ja.net") {
$code = decbin(ip2long($rbl));
//check for rbl
if ($code[30])
$spam = true;
//check for dul
if ($code[29])
//we dont care about dul
//check for rss
if ($code[28])
$spam = true;
//check for ops
if ($code[27])
$spam = true;
}
//SpamCop
if ($scbl) {
$spam = true;
}
//SORBS
if ($sorbs) {
foreach($sorbs as $result) {
$result = explode('.',$result);
//check for http
if ($result[3] == 2)
$spam = true;
//check for socks
if ($result[3] == 3)
$spam = true;
//check for misc
if ($result[3] == 4)
$spam = true;
//check for smtp
if ($result[3] == 5)
$spam = true;
//check for spam
if ($result[3] == 6)
$spam = true;
//check for web
if ($result[3] == 7)
$spam = true;
//check for block
if ($result[3] == 8)
$spam = true;
//check for zombie
if ($result[3] == 9)
$spam = true;
//check for dul
if ($result[3] == 10)
//dont care about dul
//check for badconf
if ($result[3] == 11)
$spam = true;
//check for nomail
if ($result[3] == 12)
$spam = true;
}
}
//NJABL
if ($njabl) {
foreach($njabl as $result) {
$result = explode('.',$result);
//check for relay
if ($result[3] == 2)
$spam = true;
//check for dul
if ($result[3] == 3) {
//dont care about dul
}
//check for spam
if ($result[3] == 4)
$spam = true;
//check for relay
if ($result[3] == 5)
$spam = true;
//check for web
if ($result[3] == 8)
$spam = true;
//check for proxy
if ($result[3] == 9)
$spam = true;
}
}
//SBL
if($sbl) {
$spam = true;
}
return $spam;
}
# General spam function combining all checks
function checkSpam($ip, $text) {
//Check LinkSleeve first, its a collaborative statistical thing, and will benefit from seeing all messages, spam or not
if (checkSpamLinkSleeve($text)) {
$spam = true;
//Check any URL's the Spam URL Black List
} elseif (checkSpamURLs($text)) {
$spam = true;
//If all else fails lookup the posting IP in all the normal IP Black Lists
} elseif (checkSpamIP($ip)) {
$spam = true;
//Decide its probably not spam
} else {
$spam = false;
}
return $spam;
}
<?
//check for a safe username
function safeuname($name)
{
if (strlen($name) < 2) return FALSE;
return ereg("^[a-z][a-z0-9_]*$", $name);
}
// Find out if a given user has a blog
function blogger ($user) {
global $BlogDB;
$result = $BlogDB->GetAll("select username from users where username='". $user ."'");
if (count($result)>0) return true;
else return false;
}
require_once($base."/lib/validation.php");
?>
......@@ -3,22 +3,24 @@
// Determine the academic year of a specific timestamp
// Returns the year which this academic year started, e.g. 2006 for the year 2006/07
function academicYear($timestamp) {
function academicYear($timestamp)
{
$date = getdate($timestamp);
$date = getdate($timestamp);
// Anything before September is the previous academic year
if ($date['mon'] < 9) {
return $date['year'] - 1;
} else {
return $date['year'];
}
if ($date['mon'] < 9) {
return $date['year'] - 1;
} else {
return $date['year'];
}
}
function paidUntil($timestamp) {
$nextyear = academicYear($timestamp)+1;
$paydate = "Sept. ".$nextyear;
return $paydate;
function paidUntil($timestamp)
{
$nextyear = academicYear($timestamp) + 1;
$paydate = "Sept. " . $nextyear;
return $paydate;
}
?>
<?php
function handle_messages ($errno, $errstr, $errfile, $errline) {
global $messages;
switch ($errno) {
case E_USER_ERROR:
$messages['error'][] = $errstr;
break;
case E_USER_WARNING:
$messages['warning'][] = $errstr;
break;
case E_USER_NOTICE:
$messages['notice'][] = $errstr;
break;
}
return true;
function handle_messages($errno, $errstr, $errfile, $errline)
{
global $messages;
switch ($errno) {
case E_USER_ERROR:
$messages['error'][] = $errstr;
break;
case E_USER_WARNING:
$messages['warning'][] = $errstr;
break;
case E_USER_NOTICE:
$messages['notice'][] = $errstr;
break;
}
return true;
}
function message_flash($message) {
function message_flash($message)
{
global $messages;
$messages['info'][] = $message;
}
function message_flash_postponed($message) {
global $session;
$session->data['messages']['info'][] = $message;
$session->save();
function message_flash_postponed($message)
{
global $session;
$session->data['messages']['info'][] = $message;
$session->save();
}
......@@ -36,5 +39,4 @@ set_error_handler("handle_messages", (E_USER_ERROR | E_USER_WARNING | E_USER_NOT
if (!isset($messages)) $messages = array();
?>
Source diff could not be displayed: it is too large. Options to address this: view the blob.
<?php
/*
Written by Imran Hussain ~imranh
Used to auth people, will check SUCS then the uni ldap, will only check
students on the uni ldap.
will return "sucs" if the username/password passed is a sucs member
will return "uni" if the user/pass passed has a student swan uni account
will return "nope" if the user/pass passed is inavlid
Example usage:
require "ldap-auth.php";
isAuthd = ldapAuth("usaername", "password");
if (isAuthd == "sucs"){
//do stuff for sucs auth
}elseif (isAuthd == "uni"){
//do stuff for uni auth
}else{
//do stuff for not authd peeps
}
*/
// we don't care about warnings, we write our own
error_reporting(E_ERROR | E_PARSE);
define(LDAP_OPT_DIAGNOSTIC_MESSAGE, 0x0032);
function ldapAuth($username, $password)
{
if ($username != "" && $password != "") {
// people like to use emails to login so lets detect and strip
if (filter_var($username, FILTER_VALIDATE_EMAIL)) {
//valid email, lets strip
// split the email into a string array "@" as a delim
$s = explode("@", $username);
// remove the last element (domain)
array_pop($s);
// put the array back togther using "@" as a seperator
$username = implode("@", $s);
}
// filter out everything but A-Z a-z 0-9 . - _ from username
$safeusername = preg_replace("/[^A-Za-z0-9\.\-\_]/", '', $username);
// if safeusername isn't the same as username just error out
if ($safeusername != $username) {
return "nope";
}
// ldap servers
$sucsLDAPServer = 'silver.sucs.swan.ac.uk';
$issLDAPServer = '192.168.10.16';
// how to bind
$sucsBindDn = "uid=$safeusername,ou=People,dc=sucs,dc=org";
$issBindDn = "cn=$safeusername,ou=Students,ou=Active,ou=Resources,o=Swansea";
// Main auth
// Try and connect to silver
$ldapconnSUCS = ldap_connect($sucsLDAPServer) or die("Could not connect to SUCS LDAP server.");
ldap_set_option($ldapconnSUCS,LDAP_OPT_PROTOCOL_VERSION,3);
if ($ldapconnSUCS) {
//echo "Connected to $sucsLDAPServer <br>";
// try and bind to sucs ldap
$ldapbindSUCS = ldap_bind($ldapconnSUCS, $sucsBindDn, $password);
if ($ldapbindSUCS) {
//echo "Auth'd as $username using SUCS LDAP<br>";
return "sucs";
// turns out they didn't give us valid sucs creds, lets try iss now
} else {
// try and connect to the iss ldap server
$ldapconnISS = ldap_connect($issLDAPServer) or die("Could not connect to uni LDAP server.");
// echo "Connected to $issLDAPServer <br>";
ldap_set_option($ldapconnISS,LDAP_OPT_PROTOCOL_VERSION,3);
// lets try and bind to the uni ldap
$ldapbindiss = ldap_bind($ldapconnISS, $issBindDn, $password);
/*if (ldap_get_option($ldapconnISS, LDAP_OPT_DIAGNOSTIC_MESSAGE, $extended_error)) {
echo "Error Binding to LDAP: $extended_error";
}*/
if ($ldapbindiss) {
//echo "Auth'd as $username using uni LDAP using ou=$issUsernameOu<br>";
return "uni";
} else {
//exit("Invalid Username or Password");
return "nope";
}
}
}
} else {
return "nope";
}
}
?>
\ No newline at end of file
<?
function make_password($length=8)
<?php
function make_password($length = 8)
{
$vowels = "aeiouy";
$consonants = "bcdfghjklmnprst";
$password = "";
$cn = strlen($consonants)-1;
$vn = strlen($vowels)-1;
// Start on cons or vowel
$alt = mt_rand(0, 1);
// How many numbers
$len = mt_rand($length-3,$length);
for ($i = 0; $i < $len; $i++)
{
if ($alt == 1)
{
$password .= $consonants[ mt_rand(0,$cn) ];
$alt = 0;
}
else
{
$password .= $vowels[ mt_rand(0,$vn) ];
$alt = 1;
}
}
for ($i = 0; $i < $length-$len; $i++)
{
$password .= mt_rand(0,9);
$vowels = "aeiouy";
$consonants = "bcdfghjklmnprst";
$password = "";
$cn = strlen($consonants) - 1;
$vn = strlen($vowels) - 1;
// Start on cons or vowel
$alt = mt_rand(0, 1);
// How many numbers
$len = mt_rand($length - 3, $length);
for ($i = 0; $i < $len; $i++) {
if ($alt == 1) {
$password .= $consonants[mt_rand(0, $cn)];
$alt = 0;
} else {
$password .= $vowels[mt_rand(0, $vn)];
$alt = 1;
}
return $password;
}
for ($i = 0; $i < $length - $len; $i++) {
$password .= mt_rand(0, 9);
}
return $password;
}
function findUid($start, $end) {
$ds=ldap_connect("localhost");
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
$r=ldap_bind($ds);
$sr=ldap_search($ds, "dc=sucs,dc=org", "uid=*",array(uidNumber));
$info = ldap_get_entries($ds, $sr);
for ($i = 0; $i < $info[count]; $i++) {
$uids[$info[$i][uidnumber][0]] = true;
// https://stackoverflow.com/a/44428794
function cryptPassword($password, $salt = "", $rounds = 5000)
{
if ($salt == "") {
// Generate random salt
$salt = substr(bin2hex(openssl_random_pseudo_bytes(16)),0,16);
}
for ($i = $start; $i < $end; $i++) {
if(!isset($uids[$i])) {
$safeuid = $i;
break;
}
// $6$ specifies SHA512
$hash = crypt($password, sprintf('$6$rounds=%d$%s$', $rounds, $salt));
return $hash;
}
function generateUid()
{
//get the year, this'll be the start/prefix of the uid
$prefix = date("Y");
//generate a uid
//check to see if it's taken/safe to use
$ok = false;
while ($ok == false) {
//generate random number between 00000 and 99999
$uid = sprintf("%05d", mt_rand(0, 99999));
//id return 1 for error (safe to take). 0 for success (taken) not safe
exec("id ".$prefix.$uid, $output, $returnVal);
//check the result of id
if ($returnVal == 1) {
// We have an unused one!
$ok = true;
$safeuid = $prefix.$uid;
}
return $safeuid;
}
return $safeuid;
}
function generateLdif($uid, $password, $type, $realname, $username){
// explode the realname
$nameexplode = explode(' ', trim($realname));
// hash the password
$ldappassword = "{SHA}" . base64_encode(pack("H*", sha1($password)));
// compile ldif
$ldif = "dn: uid=".$username.",ou=People,dc=sucs,dc=org\n";
$ldif .= "uid: ".$username."\n";
$ldif .= "cn: ".$realname."\n";
// if only has 1 part to real name (and therefore a soc) then set it as sn otherwise set first name to given name and last name to sn
if(count($nameexplode)>1){
$ldif .= "givenName: ".$nameexplode[0]."\n";
$ldif .= "sn: ".$nameexplode[count($nameexplode)-1]."\n";
}
else{
$ldif .= "sn: ".$realname."\n";
}
$ldif .= "mail: ".$username."@sucs.org\n";
$ldif .= "objectClass: person\n";
$ldif .= "objectClass: organizationalPerson\n";
$ldif .= "objectClass: inetOrgPerson\n";
$ldif .= "objectClass: posixAccount\n";
$ldif .= "objectClass: top\n";
$ldif .= "userPassword: ".$ldappassword. "\n";
$ldif .= "loginShell: /bin/bash\n";
$ldif .= "uidNumber: ".$uid."\n";
// make some society specific changes
if($type==2){
$gid=113;
$homebase="society";
}
elseif($type==5){
$gid=100;
$homebase="alumni";
}
else {
$gid=100;
$homebase="member";
}
$ldif .= "gidNumber: ".$gid."\n";
$ldif .= "homeDirectory: /home/".$homebase."/".$username."\n";
$ldif .= "gecos: ".$realname."\n\n";
return $ldif;
function generateLdif($uid, $password, $type, $realname, $username)
{
// explode the realname
$nameexplode = explode(' ', trim($realname));
// hash the password
$ldappassword = "{CRYPT}" . cryptPassword($password);
// compile ldif
$ldif = "dn: uid=" . $username . ",ou=People,dc=sucs,dc=org\n";
$ldif .= "uid: " . $username . "\n";
$ldif .= "cn: " . $realname . "\n";
// if only has 1 part to real name (and therefore a soc) then set it as sn otherwise set first name to given name and last name to sn
if (count($nameexplode) > 1) {
$ldif .= "givenName: " . $nameexplode[0] . "\n";
$ldif .= "sn: " . $nameexplode[count($nameexplode) - 1] . "\n";
} else {
$ldif .= "sn: " . $realname . "\n";
}
$ldif .= "mail: " . $username . "@sucs.org\n";
$ldif .= "objectClass: person\n";
$ldif .= "objectClass: organizationalPerson\n";
$ldif .= "objectClass: inetOrgPerson\n";
$ldif .= "objectClass: posixAccount\n";
$ldif .= "objectClass: top\n";
$ldif .= "userPassword: " . $ldappassword . "\n";
$ldif .= "loginShell: /bin/bash\n";
$ldif .= "uidNumber: " . $uid . "\n";
// make some society specific changes
// More like make sure peoples home dirs get made in the right place
if ($type == 2) {
$gid = 1130;
$homebase = "society";
} elseif ($type == 5) {
$gid = 100;
$homebase = "alumni";
} elseif ($type == 3) {
$gid = 100;
$homebase = "honorary";
} elseif ($type == 4) {
$gid = 100;
$homebase = "life";
} else {
$gid = 100;
$homebase = "member";
}
$ldif .= "gidNumber: " . $gid . "\n";
$ldif .= "homeDirectory: /home/" . $homebase . "/" . $username . "\n";
$ldif .= "gecos: " . $realname . "\n\n";
return $ldif;
}
// function to renew a persons sucs membership
function renew_membership($username)
{
// we need to the sucs db here
global $sucsDB;
// get their details from the sucs db
$userdata = $sucsDB->Execute("SELECT * FROM members WHERE username=?", array($username));
// include the date file so we can call the paidUntil function
include_once("date.php");
// Update their record in the DB
$sucsDB->Execute("UPDATE members SET paid=?, lastupdate=DEFAULT, lastedit=? WHERE username=?", array(paidUntil(time()), "99999", $username));
// Give them their 200 print credits
exec("sudo /usr/local/sbin/printerrenew.apache ${username} 200");
// apprently sending them an email confirming so is nice
$message = "Your Swansea University Computer Society (SUCS) membership has been renewed\n\n";
$message .= "Username: ${username}\n";
$message .= "If you do not know or have forgotten your password, please email admin@sucs.org to arrange for it to be changed.\n\n";
$message .= "Regards\n The SUCS admin";
$header = "From: admin@sucs.org\r\n";
$header .= "Reply-To: admin@sucs.org";
// send it to their personal account
mail($userdata->fields['email'], "SUCS account renewal", $message, $header);
}
?>
......@@ -2,94 +2,96 @@
define('_BASE_DN', 'ou=People,dc=sucs,dc=org');
define('_LDAP_SERVER', 'ldap://silver');
class Members {
class Members
{
private $conn; //LDAP connection
private $conn; //LDAP connection
function __construct()
{
// Connect and bind to ldap server
$this->conn = ldap_connect(_LDAP_SERVER);
ldap_set_option($this->conn, LDAP_OPT_PROTOCOL_VERSION, 3);
$bind = ldap_bind($this->conn);
}
function __construct()
{
// Connect and bind to ldap server
$this->conn = ldap_connect(_LDAP_SERVER);
ldap_set_option($this->conn, LDAP_OPT_PROTOCOL_VERSION, 3);
$bind = ldap_bind($this->conn);
}
function getMemberList()
{
function getMemberList()
{
// Search for certain members and retrieve their username and
$search = ldap_search($this->conn, _BASE_DN, 'uid=*');
// Sort By Username
ldap_sort($this->conn, $search, 'uid');
return $this->extractMember($search);
}
return $this->extractMember($search);
}
function memberView($value)
{
$search = ldap_search($this->conn, _BASE_DN, '(uid=' . $this->makeSafeUsername($value) . ')');
return $this->extractMember($search);
function memberView($value)
{
$search = ldap_search($this->conn, _BASE_DN, '(uid=' . $this->makeSafeUsername($value) . ')');
return $this->extractMember($search);
}
}
function memberSearch($value)
{
$search = ldap_search($this->conn, _BASE_DN, '(|(uid=*' . $this->makeSafeUsername($value) . '*)(cn=*' . $this->makeSafeRealName($value) . '*))');
return $this->extractMember($search);
}
function memberSearch($value)
{
$search = ldap_search($this->conn, _BASE_DN, '(|(uid=*' . $this->makeSafeUsername($value) . '*)(cn=*' . $this->makeSafeRealName($value) . '*))');
return $this->extractMember($search);
}
private function extractMember($search)
{
private function extractMember($search)
{
// Produce an array of usernames
$usernames = array();
$entryHandler = ldap_first_entry($this->conn, $search);
while($entryHandler) {
$username = ldap_get_values($this->conn, $entryHandler, 'uid');
$realname = ldap_get_values($this->conn, $entryHandler, 'cn');
$homedir = ldap_get_values($this->conn, $entryHandler, 'homedirectory');
$usernames[] = array( "uid" => $username[0], "cn" => $realname[0], "homedir" => $homedir[0], "website" => false);
$entryHandler = ldap_next_entry($this->conn, $entryHandler);
}
return $usernames;
}
while ($entryHandler) {
$username = ldap_get_values($this->conn, $entryHandler, 'uid');
$realname = ldap_get_values($this->conn, $entryHandler, 'cn');
$homedir = ldap_get_values($this->conn, $entryHandler, 'homedirectory');
$usernames[] = array("uid" => $username[0], "cn" => $realname[0], "homedir" => $homedir[0], "website" => false);
$entryHandler = ldap_next_entry($this->conn, $entryHandler);
}
return $usernames;
}
// Compares two keyed arrays ( array("uid" => ?, "cn" =>) etc)
// by the last word of the "cn" field, which would seem
// to represent the surname
private function cmpSurnames($person1, $person2)
{
private function cmpSurnames($person1, $person2)
{
$names1 = explode(' ', $person1['cn']);
$names2 = explode(' ', $person2['cn']);
return strcmp(array_pop($names1), array_pop($names2));
}
}
// Compares two keyed arrays ( array("uid" => ?, "cn" =>) etc)
// by the first word (and onward) of the "cn" field, which would seem
// to represent the name
private function cmpForenames($person1, $person2)
{
private function cmpForenames($person1, $person2)
{
return strcmp($person1['cn'], $person2['cn']);
}
}
// Converts a given string to something that can
// safely be used as a username to search for (although
// this doesn't necessarily mean it's a valid username).
private function makeSafeUserName($username)
{
private function makeSafeUserName($username)
{
$username = trim(strtolower($username));
return preg_replace('[^a-z0-9_]', '', $username);
}
}
// Converts a given string to something that can
// safely be used as a real name to search for
private function makeSafeRealName($username)
{
private function makeSafeRealName($username)
{
$username = trim(strtolower($username));
return preg_replace('[^a-z0-9_ ]', '', $username);
}
}
}
?>
......@@ -2,28 +2,20 @@
/* mechanism for members to give us feedback about web pages */
// where do website feedback mails go?
$contact = "chckens@sucs.org";
$contact = "devel@lists.sucs.org";
if ($session->loggedin) {
if ($_REQUEST['action'] == "feedback") {
$feedback = $_REQUEST['feedback'];
$msgbody = "{$session->username} had this to say about the page {$_SERVER['REQUEST_URI']}:\r\n\r\n";
$msgbody .= "\"{$feedback}\"\r\n";
mail($contact, "SUCS Website Feedback", $msgbody);
$smarty->assign("feedbacked", TRUE);
}
$secondary = $smarty->fetch("feedback.tpl");
$smarty->append("secondary", $secondary);
}
if ($_REQUEST["action"] == "feedback" && $_REQUEST["feedback"] != "") {
$feedback = $_REQUEST["feedback"];
$msgbody = "{$session->username} had this to say about the page {$_SERVER['REQUEST_URI']}:\r\n\r\n";
$msgbody .= "\"{$feedback}\"\r\n";
mail($contact, "SUCS Website Feedback", $msgbody);
$smarty->assign("feedbacked", TRUE);
}
$smarty->fetch("feedback.tpl");
}
?>
<?php
function piechart($title, $slice, $itemName, $fsizes = 0)
{
function matchset($xx)
{
$arrx = array_values($xx);
$i = 0;
while (list ($key, $val) = each($arrx)) {
$xy[$i] = $val;
$i++;
}
$cnt = $i;
return $xy;
}
$sliced = matchset($slice);
$countqw = count($sliced);
$ItemNames = matchset($itemName);
// initialize some variables
$sum = 0;
$degrees = Array();
$diameter = 250;
$radius = $diameter / 2;
// calculate sum of slices
for ($x = 0; $x < $countqw; $x++) {
$sum += $sliced[$x];
}
// convert each slice into corresponding percentage of 360-degree circle
$degCount = 0;
for ($y = 0; $y < $countqw; $y++) {
if ((($sliced[$y] / $sum) * 360) > '0') {
$degrees[$degCount] = ($sliced[$y] / $sum) * 360;
$degCount++;
}
}
// set up image and colours
Header("Content-Type: image/png");
$im = ImageCreate(550, 300);
$black = ImageColorAllocateAlpha($im, 0, 0, 0, 0);
$white = ImageColorAllocateAlpha($im, 255, 255, 255, 127);
$hexCode = array("255,153,0", "0,204,153", "204,255,102", "255,102,102", "102,204,255", "204,153,255", "255,0,0", "51,0,255", "255,51,153", "204,0,255", "255,255,51", "51,255,51", "255,102,0");
// fill image with white
ImageFill($im, 0, 0, $white);
// draw baseline
ImageLine($im, 150, 150, 225, 150, $black);
for ($z = 0; $z < $countqw; $z++) {
// calculate and draw arc corresponding to each slice
ImageArc($im, 150, 150, $diameter, $diameter, $last_angle,
($last_angle + $degrees[$z]), $black);
$last_angle = $last_angle + $degrees[$z];
// calculate coordinate of end-point of each arc by obtaining
// length of segment and adding radius
// remember that cos() and sin() return value in radians
// and have to be converted back to degrees!
$end_x = round(150 + ($radius * cos($last_angle * pi() / 180)));
$end_y = round(150 + ($radius * sin($last_angle * pi() / 180)));
// demarcate slice with another line
ImageLine($im, 150, 150, $end_x, $end_y, $black);
}
// this section is meant to calculate the mid-point of each slice
// so that it can be filled with colour
// initialize some variables
$prev_angle = 0;
$pointer = 0;
for ($z = 0; $z < $countqw; $z++) {
// to calculate mid-point of a slice, the procedure is to use an angle
//bisector
// and then obtain the mid-point of that bisector
$pointer = $prev_angle + $degrees[$z];
$this_angle = ($prev_angle + $pointer) / 2;
$prev_angle = $pointer;
// get end-point of angle bisector
$end_x = round(150 + ($radius * cos($this_angle * pi() / 180)));
$end_y = round(150 + ($radius * sin($this_angle * pi() / 180)));
// given start point (150,150) and end-point above, mid-point can be
// calculated with standard mid-point formula
$mid_x = round((150 + ($end_x)) / 2);
$mid_y = round((150 + ($end_y)) / 2);
// depending on which slice, fill with appropriate colour
$hexCodeSplit = explode(',', $hexCode[$z]);
$WedgeColor = ImageColorAllocate($im, $hexCodeSplit[0], $hexCodeSplit[1], $hexCodeSplit[2]);
ImageFillToBorder($im, $mid_x, $mid_y, $black, $WedgeColor);
}
// write string
ImageString($im, 5, 250, 10, "$title", $black);
$red = ImageColorAllocate($im, 255, 153, 153);
$blue = ImageColorAllocate($im, 0, 0, 255);
// Create Color key and slice description
$adjPosition = 40;
for ($z = 0; $z < $degCount; $z++) {
$percent = ($degrees[$z] / 360) * 100;
$percent = round($percent, 2);
$adjPosition = $adjPosition + 15;
$hexCodeSplit = explode(',', $hexCode[$z]);
$percentLen = strlen($percent);
if ($percentLen == '4') {
$percent = " " . "$percent";
}
if ($percentLen == '3') {
$percent = " " . "$percent";
}
if ($percentLen == '2') {
$percent = " " . "$percent";
}
if ($percentLen == '1') {
$percent = " " . "$percent";
}
ImageString($im, 2, 300, ($adjPosition + 1), "$percent%", $black);
$WedgeColor = ImageColorAllocate($im, $hexCodeSplit[0], $hexCodeSplit[1], $hexCodeSplit[2]);
ImageFilledRectangle($im, 340, $adjPosition, 350, ($adjPosition + 10), $black);
ImageFilledRectangle($im, 341, ($adjPosition + 1), 349, ($adjPosition + 9), $WedgeColor);
if ($fsizes) {
if ($sliced[$z] >= "1000" && $sliced[$z] < "1000000") {
$sliced[$z] = $sliced[$z] / 1000;
$sliced[$z] = sprintf("%01.2f", "$sliced[$z]") . "G";
} else
$sliced[$z] = "$sliced[$z]" . "M";
}
$sliceLen = strlen($sliced[$z]);
if ($sliceLen == '5') {
$sliced[$z] = " " . "$sliced[$z]";
}
if ($sliceLen == '4') {
$sliced[$z] = " " . "$sliced[$z]";
}
if ($sliceLen == '3') {
$sliced[$z] = " " . "$sliced[$z]";
}
if ($sliceLen == '2') {
$sliced[$z] = " " . "$sliced[$z]";
}
if ($sliceLen == '1') {
$sliced[$z] = " " . "$sliced[$z]";
}
ImageString($im, 2, 360, ($adjPosition + 1), "$sliced[$z]", $black);
ImageString($im, 2, 410, ($adjPosition + 1), "$ItemNames[$z]", $black);
}
// output to browser
ImagePNG($im);
}
?>
<?php
/***********************************************************************
Copyright (C) 2002-2008 PunBB
This file is part of PunBB.
PunBB is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published
by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
PunBB is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston,
MA 02111-1307 USA
************************************************************************/
// Tell header.php to use the admin template
define('PUN_ADMIN_CONSOLE', 1);
define('PUN_ROOT', './');
require PUN_ROOT.'include/common.php';
require PUN_ROOT.'include/common_admin.php';
if ($pun_user['g_id'] > PUN_MOD || ($pun_user['g_id'] == PUN_MOD && $pun_config['p_mod_ban_users'] == '0'))
message($lang_common['No permission']);
// Add/edit a ban (stage 1)
if (isset($_REQUEST['add_ban']) || isset($_GET['edit_ban']))
{
if (isset($_GET['add_ban']) || isset($_POST['add_ban']))
{
// If the id of the user to ban was provided through GET (a link from profile.php)
if (isset($_GET['add_ban']))
{
$add_ban = intval($_GET['add_ban']);
if ($add_ban < 2)
message($lang_common['Bad request']);
$user_id = $add_ban;
$result = $db->query('SELECT group_id, username, email FROM '.$db->prefix.'users WHERE id='.$user_id) or error('Unable to fetch user info', __FILE__, __LINE__, $db->error());
if ($db->num_rows($result))
list($group_id, $ban_user, $ban_email) = $db->fetch_row($result);
else
message('No user by that ID registered.');
}
else // Otherwise the username is in POST
{
$ban_user = trim($_POST['new_ban_user']);
if ($ban_user != '')
{
$result = $db->query('SELECT id, group_id, username, email FROM '.$db->prefix.'users WHERE username=\''.$db->escape($ban_user).'\' AND id>1') or error('Unable to fetch user info', __FILE__, __LINE__, $db->error());
if ($db->num_rows($result))
list($user_id, $group_id, $ban_user, $ban_email) = $db->fetch_row($result);
else
message('No user by that username registered. If you want to add a ban not tied to a specific username just leave the username blank.');
}
}
// Make sure we're not banning an admin
if (isset($group_id) && $group_id == PUN_ADMIN)
message('The user '.pun_htmlspecialchars($ban_user).' is an administrator and can\'t be banned. If you want to ban an administrator, you must first demote him/her to moderator or user.');
// If we have a $user_id, we can try to find the last known IP of that user
if (isset($user_id))
{
$result = $db->query('SELECT poster_ip FROM '.$db->prefix.'posts WHERE poster_id='.$user_id.' ORDER BY posted DESC LIMIT 1') or error('Unable to fetch post info', __FILE__, __LINE__, $db->error());
$ban_ip = ($db->num_rows($result)) ? $db->result($result) : '';
}
$mode = 'add';
}
else // We are editing a ban
{
$ban_id = intval($_GET['edit_ban']);
if ($ban_id < 1)
message($lang_common['Bad request']);
$result = $db->query('SELECT username, ip, email, message, expire FROM '.$db->prefix.'bans WHERE id='.$ban_id) or error('Unable to fetch ban info', __FILE__, __LINE__, $db->error());
if ($db->num_rows($result))
list($ban_user, $ban_ip, $ban_email, $ban_message, $ban_expire) = $db->fetch_row($result);
else
message($lang_common['Bad request']);
$ban_expire = ($ban_expire != '') ? date('Y-m-d', $ban_expire) : '';
$mode = 'edit';
}
$page_title = pun_htmlspecialchars($pun_config['o_board_title']).' / Admin / Bans';
$focus_element = array('bans2', 'ban_user');
require PUN_ROOT.'header.php';
generate_admin_menu('bans');
?>
<div class="blockform">
<h2><span>Ban advanced settings</span></h2>
<div class="box">
<form id="bans2" method="post" action="admin_bans.php">
<div class="inform">
<input type="hidden" name="mode" value="<?php echo $mode ?>" />
<?php if ($mode == 'edit'): ?> <input type="hidden" name="ban_id" value="<?php echo $ban_id ?>" />
<?php endif; ?> <fieldset>
<legend>Supplement ban with IP and e-mail</legend>
<div class="infldset">
<table class="aligntop" cellspacing="0">
<tr>
<th scope="row">Username</th>
<td>
<input type="text" name="ban_user" size="25" maxlength="25" value="<?php if (isset($ban_user)) echo pun_htmlspecialchars($ban_user); ?>" tabindex="1" />
<span>The username to ban.</span>
</td>
</tr>
<tr>
<th scope="row">IP-adresses</th>
<td>
<input type="text" name="ban_ip" size="45" maxlength="255" value="<?php if (isset($ban_ip)) echo $ban_ip; ?>" tabindex="2" />
<span>The IP or IP-ranges you wish to ban (e.g. 150.11.110.1 or 150.11.110). Separate addresses with spaces. If an IP is entered already it is the last known IP of this user in the database.<?php if ($ban_user != '' && isset($user_id)) echo ' Click <a href="admin_users.php?ip_stats='.$user_id.'">here</a> to see IP statistics for this user.' ?></span>
</td>
</tr>
<tr>
<th scope="row">E-mail/domain</th>
<td>
<input type="text" name="ban_email" size="40" maxlength="50" value="<?php if (isset($ban_email)) echo strtolower($ban_email); ?>" tabindex="3" />
<span>The e-mail or e-mail domain you wish to ban (e.g. someone@somewhere.com or somewhere.com). See "Allow banned e-mail addresses" in Options for more info.</span>
</td>
</tr>
</table>
<p class="topspace"><strong class="warntext">You should be very careful when banning an IP-range because of the possibility of multiple users matching the same partial IP.</strong></p>
</div>
</fieldset>
</div>
<div class="inform">
<fieldset>
<legend>Ban message and expiry</legend>
<div class="infldset">
<table class="aligntop" cellspacing="0">
<tr>
<th scope="row">Ban message</th>
<td>
<input type="text" name="ban_message" size="50" maxlength="255" value="<?php if (isset($ban_message)) echo pun_htmlspecialchars($ban_message); ?>" tabindex="4" />
<span>A message that will be displayed to the banned user when he/she visits the forums.</span>
</td>
</tr>
<tr>
<th scope="row">Expire date</th>
<td>
<input type="text" name="ban_expire" size="17" maxlength="10" value="<?php if (isset($ban_expire)) echo $ban_expire; ?>" tabindex="5" />
<span>The date when this ban should be automatically removed (format: YYYY-MM-DD). Leave blank to remove manually.</span>
</td>
</tr>
</table>
</div>
</fieldset>
</div>
<p class="submitend"><input type="submit" name="add_edit_ban" value=" Save " tabindex="6" /></p>
</form>
</div>
</div>
<div class="clearer"></div>
</div>
<?php
require PUN_ROOT.'footer.php';
}
// Add/edit a ban (stage 2)
else if (isset($_POST['add_edit_ban']))
{
confirm_referrer('admin_bans.php');
$ban_user = trim($_POST['ban_user']);
$ban_ip = trim($_POST['ban_ip']);
$ban_email = strtolower(trim($_POST['ban_email']));
$ban_message = trim($_POST['ban_message']);
$ban_expire = trim($_POST['ban_expire']);
if ($ban_user == '' && $ban_ip == '' && $ban_email == '')
message('You must enter either a username, an IP address or an e-mail address (at least).');
else if (strtolower($ban_user) == 'guest')
message('The guest user cannot be banned.');
// Validate IP/IP range (it's overkill, I know)
if ($ban_ip != '')
{
$ban_ip = preg_replace('/[\s]{2,}/', ' ', $ban_ip);
$addresses = explode(' ', $ban_ip);
$addresses = array_map('trim', $addresses);
for ($i = 0; $i < count($addresses); ++$i)
{
$octets = explode('.', $addresses[$i]);
for ($c = 0; $c < count($octets); ++$c)
{
$octets[$c] = (strlen($octets[$c]) > 1) ? ltrim($octets[$c], "0") : $octets[$c];
if ($c > 3 || preg_match('/[^0-9]/', $octets[$c]) || intval($octets[$c]) > 255)
message('You entered an invalid IP/IP-range.');
}
$cur_address = implode('.', $octets);
$addresses[$i] = $cur_address;
}
$ban_ip = implode(' ', $addresses);
}
require PUN_ROOT.'include/email.php';
if ($ban_email != '' && !is_valid_email($ban_email))
{
if (!preg_match('/^[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/', $ban_email))
message('The e-mail address (e.g. user@domain.com) or partial e-mail address domain (e.g. domain.com) you entered is invalid.');
}
if ($ban_expire != '' && $ban_expire != 'Never')
{
$ban_expire = strtotime($ban_expire);
if ($ban_expire == -1 || $ban_expire <= time())
message('You entered an invalid expire date. The format should be YYYY-MM-DD and the date must be at least one day in the future.');
}
else
$ban_expire = 'NULL';
$ban_user = ($ban_user != '') ? '\''.$db->escape($ban_user).'\'' : 'NULL';
$ban_ip = ($ban_ip != '') ? '\''.$db->escape($ban_ip).'\'' : 'NULL';
$ban_email = ($ban_email != '') ? '\''.$db->escape($ban_email).'\'' : 'NULL';
$ban_message = ($ban_message != '') ? '\''.$db->escape($ban_message).'\'' : 'NULL';
if ($_POST['mode'] == 'add')
$db->query('INSERT INTO '.$db->prefix.'bans (username, ip, email, message, expire) VALUES('.$ban_user.', '.$ban_ip.', '.$ban_email.', '.$ban_message.', '.$ban_expire.')') or error('Unable to add ban', __FILE__, __LINE__, $db->error());
else
$db->query('UPDATE '.$db->prefix.'bans SET username='.$ban_user.', ip='.$ban_ip.', email='.$ban_email.', message='.$ban_message.', expire='.$ban_expire.' WHERE id='.intval($_POST['ban_id'])) or error('Unable to update ban', __FILE__, __LINE__, $db->error());
// Regenerate the bans cache
require_once PUN_ROOT.'include/cache.php';
generate_bans_cache();
redirect('admin_bans.php', 'Ban '.(($_POST['mode'] == 'edit') ? 'edited' : 'added').'. Redirecting &hellip;');
}
// Remove a ban
else if (isset($_GET['del_ban']))
{
confirm_referrer('admin_bans.php');
$ban_id = intval($_GET['del_ban']);
if ($ban_id < 1)
message($lang_common['Bad request']);
$db->query('DELETE FROM '.$db->prefix.'bans WHERE id='.$ban_id) or error('Unable to delete ban', __FILE__, __LINE__, $db->error());
// Regenerate the bans cache
require_once PUN_ROOT.'include/cache.php';
generate_bans_cache();
redirect('admin_bans.php', 'Ban removed. Redirecting &hellip;');
}
$page_title = pun_htmlspecialchars($pun_config['o_board_title']).' / Admin / Bans';
$focus_element = array('bans', 'new_ban_user');
require PUN_ROOT.'header.php';
generate_admin_menu('bans');
?>
<div class="blockform">
<h2><span>New ban</span></h2>
<div class="box">
<form id="bans" method="post" action="admin_bans.php?action=more">
<div class="inform">
<fieldset>
<legend>Add ban</legend>
<div class="infldset">
<table class="aligntop" cellspacing="0">
<tr>
<th scope="row">Username<div><input type="submit" name="add_ban" value=" Add " tabindex="2" /></div></th>
<td>
<input type="text" name="new_ban_user" size="25" maxlength="25" tabindex="1" />
<span>The username to ban (case insensitive). The next page will let you enter a custom IP and e-mail. If you just want to ban a specific IP/IP-range or e-mail just leave it blank.</span>
</td>
</tr>
</table>
</div>
</fieldset>
</div>
</form>
</div>
<h2 class="block2"><span>Existing bans</span></h2>
<div class="box">
<div class="fakeform">
<?php
$result = $db->query('SELECT id, username, ip, email, message, expire FROM '.$db->prefix.'bans ORDER BY id') or error('Unable to fetch ban list', __FILE__, __LINE__, $db->error());
if ($db->num_rows($result))
{
while ($cur_ban = $db->fetch_assoc($result))
{
$expire = format_time($cur_ban['expire'], true);
?>
<div class="inform">
<fieldset>
<legend>Ban expires: <?php echo $expire ?></legend>
<div class="infldset">
<table cellspacing="0">
<?php if ($cur_ban['username'] != ''): ?> <tr>
<th>Username</th>
<td><?php echo pun_htmlspecialchars($cur_ban['username']) ?></td>
</tr>
<?php endif; ?><?php if ($cur_ban['email'] != ''): ?> <tr>
<th>E-mail</th>
<td><?php echo $cur_ban['email'] ?></td>
</tr>
<?php endif; ?><?php if ($cur_ban['ip'] != ''): ?> <tr>
<th>IP/IP-ranges</th>
<td><?php echo $cur_ban['ip'] ?></td>
</tr>
<?php endif; ?><?php if ($cur_ban['message'] != ''): ?> <tr>
<th>Reason</th>
<td><?php echo pun_htmlspecialchars($cur_ban['message']) ?></td>
</tr>
<?php endif; ?> </table>
<p class="linkactions"><a href="admin_bans.php?edit_ban=<?php echo $cur_ban['id'] ?>">Edit</a> - <a href="admin_bans.php?del_ban=<?php echo $cur_ban['id'] ?>">Remove</a></p>
</div>
</fieldset>
</div>
<?php
}
}
else
echo "\t\t\t\t".'<p>No bans in list.</p>'."\n";
?>
</div>
</div>
</div>
<div class="clearer"></div>
</div>
<?php
require PUN_ROOT.'footer.php';
<?php
/***********************************************************************
Copyright (C) 2002-2008 PunBB
This file is part of PunBB.
PunBB is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published
by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
PunBB is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston,
MA 02111-1307 USA
************************************************************************/
// Tell header.php to use the admin template
define('PUN_ADMIN_CONSOLE', 1);
define('PUN_ROOT', './');
require PUN_ROOT.'include/common.php';
require PUN_ROOT.'include/common_admin.php';
if ($pun_user['g_id'] > PUN_ADMIN)
message($lang_common['No permission']);
// Add a new category
if (isset($_POST['add_cat']))
{
confirm_referrer('admin_categories.php');
$new_cat_name = trim($_POST['new_cat_name']);
if ($new_cat_name == '')
message('You must enter a name for the category.');
$db->query('INSERT INTO '.$db->prefix.'categories (cat_name) VALUES(\''.$db->escape($new_cat_name).'\')') or error('Unable to create category', __FILE__, __LINE__, $db->error());
redirect('admin_categories.php', 'Category added. Redirecting &hellip;');
}
// Delete a category
else if (isset($_POST['del_cat']) || isset($_POST['del_cat_comply']))
{
confirm_referrer('admin_categories.php');
$cat_to_delete = intval($_POST['cat_to_delete']);
if ($cat_to_delete < 1)
message($lang_common['Bad request']);
if (isset($_POST['del_cat_comply'])) // Delete a category with all forums and posts
{
@set_time_limit(0);
$result = $db->query('SELECT id FROM '.$db->prefix.'forums WHERE cat_id='.$cat_to_delete) or error('Unable to fetch forum list', __FILE__, __LINE__, $db->error());
$num_forums = $db->num_rows($result);
for ($i = 0; $i < $num_forums; ++$i)
{
$cur_forum = $db->result($result, $i);
// Prune all posts and topics
prune($cur_forum, 1, -1);
// Delete the forum
$db->query('DELETE FROM '.$db->prefix.'forums WHERE id='.$cur_forum) or error('Unable to delete forum', __FILE__, __LINE__, $db->error());
}
// Locate any "orphaned redirect topics" and delete them
$result = $db->query('SELECT t1.id FROM '.$db->prefix.'topics AS t1 LEFT JOIN '.$db->prefix.'topics AS t2 ON t1.moved_to=t2.id WHERE t2.id IS NULL AND t1.moved_to IS NOT NULL') or error('Unable to fetch redirect topics', __FILE__, __LINE__, $db->error());
$num_orphans = $db->num_rows($result);
if ($num_orphans)
{
for ($i = 0; $i < $num_orphans; ++$i)
$orphans[] = $db->result($result, $i);
$db->query('DELETE FROM '.$db->prefix.'topics WHERE id IN('.implode(',', $orphans).')') or error('Unable to delete redirect topics', __FILE__, __LINE__, $db->error());
}
// Delete the category
$db->query('DELETE FROM '.$db->prefix.'categories WHERE id='.$cat_to_delete) or error('Unable to delete category', __FILE__, __LINE__, $db->error());
// Regenerate the quickjump cache
require_once PUN_ROOT.'include/cache.php';
generate_quickjump_cache();
redirect('admin_categories.php', 'Category deleted. Redirecting &hellip;');
}
else // If the user hasn't comfirmed the delete
{
$result = $db->query('SELECT cat_name FROM '.$db->prefix.'categories WHERE id='.$cat_to_delete) or error('Unable to fetch category info', __FILE__, __LINE__, $db->error());
$cat_name = $db->result($result);
$page_title = pun_htmlspecialchars($pun_config['o_board_title']).' / Admin / Categories';
require PUN_ROOT.'header.php';
generate_admin_menu('categories');
?>
<div class="blockform">
<h2><span>Category delete</span></h2>
<div class="box">
<form method="post" action="admin_categories.php">
<div class="inform">
<input type="hidden" name="cat_to_delete" value="<?php echo $cat_to_delete ?>" />
<fieldset>
<legend>Confirm delete category</legend>
<div class="infldset">
<p>Are you sure that you want to delete the category "<?php echo pun_htmlspecialchars($cat_name) ?>"?</p>
<p>WARNING! Deleting a category will delete all forums and posts (if any) in that category!</p>
</div>
</fieldset>
</div>
<p><input type="submit" name="del_cat_comply" value="Delete" /><a href="javascript:history.go(-1)">Go back</a></p>
</form>
</div>
</div>
<div class="clearer"></div>
</div>
<?php
require PUN_ROOT.'footer.php';
}
}
else if (isset($_POST['update'])) // Change position and name of the categories
{
confirm_referrer('admin_categories.php');
$cat_order = $_POST['cat_order'];
$cat_name = $_POST['cat_name'];
$result = $db->query('SELECT id, disp_position FROM '.$db->prefix.'categories ORDER BY disp_position') or error('Unable to fetch category list', __FILE__, __LINE__, $db->error());
$num_cats = $db->num_rows($result);
for ($i = 0; $i < $num_cats; ++$i)
{
if ($cat_name[$i] == '')
message('You must enter a category name.');
if (!@preg_match('#^\d+$#', $cat_order[$i]))
message('Position must be an integer value.');
list($cat_id, $position) = $db->fetch_row($result);
$db->query('UPDATE '.$db->prefix.'categories SET cat_name=\''.$db->escape($cat_name[$i]).'\', disp_position='.$cat_order[$i].' WHERE id='.$cat_id) or error('Unable to update category', __FILE__, __LINE__, $db->error());
}
// Regenerate the quickjump cache
require_once PUN_ROOT.'include/cache.php';
generate_quickjump_cache();
redirect('admin_categories.php', 'Categories updated. Redirecting &hellip;');
}
// Generate an array with all categories
$result = $db->query('SELECT id, cat_name, disp_position FROM '.$db->prefix.'categories ORDER BY disp_position') or error('Unable to fetch category list', __FILE__, __LINE__, $db->error());
$num_cats = $db->num_rows($result);
for ($i = 0; $i < $num_cats; ++$i)
$cat_list[] = $db->fetch_row($result);
$page_title = pun_htmlspecialchars($pun_config['o_board_title']).' / Admin / Categories';
require PUN_ROOT.'header.php';
generate_admin_menu('categories');
?>
<div class="blockform">
<h2><span>Add/remove/edit categories</span></h2>
<div class="box">
<form method="post" action="admin_categories.php?action=foo">
<div class="inform">
<fieldset>
<legend>Add/delete categories</legend>
<div class="infldset">
<table class="aligntop" cellspacing="0">
<tr>
<th scope="row">Add a new category<div><input type="submit" name="add_cat" value="Add New" tabindex="2" /></div></th>
<td>
<input type="text" name="new_cat_name" size="35" maxlength="80" tabindex="1" />
<span>The name of the new category you want to add. You can edit the name of the category later (see below).Go to <a href="admin_forums.php">Forums</a> to add forums to your new category.</span>
</td>
</tr>
<?php if ($num_cats): ?> <tr>
<th scope="row">Delete a category<div><input type="submit" name="del_cat" value="Delete" tabindex="4" /></div></th>
<td>
<select name="cat_to_delete" tabindex="3">
<?php
while (list(, list($cat_id, $cat_name, ,)) = @each($cat_list))
echo "\t\t\t\t\t\t\t\t\t\t".'<option value="'.$cat_id.'">'.pun_htmlspecialchars($cat_name).'</option>'."\n";
?>
</select>
<span>Select the name of the category you want to delete. You will be asked to confirm your choice of category for deletion before it is deleted.</span>
</td>
</tr>
<?php endif; ?> </table>
</div>
</fieldset>
</div>
<?php if ($num_cats): ?> <div class="inform">
<fieldset>
<legend>Edit categories</legend>
<div class="infldset">
<table id="categoryedit" cellspacing="0" >
<thead>
<tr>
<th class="tcl" scope="col">Name</th>
<th scope="col">Position</th>
<th>&nbsp;</th>
</tr>
</thead>
<tbody>
<?php
@reset($cat_list);
for ($i = 0; $i < $num_cats; ++$i)
{
list(, list($cat_id, $cat_name, $position)) = @each($cat_list);
?>
<tr><td><input type="text" name="cat_name[<?php echo $i ?>]" value="<?php echo pun_htmlspecialchars($cat_name) ?>" size="35" maxlength="80" /></td><td><input type="text" name="cat_order[<?php echo $i ?>]" value="<?php echo $position ?>" size="3" maxlength="3" /></td><td>&nbsp;</td></tr>
<?php
}
?>
</tbody>
</table>
<div class="fsetsubmit"><input type="submit" name="update" value="Update" /></div>
</div>
</fieldset>
</div>
<?php endif; ?> </form>
</div>
</div>
<div class="clearer"></div>
</div>
<?php
require PUN_ROOT.'footer.php';
<?php
/***********************************************************************
Copyright (C) 2002-2008 PunBB
This file is part of PunBB.
PunBB is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published
by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
PunBB is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston,
MA 02111-1307 USA
************************************************************************/
// Tell header.php to use the admin template
define('PUN_ADMIN_CONSOLE', 1);
define('PUN_ROOT', './');
require PUN_ROOT.'include/common.php';
require PUN_ROOT.'include/common_admin.php';
if ($pun_user['g_id'] > PUN_MOD)
message($lang_common['No permission']);
// Add a censor word
if (isset($_POST['add_word']))
{
confirm_referrer('admin_censoring.php');
$search_for = trim($_POST['new_search_for']);
$replace_with = trim($_POST['new_replace_with']);
if ($search_for == '' || $replace_with == '')
message('You must enter both a word to censor and text to replace it with.');
$db->query('INSERT INTO '.$db->prefix.'censoring (search_for, replace_with) VALUES (\''.$db->escape($search_for).'\', \''.$db->escape($replace_with).'\')') or error('Unable to add censor word', __FILE__, __LINE__, $db->error());
redirect('admin_censoring.php', 'Censor word added. Redirecting &hellip;');
}
// Update a censor word
else if (isset($_POST['update']))
{
confirm_referrer('admin_censoring.php');
$id = intval(key($_POST['update']));
$search_for = trim($_POST['search_for'][$id]);
$replace_with = trim($_POST['replace_with'][$id]);
if ($search_for == '' || $replace_with == '')
message('You must enter both text to search for and text to replace with.');
$db->query('UPDATE '.$db->prefix.'censoring SET search_for=\''.$db->escape($search_for).'\', replace_with=\''.$db->escape($replace_with).'\' WHERE id='.$id) or error('Unable to update censor word', __FILE__, __LINE__, $db->error());
redirect('admin_censoring.php', 'Censor word updated. Redirecting &hellip;');
}
// Remove a censor word
else if (isset($_POST['remove']))
{
confirm_referrer('admin_censoring.php');
$id = intval(key($_POST['remove']));
$db->query('DELETE FROM '.$db->prefix.'censoring WHERE id='.$id) or error('Unable to delete censor word', __FILE__, __LINE__, $db->error());
redirect('admin_censoring.php', 'Censor word removed. Redirecting &hellip;');
}
$page_title = pun_htmlspecialchars($pun_config['o_board_title']).' / Admin / Censoring';
$focus_element = array('censoring', 'new_search_for');
require PUN_ROOT.'header.php';
generate_admin_menu('censoring');
?>
<div class="blockform">
<h2><span>Censoring</span></h2>
<div class="box">
<form id="censoring" method="post" action="admin_censoring.php?action=foo">
<div class="inform">
<fieldset>
<legend>Add word</legend>
<div class="infldset">
<p>Enter a word that you want to censor and the replacement text for this word. Wildcards are accepted (i.e. *some* would match somewhere and lonesome). Censor words also affect usernames. New users will not be able to register with usernames containing any censored words. The search is case insensitive. <strong>Censor words must be enabled in <a href="admin_options.php#censoring">Options</a> for this to have any effect.</strong></p>
<table cellspacing="0">
<thead>
<tr>
<th class="tcl" scope="col">Censored&nbsp;word</th>
<th class="tc2" scope="col">Replacement&nbsp;text</th>
<th class="hidehead" scope="col">Action</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="new_search_for" size="24" maxlength="60" tabindex="1" /></td>
<td><input type="text" name="new_replace_with" size="24" maxlength="60" tabindex="2" /></td>
<td><input type="submit" name="add_word" value=" Add " tabindex="3" /></td>
</tr>
</tbody>
</table>
</div>
</fieldset>
</div>
<div class="inform">
<fieldset>
<legend>Edit/remove words</legend>
<div class="infldset">
<?php
$result = $db->query('SELECT id, search_for, replace_with FROM '.$db->prefix.'censoring ORDER BY id') or error('Unable to fetch censor word list', __FILE__, __LINE__, $db->error());
if ($db->num_rows($result))
{
?>
<table cellspacing="0" >
<thead>
<tr>
<th class="tcl" scope="col">Censored&nbsp;word</th>
<th class="tc2" scope="col">Replacement&nbsp;text</th>
<th class="hidehead" scope="col">Actions</th>
</tr>
</thead>
<tbody>
<?php
while ($cur_word = $db->fetch_assoc($result))
echo "\t\t\t\t\t\t\t\t".'<tr><td><input type="text" name="search_for['.$cur_word['id'].']" value="'.pun_htmlspecialchars($cur_word['search_for']).'" size="24" maxlength="60" /></td><td><input type="text" name="replace_with['.$cur_word['id'].']" value="'.pun_htmlspecialchars($cur_word['replace_with']).'" size="24" maxlength="60" /></td><td><input type="submit" name="update['.$cur_word['id'].']" value="Update" />&nbsp;<input type="submit" name="remove['.$cur_word['id'].']" value="Remove" /></td></tr>'."\n";
?>
</tbody>
</table>
<?php
}
else
echo "\t\t\t\t\t\t\t".'<p>No censor words in list.</p>'."\n";
?>
</div>
</fieldset>
</div>
</form>
</div>
</div>
<div class="clearer"></div>
</div>
<?php
require PUN_ROOT.'footer.php';
<?php
/***********************************************************************
Copyright (C) 2002-2008 PunBB
This file is part of PunBB.
PunBB is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published
by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
PunBB is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston,
MA 02111-1307 USA
************************************************************************/
// Tell header.php to use the admin template
define('PUN_ADMIN_CONSOLE', 1);
define('PUN_ROOT', './');
require PUN_ROOT.'include/common.php';
require PUN_ROOT.'include/common_admin.php';
if ($pun_user['g_id'] > PUN_ADMIN)
message($lang_common['No permission']);
// Add a "default" forum
if (isset($_POST['add_forum']))
{
confirm_referrer('admin_forums.php');
$add_to_cat = intval($_POST['add_to_cat']);
if ($add_to_cat < 1)
message($lang_common['Bad request']);
$db->query('INSERT INTO '.$db->prefix.'forums (cat_id) VALUES('.$add_to_cat.')') or error('Unable to create forum', __FILE__, __LINE__, $db->error());
// Regenerate the quickjump cache
require_once PUN_ROOT.'include/cache.php';
generate_quickjump_cache();
redirect('admin_forums.php', 'Forum added. Redirecting &hellip;');
}
// Delete a forum
else if (isset($_GET['del_forum']))
{
confirm_referrer('admin_forums.php');
$forum_id = intval($_GET['del_forum']);
if ($forum_id < 1)
message($lang_common['Bad request']);
if (isset($_POST['del_forum_comply'])) // Delete a forum with all posts
{
@set_time_limit(0);
// Prune all posts and topics
prune($forum_id, 1, -1);
// Locate any "orphaned redirect topics" and delete them
$result = $db->query('SELECT t1.id FROM '.$db->prefix.'topics AS t1 LEFT JOIN '.$db->prefix.'topics AS t2 ON t1.moved_to=t2.id WHERE t2.id IS NULL AND t1.moved_to IS NOT NULL') or error('Unable to fetch redirect topics', __FILE__, __LINE__, $db->error());
$num_orphans = $db->num_rows($result);
if ($num_orphans)
{
for ($i = 0; $i < $num_orphans; ++$i)
$orphans[] = $db->result($result, $i);
$db->query('DELETE FROM '.$db->prefix.'topics WHERE id IN('.implode(',', $orphans).')') or error('Unable to delete redirect topics', __FILE__, __LINE__, $db->error());
}
// Delete the forum and any forum specific group permissions
$db->query('DELETE FROM '.$db->prefix.'forums WHERE id='.$forum_id) or error('Unable to delete forum', __FILE__, __LINE__, $db->error());
$db->query('DELETE FROM '.$db->prefix.'forum_perms WHERE forum_id='.$forum_id) or error('Unable to delete group forum permissions', __FILE__, __LINE__, $db->error());
// Regenerate the quickjump cache
require_once PUN_ROOT.'include/cache.php';
generate_quickjump_cache();
redirect('admin_forums.php', 'Forum deleted. Redirecting &hellip;');
}
else // If the user hasn't confirmed the delete
{
$result = $db->query('SELECT forum_name FROM '.$db->prefix.'forums WHERE id='.$forum_id) or error('Unable to fetch forum info', __FILE__, __LINE__, $db->error());
$forum_name = pun_htmlspecialchars($db->result($result));
$page_title = pun_htmlspecialchars($pun_config['o_board_title']).' / Admin / Forums';
require PUN_ROOT.'header.php';
generate_admin_menu('forums');
?>
<div class="blockform">
<h2><span>Confirm delete forum</span></h2>
<div class="box">
<form method="post" action="admin_forums.php?del_forum=<?php echo $forum_id ?>">
<div class="inform">
<fieldset>
<legend>Important! Read before deleting</legend>
<div class="infldset">
<p>Are you sure that you want to delete the forum "<?php echo $forum_name ?>"?</p>
<p>WARNING! Deleting a forum will delete all posts (if any) in that forum!</p>
</div>
</fieldset>
</div>
<p><input type="submit" name="del_forum_comply" value="Delete" /><a href="javascript:history.go(-1)">Go back</a></p>
</form>
</div>
</div>
<div class="clearer"></div>
</div>
<?php
require PUN_ROOT.'footer.php';
}
}
// Update forum positions
else if (isset($_POST['update_positions']))
{
confirm_referrer('admin_forums.php');
while (list($forum_id, $disp_position) = @each($_POST['position']))
{
if (!@preg_match('#^\d+$#', $disp_position))
message('Position must be a positive integer value.');
$db->query('UPDATE '.$db->prefix.'forums SET disp_position='.$disp_position.' WHERE id='.intval($forum_id)) or error('Unable to update forum', __FILE__, __LINE__, $db->error());
}
// Regenerate the quickjump cache
require_once PUN_ROOT.'include/cache.php';
generate_quickjump_cache();
redirect('admin_forums.php', 'Forums updated. Redirecting &hellip;');
}
else if (isset($_GET['edit_forum']))
{
$forum_id = intval($_GET['edit_forum']);
if ($forum_id < 1)
message($lang_common['Bad request']);
// Update group permissions for $forum_id
if (isset($_POST['save']))
{
confirm_referrer('admin_forums.php');
// Start with the forum details
$forum_name = trim($_POST['forum_name']);
$forum_desc = pun_linebreaks(trim($_POST['forum_desc']));
$cat_id = intval($_POST['cat_id']);
$sort_by = intval($_POST['sort_by']);
$redirect_url = isset($_POST['redirect_url']) ? trim($_POST['redirect_url']) : null;
if ($forum_name == '')
message('You must enter a forum name.');
if ($cat_id < 1)
message($lang_common['Bad request']);
$forum_desc = ($forum_desc != '') ? '\''.$db->escape($forum_desc).'\'' : 'NULL';
$redirect_url = ($redirect_url != '') ? '\''.$db->escape($redirect_url).'\'' : 'NULL';
$db->query('UPDATE '.$db->prefix.'forums SET forum_name=\''.$db->escape($forum_name).'\', forum_desc='.$forum_desc.', redirect_url='.$redirect_url.', sort_by='.$sort_by.', cat_id='.$cat_id.' WHERE id='.$forum_id) or error('Unable to update forum', __FILE__, __LINE__, $db->error());
// Now let's deal with the permissions
if (isset($_POST['read_forum_old']))
{
$result = $db->query('SELECT g_id, g_read_board, g_post_replies, g_post_topics FROM '.$db->prefix.'groups WHERE g_id!='.PUN_ADMIN) or error('Unable to fetch user group list', __FILE__, __LINE__, $db->error());
while ($cur_group = $db->fetch_assoc($result))
{
$read_forum_new = ($cur_group['g_read_board'] == '1') ? isset($_POST['read_forum_new'][$cur_group['g_id']]) ? '1' : '0' : intval($_POST['read_forum_old'][$cur_group['g_id']]);
$post_replies_new = isset($_POST['post_replies_new'][$cur_group['g_id']]) ? '1' : '0';
$post_topics_new = isset($_POST['post_topics_new'][$cur_group['g_id']]) ? '1' : '0';
// Check if the new settings differ from the old
if ($read_forum_new != $_POST['read_forum_old'][$cur_group['g_id']] || $post_replies_new != $_POST['post_replies_old'][$cur_group['g_id']] || $post_topics_new != $_POST['post_topics_old'][$cur_group['g_id']])
{
// If the new settings are identical to the default settings for this group, delete it's row in forum_perms
if ($read_forum_new == '1' && $post_replies_new == $cur_group['g_post_replies'] && $post_topics_new == $cur_group['g_post_topics'])
$db->query('DELETE FROM '.$db->prefix.'forum_perms WHERE group_id='.$cur_group['g_id'].' AND forum_id='.$forum_id) or error('Unable to delete group forum permissions', __FILE__, __LINE__, $db->error());
else
{
// Run an UPDATE and see if it affected a row, if not, INSERT
$db->query('UPDATE '.$db->prefix.'forum_perms SET read_forum='.$read_forum_new.', post_replies='.$post_replies_new.', post_topics='.$post_topics_new.' WHERE group_id='.$cur_group['g_id'].' AND forum_id='.$forum_id) or error('Unable to insert group forum permissions', __FILE__, __LINE__, $db->error());
if (!$db->affected_rows())
$db->query('INSERT INTO '.$db->prefix.'forum_perms (group_id, forum_id, read_forum, post_replies, post_topics) VALUES('.$cur_group['g_id'].', '.$forum_id.', '.$read_forum_new.', '.$post_replies_new.', '.$post_topics_new.')') or error('Unable to insert group forum permissions', __FILE__, __LINE__, $db->error());
}
}
}
}
// Regenerate the quickjump cache
require_once PUN_ROOT.'include/cache.php';
generate_quickjump_cache();
redirect('admin_forums.php', 'Forum updated. Redirecting &hellip;');
}
else if (isset($_POST['revert_perms']))
{
confirm_referrer('admin_forums.php');
$db->query('DELETE FROM '.$db->prefix.'forum_perms WHERE forum_id='.$forum_id) or error('Unable to delete group forum permissions', __FILE__, __LINE__, $db->error());
// Regenerate the quickjump cache
require_once PUN_ROOT.'include/cache.php';
generate_quickjump_cache();
redirect('admin_forums.php?edit_forum='.$forum_id, 'Permissions reverted to defaults. Redirecting &hellip;');
}
// Fetch forum info
$result = $db->query('SELECT id, forum_name, forum_desc, redirect_url, num_topics, sort_by, cat_id FROM '.$db->prefix.'forums WHERE id='.$forum_id) or error('Unable to fetch forum info', __FILE__, __LINE__, $db->error());
if (!$db->num_rows($result))
message($lang_common['Bad request']);
$cur_forum = $db->fetch_assoc($result);
$page_title = pun_htmlspecialchars($pun_config['o_board_title']).' / Admin / Forums';
require PUN_ROOT.'header.php';
generate_admin_menu('forums');
?>
<div class="blockform">
<h2><span>Edit forum</span></h2>
<div class="box">
<form id="edit_forum" method="post" action="admin_forums.php?edit_forum=<?php echo $forum_id ?>">
<p class="submittop"><input type="submit" name="save" value="Save changes" tabindex="6" /></p>
<div class="inform">
<fieldset>
<legend>Edit forum details</legend>
<div class="infldset">
<table class="aligntop" cellspacing="0">
<tr>
<th scope="row">Forum name</th>
<td><input type="text" name="forum_name" size="35" maxlength="80" value="<?php echo pun_htmlspecialchars($cur_forum['forum_name']) ?>" tabindex="1" /></td>
</tr>
<tr>
<th scope="row">Description (HTML)</th>
<td><textarea name="forum_desc" rows="3" cols="50" tabindex="2"><?php echo pun_htmlspecialchars($cur_forum['forum_desc']) ?></textarea></td>
</tr>
<tr>
<th scope="row">Category</th>
<td>
<select name="cat_id" tabindex="3">
<?php
$result = $db->query('SELECT id, cat_name FROM '.$db->prefix.'categories ORDER BY disp_position') or error('Unable to fetch category list', __FILE__, __LINE__, $db->error());
while ($cur_cat = $db->fetch_assoc($result))
{
$selected = ($cur_cat['id'] == $cur_forum['cat_id']) ? ' selected="selected"' : '';
echo "\t\t\t\t\t\t\t\t\t\t\t".'<option value="'.$cur_cat['id'].'"'.$selected.'>'.pun_htmlspecialchars($cur_cat['cat_name']).'</option>'."\n";
}
?>
</select>
</td>
</tr>
<tr>
<th scope="row">Sort topics by</th>
<td>
<select name="sort_by" tabindex="4">
<option value="0"<?php if ($cur_forum['sort_by'] == '0') echo ' selected="selected"' ?>>Last post</option>
<option value="1"<?php if ($cur_forum['sort_by'] == '1') echo ' selected="selected"' ?>>Topic start</option>
</select>
</td>
</tr>
<tr>
<th scope="row">Redirect URL</th>
<td><?php echo ($cur_forum['num_topics']) ? 'Only available in empty forums' : '<input type="text" name="redirect_url" size="45" maxlength="100" value="'.pun_htmlspecialchars($cur_forum['redirect_url']).'" tabindex="5" />'; ?></td>
</tr>
</table>
</div>
</fieldset>
</div>
<div class="inform">
<fieldset>
<legend>Edit group permissions for this forum</legend>
<div class="infldset">
<p>In this form, you can set the forum specific permissions for the different user groups. If you haven't made any changes to this forums group permissions, what you see below is the default based on settings in <a href="admin_groups.php">User groups</a>. Administrators always have full permissions and are thus excluded. Permission settings that differ from the default permissions for the user group are marked red. The "Read forum" permission checkbox will be disabled if the group in question lacks the "Read board" permission. For redirect forums, only the "Read forum" permission is editable.</p>
<table id="forumperms" cellspacing="0">
<thead>
<tr>
<th class="atcl">&nbsp;</th>
<th>Read forum</th>
<th>Post replies</th>
<th>Post topics</th>
</tr>
</thead>
<tbody>
<?php
$result = $db->query('SELECT g.g_id, g.g_title, g.g_read_board, g.g_post_replies, g.g_post_topics, fp.read_forum, fp.post_replies, fp.post_topics FROM '.$db->prefix.'groups AS g LEFT JOIN '.$db->prefix.'forum_perms AS fp ON (g.g_id=fp.group_id AND fp.forum_id='.$forum_id.') WHERE g.g_id!='.PUN_ADMIN.' ORDER BY g.g_id') or error('Unable to fetch group forum permission list', __FILE__, __LINE__, $db->error());
while ($cur_perm = $db->fetch_assoc($result))
{
$read_forum = ($cur_perm['read_forum'] != '0') ? true : false;
$post_replies = (($cur_perm['g_post_replies'] == '0' && $cur_perm['post_replies'] == '1') || ($cur_perm['g_post_replies'] == '1' && $cur_perm['post_replies'] != '0')) ? true : false;
$post_topics = (($cur_perm['g_post_topics'] == '0' && $cur_perm['post_topics'] == '1') || ($cur_perm['g_post_topics'] == '1' && $cur_perm['post_topics'] != '0')) ? true : false;
// Determine if the current sittings differ from the default or not
$read_forum_def = ($cur_perm['read_forum'] == '0') ? false : true;
$post_replies_def = (($post_replies && $cur_perm['g_post_replies'] == '0') || (!$post_replies && ($cur_perm['g_post_replies'] == '' || $cur_perm['g_post_replies'] == '1'))) ? false : true;
$post_topics_def = (($post_topics && $cur_perm['g_post_topics'] == '0') || (!$post_topics && ($cur_perm['g_post_topics'] == '' || $cur_perm['g_post_topics'] == '1'))) ? false : true;
?>
<tr>
<th class="atcl"><?php echo pun_htmlspecialchars($cur_perm['g_title']) ?></th>
<td<?php if (!$read_forum_def) echo ' class="nodefault"'; ?>>
<input type="hidden" name="read_forum_old[<?php echo $cur_perm['g_id'] ?>]" value="<?php echo ($read_forum) ? '1' : '0'; ?>" />
<input type="checkbox" name="read_forum_new[<?php echo $cur_perm['g_id'] ?>]" value="1"<?php echo ($read_forum) ? ' checked="checked"' : ''; ?><?php echo ($cur_perm['g_read_board'] == '0') ? ' disabled="disabled"' : ''; ?> />
</td>
<td<?php if (!$post_replies_def && $cur_forum['redirect_url'] == '') echo ' class="nodefault"'; ?>>
<input type="hidden" name="post_replies_old[<?php echo $cur_perm['g_id'] ?>]" value="<?php echo ($post_replies) ? '1' : '0'; ?>" />
<input type="checkbox" name="post_replies_new[<?php echo $cur_perm['g_id'] ?>]" value="1"<?php echo ($post_replies) ? ' checked="checked"' : ''; ?><?php echo ($cur_forum['redirect_url'] != '') ? ' disabled="disabled"' : ''; ?> />
</td>
<td<?php if (!$post_topics_def && $cur_forum['redirect_url'] == '') echo ' class="nodefault"'; ?>>
<input type="hidden" name="post_topics_old[<?php echo $cur_perm['g_id'] ?>]" value="<?php echo ($post_topics) ? '1' : '0'; ?>" />
<input type="checkbox" name="post_topics_new[<?php echo $cur_perm['g_id'] ?>]" value="1"<?php echo ($post_topics) ? ' checked="checked"' : ''; ?><?php echo ($cur_forum['redirect_url'] != '') ? ' disabled="disabled"' : ''; ?> />
</td>
</tr>
<?php
}
?>
</tbody>
</table>
<div class="fsetsubmit"><input type="submit" name="revert_perms" value="Revert to default" /></div>
</div>
</fieldset>
</div>
<p class="submitend"><input type="submit" name="save" value="Save changes" /></p>
</form>
</div>
</div>
<div class="clearer"></div>
</div>
<?php
require PUN_ROOT.'footer.php';
}
$page_title = pun_htmlspecialchars($pun_config['o_board_title']).' / Admin / Forums';
require PUN_ROOT.'header.php';
generate_admin_menu('forums');
?>
<div class="blockform">
<h2><span>Add forum</span></h2>
<div class="box">
<form method="post" action="admin_forums.php?action=adddel">
<div class="inform">
<fieldset>
<legend>Create a new forum</legend>
<div class="infldset">
<table class="aligntop" cellspacing="0">
<tr>
<th scope="row">Add forum to category<div><input type="submit" name="add_forum" value=" Add " tabindex="2" /></div></th>
<td>
<select name="add_to_cat" tabindex="1">
<?php
$result = $db->query('SELECT id, cat_name FROM '.$db->prefix.'categories ORDER BY disp_position') or error('Unable to fetch category list', __FILE__, __LINE__, $db->error());
if ($db->num_rows($result) > 0)
{
while ($cur_cat = $db->fetch_assoc($result))
echo "\t\t\t\t\t\t\t\t\t".'<option value="'.$cur_cat['id'].'">'.pun_htmlspecialchars($cur_cat['cat_name']).'</option>'."\n";
}
else
echo "\t\t\t\t\t\t\t\t\t".'<option value="0" disabled="disabled">No categories exist</option>'."\n";
?>
</select>
<span>Select the category to which you wish to add a new forum.</span>
</td>
</tr>
</table>
</div>
</fieldset>
</div>
</form>
</div>
<?php
// Display all the categories and forums
$result = $db->query('SELECT c.id AS cid, c.cat_name, f.id AS fid, f.forum_name, f.disp_position FROM '.$db->prefix.'categories AS c INNER JOIN '.$db->prefix.'forums AS f ON c.id=f.cat_id ORDER BY c.disp_position, c.id, f.disp_position') or error('Unable to fetch category/forum list', __FILE__, __LINE__, $db->error());
if ($db->num_rows($result) > 0)
{
?>
<h2 class="block2"><span>Edit forums</span></h2>
<div class="box">
<form id="edforum" method="post" action="admin_forums.php?action=edit">
<p class="submittop"><input type="submit" name="update_positions" value="Update positions" tabindex="3" /></p>
<?php
$tabindex_count = 4;
$cur_category = 0;
while ($cur_forum = $db->fetch_assoc($result))
{
if ($cur_forum['cid'] != $cur_category) // A new category since last iteration?
{
if ($cur_category != 0)
echo "\t\t\t\t\t\t\t".'</table>'."\n\t\t\t\t\t\t".'</div>'."\n\t\t\t\t\t".'</fieldset>'."\n\t\t\t\t".'</div>'."\n";
?>
<div class="inform">
<fieldset>
<legend>Category: <?php echo pun_htmlspecialchars($cur_forum['cat_name']) ?></legend>
<div class="infldset">
<table cellspacing="0">
<?php
$cur_category = $cur_forum['cid'];
}
?>
<tr>
<th><a href="admin_forums.php?edit_forum=<?php echo $cur_forum['fid'] ?>">Edit</a> - <a href="admin_forums.php?del_forum=<?php echo $cur_forum['fid'] ?>">Delete</a></th>
<td>Position&nbsp;&nbsp;<input type="text" name="position[<?php echo $cur_forum['fid'] ?>]" size="3" maxlength="3" value="<?php echo $cur_forum['disp_position'] ?>" tabindex="<?php echo $tabindex_count ?>" />
&nbsp;&nbsp;<strong><?php echo pun_htmlspecialchars($cur_forum['forum_name']) ?></strong></td>
</tr>
<?php
$tabindex_count += 2;
}
?>
</table>
</div>
</fieldset>
</div>
<p class="submitend"><input type="submit" name="update_positions" value="Update positions" tabindex="<?php echo $tabindex_count ?>" /></p>
</form>
</div>
<?php
}
?>
</div>
<div class="clearer"></div>
</div>
<?php
require PUN_ROOT.'footer.php';
<?php
/***********************************************************************
Copyright (C) 2002-2008 PunBB
This file is part of PunBB.
PunBB is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published
by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
PunBB is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston,
MA 02111-1307 USA
************************************************************************/
// Tell header.php to use the admin template
define('PUN_ADMIN_CONSOLE', 1);
define('PUN_ROOT', './');
require PUN_ROOT.'include/common.php';
require PUN_ROOT.'include/common_admin.php';
if ($pun_user['g_id'] > PUN_ADMIN)
message($lang_common['No permission']);
// Add/edit a group (stage 1)
if (isset($_POST['add_group']) || isset($_GET['edit_group']))
{
if (isset($_POST['add_group']))
{
$base_group = intval($_POST['base_group']);
$result = $db->query('SELECT * FROM '.$db->prefix.'groups WHERE g_id='.$base_group) or error('Unable to fetch user group info', __FILE__, __LINE__, $db->error());
$group = $db->fetch_assoc($result);
$mode = 'add';
}
else // We are editing a group
{
$group_id = intval($_GET['edit_group']);
if ($group_id < 1)
message($lang_common['Bad request']);
$result = $db->query('SELECT * FROM '.$db->prefix.'groups WHERE g_id='.$group_id) or error('Unable to fetch user group info', __FILE__, __LINE__, $db->error());
if (!$db->num_rows($result))
message($lang_common['Bad request']);
$group = $db->fetch_assoc($result);
$mode = 'edit';
}
$page_title = pun_htmlspecialchars($pun_config['o_board_title']).' / Admin / User groups';
$required_fields = array('req_title' => 'Group title');
$focus_element = array('groups2', 'req_title');
require PUN_ROOT.'header.php';
generate_admin_menu('groups');
?>
<div class="blockform">
<h2><span>Group settings</span></h2>
<div class="box">
<form id="groups2" method="post" action="admin_groups.php" onsubmit="return process_form(this)">
<p class="submittop"><input type="submit" name="add_edit_group" value=" Save " /></p>
<div class="inform">
<input type="hidden" name="mode" value="<?php echo $mode ?>" />
<?php if ($mode == 'edit'): ?> <input type="hidden" name="group_id" value="<?php echo $group_id ?>" />
<?php endif; ?><?php if ($mode == 'add'): ?> <input type="hidden" name="base_group" value="<?php echo $base_group ?>" />
<?php endif; ?> <fieldset>
<legend>Setup group options and permissions</legend>
<div class="infldset">
<p>Below options and permissions are the default permissions for the user group. These options apply if no forum specific permissions are in effect.</p>
<table class="aligntop" cellspacing="0">
<tr>
<th scope="row">Group title</th>
<td>
<input type="text" name="req_title" size="25" maxlength="50" value="<?php if ($mode == 'edit') echo pun_htmlspecialchars($group['g_title']); ?>" tabindex="1" />
</td>
</tr>
<tr>
<th scope="row">User title</th>
<td>
<input type="text" name="user_title" size="25" maxlength="50" value="<?php echo pun_htmlspecialchars($group['g_user_title']) ?>" tabindex="2" />
<span>This title will override any rank users in this group have attained. Leave blank to use default title or rank.</span>
</td>
</tr>
<?php if ($group['g_id'] != PUN_ADMIN): ?> <tr>
<th scope="row">Read board</th>
<td>
<input type="radio" name="read_board" value="1"<?php if ($group['g_read_board'] == '1') echo ' checked="checked"' ?> tabindex="3" />&nbsp;<strong>Yes</strong>&nbsp;&nbsp;&nbsp;<input type="radio" name="read_board" value="0"<?php if ($group['g_read_board'] == '0') echo ' checked="checked"' ?> tabindex="4" />&nbsp;<strong>No</strong>
<span>Allow users in this group to view the board. This setting applies to every aspect of the board and can therefore not be overridden by forum specific settings. If this is set to "No", users in this group will only be able to login/logout and register.</span>
</td>
</tr>
<tr>
<th scope="row">Post replies</th>
<td>
<input type="radio" name="post_replies" value="1"<?php if ($group['g_post_replies'] == '1') echo ' checked="checked"' ?> tabindex="5" />&nbsp;<strong>Yes</strong>&nbsp;&nbsp;&nbsp;<input type="radio" name="post_replies" value="0"<?php if ($group['g_post_replies'] == '0') echo ' checked="checked"' ?> tabindex="6" />&nbsp;<strong>No</strong>
<span>Allow users in this group to post replies in topics.</span>
</td>
</tr>
<tr>
<th scope="row">Post topics</th>
<td>
<input type="radio" name="post_topics" value="1"<?php if ($group['g_post_topics'] == '1') echo ' checked="checked"' ?> tabindex="7" />&nbsp;<strong>Yes</strong>&nbsp;&nbsp;&nbsp;<input type="radio" name="post_topics" value="0"<?php if ($group['g_post_topics'] == '0') echo ' checked="checked"' ?> tabindex="8" />&nbsp;<strong>No</strong>
<span>Allow users in this group to post new topics.</span>
</td>
</tr>
<?php if ($group['g_id'] != PUN_GUEST): ?> <tr>
<th scope="row">Edit posts</th>
<td>
<input type="radio" name="edit_posts" value="1"<?php if ($group['g_edit_posts'] == '1') echo ' checked="checked"' ?> tabindex="11" />&nbsp;<strong>Yes</strong>&nbsp;&nbsp;&nbsp;<input type="radio" name="edit_posts" value="0"<?php if ($group['g_edit_posts'] == '0') echo ' checked="checked"' ?> tabindex="12" />&nbsp;<strong>No</strong>
<span>Allow users in this group to edit their own posts.</span>
</td>
</tr>
<tr>
<th scope="row">Delete posts</th>
<td>
<input type="radio" name="delete_posts" value="1"<?php if ($group['g_delete_posts'] == '1') echo ' checked="checked"' ?> tabindex="13" />&nbsp;<strong>Yes</strong>&nbsp;&nbsp;&nbsp;<input type="radio" name="delete_posts" value="0"<?php if ($group['g_delete_posts'] == '0') echo ' checked="checked"' ?> tabindex="14" />&nbsp;<strong>No</strong>
<span>Allow users in this group to delete their own posts.</span>
</td>
</tr>
<tr>
<th scope="row">Delete topics</th>
<td>
<input type="radio" name="delete_topics" value="1"<?php if ($group['g_delete_topics'] == '1') echo ' checked="checked"' ?> tabindex="15" />&nbsp;<strong>Yes</strong>&nbsp;&nbsp;&nbsp;<input type="radio" name="delete_topics" value="0"<?php if ($group['g_delete_topics'] == '0') echo ' checked="checked"' ?> tabindex="16" />&nbsp;<strong>No</strong>
<span>Allow users in this group to delete their own topics (including any replies).</span>
</td>
</tr>
<tr>
<th scope="row">Set user title</th>
<td>
<input type="radio" name="set_title" value="1"<?php if ($group['g_set_title'] == '1') echo ' checked="checked"' ?> tabindex="17" />&nbsp;<strong>Yes</strong>&nbsp;&nbsp;&nbsp;<input type="radio" name="set_title" value="0"<?php if ($group['g_set_title'] == '0') echo ' checked="checked"' ?> tabindex="18" />&nbsp;<strong>No</strong>
<span>Allow users in this group to set their own user title.</span>
</td>
</tr>
<?php endif; ?> <tr>
<th scope="row">Use search</th>
<td>
<input type="radio" name="search" value="1"<?php if ($group['g_search'] == '1') echo ' checked="checked"' ?> tabindex="19" />&nbsp;<strong>Yes</strong>&nbsp;&nbsp;&nbsp;<input type="radio" name="search" value="0"<?php if ($group['g_search'] == '0') echo ' checked="checked"' ?> tabindex="20" />&nbsp;<strong>No</strong>
<span>Allow users in this group to use the search feature.</span>
</td>
</tr>
<tr>
<th scope="row">Search user list</th>
<td>
<input type="radio" name="search_users" value="1"<?php if ($group['g_search_users'] == '1') echo ' checked="checked"' ?> tabindex="21" />&nbsp;<strong>Yes</strong>&nbsp;&nbsp;&nbsp;<input type="radio" name="search_users" value="0"<?php if ($group['g_search_users'] == '0') echo ' checked="checked"' ?> tabindex="22" />&nbsp;<strong>No</strong>
<span>Allow users in this group to freetext search for users in the user list.</span>
</td>
</tr>
<?php if ($group['g_id'] != PUN_GUEST): ?> <tr>
<th scope="row">Edit subjects interval</th>
<td>
<input type="text" name="edit_subjects_interval" size="5" maxlength="5" value="<?php echo $group['g_edit_subjects_interval'] ?>" tabindex="23" />
<span>Number of seconds after post time that users in this group may edit the subject of topics they've posted. Set to 0 to allow edits indefinitely.</span>
</td>
</tr>
<tr>
<th scope="row">Post flood interval</th>
<td>
<input type="text" name="post_flood" size="5" maxlength="4" value="<?php echo $group['g_post_flood'] ?>" tabindex="24" />
<span>Number of seconds that users in this group have to wait between posts. Set to 0 to disable.</span>
</td>
</tr>
<tr>
<th scope="row">Search flood interval</th>
<td>
<input type="text" name="search_flood" size="5" maxlength="4" value="<?php echo $group['g_search_flood'] ?>" tabindex="25" />
<span>Number of seconds that users in this group have to wait between searches. Set to 0 to disable.</span>
</td>
</tr>
<?php endif; ?><?php endif; ?> </table>
<?php if ($group['g_id'] == PUN_MOD ): ?> <p class="warntext">Please note that in order for a user in this group to have moderator abilities, he/she must be assigned to moderate one or more forums. This is done via the user administration page of the user's profile.</p>
<?php endif; ?> </div>
</fieldset>
</div>
<p class="submitend"><input type="submit" name="add_edit_group" value=" Save " tabindex="26" /></p>
</form>
</div>
</div>
<div class="clearer"></div>
</div>
<?php
require PUN_ROOT.'footer.php';
}
// Add/edit a group (stage 2)
else if (isset($_POST['add_edit_group']))
{
confirm_referrer('admin_groups.php');
// Is this the admin group? (special rules apply)
$is_admin_group = (isset($_POST['group_id']) && $_POST['group_id'] == PUN_ADMIN) ? true : false;
$title = trim($_POST['req_title']);
$user_title = trim($_POST['user_title']);
$read_board = isset($_POST['read_board']) ? intval($_POST['read_board']) : '1';
$post_replies = isset($_POST['post_replies']) ? intval($_POST['post_replies']) : '1';
$post_topics = isset($_POST['post_topics']) ? intval($_POST['post_topics']) : '1';
$edit_posts = isset($_POST['edit_posts']) ? intval($_POST['edit_posts']) : ($is_admin_group) ? '1' : '0';
$delete_posts = isset($_POST['delete_posts']) ? intval($_POST['delete_posts']) : ($is_admin_group) ? '1' : '0';
$delete_topics = isset($_POST['delete_topics']) ? intval($_POST['delete_topics']) : ($is_admin_group) ? '1' : '0';
$set_title = isset($_POST['set_title']) ? intval($_POST['set_title']) : ($is_admin_group) ? '1' : '0';
$search = isset($_POST['search']) ? intval($_POST['search']) : '1';
$search_users = isset($_POST['search_users']) ? intval($_POST['search_users']) : '1';
$edit_subjects_interval = isset($_POST['edit_subjects_interval']) ? intval($_POST['edit_subjects_interval']) : '0';
$post_flood = isset($_POST['post_flood']) ? intval($_POST['post_flood']) : '0';
$search_flood = isset($_POST['search_flood']) ? intval($_POST['search_flood']) : '0';
if ($title == '')
message('You must enter a group title.');
$user_title = ($user_title != '') ? '\''.$db->escape($user_title).'\'' : 'NULL';
if ($_POST['mode'] == 'add')
{
$result = $db->query('SELECT 1 FROM '.$db->prefix.'groups WHERE g_title=\''.$db->escape($title).'\'') or error('Unable to check group title collision', __FILE__, __LINE__, $db->error());
if ($db->num_rows($result))
message('There is already a group with the title \''.pun_htmlspecialchars($title).'\'.');
$db->query('INSERT INTO '.$db->prefix.'groups (g_title, g_user_title, g_read_board, g_post_replies, g_post_topics, g_edit_posts, g_delete_posts, g_delete_topics, g_set_title, g_search, g_search_users, g_edit_subjects_interval, g_post_flood, g_search_flood) VALUES(\''.$db->escape($title).'\', '.$user_title.', '.$read_board.', '.$post_replies.', '.$post_topics.', '.$edit_posts.', '.$delete_posts.', '.$delete_topics.', '.$set_title.', '.$search.', '.$search_users.', '.$edit_subjects_interval.', '.$post_flood.', '.$search_flood.')') or error('Unable to add group', __FILE__, __LINE__, $db->error());
$new_group_id = $db->insert_id();
// Now lets copy the forum specific permissions from the group which this group is based on
$result = $db->query('SELECT forum_id, read_forum, post_replies, post_topics FROM '.$db->prefix.'forum_perms WHERE group_id='.intval($_POST['base_group'])) or error('Unable to fetch group forum permission list', __FILE__, __LINE__, $db->error());
while ($cur_forum_perm = $db->fetch_assoc($result))
$db->query('INSERT INTO '.$db->prefix.'forum_perms (group_id, forum_id, read_forum, post_replies, post_topics) VALUES('.$new_group_id.', '.$cur_forum_perm['forum_id'].', '.$cur_forum_perm['read_forum'].', '.$cur_forum_perm['post_replies'].', '.$cur_forum_perm['post_topics'].')') or error('Unable to insert group forum permissions', __FILE__, __LINE__, $db->error());
}
else
{
$result = $db->query('SELECT 1 FROM '.$db->prefix.'groups WHERE g_title=\''.$db->escape($title).'\' AND g_id!='.intval($_POST['group_id'])) or error('Unable to check group title collision', __FILE__, __LINE__, $db->error());
if ($db->num_rows($result))
message('There is already a group with the title \''.pun_htmlspecialchars($title).'\'.');
$db->query('UPDATE '.$db->prefix.'groups SET g_title=\''.$db->escape($title).'\', g_user_title='.$user_title.', g_read_board='.$read_board.', g_post_replies='.$post_replies.', g_post_topics='.$post_topics.', g_edit_posts='.$edit_posts.', g_delete_posts='.$delete_posts.', g_delete_topics='.$delete_topics.', g_set_title='.$set_title.', g_search='.$search.', g_search_users='.$search_users.', g_edit_subjects_interval='.$edit_subjects_interval.', g_post_flood='.$post_flood.', g_search_flood='.$search_flood.' WHERE g_id='.intval($_POST['group_id'])) or error('Unable to update group', __FILE__, __LINE__, $db->error());
}
// Regenerate the quickjump cache
require_once PUN_ROOT.'include/cache.php';
generate_quickjump_cache();
redirect('admin_groups.php', 'Group '.(($_POST['mode'] == 'edit') ? 'edited' : 'added').'. Redirecting &hellip;');
}
// Set default group
else if (isset($_POST['set_default_group']))
{
confirm_referrer('admin_groups.php');
$group_id = intval($_POST['default_group']);
if ($group_id < 4)
message($lang_common['Bad request']);
$db->query('UPDATE '.$db->prefix.'config SET conf_value='.$group_id.' WHERE conf_name=\'o_default_user_group\'') or error('Unable to update board config', __FILE__, __LINE__, $db->error());
// Regenerate the config cache
require_once PUN_ROOT.'include/cache.php';
generate_config_cache();
redirect('admin_groups.php', 'Default group set. Redirecting &hellip;');
}
// Remove a group
else if (isset($_GET['del_group']))
{
confirm_referrer('admin_groups.php');
$group_id = intval($_GET['del_group']);
if ($group_id < 5)
message($lang_common['Bad request']);
// Make sure we don't remove the default group
if ($group_id == $pun_config['o_default_user_group'])
message('The default group cannot be removed. In order to delete this group, you must first setup a different group as the default.');
// Check if this group has any members
$result = $db->query('SELECT g.g_title, COUNT(u.id) FROM '.$db->prefix.'groups AS g INNER JOIN '.$db->prefix.'users AS u ON g.g_id=u.group_id WHERE g.g_id='.$group_id.' GROUP BY g.g_id, g_title') or error('Unable to fetch group info', __FILE__, __LINE__, $db->error());
// If the group doesn't have any members or if we've already selected a group to move the members to
if (!$db->num_rows($result) || isset($_POST['del_group']))
{
if (isset($_POST['del_group']))
{
$move_to_group = intval($_POST['move_to_group']);
$db->query('UPDATE '.$db->prefix.'users SET group_id='.$move_to_group.' WHERE group_id='.$group_id) or error('Unable to move users into group', __FILE__, __LINE__, $db->error());
}
// Delete the group and any forum specific permissions
$db->query('DELETE FROM '.$db->prefix.'groups WHERE g_id='.$group_id) or error('Unable to delete group', __FILE__, __LINE__, $db->error());
$db->query('DELETE FROM '.$db->prefix.'forum_perms WHERE group_id='.$group_id) or error('Unable to delete group forum permissions', __FILE__, __LINE__, $db->error());
// Regenerate the quickjump cache
require_once PUN_ROOT.'include/cache.php';
generate_quickjump_cache();
redirect('admin_groups.php', 'Group removed. Redirecting &hellip;');
}
list($group_title, $group_members) = $db->fetch_row($result);
$page_title = pun_htmlspecialchars($pun_config['o_board_title']).' / Admin / User groups';
require PUN_ROOT.'header.php';
generate_admin_menu('groups');
?>
<div class="blockform">
<h2><span>Remove group</span></h2>
<div class="box">
<form id="groups" method="post" action="admin_groups.php?del_group=<?php echo $group_id ?>">
<div class="inform">
<fieldset>
<legend>Move users currently in group</legend>
<div class="infldset">
<p>The group "<?php echo pun_htmlspecialchars($group_title) ?>" currently has <?php echo $group_members ?> members. Please select a group to which these members will be assigned upon removal.</p>
<label>Move users to
<select name="move_to_group">
<?php
$result = $db->query('SELECT g_id, g_title FROM '.$db->prefix.'groups WHERE g_id!='.PUN_GUEST.' AND g_id!='.$group_id.' ORDER BY g_title') or error('Unable to fetch user group list', __FILE__, __LINE__, $db->error());
while ($cur_group = $db->fetch_assoc($result))
{
if ($cur_group['g_id'] == PUN_MEMBER) // Pre-select the pre-defined Members group
echo "\t\t\t\t\t\t\t\t\t\t".'<option value="'.$cur_group['g_id'].'" selected="selected">'.pun_htmlspecialchars($cur_group['g_title']).'</option>'."\n";
else
echo "\t\t\t\t\t\t\t\t\t\t".'<option value="'.$cur_group['g_id'].'">'.pun_htmlspecialchars($cur_group['g_title']).'</option>'."\n";
}
?>
</select>
</br></label>
</div>
</fieldset>
</div>
<p><input type="submit" name="del_group" value="Delete group" /></p>
</form>
</div>
</div>
<div class="clearer"></div>
</div>
<?php
require PUN_ROOT.'footer.php';
}
$page_title = pun_htmlspecialchars($pun_config['o_board_title']).' / Admin / User groups';
require PUN_ROOT.'header.php';
generate_admin_menu('groups');
?>
<div class="blockform">
<h2><span>Add/setup groups</span></h2>
<div class="box">
<form id="groups" method="post" action="admin_groups.php?action=foo">
<div class="inform">
<fieldset>
<legend>Add new group</legend>
<div class="infldset">
<table class="aligntop" cellspacing="0">
<tr>
<th scope="row">Base new group on<div><input type="submit" name="add_group" value=" Add " tabindex="2" /></div></th>
<td>
<select id="base_group" name="base_group" tabindex="1">
<?php
$result = $db->query('SELECT g_id, g_title FROM '.$db->prefix.'groups WHERE g_id>'.PUN_GUEST.' ORDER BY g_title') or error('Unable to fetch user group list', __FILE__, __LINE__, $db->error());
while ($cur_group = $db->fetch_assoc($result))
{
if ($cur_group['g_id'] == $pun_config['o_default_user_group'])
echo "\t\t\t\t\t\t\t\t\t\t\t".'<option value="'.$cur_group['g_id'].'" selected="selected">'.pun_htmlspecialchars($cur_group['g_title']).'</option>'."\n";
else
echo "\t\t\t\t\t\t\t\t\t\t\t".'<option value="'.$cur_group['g_id'].'">'.pun_htmlspecialchars($cur_group['g_title']).'</option>'."\n";
}
?>
</select>
<span>Select a user group from which the new group will inherit it's permission settings. The next page will let you fine-tune said settings.</span>
</td>
</tr>
</table>
</div>
</fieldset>
</div>
<div class="inform">
<fieldset>
<legend>Set default group</legend>
<div class="infldset">
<table class="aligntop" cellspacing="0">
<tr>
<th scope="row">Default group<div><input type="submit" name="set_default_group" value=" Save " tabindex="4" /></div></th>
<td>
<select id="default_group" name="default_group" tabindex="3">
<?php
$result = $db->query('SELECT g_id, g_title FROM '.$db->prefix.'groups WHERE g_id>'.PUN_GUEST.' ORDER BY g_title') or error('Unable to fetch user group list', __FILE__, __LINE__, $db->error());
while ($cur_group = $db->fetch_assoc($result))
{
if ($cur_group['g_id'] == $pun_config['o_default_user_group'])
echo "\t\t\t\t\t\t\t\t\t\t\t".'<option value="'.$cur_group['g_id'].'" selected="selected">'.pun_htmlspecialchars($cur_group['g_title']).'</option>'."\n";
else
echo "\t\t\t\t\t\t\t\t\t\t\t".'<option value="'.$cur_group['g_id'].'">'.pun_htmlspecialchars($cur_group['g_title']).'</option>'."\n";
}
?>
</select>
<span>This is the default user group, e.g. the group users are placed in when they register. For security reasons, users can't be placed in either the moderator or administrator user groups by default.</span>
</td>
</tr>
</table>
</div>
</fieldset>
</div>
</form>
</div>
<h2 class="block2"><span>Existing groups</span></h2>
<div class="box">
<div class="fakeform">
<div class="inform">
<fieldset>
<legend>Edit/remove groups</legend>
<div class="infldset">
<p>The pre-defined groups Guests, Administrators, Moderators and Members cannot be removed. They can however be edited. Please note though, that in some groups, some options are unavailable (e.g. the <em>edit posts</em> permission for guests). Administrators always have full permissions.</p>
<table cellspacing="0">
<?php
$result = $db->query('SELECT g_id, g_title FROM '.$db->prefix.'groups ORDER BY g_id') or error('Unable to fetch user group list', __FILE__, __LINE__, $db->error());
while ($cur_group = $db->fetch_assoc($result))
echo "\t\t\t\t\t\t\t\t".'<tr><th scope="row"><a href="admin_groups.php?edit_group='.$cur_group['g_id'].'">Edit</a>'.(($cur_group['g_id'] > PUN_MEMBER) ? ' - <a href="admin_groups.php?del_group='.$cur_group['g_id'].'">Remove</a>' : '').'</th><td>'.pun_htmlspecialchars($cur_group['g_title']).'</td></tr>'."\n";
?>
</table>
</div>
</fieldset>
</div>
</div>
</div>
</div>
<div class="clearer"></div>
</div>
<?php
require PUN_ROOT.'footer.php';
<?php
/***********************************************************************
Copyright (C) 2002-2008 PunBB
This file is part of PunBB.
PunBB is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published
by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
PunBB is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston,
MA 02111-1307 USA
************************************************************************/
// Tell header.php to use the admin template
define('PUN_ADMIN_CONSOLE', 1);
define('PUN_ROOT', './');
require PUN_ROOT.'include/common.php';
require PUN_ROOT.'include/common_admin.php';
if ($pun_user['g_id'] > PUN_MOD)
message($lang_common['No permission']);
$action = isset($_GET['action']) ? $_GET['action'] : null;
// Check for upgrade
if ($action == 'check_upgrade')
{
if (!ini_get('allow_url_fopen'))
message('Unable to check for upgrade since \'allow_url_fopen\' is disabled on this system.');
$fp = @fopen('http://punbb.informer.com/latest_version', 'r');
$latest_version = trim(@fread($fp, 16));
@fclose($fp);
if ($latest_version == '')
message('Check for upgrade failed for unknown reasons.');
$cur_version = str_replace(array('.', 'dev', 'beta', ' '), '', strtolower($pun_config['o_cur_version']));
$cur_version = (strlen($cur_version) == 2) ? intval($cur_version) * 10 : intval($cur_version);
$latest_version = str_replace('.', '', strtolower($latest_version));
$latest_version = (strlen($latest_version) == 2) ? intval($latest_version) * 10 : intval($latest_version);
if ($cur_version >= $latest_version)
message('You are running the latest version of PunBB.');
else
message('A new version of PunBB has been released. You can download the latest version at <a href="http://punbb.informer.com/">PunBB.Informer.Com</a>.');
}
// Show phpinfo() output
else if ($action == 'phpinfo' && $pun_user['g_id'] == PUN_ADMIN)
{
// Is phpinfo() a disabled function?
if (strpos(strtolower((string)@ini_get('disable_functions')), 'phpinfo') !== false)
message('The PHP function phpinfo() has been disabled on this server.');
phpinfo();
pun_exit();
}
// Get the server load averages (if possible)
if (@file_exists('/proc/loadavg') && is_readable('/proc/loadavg'))
{
// We use @ just in case
$fh = @fopen('/proc/loadavg', 'r');
$load_averages = @fread($fh, 64);
@fclose($fh);
$load_averages = @explode(' ', $load_averages);
$server_load = isset($load_averages[2]) ? $load_averages[0].' '.$load_averages[1].' '.$load_averages[2] : 'Not available';
}
else if (!in_array(PHP_OS, array('WINNT', 'WIN32')) && preg_match('/averages?: ([0-9\.]+),[\s]+([0-9\.]+),[\s]+([0-9\.]+)/i', @exec('uptime'), $load_averages))
$server_load = $load_averages[1].' '.$load_averages[2].' '.$load_averages[3];
else
$server_load = 'Not available';
// Get number of current visitors
$result = $db->query('SELECT COUNT(user_id) FROM '.$db->prefix.'online WHERE idle=0') or error('Unable to fetch online count', __FILE__, __LINE__, $db->error());
$num_online = $db->result($result);
// Get the database system version
switch ($db_type)
{
case 'sqlite':
$db_version = 'SQLite '.sqlite_libversion();
break;
default:
$result = $db->query('SELECT VERSION()') or error('Unable to fetch version info', __FILE__, __LINE__, $db->error());
$db_version = $db->result($result);
break;
}
// Collect some additional info about MySQL
if ($db_type == 'mysql' || $db_type == 'mysqli')
{
$db_version = 'MySQL '.$db_version;
// Calculate total db size/row count
$result = $db->query('SHOW TABLE STATUS FROM `'.$db_name.'`') or error('Unable to fetch table status', __FILE__, __LINE__, $db->error());
$total_records = $total_size = 0;
while ($status = $db->fetch_assoc($result))
{
$total_records += $status['Rows'];
$total_size += $status['Data_length'] + $status['Index_length'];
}
$total_size = $total_size / 1024;
if ($total_size > 1024)
$total_size = round($total_size / 1024, 2).' MB';
else
$total_size = round($total_size, 2).' KB';
}
// See if MMCache or PHPA is loaded
if (function_exists('mmcache'))
$php_accelerator = '<a href="http://turck-mmcache.sourceforge.net/">Turck MMCache</a>';
else if (isset($_PHPA))
$php_accelerator = '<a href="http://www.php-accelerator.co.uk/">ionCube PHP Accelerator</a>';
else
$php_accelerator = 'N/A';
$page_title = pun_htmlspecialchars($pun_config['o_board_title']).' / Admin';
require PUN_ROOT.'header.php';
generate_admin_menu('index');
?>
<div class="block">
<h2>Forum administration</h2>
<div id="adintro" class="box">
<div class="inbox">
<p>
Welcome to the PunBB administration control panel. From here you can control vital aspects of the forum. Depending on whether you are an administrator or a moderator you can<br /><br />
&nbsp;- organize categories and forums.<br />
&nbsp;- set forum-wide options and preferences.<br />
&nbsp;- control permissions for users and guests.<br />
&nbsp;- view IP statistics for users.<br />
&nbsp;- ban users.<br />
&nbsp;- censor words.<br />
&nbsp;- set up user ranks.<br />
&nbsp;- prune old posts.<br />
&nbsp;- handle post reports.
</p>
</div>
</div>
<h2 class="block2"><span>Statistics</span></h2>
<div id="adstats" class="box">
<div class="inbox">
<dl>
<dt>PunBB version</dt>
<dd>
PunBB <?php echo $pun_config['o_cur_version'] ?> - <a href="admin_index.php?action=check_upgrade">Check for upgrade</a><br />
&copy; Copyright 2002-2008 PunBB
</dd>
<dt>Server load</dt>
<dd>
<?php echo $server_load ?> (<?php echo $num_online ?> users online)
</dd>
<?php if ($pun_user['g_id'] == PUN_ADMIN): ?> <dt>Environment</dt>
<dd>
Operating system: <?php echo PHP_OS ?><br />
PHP: <?php echo phpversion() ?> - <a href="admin_index.php?action=phpinfo">Show info</a><br />
Accelerator: <?php echo $php_accelerator."\n" ?>
</dd>
<dt>Database</dt>
<dd>
<?php echo $db_version."\n" ?>
<?php if (isset($total_records) && isset($total_size)): ?> <br />Rows: <?php echo $total_records."\n" ?>
<br />Size: <?php echo $total_size."\n" ?>
<?php endif; endif; ?> </dd>
</dl>
</div>
</div>
</div>
<div class="clearer"></div>
</div>
<?php
require PUN_ROOT.'footer.php';
<?php
/***********************************************************************
Copyright (C) 2002-2008 PunBB
This file is part of PunBB.
PunBB is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published
by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
PunBB is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston,
MA 02111-1307 USA
************************************************************************/
// Tell header.php to use the admin template
define('PUN_ADMIN_CONSOLE', 1);
define('PUN_ROOT', './');
require PUN_ROOT.'include/common.php';
require PUN_ROOT.'include/common_admin.php';
if ($pun_user['g_id'] > PUN_MOD)
message($lang_common['No permission']);
// The plugin to load should be supplied via GET
$plugin = isset($_GET['plugin']) ? $_GET['plugin'] : '';
if (!@preg_match('/^AM?P_(\w*?)\.php$/i', $plugin))
message($lang_common['Bad request']);
// AP_ == Admins only, AMP_ == admins and moderators
$prefix = substr($plugin, 0, strpos($plugin, '_'));
if ($pun_user['g_id'] == PUN_MOD && $prefix == 'AP')
message($lang_common['No permission']);
// Make sure the file actually exists
if (!file_exists(PUN_ROOT.'plugins/'.$plugin))
message('There is no plugin called \''.$plugin.'\' in the plugin directory.');
// Construct REQUEST_URI if it isn't set
if (!isset($_SERVER['REQUEST_URI']))
$_SERVER['REQUEST_URI'] = (isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : '').'?'.(isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : '');
$page_title = pun_htmlspecialchars($pun_config['o_board_title']).' / Admin / '.$plugin;
require PUN_ROOT.'header.php';
// Attempt to load the plugin. We don't use @ here to supress error messages,
// because if we did and a parse error occurred in the plugin, we would only
// get the "blank page of death".
include PUN_ROOT.'plugins/'.$plugin;
if (!defined('PUN_PLUGIN_LOADED'))
message('Loading of the plugin \''.$plugin.'\' failed.');
// Output the clearer div
?>
<div class="clearer"></div>
</div>
<?php
require PUN_ROOT.'footer.php';