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 896 additions and 1363 deletions
<?php
/***********************************************************************
Copyright (C) 2002-2008 PunBB
Partially based on code copyright (C) 2008 FluxBB.org
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
************************************************************************/
define('PUN_ROOT', './');
require PUN_ROOT.'include/common.php';
if ($pun_user['g_read_board'] == '0')
message($lang_common['No view']);
// Load the userlist.php language file
require PUN_ROOT.'lang/'.$pun_user['language'].'/userlist.php';
// Load the search.php language file
require PUN_ROOT.'lang/'.$pun_user['language'].'/search.php';
// Determine if we are allowed to view post counts
$show_post_count = ($pun_config['o_show_post_count'] == '1' || $pun_user['g_id'] < PUN_GUEST) ? true : false;
$username = (isset($_GET['username']) && $pun_user['g_search_users'] == '1') ? pun_trim($_GET['username']) : '';
$show_group = (!isset($_GET['show_group']) || intval($_GET['show_group']) < -1 && intval($_GET['show_group']) > 2) ? -1 : intval($_GET['show_group']);
$sort_by = (!isset($_GET['sort_by']) || $_GET['sort_by'] != 'username' && $_GET['sort_by'] != 'registered' && ($_GET['sort_by'] != 'num_posts' || !$show_post_count)) ? 'username' : $_GET['sort_by'];
$sort_dir = (!isset($_GET['sort_dir']) || $_GET['sort_dir'] != 'ASC' && $_GET['sort_dir'] != 'DESC') ? 'ASC' : strtoupper($_GET['sort_dir']);
$page_title = pun_htmlspecialchars($pun_config['o_board_title']).' / '.$lang_common['User list'];
if ($pun_user['g_search_users'] == '1')
$focus_element = array('userlist', 'username');
define('PUN_ALLOW_INDEX', 1);
require PUN_ROOT.'header.php';
?>
<div class="blockform">
<h2><span><?php echo $lang_search['User search'] ?></span></h2>
<div class="box">
<form id="userlist" method="get" action="userlist.php">
<div class="inform">
<fieldset>
<legend><?php echo $lang_ul['User find legend'] ?></legend>
<div class="infldset">
<?php if ($pun_user['g_search_users'] == '1'): ?> <label class="conl"><?php echo $lang_common['Username'] ?><br /><input type="text" name="username" value="<?php echo pun_htmlspecialchars($username) ?>" size="25" maxlength="25" /><br /></label>
<?php endif; ?> <label class="conl"><?php echo $lang_ul['User group']."\n" ?>
<br /><select name="show_group">
<option value="-1"<?php if ($show_group == -1) echo ' selected="selected"' ?>><?php echo $lang_ul['All users'] ?></option>
<?php
$result = $db->query('SELECT g_id, g_title FROM '.$db->prefix.'groups WHERE g_id!='.PUN_GUEST.' ORDER BY g_id') or error('Unable to fetch user group list', __FILE__, __LINE__, $db->error());
while ($cur_group = $db->fetch_assoc($result))
{
if ($cur_group['g_id'] == $show_group)
echo "\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".'<option value="'.$cur_group['g_id'].'">'.pun_htmlspecialchars($cur_group['g_title']).'</option>'."\n";
}
?>
</select>
<br /></label>
<label class="conl"><?php echo $lang_search['Sort by']."\n" ?>
<br /><select name="sort_by">
<option value="username"<?php if ($sort_by == 'username') echo ' selected="selected"' ?>><?php echo $lang_common['Username'] ?></option>
<option value="registered"<?php if ($sort_by == 'registered') echo ' selected="selected"' ?>><?php echo $lang_common['Registered'] ?></option>
<?php if ($show_post_count): ?> <option value="num_posts"<?php if ($sort_by == 'num_posts') echo ' selected="selected"' ?>><?php echo $lang_ul['No of posts'] ?></option>
<?php endif; ?> </select>
<br /></label>
<label class="conl"><?php echo $lang_search['Sort order']."\n" ?>
<br /><select name="sort_dir">
<option value="ASC"<?php if ($sort_dir == 'ASC') echo ' selected="selected"' ?>><?php echo $lang_search['Ascending'] ?></option>
<option value="DESC"<?php if ($sort_dir == 'DESC') echo ' selected="selected"' ?>><?php echo $lang_search['Descending'] ?></option>
</select>
<br /></label>
<p class="clearb"><?php echo $lang_ul['User search info'] ?></p>
</div>
</fieldset>
</div>
<p><input type="submit" name="search" value="<?php echo $lang_common['Submit'] ?>" accesskey="s" /></p>
</form>
</div>
</div>
<?php
// Create any SQL for the WHERE clause
$where_sql = array();
$like_command = ($db_type == 'pgsql') ? 'ILIKE' : 'LIKE';
if ($pun_user['g_search_users'] == '1' && $username != '')
$where_sql[] = 'u.username '.$like_command.' \''.$db->escape(str_replace('*', '%', $username)).'\'';
if ($show_group > -1)
$where_sql[] = 'u.group_id='.$show_group;
// Fetch user count
$result = $db->query('SELECT COUNT(id) FROM '.$db->prefix.'users AS u WHERE u.id>1'.(!empty($where_sql) ? ' AND '.implode(' AND ', $where_sql) : '')) or error('Unable to fetch user list count', __FILE__, __LINE__, $db->error());
$num_users = $db->result($result);
// Determine the user offset (based on $_GET['p'])
$num_pages = ceil($num_users / 50);
$p = (!isset($_GET['p']) || $_GET['p'] <= 1 || $_GET['p'] > $num_pages) ? 1 : $_GET['p'];
$start_from = 50 * ($p - 1);
// Generate paging links
$paging_links = $lang_common['Pages'].': '.paginate($num_pages, $p, 'userlist.php?username='.urlencode($username).'&amp;show_group='.$show_group.'&amp;sort_by='.$sort_by.'&amp;sort_dir='.strtoupper($sort_dir));
?>
<div class="linkst">
<div class="inbox">
<p class="pagelink"><?php echo $paging_links ?></p>
</div>
</div>
<div id="users1" class="blocktable">
<h2><span><?php echo $lang_common['User list'] ?></span></h2>
<div class="box">
<div class="inbox">
<table cellspacing="0">
<thead>
<tr>
<th class="tcl" scope="col"><?php echo $lang_common['Username'] ?></th>
<th class="tc2" scope="col"><?php echo $lang_common['Title'] ?></th>
<?php if ($show_post_count): ?> <th class="tc3" scope="col"><?php echo $lang_common['Posts'] ?></th>
<?php endif; ?> <th class="tcr" scope="col"><?php echo $lang_common['Registered'] ?></th>
</tr>
</thead>
<tbody>
<?php
// Grab the users
$result = $db->query('SELECT u.id, u.username, u.title, u.num_posts, u.registered, g.g_id, g.g_user_title FROM '.$db->prefix.'users AS u LEFT JOIN '.$db->prefix.'groups AS g ON g.g_id=u.group_id WHERE u.id>1'.(!empty($where_sql) ? ' AND '.implode(' AND ', $where_sql) : '').' ORDER BY '.$sort_by.' '.$sort_dir.', u.id ASC LIMIT '.$start_from.', 50') or error('Unable to fetch user list', __FILE__, __LINE__, $db->error());
if ($db->num_rows($result))
{
while ($user_data = $db->fetch_assoc($result))
{
$user_title_field = get_title($user_data);
?>
<tr>
<td class="tcl"><?php echo '<a href="profile.php?id='.$user_data['id'].'">'.pun_htmlspecialchars($user_data['username']).'</a>' ?></td>
<td class="tc2"><?php echo $user_title_field ?></td>
<?php if ($show_post_count): ?> <td class="tc3"><?php echo $user_data['num_posts'] ?></td>
<?php endif; ?>
<td class="tcr"><?php echo format_time($user_data['registered'], true) ?></td>
</tr>
<?php
}
}
else
echo "\t\t\t".'<tr>'."\n\t\t\t\t\t".'<td class="tcl" colspan="'.(($show_post_count) ? 4 : 3).'">'.$lang_search['No hits'].'</td></tr>'."\n";
?>
</tbody>
</table>
</div>
</div>
</div>
<div class="linksb">
<div class="inbox">
<p class="pagelink"><?php echo $paging_links ?></p>
</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
************************************************************************/
define('PUN_ROOT', './');
require PUN_ROOT.'include/common.php';
if ($pun_user['g_read_board'] == '0')
message($lang_common['No view']);
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
if ($id < 1)
message($lang_common['Bad request']);
// Load the viewforum.php language file
require PUN_ROOT.'lang/'.$pun_user['language'].'/forum.php';
// Fetch some info about the forum
$result = $db->query('SELECT f.forum_name, f.redirect_url, f.moderators, f.num_topics, f.sort_by, fp.post_topics FROM '.$db->prefix.'forums AS f LEFT JOIN '.$db->prefix.'forum_perms AS fp ON (fp.forum_id=f.id AND fp.group_id='.$pun_user['g_id'].') WHERE (fp.read_forum IS NULL OR fp.read_forum=1) AND f.id='.$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);
// Is this a redirect forum? In that case, redirect!
if ($cur_forum['redirect_url'] != '')
{
header('Location: '.$cur_forum['redirect_url']);
pun_exit();
}
// Sort out who the moderators are and if we are currently a moderator (or an admin)
$mods_array = array();
if ($cur_forum['moderators'] != '')
$mods_array = unserialize($cur_forum['moderators']);
$is_admmod = ($pun_user['g_id'] == PUN_ADMIN || ($pun_user['g_id'] == PUN_MOD && array_key_exists($pun_user['username'], $mods_array))) ? true : false;
// Can we or can we not post new topics?
if (($cur_forum['post_topics'] == '' && $pun_user['g_post_topics'] == '1') || $cur_forum['post_topics'] == '1' || $is_admmod)
$post_link = "\t\t".'<p class="postlink conr"><a href="post.php?fid='.$id.'">'.$lang_forum['Post topic'].'</a></p>'."\n";
else
$post_link = '';
// Determine the topic offset (based on $_GET['p'])
$num_pages = ceil($cur_forum['num_topics'] / $pun_user['disp_topics']);
$p = (!isset($_GET['p']) || $_GET['p'] <= 1 || $_GET['p'] > $num_pages) ? 1 : $_GET['p'];
$start_from = $pun_user['disp_topics'] * ($p - 1);
// Generate paging links
$paging_links = $lang_common['Pages'].': '.paginate($num_pages, $p, 'viewforum.php?id='.$id);
$page_title = pun_htmlspecialchars($pun_config['o_board_title'].' / '.$cur_forum['forum_name']);
define('PUN_ALLOW_INDEX', 1);
require PUN_ROOT.'header.php';
?>
<div class="linkst">
<div class="inbox">
<p class="pagelink conl"><?php echo $paging_links ?></p>
<?php echo $post_link ?>
<ul><li><a href="index.php"><?php echo $lang_common['Index'] ?></a>&nbsp;</li><li>&raquo;&nbsp;<?php echo pun_htmlspecialchars($cur_forum['forum_name']) ?></li></ul>
<div class="clearer"></div>
</div>
</div>
<div id="vf" class="blocktable">
<h2><span><?php echo pun_htmlspecialchars($cur_forum['forum_name']) ?></span></h2>
<div class="box">
<div class="inbox">
<table cellspacing="0">
<thead>
<tr>
<th class="tcl" scope="col"><?php echo $lang_common['Topic'] ?></th>
<th class="tc2" scope="col"><?php echo $lang_common['Replies'] ?></th>
<th class="tc3" scope="col"><?php echo $lang_forum['Views'] ?></th>
<th class="tcr" scope="col"><?php echo $lang_common['Last post'] ?></th>
</tr>
</thead>
<tbody>
<?php
// Fetch list of topics to display on this page
if ($pun_user['is_guest'] || $pun_config['o_show_dot'] == '0')
{
// Without "the dot"
$sql = 'SELECT id, poster, subject, posted, last_post, last_post_id, last_poster, num_views, num_replies, closed, sticky, moved_to FROM '.$db->prefix.'topics WHERE forum_id='.$id.' ORDER BY sticky DESC, '.(($cur_forum['sort_by'] == '1') ? 'posted' : 'last_post').' DESC LIMIT '.$start_from.', '.$pun_user['disp_topics'];
}
else
{
// With "the dot"
switch ($db_type)
{
case 'mysql':
case 'mysqli':
$sql = 'SELECT p.poster_id AS has_posted, t.id, t.subject, t.poster, t.posted, t.last_post, t.last_post_id, t.last_poster, t.num_views, t.num_replies, t.closed, t.sticky, t.moved_to FROM '.$db->prefix.'topics AS t LEFT JOIN '.$db->prefix.'posts AS p ON t.id=p.topic_id AND p.poster_id='.$pun_user['id'].' WHERE t.forum_id='.$id.' GROUP BY t.id ORDER BY sticky DESC, '.(($cur_forum['sort_by'] == '1') ? 'posted' : 'last_post').' DESC LIMIT '.$start_from.', '.$pun_user['disp_topics'];
break;
case 'sqlite':
$sql = 'SELECT p.poster_id AS has_posted, t.id, t.subject, t.poster, t.posted, t.last_post, t.last_post_id, t.last_poster, t.num_views, t.num_replies, t.closed, t.sticky, t.moved_to FROM '.$db->prefix.'topics AS t LEFT JOIN '.$db->prefix.'posts AS p ON t.id=p.topic_id AND p.poster_id='.$pun_user['id'].' WHERE t.id IN(SELECT id FROM '.$db->prefix.'topics WHERE forum_id='.$id.' ORDER BY sticky DESC, '.(($cur_forum['sort_by'] == '1') ? 'posted' : 'last_post').' DESC LIMIT '.$start_from.', '.$pun_user['disp_topics'].') GROUP BY t.id ORDER BY t.sticky DESC, t.last_post DESC';
break;
default:
$sql = 'SELECT p.poster_id AS has_posted, t.id, t.subject, t.poster, t.posted, t.last_post, t.last_post_id, t.last_poster, t.num_views, t.num_replies, t.closed, t.sticky, t.moved_to FROM '.$db->prefix.'topics AS t LEFT JOIN '.$db->prefix.'posts AS p ON t.id=p.topic_id AND p.poster_id='.$pun_user['id'].' WHERE t.forum_id='.$id.' GROUP BY t.id, t.subject, t.poster, t.posted, t.last_post, t.last_post_id, t.last_poster, t.num_views, t.num_replies, t.closed, t.sticky, t.moved_to, p.poster_id ORDER BY sticky DESC, '.(($cur_forum['sort_by'] == '1') ? 'posted' : 'last_post').' DESC LIMIT '.$start_from.', '.$pun_user['disp_topics'];
break;
}
}
$result = $db->query($sql) or error('Unable to fetch topic list', __FILE__, __LINE__, $db->error());
// If there are topics in this forum.
if ($db->num_rows($result))
{
while ($cur_topic = $db->fetch_assoc($result))
{
$icon_text = $lang_common['Normal icon'];
$item_status = '';
$icon_type = 'icon';
if ($cur_topic['moved_to'] == null)
$last_post = '<a href="viewtopic.php?pid='.$cur_topic['last_post_id'].'#p'.$cur_topic['last_post_id'].'">'.format_time($cur_topic['last_post']).'</a> <span class="byuser">'.$lang_common['by'].'&nbsp;'.pun_htmlspecialchars($cur_topic['last_poster']).'</span>';
else
$last_post = '&nbsp;';
if ($pun_config['o_censoring'] == '1')
$cur_topic['subject'] = censor_words($cur_topic['subject']);
if ($cur_topic['moved_to'] != 0)
$subject = $lang_forum['Moved'].': <a href="viewtopic.php?id='.$cur_topic['moved_to'].'">'.pun_htmlspecialchars($cur_topic['subject']).'</a> <span class="byuser">'.$lang_common['by'].'&nbsp;'.pun_htmlspecialchars($cur_topic['poster']).'</span>';
else if ($cur_topic['closed'] == '0')
$subject = '<a href="viewtopic.php?id='.$cur_topic['id'].'">'.pun_htmlspecialchars($cur_topic['subject']).'</a> <span class="byuser">'.$lang_common['by'].'&nbsp;'.pun_htmlspecialchars($cur_topic['poster']).'</span>';
else
{
$subject = '<a href="viewtopic.php?id='.$cur_topic['id'].'">'.pun_htmlspecialchars($cur_topic['subject']).'</a> <span class="byuser">'.$lang_common['by'].'&nbsp;'.pun_htmlspecialchars($cur_topic['poster']).'</span>';
$icon_text = $lang_common['Closed icon'];
$item_status = 'iclosed';
}
if (!$pun_user['is_guest'] && $cur_topic['last_post'] > $pun_user['last_visit'] && $cur_topic['moved_to'] == null)
{
$icon_text .= ' '.$lang_common['New icon'];
$item_status .= ' inew';
$icon_type = 'icon inew';
$subject = '<strong>'.$subject.'</strong>';
$subject_new_posts = '<span class="newtext">[&nbsp;<a href="viewtopic.php?id='.$cur_topic['id'].'&amp;action=new" title="'.$lang_common['New posts info'].'">'.$lang_common['New posts'].'</a>&nbsp;]</span>';
}
else
$subject_new_posts = null;
// Should we display the dot or not? :)
if (!$pun_user['is_guest'] && $pun_config['o_show_dot'] == '1')
{
if ($cur_topic['has_posted'] == $pun_user['id'])
$subject = '<strong>&middot;</strong>&nbsp;'.$subject;
else
$subject = '&nbsp;&nbsp;'.$subject;
}
if ($cur_topic['sticky'] == '1')
{
$subject = '<span class="stickytext">'.$lang_forum['Sticky'].': </span>'.$subject;
$item_status .= ' isticky';
$icon_text .= ' '.$lang_forum['Sticky'];
}
$num_pages_topic = ceil(($cur_topic['num_replies'] + 1) / $pun_user['disp_posts']);
if ($num_pages_topic > 1)
$subject_multipage = '[ '.paginate($num_pages_topic, -1, 'viewtopic.php?id='.$cur_topic['id']).' ]';
else
$subject_multipage = null;
// Should we show the "New posts" and/or the multipage links?
if (!empty($subject_new_posts) || !empty($subject_multipage))
{
$subject .= '&nbsp; '.(!empty($subject_new_posts) ? $subject_new_posts : '');
$subject .= !empty($subject_multipage) ? ' '.$subject_multipage : '';
}
?>
<tr<?php if ($item_status != '') echo ' class="'.trim($item_status).'"'; ?>>
<td class="tcl">
<div class="intd">
<div class="<?php echo $icon_type ?>"><div class="nosize"><?php echo trim($icon_text) ?></div></div>
<div class="tclcon">
<?php echo $subject."\n" ?>
</div>
</div>
</td>
<td class="tc2"><?php echo ($cur_topic['moved_to'] == null) ? $cur_topic['num_replies'] : '&nbsp;' ?></td>
<td class="tc3"><?php echo ($cur_topic['moved_to'] == null) ? $cur_topic['num_views'] : '&nbsp;' ?></td>
<td class="tcr"><?php echo $last_post ?></td>
</tr>
<?php
}
}
else
{
?>
<tr>
<td class="tcl" colspan="4"><?php echo $lang_forum['Empty forum'] ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
</div>
<div class="linksb">
<div class="inbox">
<p class="pagelink conl"><?php echo $paging_links ?></p>
<?php echo $post_link ?>
<ul><li><a href="index.php"><?php echo $lang_common['Index'] ?></a>&nbsp;</li><li>&raquo;&nbsp;<?php echo pun_htmlspecialchars($cur_forum['forum_name']) ?></li></ul>
<div class="clearer"></div>
</div>
</div>
<?php
$forum_id = $id;
$footer_style = 'viewforum';
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
************************************************************************/
define('PUN_ROOT', './');
require PUN_ROOT.'include/common.php';
if ($pun_user['g_read_board'] == '0')
message($lang_common['No view']);
$action = isset($_GET['action']) ? $_GET['action'] : null;
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$pid = isset($_GET['pid']) ? intval($_GET['pid']) : 0;
if ($id < 1 && $pid < 1)
message($lang_common['Bad request']);
// Load the viewtopic.php language file
require PUN_ROOT.'lang/'.$pun_user['language'].'/topic.php';
// If a post ID is specified we determine topic ID and page number so we can redirect to the correct message
if ($pid)
{
$result = $db->query('SELECT topic_id FROM '.$db->prefix.'posts WHERE id='.$pid) or error('Unable to fetch post info', __FILE__, __LINE__, $db->error());
if (!$db->num_rows($result))
message($lang_common['Bad request']);
$id = $db->result($result);
// Determine on what page the post is located (depending on $pun_user['disp_posts'])
$result = $db->query('SELECT id FROM '.$db->prefix.'posts WHERE topic_id='.$id.' ORDER BY posted') or error('Unable to fetch post info', __FILE__, __LINE__, $db->error());
$num_posts = $db->num_rows($result);
for ($i = 0; $i < $num_posts; ++$i)
{
$cur_id = $db->result($result, $i);
if ($cur_id == $pid)
break;
}
++$i; // we started at 0
$_GET['p'] = ceil($i / $pun_user['disp_posts']);
}
// If action=new, we redirect to the first new post (if any)
else if ($action == 'new' && !$pun_user['is_guest'])
{
$result = $db->query('SELECT MIN(id) FROM '.$db->prefix.'posts WHERE topic_id='.$id.' AND posted>'.$pun_user['last_visit']) or error('Unable to fetch post info', __FILE__, __LINE__, $db->error());
$first_new_post_id = $db->result($result);
if ($first_new_post_id)
header('Location: viewtopic.php?pid='.$first_new_post_id.'#p'.$first_new_post_id);
else // If there is no new post, we go to the last post
header('Location: viewtopic.php?id='.$id.'&action=last');
pun_exit();
}
// If action=last, we redirect to the last post
else if ($action == 'last')
{
$result = $db->query('SELECT MAX(id) FROM '.$db->prefix.'posts WHERE topic_id='.$id) or error('Unable to fetch post info', __FILE__, __LINE__, $db->error());
$last_post_id = $db->result($result);
if ($last_post_id)
{
header('Location: viewtopic.php?pid='.$last_post_id.'#p'.$last_post_id);
pun_exit();
}
}
// Fetch some info about the topic
if (!$pun_user['is_guest'])
$result = $db->query('SELECT t.subject, t.closed, t.num_replies, t.sticky, f.id AS forum_id, f.forum_name, f.moderators, fp.post_replies, s.user_id AS is_subscribed FROM '.$db->prefix.'topics AS t INNER JOIN '.$db->prefix.'forums AS f ON f.id=t.forum_id LEFT JOIN '.$db->prefix.'subscriptions AS s ON (t.id=s.topic_id AND s.user_id='.$pun_user['id'].') LEFT JOIN '.$db->prefix.'forum_perms AS fp ON (fp.forum_id=f.id AND fp.group_id='.$pun_user['g_id'].') WHERE (fp.read_forum IS NULL OR fp.read_forum=1) AND t.id='.$id.' AND t.moved_to IS NULL') or error('Unable to fetch topic info', __FILE__, __LINE__, $db->error());
else
$result = $db->query('SELECT t.subject, t.closed, t.num_replies, t.sticky, f.id AS forum_id, f.forum_name, f.moderators, fp.post_replies, 0 FROM '.$db->prefix.'topics AS t INNER JOIN '.$db->prefix.'forums AS f ON f.id=t.forum_id LEFT JOIN '.$db->prefix.'forum_perms AS fp ON (fp.forum_id=f.id AND fp.group_id='.$pun_user['g_id'].') WHERE (fp.read_forum IS NULL OR fp.read_forum=1) AND t.id='.$id.' AND t.moved_to IS NULL') or error('Unable to fetch topic info', __FILE__, __LINE__, $db->error());
if (!$db->num_rows($result))
message($lang_common['Bad request']);
$cur_topic = $db->fetch_assoc($result);
// Sort out who the moderators are and if we are currently a moderator (or an admin)
$mods_array = ($cur_topic['moderators'] != '') ? unserialize($cur_topic['moderators']) : array();
$is_admmod = ($pun_user['g_id'] == PUN_ADMIN || ($pun_user['g_id'] == PUN_MOD && array_key_exists($pun_user['username'], $mods_array))) ? true : false;
// Can we or can we not post replies?
if ($cur_topic['closed'] == '0')
{
if (($cur_topic['post_replies'] == '' && $pun_user['g_post_replies'] == '1') || $cur_topic['post_replies'] == '1' || $is_admmod)
$post_link = '<a href="post.php?tid='.$id.'">'.$lang_topic['Post reply'].'</a>';
else
$post_link = '&nbsp;';
}
else
{
$post_link = $lang_topic['Topic closed'];
if ($is_admmod)
$post_link .= ' / <a href="post.php?tid='.$id.'">'.$lang_topic['Post reply'].'</a>';
}
// Determine the post offset (based on $_GET['p'])
$num_pages = ceil(($cur_topic['num_replies'] + 1) / $pun_user['disp_posts']);
$p = (!isset($_GET['p']) || $_GET['p'] <= 1 || $_GET['p'] > $num_pages) ? 1 : $_GET['p'];
$start_from = $pun_user['disp_posts'] * ($p - 1);
// Generate paging links
$paging_links = $lang_common['Pages'].': '.paginate($num_pages, $p, 'viewtopic.php?id='.$id);
if ($pun_config['o_censoring'] == '1')
$cur_topic['subject'] = censor_words($cur_topic['subject']);
$quickpost = false;
if ($pun_config['o_quickpost'] == '1' &&
!$pun_user['is_guest'] &&
($cur_topic['post_replies'] == '1' || ($cur_topic['post_replies'] == '' && $pun_user['g_post_replies'] == '1')) &&
($cur_topic['closed'] == '0' || $is_admmod))
{
$required_fields = array('req_message' => $lang_common['Message']);
$quickpost = true;
}
if (!$pun_user['is_guest'] && $pun_config['o_subscriptions'] == '1')
{
if ($cur_topic['is_subscribed'])
// I apologize for the variable naming here. It's a mix of subscription and action I guess :-)
$subscraction = '<p class="subscribelink clearb">'.$lang_topic['Is subscribed'].' - <a href="misc.php?unsubscribe='.$id.'">'.$lang_topic['Unsubscribe'].'</a></p>'."\n";
else
$subscraction = '<p class="subscribelink clearb"><a href="misc.php?subscribe='.$id.'">'.$lang_topic['Subscribe'].'</a></p>'."\n";
}
else
$subscraction = '<div class="clearer"></div>'."\n";
$page_title = pun_htmlspecialchars($pun_config['o_board_title'].' / '.$cur_topic['subject']);
define('PUN_ALLOW_INDEX', 1);
require PUN_ROOT.'header.php';
?>
<div class="linkst">
<div class="inbox">
<p class="pagelink conl"><?php echo $paging_links ?></p>
<p class="postlink conr"><?php echo $post_link ?></p>
<ul><li><a href="index.php"><?php echo $lang_common['Index'] ?></a></li><li>&nbsp;&raquo;&nbsp;<a href="viewforum.php?id=<?php echo $cur_topic['forum_id'] ?>"><?php echo pun_htmlspecialchars($cur_topic['forum_name']) ?></a></li><li>&nbsp;&raquo;&nbsp;<?php echo pun_htmlspecialchars($cur_topic['subject']) ?></li></ul>
<div class="clearer"></div>
</div>
</div>
<?php
require PUN_ROOT.'include/parser.php';
$bg_switch = true; // Used for switching background color in posts
$post_count = 0; // Keep track of post numbers
// Retrieve the posts (and their respective poster/online status)
$result = $db->query('SELECT u.email, u.title, u.url, u.location, u.use_avatar, u.signature, u.email_setting, u.num_posts, u.registered, u.admin_note, p.id, p.poster AS username, p.poster_id, p.poster_ip, p.poster_email, p.message, p.hide_smilies, p.posted, p.edited, p.edited_by, g.g_id, g.g_user_title, o.user_id AS is_online FROM '.$db->prefix.'posts AS p INNER JOIN '.$db->prefix.'users AS u ON u.id=p.poster_id INNER JOIN '.$db->prefix.'groups AS g ON g.g_id=u.group_id LEFT JOIN '.$db->prefix.'online AS o ON (o.user_id=u.id AND o.user_id!=1 AND o.idle=0) WHERE p.topic_id='.$id.' ORDER BY p.id LIMIT '.$start_from.','.$pun_user['disp_posts'], true) or error('Unable to fetch post info', __FILE__, __LINE__, $db->error());
while ($cur_post = $db->fetch_assoc($result))
{
$post_count++;
$user_avatar = '';
$user_info = array();
$user_contacts = array();
$post_actions = array();
$is_online = '';
$signature = '';
// If the poster is a registered user.
if ($cur_post['poster_id'] > 1)
{
$username = '<a href="profile.php?id='.$cur_post['poster_id'].'">'.pun_htmlspecialchars($cur_post['username']).'</a>';
$user_title = get_title($cur_post);
if ($pun_config['o_censoring'] == '1')
$user_title = censor_words($user_title);
// Format the online indicator
$is_online = ($cur_post['is_online'] == $cur_post['poster_id']) ? '<strong>'.$lang_topic['Online'].'</strong>' : $lang_topic['Offline'];
/* begin SUCS avatar/hackergotchi hack
if ($pun_config['o_avatars'] == '1' && $cur_post['use_avatar'] == '1' && $pun_user['show_avatars'] != '0')
{
if ($img_size = @getimagesize($pun_config['o_avatars_dir'].'/'.$cur_post['poster_id'].'.gif'))
$user_avatar = '<img src="'.$pun_config['o_avatars_dir'].'/'.$cur_post['poster_id'].'.gif" '.$img_size[3].' alt="" />';
else if ($img_size = @getimagesize($pun_config['o_avatars_dir'].'/'.$cur_post['poster_id'].'.jpg'))
$user_avatar = '<img src="'.$pun_config['o_avatars_dir'].'/'.$cur_post['poster_id'].'.jpg" '.$img_size[3].' alt="" />';
*/
if ($img_size = @getimagesize("/var/www/sucssite/htdocs/pictures/people".'/'.$cur_post['username'].'.png')) {
$user_avatar = '<img src="/pictures/people/'.$cur_post['username'].'.png" '.$img_size[3].' alt="" />';
} else {
$user_avatar = '';
}
// We only show location, register date, post count and the contact links if "Show user info" is enabled
if ($pun_config['o_show_user_info'] == '1')
{
if ($cur_post['location'] != '')
{
if ($pun_config['o_censoring'] == '1')
$cur_post['location'] = censor_words($cur_post['location']);
$user_info[] = '<dd>'.$lang_topic['From'].': '.pun_htmlspecialchars($cur_post['location']);
}
//This is totally irrelavent to SUCS
//$user_info[] = '<dd>'.$lang_common['Registered'].': '.date($pun_config['o_date_format'], $cur_post['registered']);
if ($pun_config['o_show_post_count'] == '1' || $pun_user['g_id'] < PUN_GUEST)
$user_info[] = '<dd>'.$lang_common['Posts'].': '.$cur_post['num_posts'];
// Now let's deal with the contact links (E-mail and URL)
if (($cur_post['email_setting'] == '0' && !$pun_user['is_guest']) || $pun_user['g_id'] < PUN_GUEST)
$user_contacts[] = '<a href="mailto:'.$cur_post['email'].'">'.$lang_common['E-mail'].'</a>';
else if ($cur_post['email_setting'] == '1' && !$pun_user['is_guest'])
$user_contacts[] = '<a href="misc.php?email='.$cur_post['poster_id'].'">'.$lang_common['E-mail'].'</a>';
if ($cur_post['url'] != '')
$user_contacts[] = '<a href="'.pun_htmlspecialchars($cur_post['url']).'">'.$lang_topic['Website'].'</a>';
}
if ($pun_user['g_id'] < PUN_GUEST)
{
$user_info[] = '<dd>IP: <a href="moderate.php?get_host='.$cur_post['id'].'">'.$cur_post['poster_ip'].'</a>';
if ($cur_post['admin_note'] != '')
$user_info[] = '<dd>'.$lang_topic['Note'].': <strong>'.pun_htmlspecialchars($cur_post['admin_note']).'</strong>';
}
}
// If the poster is a guest (or a user that has been deleted)
else
{
$username = pun_htmlspecialchars($cur_post['username']);
$user_title = get_title($cur_post);
if ($pun_user['g_id'] < PUN_GUEST)
$user_info[] = '<dd>IP: <a href="moderate.php?get_host='.$cur_post['id'].'">'.$cur_post['poster_ip'].'</a>';
if ($pun_config['o_show_user_info'] == '1' && $cur_post['poster_email'] != '' && !$pun_user['is_guest'])
$user_contacts[] = '<a href="mailto:'.$cur_post['poster_email'].'">'.$lang_common['E-mail'].'</a>';
}
// Generation post action array (quote, edit, delete etc.)
if (!$is_admmod)
{
if (!$pun_user['is_guest'])
$post_actions[] = '<li class="postreport"><a href="misc.php?report='.$cur_post['id'].'">'.$lang_topic['Report'].'</a>';
if ($cur_topic['closed'] == '0')
{
if ($cur_post['poster_id'] == $pun_user['id'])
{
if ((($start_from + $post_count) == 1 && $pun_user['g_delete_topics'] == '1') || (($start_from + $post_count) > 1 && $pun_user['g_delete_posts'] == '1'))
$post_actions[] = '<li class="postdelete"><a href="delete.php?id='.$cur_post['id'].'">'.$lang_topic['Delete'].'</a>';
if ($pun_user['g_edit_posts'] == '1')
$post_actions[] = '<li class="postedit"><a href="edit.php?id='.$cur_post['id'].'">'.$lang_topic['Edit'].'</a>';
}
if (($cur_topic['post_replies'] == '' && $pun_user['g_post_replies'] == '1') || $cur_topic['post_replies'] == '1')
$post_actions[] = '<li class="postquote"><a href="post.php?tid='.$id.'&amp;qid='.$cur_post['id'].'">'.$lang_topic['Quote'].'</a>';
}
}
else
$post_actions[] = '<li class="postreport"><a href="misc.php?report='.$cur_post['id'].'">'.$lang_topic['Report'].'</a>'.$lang_topic['Link separator'].'</li><li class="postdelete"><a href="delete.php?id='.$cur_post['id'].'">'.$lang_topic['Delete'].'</a>'.$lang_topic['Link separator'].'</li><li class="postedit"><a href="edit.php?id='.$cur_post['id'].'">'.$lang_topic['Edit'].'</a>'.$lang_topic['Link separator'].'</li><li class="postquote"><a href="post.php?tid='.$id.'&amp;qid='.$cur_post['id'].'">'.$lang_topic['Quote'].'</a>';
// Switch the background color for every message.
$bg_switch = ($bg_switch) ? $bg_switch = false : $bg_switch = true;
$vtbg = ($bg_switch) ? ' roweven' : ' rowodd';
// Perform the main parsing of the message (BBCode, smilies, censor words etc)
$cur_post['message'] = parse_message($cur_post['message'], $cur_post['hide_smilies']);
// Do signature parsing/caching
if ($cur_post['signature'] != '' && $pun_user['show_sig'] != '0')
{
if (isset($signature_cache[$cur_post['poster_id']]))
$signature = $signature_cache[$cur_post['poster_id']];
else
{
$signature = parse_signature($cur_post['signature']);
$signature_cache[$cur_post['poster_id']] = $signature;
}
}
?>
<div id="p<?php echo $cur_post['id'] ?>" class="blockpost<?php echo $vtbg ?><?php if (($post_count + $start_from) == 1) echo ' firstpost'; ?>">
<h2><span><span class="conr">#<?php echo ($start_from + $post_count) ?>&nbsp;</span><a href="viewtopic.php?pid=<?php echo $cur_post['id'].'#p'.$cur_post['id'] ?>"><?php echo format_time($cur_post['posted']) ?></a></span></h2>
<div class="box">
<div class="inbox">
<div class="postleft">
<dl>
<dt><strong><?php echo $username ?></strong></dt>
<?php /*
<dd class="usertitle"><strong><?php echo $user_title ?></strong></dd> */ ?>
<dd class="postavatar"><?php echo $user_avatar ?></dd>
<?php if (count($user_info)) echo "\t\t\t\t\t".implode('</dd>'."\n\t\t\t\t\t", $user_info).'</dd>'."\n"; ?>
<?php if (count($user_contacts)) echo "\t\t\t\t\t".'<dd class="usercontacts">'.implode('&nbsp;&nbsp;', $user_contacts).'</dd>'."\n"; ?>
</dl>
</div>
<div class="postright">
<h3><?php if (($post_count + $start_from) > 1) echo ' Re: '; ?><?php echo pun_htmlspecialchars($cur_topic['subject']) ?></h3>
<div class="postmsg">
<?php echo $cur_post['message']."\n" ?>
<?php if ($cur_post['edited'] != '') echo "\t\t\t\t\t".'<p class="postedit"><em>'.$lang_topic['Last edit'].' '.pun_htmlspecialchars($cur_post['edited_by']).' ('.format_time($cur_post['edited']).')</em></p>'."\n"; ?>
</div>
<?php if ($signature != '') echo "\t\t\t\t".'<div class="postsignature"><hr />'.$signature.'</div>'."\n"; ?>
</div>
<div class="clearer"></div>
<div class="postfootleft"><?php if ($cur_post['poster_id'] > 1) echo '<p>'.$is_online.'</p>'; ?></div>
<div class="postfootright"><?php echo (count($post_actions)) ? '<ul>'.implode($lang_topic['Link separator'].'</li>', $post_actions).'</li></ul></div>'."\n" : '<div>&nbsp;</div></div>'."\n" ?>
</div>
</div>
</div>
<?php
}
?>
<div class="postlinksb">
<div class="inbox">
<p class="postlink conr"><?php echo $post_link ?></p>
<p class="pagelink conl"><?php echo $paging_links ?></p>
<ul><li><a href="index.php"><?php echo $lang_common['Index'] ?></a></li><li>&nbsp;&raquo;&nbsp;<a href="viewforum.php?id=<?php echo $cur_topic['forum_id'] ?>"><?php echo pun_htmlspecialchars($cur_topic['forum_name']) ?></a></li><li>&nbsp;&raquo;&nbsp;<?php echo pun_htmlspecialchars($cur_topic['subject']) ?></li></ul>
<?php echo $subscraction ?>
</div>
</div>
<?php
// Display quick post if enabled
if ($quickpost)
{
?>
<div class="blockform">
<h2><span><?php echo $lang_topic['Quick post'] ?></span></h2>
<div class="box">
<form method="post" action="post.php?tid=<?php echo $id ?>" onsubmit="this.submit.disabled=true;if(process_form(this)){return true;}else{this.submit.disabled=false;return false;}">
<div class="inform">
<fieldset>
<legend><?php echo $lang_common['Write message legend'] ?></legend>
<div class="infldset txtarea">
<input type="hidden" name="form_sent" value="1" />
<input type="hidden" name="form_user" value="<?php echo (!$pun_user['is_guest']) ? pun_htmlspecialchars($pun_user['username']) : 'Guest'; ?>" />
<label><textarea name="req_message" rows="7" cols="75" tabindex="1"></textarea></label>
<ul class="bblinks">
<li><a href="help.php#bbcode" onclick="window.open(this.href); return false;"><?php echo $lang_common['BBCode'] ?></a>: <?php echo ($pun_config['p_message_bbcode'] == '1') ? $lang_common['on'] : $lang_common['off']; ?></li>
<li><a href="help.php#img" onclick="window.open(this.href); return false;"><?php echo $lang_common['img tag'] ?></a>: <?php echo ($pun_config['p_message_img_tag'] == '1') ? $lang_common['on'] : $lang_common['off']; ?></li>
<li><a href="help.php#smilies" onclick="window.open(this.href); return false;"><?php echo $lang_common['Smilies'] ?></a>: <?php echo ($pun_config['o_smilies'] == '1') ? $lang_common['on'] : $lang_common['off']; ?></li>
</ul>
</div>
</fieldset>
</div>
<p><input type="submit" name="submit" tabindex="2" value="<?php echo $lang_common['Submit'] ?>" accesskey="s" /></p>
</form>
</div>
</div>
<?php
}
// Increment "num_views" for topic
$low_prio = ($db_type == 'mysql') ? 'LOW_PRIORITY ' : '';
$db->query('UPDATE '.$low_prio.$db->prefix.'topics SET num_views=num_views+1 WHERE id='.$id) or error('Unable to update topic', __FILE__, __LINE__, $db->error());
$forum_id = $cur_topic['forum_id'];
$footer_style = 'viewtopic';
require PUN_ROOT.'footer.php';
<?php
function sanitizePhone($phone)
{
return preg_replace("/[ ()]/", "", $phone);
}
function sanitizeAddress($address)
{
return str_replace(array("\r\n", "\r"), array("\n", "\n"), $address);
}
function sanitizePostcode($postcode)
{
//force uppercase, remove any possible stupid spaces and add the single space in the correct place
$postcode = strtoupper($postcode);
$postcode = str_replace(" ", "", $postcode);
return substr_replace($postcode, " ", -3, 0);
}
?>
<?
<?php
// To use:
// include_once "session.php"
// $mysession = new Session;
//
//
// $mysession->loggedin is TRUE if they have logged in
//
// other attributes are :
......@@ -11,323 +11,348 @@
// lastseen - unix timestamp for their previous page access
// data - var/array for persistant data, commit by calling the 'save' method
// Session management and authentication mechanism.
class Session {
public $loggedin=FALSE; // Is this a valid logged in user ?
public $username=''; // Username
public $fullname; // Fullname
public $email=0; // Email waiting?
public $email_forward; // Email forwarded?
public $groups =array(); // users groups
public $data=''; // Var/array for session persistant data
public $token=''; // session identifier
public $logintime=''; // Time which user last gave us credentials
public $lastseen=''; // Time of last page request
private $timeout = 2880; // Idle timeout limit in minutes (session deleted), 2880 == 48 hours
private $anonymous_timeout = 120; // Idle timeout limit for sessions which aren't logged in (set lower to stop the session table getting swamped)
private $secure_timeout = 30; // Idle timeout limit in minutes (consider session less secure, require reauth for sensitive ops)
private $max_session_length = 11520; // maximum length of a session, 11520 == 8 days
private $table = "session"; // session storage table (const)
private $datahash=''; // hash of data field
// Create a new (insecure) session
private function newsession()
{
global $DB, $preferred_hostname;
$token = $this->genSessionID();
$DB->Execute("insert into {$this->table} (hash, lastseen, ip) values (?,NOW(),?)", array($token, $_SERVER['REMOTE_ADDR']));
setcookie("sucssite_session", $token, NULL, "/", $preferred_hostname);
// delete loggedin cookie if it exists
setcookie("sucssite_loggedin", FALSE, time(), "/");
$this->token = $token;
return;
}
public function isSecure()
{
global $DB;
// is user coming from the IP address they were when they logged in?
if ($detail['ip'] != $_SERVER['REMOTE_ADDR']) {
return false;
} elseif (time() > ($this->logintime + $this->secure_timeout)) {
// has it been too long since we last asked for credentials?
return false;
}
}
// Public Object constructor
function __construct()
{
global $DB, $preferred_hostname, $baseurl;
unset($token);
// if user requests a page via HTTP and claims to be logged in, bump them to HTTPS
if (!isset($_SERVER['HTTPS']) && (@$_COOKIE['sucssite_loggedin'] == "true")) {
header("HTTP/1.0 307 Temporary redirect");
header("Location: https://{$preferred_hostname}{$baseurl}{$_SERVER['PATH_INFO']}");
return;
}
// The possible form elements
$submit = @$_POST['Login'];
$logout = @$_POST['Logout'];
$session_user = strtolower(@$_POST['session_user']);
$session_pass = @$_POST['session_pass'];
// We havent logged them in yet
$this->loggedin = FALSE;
// Time out any old sessions
$DB->Execute(
"delete from {$this->table} where lastseen < NOW() - '{$this->timeout} minutes'::reltime ".
"or logintime < NOW() - '{$this->max_session_length} minutes'::reltime ".
"or (username IS NULL AND lastseen < NOW() - '{$this->anonymous_timeout} minutes'::reltime)"
);
// the possible token data passed from a form
if (isset($_REQUEST['token']))
$token = $_REQUEST['token'];
// Check if we were handed a specific token identifier
// Otherwise use the value from the cookie we gave out
if (!isset($token) && isset($_COOKIE['sucssite_session']))
$token=@$_COOKIE['sucssite_session'];
if (isset($token)) $this->token = $token;
// Log them out if they ask
if ($logout=="Logout") {
$this->logout();
return;
}
// Okay, so we still dont have a session id
// so issue a new one and go back to core
if (!isset($token))
{
$this->newsession();
return;
}
// Is this a login attempt ?
if ($submit != '' && $session_user != '' && $session_pass != '')
{
$this->session_init($session_user, $session_pass);
}
// Retrieve session information
$oldsess=$DB->GetAll("select * from {$this->table} where hash=?", array($this->token));
if (!$oldsess || count($oldsess) < 1) {
trigger_error("Session timed out", E_USER_NOTICE);
$this->newsession();
return;
}
// Extract detail of session for pass-back
$detail = $oldsess[0];
$this->data = unserialize((string)$detail['data']);
$this->lastseen = strtotime($detail['lastseen']);
$this->logintime = strtotime($detail['logintime']);
$this->datahash = md5(serialize($this->data));
// are we actually logged in, fill in more
if ($detail['username']) {
// Are we using HTTPS?
if (!isset($_SERVER['HTTPS'])) {
trigger_error("Insecure Connection", E_USER_NOTICE);
$this->loggedin = FALSE;
return;
}
$this->username=$detail['username'];
$this->fetch_detail($detail['username']);
$this->loggedin = TRUE;
}
// update time stamp
$DB->Execute( "update {$this->table} set lastseen=NOW() where hash=?", array($this->token));
}
// generate a string suitable to be used as a session ID
private function genSessionID()
{
global $DB;
$try = 0;
$tt=date("D M d H:i:s Y");
$ip = $_SERVER['REMOTE_ADDR'];
$nonce = rand(); // this should stop session IDs being (easily) guessable by someone with the algorithm
do {
$token = md5("$ip$tt$nonce".$try++);
$old = $DB->GetAll("select hash from {$this->table} where hash=?", array($token));
} while ($old);
return $token;
}
// Public function: Store the session data away in the database
public function save( )
{
global $DB;
$newhash = md5(serialize($this->data));
if ($newhash == $this->datahash) {
// no change in data, dont save
return;
}
$DB->Execute("update {$this->table} set data=? where hash=?", array(serialize($this->data),$this->token));
}
// Public function: force a logout of the session
public function logout( )
{
global $DB;
$DB->Execute("delete from {$this->table} where hash=?", array($this->token));
$this->newsession();
$this->loggedin = FALSE;
setcookie("sucssite_loggedin", FALSE, time(), "/");
}
// Fill out any extra details we know about the user
private function fetch_detail( $user )
{
if (!($ldap = @ldap_connect("ldap://localhost"))) {
trigger_error("LDAP connect failed", E_USER_ERROR);
return FALSE;
}
$info = $this->ldap_getuser($ldap, $user);
if (!$info) return FALSE;
ldap_close($ldap);
// Check the user's email status
$mailstat = @stat("/var/spool/mail/".$user);
if ($mailstat[size]>0) {
if ($mailstat[mtime]>$mailstat[atime]) $this->email = 2;
else $this->email = 1;
}
if (file_exists($info['homedirectory'][0]."/.forward")) {
$forward = file($info['homedirectory'][0]."/.forward");
$this->email_forward = ereg_replace("\n", "", $forward[0]);
}
$this->fullname = $info['cn'][0];
$this->groups = $info['grouplist'];
}
/* check using mod_auth_externals helper
private function check_pass($user, $pass)
{
if ($fd === FALSE) {
$this->errormsg = "Auth system error";
return FALSE;
}
fwrite($fd, "$user\n");
fwrite($fd, "$pass\n");
$ret = pclose($fd);
if ($ret == 0) return TRUE;
$this->autherror = "u='$user' p='$pass' ret=$ret";
$this->errormsg = "Invalid Username or Password";
return FALSE;
}
*/
// Get a users full record from ldap
private function ldap_getuser($ldap, $user)
{
// publically bind to find user
if (!($bind=@ldap_bind($ldap, "", ""))) {
trigger_error("LDAP bind failed", E_USER_ERROR);
return NULL;
}
// find the user
if (!($search=@ldap_search($ldap, "dc=sucs,dc=org", "(&(uid=$user))"))) {
trigger_error("LDAP search fail", E_USER_ERROR);
return NULL;
}
$n = ldap_count_entries($ldap, $search);
if ($n < 1) {
trigger_error("Username or Password Incorrect", E_USER_WARNING);
return NULL;
}
$info = ldap_get_entries($ldap, $search);
if (($grpsearch=@ldap_search($ldap, "ou=Group,dc=sucs,dc=org", "memberuid=$user"))) {
$gn = ldap_count_entries($ldap,$grpsearch);
$gpile = ldap_get_entries($ldap, $grpsearch);
$glist=array();
for ($i=0;$i<$gn;$i++) {
$glist[ $gpile[$i]['cn'][0] ] = $gpile[$i]['gidnumber'][0];
}
$info[0]['grouplist'] = $glist;
}
return $info[0];
}
/* check using ldap directly */
private function check_pass($user, $pass)
{
// Open connection
if (!($ldap = @ldap_connect("ldap://localhost"))) {
trigger_error("LDAP connect failed", E_USER_ERROR);
return FALSE;
}
$info = $this->ldap_getuser($ldap, $user);
if (!$info) return FALSE;
$real = @ldap_bind($ldap, $info['dn'], $pass);
ldap_close($ldap);
if ($real) return TRUE;
trigger_error("Username or Password Incorrect", E_USER_WARNING);
return FALSE;
}
// Private function: process login form
private function session_init($user, $pass)
{
global $DB, $preferred_hostname;
// Check that this is a valid session start
// This prevents replay attacks
$sess = $DB->GetAll("select * from {$this->table} where hash=? and username is NULL", array($this->token));
if (!$sess || count($sess)<1) {
trigger_error("Invalid session, login again.", E_USER_WARNING);
return;
}
if (!$this->check_pass($user, $pass)) return;
$this->username = $user;
// the token has likely been used on an insecure connection
// so generate a new one with the secure flag set
$oldtoken = $this->token;
$this->token = $this->genSessionID();
setcookie("sucssite_session", $this->token, time() + $this->max_session_length * 60, "/", $preferred_hostname, TRUE);
// set a cookie as a hint that we're logged in
// this can be checked for to allow redirecting to SSL to get the secure cookie
setcookie("sucssite_loggedin", "true", time() + $this->max_session_length * 60, "/");
// Update the session, filling in the blanks
$DB->Execute("update {$this->table} set hash=?, username=?, logintime='NOW()', lastseen='NOW()', ip=? where hash=?",
array($this->token, $this->username, $_SERVER['REMOTE_ADDR'], $oldtoken));
// Return back to normal session retrieval
}
class Session
{
public $loggedin = FALSE; // Is this a valid logged in user ?
public $username = ''; // Username
public $fullname; // Fullname
public $email = 0; // Email waiting?
public $email_forward; // Email forwarded?
public $groups = array(); // users groups
public $printbalance; // printer balance
public $data = ''; // Var/array for session persistant data
public $token = ''; // session identifier
public $logintime = ''; // Time which user last gave us credentials
public $lastseen = ''; // Time of last page request
private $timeout = 2880; // Idle timeout limit in minutes (session deleted), 2880 == 48 hours
private $anonymous_timeout = 120; // Idle timeout limit for sessions which aren't logged in (set lower to stop the session table getting swamped)
private $secure_timeout = 30; // Idle timeout limit in minutes (consider session less secure, require reauth for sensitive ops)
private $max_session_length = 11520; // maximum length of a session, 11520 == 8 days
private $table = "session"; // session storage table (const)
private $datahash = ''; // hash of data field
// Create a new (insecure) session
private function newsession()
{
global $DB, $preferred_hostname, $dbname;
$token = $this->genSessionID();
$DB->Execute("insert into {$this->table} (hash, lastseen, ip) values (?,NOW(),?)", array($token, $_SERVER['REMOTE_ADDR']));
setcookie($dbname . "_session", $token, NULL, "/", $preferred_hostname);
// delete loggedin cookie if it exists
setcookie($dbname . "_loggedin", FALSE, time(), "/");
$this->token = $token;
return;
}
public function isSecure()
{
global $DB;
// is user coming from the IP address they were when they logged in?
if ($detail['ip'] != $_SERVER['REMOTE_ADDR']) {
return false;
} elseif (time() > ($this->logintime + $this->secure_timeout)) {
// has it been too long since we last asked for credentials?
return false;
}
}
// Public Object constructor
function __construct()
{
global $DB, $preferred_hostname, $baseurl, $dbname;
unset($token);
// if user requests a page via HTTP and claims to be logged in, bump them to HTTPS
if (!isset($_SERVER['HTTPS']) && (@$_COOKIE[$dbname . '_loggedin'] == "true")) {
header("HTTP/1.0 307 Temporary redirect");
header("Location: https://{$preferred_hostname}{$baseurl}{$_SERVER['PATH_INFO']}");
return;
}
// The possible form elements
$submit = @$_POST['Login'];
$logout = @$_POST['Logout'];
$session_user = strtolower(@$_POST['session_user']);
$session_pass = @$_POST['session_pass'];
// We havent logged them in yet
$this->loggedin = FALSE;
// Time out any old sessions
$DB->Execute(
"delete from {$this->table} where lastseen < NOW() - '{$this->timeout} minutes'::reltime " .
"or logintime < NOW() - '{$this->max_session_length} minutes'::reltime " .
"or (username IS NULL AND lastseen < NOW() - '{$this->anonymous_timeout} minutes'::reltime)"
);
// the possible token data passed from a form
if (isset($_REQUEST['token']))
$token = $_REQUEST['token'];
// Check if we were handed a specific token identifier
// Otherwise use the value from the cookie we gave out
if (!isset($token) && isset($_COOKIE[$dbname . '_session']))
$token = @$_COOKIE[$dbname . '_session'];
if (isset($token)) $this->token = $token;
// Log them out if they ask
if ($logout == "Logout") {
$this->logout();
return;
}
// Okay, so we still dont have a session id
// so issue a new one and go back to core
if (!isset($token)) {
$this->newsession();
return;
}
// Is this a login attempt ?
if ($submit != '' && $session_user != '' && $session_pass != '') {
// filter out everything but A-Z a-z 0-9 . - _ from username
$safeusername = preg_replace("/[^A-Za-z0-9\.\-\_]/", '', $session_user);
if ($safeusername != $session_user) {
trigger_error("Invalid username", E_USER_NOTICE);
$this->newsession();
return;
} elseif ($safeusername == $session_user) {
$this->session_init($safeusername, $session_pass);
}
}
// Retrieve session information
$oldsess = $DB->GetAll("select * from {$this->table} where hash=?", array($this->token));
if (!$oldsess || count($oldsess) < 1) {
trigger_error("Session timed out", E_USER_NOTICE);
$this->newsession();
return;
}
// Extract detail of session for pass-back
$detail = $oldsess[0];
$this->data = unserialize((string)$detail['data']);
$this->lastseen = strtotime($detail['lastseen']);
$this->logintime = strtotime($detail['logintime']);
$this->datahash = md5(serialize($this->data));
// are we actually logged in, fill in more
if ($detail['username']) {
// Are we using HTTPS?
if (!isset($_SERVER['HTTPS'])) {
trigger_error("Insecure Connection", E_USER_NOTICE);
$this->loggedin = FALSE;
return;
}
$this->username = $detail['username'];
$this->fetch_detail($detail['username']);
$this->loggedin = TRUE;
}
// update time stamp
$DB->Execute("update {$this->table} set lastseen=NOW() where hash=?", array($this->token));
// check to see if there any messages stored for this user
if (isset($this->data['messages'])) {
global $messages;
if (is_array($messages)) {
$messages += $this->data['messages'];
} else {
$messages = $this->data['messages'];
}
unset($this->data['messages']);
$this->save();
}
}
// generate a string suitable to be used as a session ID
private function genSessionID()
{
global $DB;
$try = 0;
$tt = date("D M d H:i:s Y");
$ip = $_SERVER['REMOTE_ADDR'];
$nonce = rand(); // this should stop session IDs being (easily) guessable by someone with the algorithm
do {
$token = md5("$ip$tt$nonce" . $try++);
$old = $DB->GetAll("select hash from {$this->table} where hash=?", array($token));
} while ($old);
return $token;
}
// Public function: Store the session data away in the database
public function save()
{
global $DB;
$newhash = md5(serialize($this->data));
if ($newhash == $this->datahash) {
// no change in data, dont save
return;
}
$DB->Execute("update {$this->table} set data=? where hash=?", array(serialize($this->data), $this->token));
}
// Public function: force a logout of the session
public function logout()
{
global $DB, $dbname;
$DB->Execute("delete from {$this->table} where hash=?", array($this->token));
$this->newsession();
$this->loggedin = FALSE;
setcookie($dbname . "_loggedin", FALSE, time(), "/");
}
// Fill out any extra details we know about the user
private function fetch_detail($user)
{
if (!($ldap = @ldap_connect("ldap://localhost"))) {
trigger_error("LDAP connect failed", E_USER_ERROR);
return FALSE;
}
$info = $this->ldap_getuser($ldap, $user);
if (!$info) return FALSE;
ldap_close($ldap);
// Check the user's email status
/*$mailstat = @stat("/var/spool/mail/".$user);
if ($mailstat[size]>0) {
if ($mailstat[mtime]>$mailstat[atime]) $this->email = 2;
else $this->email = 1;
}*/
// a sure-fire way to check to see if the user has any unread email
// the bash script returns 0 for no and 1 for yes, takes one arg, username
$this->email = shell_exec("../plugins/sucsunreadmail $user");
if (file_exists($info['homedirectory'][0] . "/.forward") && ! is_link($info['homedirectory'][0] . "/.forward")) {
$forward = file($info['homedirectory'][0] . "/.forward");
$this->email_forward = preg_replace("/\n/", "", $forward[0]);
}
$this->fullname = $info['cn'][0];
$this->groups = $info['grouplist'];
$db = new SQLite3('/etc/pykota/pykota.db');
$result = $db->query("SELECT balance FROM users WHERE username='$user';");
$this->printbalance = $result->fetchArray()[0];
}
/* check using mod_auth_externals helper
private function check_pass($user, $pass)
{
if ($fd === FALSE) {
$this->errormsg = "Auth system error";
return FALSE;
}
fwrite($fd, "$user\n");
fwrite($fd, "$pass\n");
$ret = pclose($fd);
if ($ret == 0) return TRUE;
$this->autherror = "u='$user' p='$pass' ret=$ret";
$this->errormsg = "Invalid Username or Password";
return FALSE;
}
*/
// Get a users full record from ldap
private function ldap_getuser($ldap, $user)
{
// publically bind to find user
ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
if (!($bind = @ldap_bind($ldap))) {
trigger_error("LDAP bind failed", E_USER_ERROR);
return NULL;
}
// find the user
if (!($search = @ldap_search($ldap, "dc=sucs,dc=org", "(&(uid=$user))"))) {
trigger_error("LDAP search fail", E_USER_ERROR);
return NULL;
}
$n = ldap_count_entries($ldap, $search);
if ($n < 1) {
trigger_error("Username or Password Incorrect", E_USER_WARNING);
return NULL;
}
$info = ldap_get_entries($ldap, $search);
if (($grpsearch = @ldap_search($ldap, "ou=Group,dc=sucs,dc=org", "memberuid=$user"))) {
$gn = ldap_count_entries($ldap, $grpsearch);
$gpile = ldap_get_entries($ldap, $grpsearch);
$glist = array();
for ($i = 0; $i < $gn; $i++) {
$glist[$gpile[$i]['cn'][0]] = $gpile[$i]['gidnumber'][0];
}
$info[0]['grouplist'] = $glist;
}
return $info[0];
}
/* check using ldap directly */
public function check_pass($user, $pass)
{
// Open connection
if (!($ldap = @ldap_connect("ldap://localhost"))) {
trigger_error("LDAP connect failed", E_USER_ERROR);
return FALSE;
}
$info = $this->ldap_getuser($ldap, $user);
if (!$info) return FALSE;
$real = @ldap_bind($ldap, $info['dn'], $pass);
ldap_close($ldap);
if ($real) return TRUE;
trigger_error("Username or Password Incorrect", E_USER_WARNING);
return FALSE;
}
// Private function: process login form
private function session_init($user, $pass)
{
global $DB, $preferred_hostname, $dbname;
// Check that this is a valid session start
// This prevents replay attacks
$sess = $DB->GetAll("select * from {$this->table} where hash=? and username is NULL", array($this->token));
if (!$sess || count($sess) < 1) {
trigger_error("Invalid session, login again.", E_USER_WARNING);
return;
}
if (!$this->check_pass($user, $pass)) return;
$this->username = $user;
// the token has likely been used on an insecure connection
// so generate a new one with the secure flag set
$oldtoken = $this->token;
$this->token = $this->genSessionID();
setcookie($dbname . "_session", $this->token, time() + $this->max_session_length * 60, "/", $preferred_hostname, TRUE);
// set a cookie as a hint that we're logged in
// this can be checked for to allow redirecting to SSL to get the secure cookie
setcookie($dbname . "_loggedin", "true", time() + $this->max_session_length * 60, "/");
// Update the session, filling in the blanks
$DB->Execute("update {$this->table} set hash=?, username=?, logintime='NOW()', lastseen='NOW()', ip=? where hash=?",
array($this->token, $this->username, $_SERVER['REMOTE_ADDR'], $oldtoken));
// Return back to normal session retrieval
}
} // end of Class
<?php
// sorry
// gib errars plox
//error_reporting(E_ALL);
//ini_set('display_errors', 1);
// without this the entire thing doesn't work
include_once("../suapiv2-key.php");
//SUCS Org ID According to the SU
$orgid = "6613";
$apibaseurl = "http://su-apiv2.sucs.org/?apikey=${apikey}&orgid=${orgid}";
// Get the shit json the suapiv2 spits out
$ch = curl_init($apibaseurl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$raw_data = curl_exec($ch);
curl_close($ch);
$formated_raw_data = json_decode($raw_data, true); //convert it into php arrays
/*
* $membership_data is an array where each type of memebrship is it;s own array
* Insdie each of those arrays the actual arrary of members is under ["Detail_Collection"]["Detail"]
* So $membership_data[0]["Detail_Collection"]["Detail"][0] will get you the array containing the
* first member in the data
*/
$membership_data = $formated_raw_data["table1"]["table1_Product_Collection"]["table1_Product"];
// make a new array that just contains *every* member no matter what they bought
$just_members = array();
function filter_array($data){
global $just_members;
// we have more than one type of member if this is true
if (count($data[0]["Detail_Collection"]["Detail"][0]["@attributes"]) == 7){
//split them up then feed them back
foreach ($data as $membershipType){
filter_array($membershipType);
}
// we have more then 1 of the same type of member if this is true
} else if (count($data["Detail_Collection"]["Detail"][0]["@attributes"]) == 7) {
//wack them onto the used array
foreach ($data["Detail_Collection"]["Detail"] as $member) {
array_push($just_members, $member["@attributes"]);
}
// we have 1 member :(
} else if (count($data["Detail_Collection"]["Detail"]["@attributes"]) == 7) {
array_push($just_members, $data["Detail_Collection"]["Detail"]["@attributes"]);
}
}
filter_array($membership_data);
/* You can now use $just_members to probe member detials. It's an array of arrays which each contain:
* transaction_id (recepit id)
* purchaser (full name)
* textbox6 (under 18 or not) NOT SURE OF THE FORMAT
* card_number (student number)
* shop_name (where they bought sucs memebrship)
* qty (how many sucs memebrships they bought)
* purchase_date (timestamp of when they bought memebrship)4
*/
/*
* Used by /susignup to verify that the stduent number and transaction id combo are valid
* returns true or false
*/
function check_su_sid_and_trans($sid, $transid)
{
global $just_members;
foreach ($just_members as $member) {
if ($sid == $member["card_number"] && $transid == $member["transaction_id"]) {
return true;
}
}
return false;
}
/*
* Used to verify taht a given stduent number has paid for membership via the su system.
* returns false or true
*/
function check_su_sid($sid)
{
global $just_members;
foreach ($just_members as $member) {
if ($sid == $member["card_number"]) {
return true;
}
}
return false;
}
?>
<?
<?php
require_once("validationData.php");
require_once("sanitization.php");
/* useful validation functions */
//check for a valid email address
function validEmail ($email)
function validEmail($email)
{
global $error;
//split user and domain
list($user,$domain) = explode("@", $email);
// check for bad characters, and check for zero length user & domain
if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$",$email) or !$user or !$domain )
{
$error = 'an invalid email address (syntax)';
return false;
}
// Syntax OK
// Check for an mail server
elseif(!getmxrr($domain,$mx) or !gethostbyname($domain))
{
$error = "no mail servers listed for '$domain'";
return false;
}
else
{
// Email address valid from technical point of view
return true;
}
global $error;
// check for valid syntax
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error = 'Invalid email address (syntax)';
return false;
}
// Syntax OK
// domain consists of any character after a '@' and cannot contain '@'
// therefore any character after the last '@' is part of the domain
$domain = substr($email, strrpos($email, '@') + 1);
// Check for an mail server
if (!getmxrr($domain, $mx) or !gethostbyname($domain)) {
$error = "No mail servers listed for '$domain'";
return false;
} else {
// Email address valid from technical point of view
return true;
}
}
# Use cracklib to check for weak passwords.
# returns FALSE if the password is good i.e. not weak
# otherwise returns a string saying why its weak
function weakPassword($password)
{
// Try fedora then debian known paths
if (file_exists("/usr/sbin/cracklib-check"))
$cracklib = "/usr/sbin/cracklib-check";
else
if (file_exists("/usr/sbin/crack_testlib"))
$cracklib = "/usr/sbin/crack_testlib";
else
return "Cannot find cracklib";
$proc = proc_open($cracklib, array(0 => array("pipe", "r"), 1 => array("pipe", "w")), $pipes, '/tmp/', NULL);
if (!is_resource($proc)) {
return "Cannot find cracklib";
}
fwrite($pipes[0], $password);
fclose($pipes[0]);
$last = "";
do {
$last = fgets($pipes[1]);
if ($last !== FALSE) $answer = trim($last);
} while ($last !== FALSE);
fclose($pipes[1]);
proc_close($proc);
$answer = substr(strrchr($answer, ":"), 2);
if (strtolower($answer) == "ok") return FALSE;
if ($answer == "") return ("Empty password");
return $answer;
}
// check if username is an alias
function isAlias($username)
{
$ok = false;
// check its not an alias
$aliasesfile = file('/etc/aliases');
foreach ($aliasesfile as $aliasline) {
if (trim($aliasline) && $aliasline[0] != "#") {
$anAlias = explode(":", trim($aliasline));
if ($anAlias[0] && !posix_getpwnam($anAlias[0]) && ($anAlias[0] == $username)) {
$ok = true;
return true;
}
}
}
return $ok;
}
//check if a user with a sid already exists
function sidUsed($sid)
{
$sucsDB = NewADOConnection('postgres8');
$sucsDB->Connect('dbname=sucs');
$sucsDB->SetFetchMode(ADODB_FETCH_ASSOC);
$query = "SELECT * FROM members WHERE sid=?";
$data = $sucsDB->GetAll($query, $sid);
return (sizeof($data) > 0);
}
function validUsername($username)
{
global $error;
// check if uname is syntactically valid
$syntax = preg_match("/^[a-z][a-z0-9_]*$/", $username);
if (!$syntax || (strlen($username) < 2)) {
$error = "Usernames must start with a letter, only contain lowercase letters, numbers 0-9 and underscores (_) and be at least 2 characters.";
return false;
} // check if the username already exists
elseif (posix_getpwnam($username)) {
$error = "Username already taken";
return false;
} // check if its a mail alias
elseif (isAlias($username)) {
$error = "Username is a mail alias";
return false;
} else {
return true;
}
}
// test whether a password is considered Strong Enough
// ideally we'd want to use cracklib or something here, but no RPM for the php bindings :-(
function strongPassword ($pass) {
// you call this a password? my cat could bruteforce this.
if (strlen($pass) < 6) {
return false;
}
// start at 0, and increment for certain features
$score = 0;
// greater than 8 characters
if (strlen($pass) > 8) $score++;
// includes lowercase characters
if (preg_match("/[a-z]/", $pass)) $score++;
// includes uppercase characters
if (preg_match("/[A-Z]/", $pass)) $score++;
// includes digits
if (preg_match("/\d/", $pass)) $score++;
// includes "non-word" characters
if (preg_match("/\W/", $pass)) $score++;
// I reckons if it has at least 3 of the above it should be... adequate
// better if it checked for dictionary words too though
if ($score > 3) {
return true;
} else {
return false;
}
function validSID($SID, $override)
{
global $error;
if ($override) {
if ($SID == "") {
$error = "You MUST provide some sort of student number";
return false;
} else {
return true;
}
} else {
if (!preg_match("/^[0-9]{6,}$/", $SID)) {
$error = "Invalid student ID";
return false;
} elseif (sidUsed($SID)) {
$error = "A user with that student ID already exists, email <a href=\"mailto:admin@sucs.org\">admin@sucs.org</a> if this is an error.";
return false;
} elseif (lookupSID($SID) == " ") {
$error = "Student not found, email <a href=\"mailto:admin@sucs.org\">admin@sucs.org</a> if this is an error.";
return false;
} else {
return true;
}
}
}
function validName($realName, $override)
{
global $error;
if ($override) {
if ($realName == "") {
$error = "You MUST provide some sort of name";
return false;
} else {
return true;
}
} else {
// names can legally be really weird so just check that it is at least 1 visible character
// followed by any number of non-control characters
$realName = trim($realName);
if (!preg_match("/^[[:graph:]][[:print:]]*$/", $realName)) {
$error = "Invalid name";
return false;
} else {
return true;
}
}
}
function validAddress($address)
{
global $error;
$address = sanitizeAddress($address);
// check that they at least entered in something. Address doesn't need to be as strict when the postcode is.
$regex = "/^.{5,}+$/s";
if (!preg_match($regex, $address)) {
$error = "Please supply a valid address.";
return false;
} else {
return true;
}
}
function validPostcode($postcode)
{
$postcode = sanitizePostcode($postcode);
// matches all postcodes following the valid format described in a 2012 government published document
$postcodeRegex = "/^([A-Z](([0-9][0-9]?)|([A-Z][0-9][0-9]?)|([A-Z]?[0-9][A-Z])) ?[0-9][ABD-HJLNP-UW-Z]{2})$/";
if (!preg_match($postcodeRegex, $postcode)) {
return false;
} else {
return $postcode;
}
}
function validPhone($phone)
{
global $error;
$phone = sanitizePhone($phone);
if (!preg_match("/^\+?[0-9-]{10,}$/", $phone)) {
$error = "Must be all numbers";
return false;
}
return true;
}
function validSignupEmail($email)
{
global $error;
if (preg_match('/@sucs\.$/', $email)) {
$error = "SUCS email addresses are not allowed";
return false;
} elseif (!validEmail($email)) {
return false;
} else {
return true;
}
}
?>
<?php
// lookup real names from sid's using campus ldap
function lookupSID($sid)
{
$ds = ldap_connect("192.168.10.16");
ldap_set_option($ds, LDAP_OPT_NETWORK_TIMEOUT, 10); /* 10 second timeout */
ldap_bind($ds);
$sr = ldap_search($ds, "ou=Active,ou=Resources,o=Swansea", "EDUPERSONTARGETEDID=" . $sid);
$info = ldap_get_entries($ds, $sr);
ldap_unbind($ds);
return ucwords(strtolower($info[0]['givenname'][0] . " " . $info[0]['sn'][0]));
}
// lookup addresses from postcodes using the university's website
function lookup_postcode($postcode)
{
include_once "../paf-key.php";
$url = "http://paf.sucs.org/?apikey=$apikey&postcode=" . rawurlencode($postcode);
$req = curl_init($url);
curl_exec($req);
curl_close($req);
}
?>
<?php
function smarty_function_articlesummary($params, &$smarty) {
$article = $params['article'];
$id = $params['id'];
$title = rawurlencode($params['title']);
function smarty_function_articlesummary($params, &$smarty)
{
$linky = "<span style=\"float: right\"><a href=\"/News/".rawurlencode($title)."\">Read More</a></span>";
$article = $params['article'];
$id = $params['id'];
$title = rawurlencode($params['title']);
$matches = array();
preg_match("/^(<p>.*?<\/p>)/s", $article, $matches);
$summary = preg_replace("/<\/p>/","$linky</p>", $matches[0]);
return $summary;
}
$linky = "<span style=\"float: right\"><a href=\"/News/" . rawurlencode($title) . "\">Read More</a></span>";
$matches = array();
preg_match("/^(<p>.*?<\/p>)/s", $article, $matches);
$summary = preg_replace("/<\/p>/", "$linky</p>", $matches[0]);
return $summary;
}
?>
<?php
// map number of bananas (-3 to 3) to a CSS class name
function smarty_function_award_image_class($params, &$smarty) {
$number = $params['number'];
function smarty_function_award_image_class($params, &$smarty)
{
$number = $params['number'];
$image_class = "";
$image_class = "";
switch ($number) {
case -3:
$image_class = "green3";
break;
case -2:
$image_class = "green2";
break;
case -1:
$image_class = "green1";
break;
case 1:
$image_class = "yellow1";
break;
case 2:
$image_class = "yellow2";
break;
case 3:
$image_class = "yellow3";
break;
}
switch ($number) {
case -3:
$image_class = "green3";
break;
case -2:
$image_class = "green2";
break;
case -1:
$image_class = "green1";
break;
case 1:
$image_class = "yellow1";
break;
case 2:
$image_class = "yellow2";
break;
case 3:
$image_class = "yellow3";
break;
}
return $image_class;
return $image_class;
}
?>
<?php
function smarty_function_bananaprint($params, &$smarty) {
$output = "";
$score = $params['score'];
if ($score > 0) {
while ($score >= 50) {
$output .= " <img src=\"/images/bananas/banana-crate.png\" width=\"92\" height=\"64\" alt=\"50\" title=\"Crate of 50 Bananas\" />\n";
$score -= 50;
}
while ($score >= 5) {
$output .= " <img src=\"/images/bananas/banana-bunch.png\" alt=\"5\" width=\"64px\" height=\"64px\" title=\"Bunch of 5 Bananas\" />\n";
$score -= 5;
}
while ($score > 0) {
$output .= " <img src=\"/images/bananas/banana-one.png\" alt=\"1\" width=\"25px\" height=\"64px\" title=\"1 Banana\" />\n";
$score -= 1;
}
}else if ($score == 0) {
$output .= " <img src=\"/images/bananas/banana-zero.png\" alt=\"0\" width=\"25px\" height=\"64px\" title=\"0 Bananas\" />\n";
}else {
while ($score <= -50) {
$output .= " <img src=\"/images/bananas/banana-g-crate.png\" width=\"92\" height=\"64\" alt=\"-50\" title=\"Crate of 50 Green Bananas\" />\n";
$score += 50;
}
while ($score <= -5) {
$output .= " <img src=\"/images/bananas/banana-g-bunch.png\" width=\"64px\" height=\"64px\" alt=\"-5\" title=\"Bunch of 5 Green Bananas\" />\n";
$score += 5;
}
while ($score < 0) {
$output .= " <img src=\"/images/bananas/banana-g-one.png\" width=\"25px\" height=\"64px\" alt=\"-1\" title=\"1 Green Banana\" />\n";
$score += 1;
}
}
return $output;
}
function smarty_function_bananaprint($params, &$smarty)
{
$output = "";
$score = $params['score'];
if ($score > 0) {
while ($score >= 250) {
$output .= " <img src=\"/images/bananas/banana-container.png\" width=\"92\" height=\"64\" alt=\"250\" title=\"Container of 250 Bananas\" />\n";
$score -= 250;
}
while ($score >= 50) {
$output .= " <img src=\"/images/bananas/banana-crate.png\" width=\"92\" height=\"64\" alt=\"50\" title=\"Crate of 50 Bananas\" />\n";
$score -= 50;
}
while ($score >= 5) {
$output .= " <img src=\"/images/bananas/banana-bunch.png\" alt=\"5\" width=\"64px\" height=\"64px\" title=\"Bunch of 5 Bananas\" />\n";
$score -= 5;
}
while ($score > 0) {
$output .= " <img src=\"/images/bananas/banana-one.png\" alt=\"1\" width=\"25px\" height=\"64px\" title=\"1 Banana\" />\n";
$score -= 1;
}
} else if ($score == 0) {
$output .= " <img src=\"/images/bananas/banana-zero.png\" alt=\"0\" width=\"25px\" height=\"64px\" title=\"0 Bananas\" />\n";
} else {
while ($score <= -250) {
$output .= " <img src=\"/images/bananas/banana-g-container.png\" width=\"92\" height=\"64\" alt=\"250\" title=\"Container of 250 Green Bananas\" />\n";
$score += 250;
}
while ($score <= -50) {
$output .= " <img src=\"/images/bananas/banana-g-crate.png\" width=\"92\" height=\"64\" alt=\"-50\" title=\"Crate of 50 Green Bananas\" />\n";
$score += 50;
}
while ($score <= -5) {
$output .= " <img src=\"/images/bananas/banana-g-bunch.png\" width=\"64px\" height=\"64px\" alt=\"-5\" title=\"Bunch of 5 Green Bananas\" />\n";
$score += 5;
}
while ($score < 0) {
$output .= " <img src=\"/images/bananas/banana-g-one.png\" width=\"25px\" height=\"64px\" alt=\"-1\" title=\"1 Green Banana\" />\n";
$score += 1;
}
}
return $output;
}
?>
<?php
function smarty_function_buildpath($params, &$smarty) {
if ($params['item']=="") return "/";
foreach ($params['list'] as $crumb) {
if ($crumb!="") $output.="/".$crumb;
if ($crumb==$params['item']) return $output;
}
function smarty_function_buildpath($params, &$smarty)
{
if ($params['item'] == "") return "/";
foreach ($params['list'] as $crumb) {
if ($crumb != "") $output .= "/" . rawurlencode($crumb);
if ($crumb == $params['item']) return $output;
}
}
}
?>
<?php
function smarty_function_getparams($params, &$smarty) {
function smarty_function_getparams($params, &$smarty)
{
$output = "";
$output = "";
if (isset($params['gets'])) {
$output .= "?";
$i = 0;
foreach ($params['gets'] as $name => $value) {
if ((trim($name) == "") || (trim($value) == ""))
continue;
if (isset($params['gets'])) {
$output .= "?";
$i = 0;
foreach ($params['gets'] as $name => $value) {
if ((trim($name) == "") || (trim($value) == ""))
continue;
if ($i != 0) {
$output .= "&amp;";
} else {
$i++;
}
$output .= "$name="."$value";
}
}
if ($i != 0) {
$output .= "&amp;";
} else {
$i++;
}
$output .= "$name=" . "$value";
}
}
return $output;
return $output;
}
?>
<?php
function smarty_function_logo_of_the_day($params, &$smarty)
{
$logos = glob("../htdocs/images/awesomelogos/*.png");
$logo_of_the_day = $logos[array_rand($logos)];
$logo_size = getimagesize($logo_of_the_day);
$width_height_string = $logo_size[3];
$logo_src = str_replace("../htdocs", "", $logo_of_the_day);
return "<img src=\"$logo_src\" $width_height_string alt=\"SUCS\" />";
}
?>
<?php
function smarty_function_memberwebsitelist($params, &$smarty) {
$list = $params['members'];
$letter = "";
foreach ($list as $item) {
if ($letter != strtoupper(substr($item['uid'], 0, 1))) {
$letter = strtoupper(substr($item['uid'], 0, 1));
}
$members[$letter][] = $item['uid'];
}
foreach ($members as $letter => $lettermembers) {
$memcount = sizeof($lettermembers);
$col1count = round($memcount / 2);
$col1height = $col1count * 1.2;
$output .= "<h4>$letter</h4>\n<ul>\n";
for ($i = 0; $i < $memcount; $i++) {
$member = $lettermembers[$i];
if ($i < $col1count) {
$output .= "<li class=\"column1\">";
} elseif ($i == $col1count) {
$output .= "<li class=\"column2\" style=\"margin-top: -{$col1height}em\">";
} else {
$output .= "<li class=\"column2\">";
}
$output .= "<a href=\"http://sucs.org/~$member\">$member</a></li>\n";
}
$output .= "</ul>\n";
}
return $output;
function smarty_function_memberwebsitelist($params, &$smarty)
{
$list = $params['members'];
$letter = "";
foreach ($list as $item) {
if ($letter != strtoupper(substr($item['uid'], 0, 1))) {
$letter = strtoupper(substr($item['uid'], 0, 1));
}
$members[$letter][] = $item['uid'];
}
foreach ($members as $letter => $lettermembers) {
$memcount = sizeof($lettermembers);
$col1count = round($memcount / 2);
$col1height = $col1count * 1.2;
$output .= "<h4>$letter</h4>\n<ul>\n";
for ($i = 0; $i < $memcount; $i++) {
$member = $lettermembers[$i];
if ($i < $col1count) {
$output .= "<li class=\"column1\">";
} elseif ($i == $col1count) {
$output .= "<li class=\"column2\" style=\"margin-top: -{$col1height}em\">";
} else {
$output .= "<li class=\"column2\">";
}
$output .= "<a href=\"http://sucs.org/~$member\">$member</a></li>\n";
}
$output .= "</ul>\n";
}
return $output;
}
?>
<?php
function smarty_modifier_encodestring($string)
{
$string = rawurlencode($string);
$string = str_replace("_", "%5F", $string);
$string = str_replace("%20", "_", $string);
return $string;
}
?>
#!/bin/bash
if finger -m $1 | grep "New mail" &> /dev/null
then
echo "1"
else
echo "0"
fi
\ No newline at end of file
......@@ -4,5 +4,13 @@ $base = "$BASEDIR/";
$baseurl = "/~$USERNAME/sucssite";
$preferred_hostname = "sucs.org";
$dbname="beta";
$sucsdbname="sucs-dummy";
$dbuser="$USERNAME";
// Settings for current election (god knows why they are here):
define('ELECTION_YEAR', '2015');
define('ELECTION_START', '2014-12-01 00:00');
define('ELECTION_END', '2014-12-07 23:59');
define('ELECTION_NO_MANIFESTO', 'https://sucs.org/~$USERNAME/sucssite/Vote/No%20Manifesto');
?>
......@@ -3,11 +3,7 @@
# Setup script for SUCS website in users' public_html dirs
echo "SUCS website setup script"
# (try and) make sure we're running this from the right place
# SUCS website
# ^ a nasty kludge cause I don't know how to do it more sensibly
# test for the magic phrase on line 7 of this very file
head -n 7 setup.sh 2> /dev/null | tail -n 1 | grep -q "SUCS website"
ls $(pwd)/setup.sh &> /dev/null
if [ $? -ne 0 ]; then echo "Please run this script from its containing directory"; exit; fi
# generate correct .htaccess
......@@ -27,5 +23,4 @@ echo "Done!"
# and you're done!
echo -e "\nYou should now be able to view your local copy of the SUCS site at http://sucs.org/~$USER/sucssite/"
echo "Please contact a member of the admin team if you require use of the development database"
echo "Please contact a member of the admin team to gain access to the development database"
\ No newline at end of file
<p>Sorry, but the page you requested does not exist on our server.</p>
<p>Try searching for it instead using the <em>Search SUCS</em> box.</p>