<?php if (!defined('readit')) exit ();
/*
Copyright 2008-2009 Peter Reuterås <peter@reuteras.com>
This file is part of Read it!.
Read it! 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 3 of the License, or
(at your option) any later version.
Read it! 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 Read it!. If not, see <http://www.gnu.org/licenses/>.
$Id$
*/
// This file contains some common functions used in different files
// Print DOCTYPE
function print_doctype(){
echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"'."\n".
' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'."\n";
}
// Print page title
function print_h1(){
echo '<h1><a href="index.php">read it!</a></h1>'."\n\n";
}
// Main menu list
function print_main_menu(){
echo '<div id="menu">'."\n".
'<a href="index.php?upload">upload</a> '.
':: <a href="index.php?search&list=read_it&dir=asc">search</a> ';
if ($_SESSION['admin'] == "yes"){
echo ':: <a href="index.php?admin">admin'.nr_new_users().'</a> ';
}
echo "\n</div>\n";
}
// Print common content start
function print_content_start($text, $id="default"){
echo "\n".'<fieldset>'."\n";
echo "<legend>$text</legend>\n";
echo '<div class="container" id="'.$id.'">'."\n\n";
}
// Print common content end
function print_content_end(){
echo '</div>'."\n";
echo '</fieldset>'."\n\n";
}
// Print welcome text message
function welcome_text(){
$sql='SELECT firstname FROM members WHERE memberid='.$_SESSION["memberid"];
$result=mysql_query($sql);
if(!$result){
readit_error("Your name is not in the database");
}
$row=mysql_fetch_array($result);
print_text($row[0].', welcome to <span class="readit">read it!</span>. '.
'Maybe you would like to <a href="index.php?upload">upload</a> '.
'a document?');
mysql_free_result($result);
}
// Print this message if the user hasn't logged in yet
function print_anonymous(){
print_text('Welcome to <span class="readit">read it!</span>, a tool for '.
'storing documents on the webb and make it easy to rate, tag and '.
'find them. You can also prioritize how important it is to read an '.
'unread document.');
print_text('You can either proceed to the '.
'<a href="index.php?login">login</a> or the '.
'<a href="index.php?registration">registration</a> page.');
}
// Include the specified template
// and use the local version if it exists
function print_template($template){
//This is ugly. Should look at path in some good way
if(file_exists("registration.php")){
$change_dir="../";
} else {
$change_dir="";
}
if (file_exists($change_dir."template/".$template."-local.php")) {
require($change_dir."template/".$template."-local.php");
}else{
require($change_dir."template/".$template.".php");
}
}
// Print some statistics. In the future I should add statistics for
// read/unread and ratings etc
function statistics(){
// The number of different documents in the database
$sql="SELECT count(result) FROM (SELECT count(sha1) AS result FROM ".
"member_file GROUP BY sha1) AS total";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
$nr_docs=$row['0'];
mysql_free_result($result);
// The number of users in the system
$sql="SELECT count(*) FROM members";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
mysql_free_result($result);
$nr_users=$row['0'];
// Number of read documents (can be more then the number of
// different documents above...
$sql="SELECT count(*) FROM member_file WHERE read_it='0'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
mysql_free_result($result);
$unread=$row['0'];
// Total sum of all copies of files (not the real value on disc, this is
// higher)
$sql="SELECT sum(docsize) FROM member_file";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
mysql_free_result($result);
$size=$row['0'];
// Last uploaded time
$sql="SELECT timestamp FROM member_file ORDER BY timestamp LIMIT 1";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
mysql_free_result($result);
$newest=$row['0'];
// First uploaded document
$sql="SELECT timestamp FROM member_file ORDER BY timestamp DESC LIMIT 1";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
mysql_free_result($result);
$oldest=$row['0'];
// Print a nice summary
print_text('There are currently '.$nr_docs.' different documents, '.
$unread.' unread, from '.$nr_users.' user'.($nr_users>1?"s":"").
' with a total size of '.sprintf("%d",$size/1024/1024).' MB. '.
'The first document was uploaded on '.
date('F j, Y, \a\t H:i:s', $oldest).'. '.
'The latest document was on '.date('F j, Y, \a\t H:i:s', $newest).'.');
}
// Give information about a successful operation
// print string
function readit_success($string){
echo '<div id="success">'."\n".
$string."\n".
"</div>\n";
}
// Error, print error message and make sure we
// exit and don't continue
function readit_error($string){
echo '<div id="failure">'."\n".
"Error: ".$string."\n".
"</div>\n";
print_template("page_end");
print_template("footer");
exit;
}
//
// Translate functions for numbers stored in the database
//
// Translate the numeric value of privacy from the database into more
// userfriendly text
function translate_privacy($privacy){
if($privacy == 0){
$status="public";
}elseif($privacy == 1){
$status="friends";
}elseif($privacy == 2){
$status="private";
}
return $status;
}
// Translate the numeric value of read it status from the database into more
// userfriendly text (yes or no)
function translate_read_it($read_it){
return $read_it?'yes':'no';
}
// Translate the numeric value of rate from the database into more
// userfriendly text
function translate_rate($rate){
if($rate == 5){
$status="5 - very good";
}elseif($rate == 4){
$status="4 - good";
}elseif($rate == 3){
$status="3 - ok";
}elseif($rate == 2){
$status="2 - not good";
}elseif($rate == 1){
$status="1 - bad";
}elseif($rate == 0){
$status="0 - not read";
}
return $status;
}
// Translate the numeric value of priority from the database into more
// userfriendly text
function translate_priority($priority){
if($priority == 5){
$status="5 - read now!";
}elseif($priority == 4){
$status="4 - soon";
}elseif($priority == 3){
$status="3 - standard";
}elseif($priority == 2){
$status="2 - not now";
}elseif($priority == 1){
$status="1 - ?";
}elseif($priority == 0){
$status="0 - read it";
}
return $status;
}
// Validate functions
// Always check input and always use the functions below, that way validation
// will be the same in all functions
// Check valid sha1 sum for the document id used as key in the database
function valid_sha1($sha1){
return preg_match('/^[0-9a-z]*$/', $sha1);
}
// Check valid token
function valid_token($token){
return preg_match('/^[0-9a-zA-Z]{36}$/', $token);
}
// Check valid read priority
function valid_priority($priority){
return preg_match('/^[0-5]$/', $priority);
}
// Check valid privacy level
function valid_privacy($privacy){
return preg_match('/^[0-2]$/', $privacy);
}
// Check valid rate
function valid_rate($rate){
return preg_match('/^[0-5]$/', $rate);
}
// Check valid search term
function valid_search_term($search_term){
return preg_match('/^[-0-9A-Za-zåäöÅÄÖ.,_ =()]*$/', $search_term);
}
// Check that read status (rstatus) is valid
function valid_search_rstatus($rstatus){
return preg_match('/^[0-2]$/', $rstatus);
}
// Check that the chars in mime is correct
function valid_mime($mime){
return preg_match('/^application\/[-0-9a-z.]+$/', $mime);
}
// Check valid password
function valid_password($passwd){
$isvalid=true;
if(strlen($passwd) < 8){
$isvalid=false;
}
$count=0;
$count=(preg_match('/[0-9]+/',$passwd))?++$count:$count;
$count=(preg_match('/[a-z]+/',$passwd))?++$count:$count;
$count=(preg_match('/[A-Z]+/',$passwd))?++$count:$count;
$count=(preg_match('/[-_!"#%&\/()=.:,;*]+/',$passwd))?++$count:$count;
if($count < 3){
$isvalid=false;
}
return $isvalid;
}
// Check valid tags
function valid_tags($tags){
return preg_match('/^[-\/@#0-9A-Za-z.åäöÅÄÖ_ ?!&%]*$/', $tags);
}
// Check valid url
function valid_url($url){
return preg_match('/^[-_\/:0-9A-Za-zåäöÅÄÖ., =()&?%#]*$/', $url);
}
// Check valid comment
function valid_comment($comment){
return preg_match('/^[-_\/:0-9A-Za-zåäöÅÄÖ., =()?!&]*$/', $comment);
}
// Check vadid firstname and lastname
function valid_name($name){
return preg_match('/^[-0-9A-Za-zåäöÅÄÖ., ()]+$/', $name);
}
// Check valid username
function valid_username($username){
return preg_match('/^[0-9a-z]+$/', $username);
}
// Check valid memberid
function valid_memberid($memberid){
return preg_match('/^[1-9]+[0-9]*$/', $memberid);
}
// Bad check for valid email address
// This function is taken from:
// http://www.linuxjournal.com/article/9585
function valid_email($email){
/**
Validate an email address.
Provide email address (raw input)
Returns true if the email address has the email
address format and the domain exists.
*/
$isValid = true;
$atIndex = strrpos($email, "@");
if(is_bool($atIndex) && !$atIndex){
$isValid = false;
} else {
$domain = substr($email, $atIndex+1);
$local = substr($email, 0, $atIndex);
$localLen = strlen($local);
$domainLen = strlen($domain);
if ($localLen < 1 || $localLen > 64){
// local part length exceeded
$isValid = false;
} else if($domainLen < 1 || $domainLen > 255){
// domain part length exceeded
$isValid = false;
} else if ($local[0] == '.' || $local[$localLen-1] == '.'){
// local part starts or ends with '.'
$isValid = false;
} else if (preg_match('/\\.\\./', $local)){
// local part has two consecutive dots
$isValid = false;
} else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)){
// character not valid in domain part
$isValid = false;
} else if (preg_match('/\\.\\./', $domain)){
// domain part has two consecutive dots
$isValid = false;
} else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',
str_replace("\\\\","",$local))){
// character not valid in local part unless
// local part is quoted
if (!preg_match('/^"(\\\\"|[^"])+"$/',
str_replace("\\\\","",$local))){
$isValid = false;
}
}
if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A"))) {
// domain not found in DNS
$isValid = false;
}
}
return $isValid;
}
// Generate random string
function random_string($length=10){
$string="";
$chars="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
for($i=0;$i<$length;$i++){
$string.=$chars[mt_rand(0,strlen($chars)-1)];
}
return $string;
}
// Print word with javascript update functions
// function text_admin_new(action, memberid)
// action - take this action on the user
// - accept: let the user access the system
// - block: mark as not allowed and don't show after reload
// - admin: allow as admin
function text_admin_new($action, $memberid){
return '<span id="req'.$memberid.
'" >.
"'lib/ajax/admin.php', 'req".$memberid."', 'admin', '".$memberid.
"', '');window.location.reload()\">".$action."</span>\n";
}
// This function lets you edit a single word in the page
// column - column to change in the database
// memberid - change this id in the database
// value - current value
// ajax_url - url to ajax file
function print_prompt_word($column, $memberid, $value, $ajax_url){
$spanid=$column.$memberid;
echo '<div class="word">'."\n".
'<span id="'.$spanid.'" '.
'>.$spanid.'\').toggle();'.
'$(\'#'.$spanid.'-form\').toggle()">'.$value.'</span>'."\n".
'<div id="'.$spanid.'-form" style="display: none">'."\n".
'<form method="post" action="" '.
'>.$spanid.'\').toggle();'.
'$(\'#'.$spanid.'-form\').toggle();'.
"updateContent('".$ajax_url."','".$spanid."','".$column."',".
"'".$memberid."',".
"document.getElementById('".$spanid.'-input\').value);return false" >'.
"\n<div>\n".
'<input type="text" size="20" id="'.$spanid.'-input" '.
'value="'.$value.'" />'."\n".
'</div>'."\n".
'</form>'."\n".
'</div>'."\n";
}
// function: print_table_start($array, $id)
// $array - array with column names
// $id - div id
// desc: Print table start
function print_table_start($array, $id=""){
echo "<table";
if(!empty($id)){
echo ">\n";
}else{
echo ' id="'.$id.'">'."\n";
}
echo "<thead>\n".
"<tr>\n";
for($i=0;$i<count($array);$i++){
echo "<th>".$array[$i]."</th>\n";
}
echo "</tr>\n".
"</thead>\n".
"<tbody>\n";
}
// function print_table_row($array, $colspan=0)
// $array - array whith content for each column
// $colspan - if only displaying one column for all columns
// dec: Print table row
function print_table_row($array, $colspan=0){
echo "<tr>";
if($colspan!=0){
echo '<td colspan="'.$colspan.'">'.$array[0].'</td>';
}else{
for($i=0;$i<count($array);$i++){
echo "<td>".$array[$i]."</td>\n";
}
}
echo "</tr>\n";
}
// Print table end
function print_table_end(){
echo "</tbody>\n".
"</table>\n".
"\n";
}
// function: print_text($text)
// $text - text to print
// dec: at the moment print the text in a regular <p></p>
function print_text($text){
echo "<p>$text</p>\n";
}
// Print table row with javascript update functions
// description - text to descripte the row, ie url, email, firstname, lastname
// column - column to change in the database
// rowid - id for the row to update, ie memberid or docsha1
// value - current value to print
// ajax_url - url to ajax file
function text_prompt_row($description, $column, $rowid, $value, $ajax_url){
if($description == 'url'){
$sql = "SELECT url FROM member_file WHERE sha1='".$rowid."'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
$url=$row['0'];
if($url != ""){
$url_link='</span>'."\n".' <span id="url"><a href="'.$url.
'">(open)</a></span>';
} else {
$url_link="</span>\n";
}
} else {
$url_link="</span>\n";
}
$spanid=$column.$rowid;
return '<div class="ldesc">'.$description.': </div>'."\n".
'<div class="rvalue">'."\n".
'<span id="'.$spanid.'" '.
'>.$spanid.'\').toggle();'.
'$(\'#'.$spanid.'-form\').toggle()">'.$value.$url_link.
'</span>'."\n".
'<div id="'.$spanid.'-form" style="display: none">'."\n".
'<form method="post" action="" '.
'>.$spanid.'\').toggle();'.
'$(\'#'.$spanid.'-form\').toggle();'.
"updateContent('".$ajax_url."','".$spanid."','".$column."','".$rowid.
"',document.getElementById('".$spanid."-input').value);".
'return false">'."\n".
'<div>'.
'<input type="text" size="80" id="'.$spanid.'-input" '.
'value="'.$value.'" />'."\n".
'</div>'."\n".
'</form>'."\n".
'</div>'."\n".
'</div>'."\n";
}
// Print static table row from input
// text - description of object
// value - value of the current object
function print_static_row($text, $value){
echo '<div class="ldesc">'.$text.':</div>'.
'<div class="rvalue">'.$value.'</div>'."\n";
}
// print row with a +/- change type
// pmt - pm text
// pmv - pm value
// docsha1 - sha1 for current document
function print_pm_row($pmt, $pmv, $docsha1){
echo '<div class="ldesc" id="'.$pmt.'-divl">'."\n".
'<span id="'.$pmt.'1">'."\n".
$pmt."\n".
':</span>'."\n".
'</div>'."\n".
'<div class="rvalue" id="'.$pmt.'-divr">'."\n".
'<span id="'.$pmt.'">'.$pmv.'</span> '."\n".
'<span id="'.$pmt.'-all">(<span >.
"updateContent('lib/ajax/file.php','".$pmt."','".$pmt."','".
$docsha1."','up')\">+</span>/".
'<span >.
"updateContent('lib/ajax/file.php','".$pmt."','".$pmt.
"','".$docsha1."','down')\">-</span>)</span>\n".
"</div>\n";
}
// Update column data for one row in the member_file table
// memberid - id of the user
// docsha1 - file id to update
// column - which type of data about the file should be updated
// new - the new value
function update_member_file($memberid, $docsha1, $column, $new){
$sql="UPDATE member_file
SET ".$column."='$new'
WHERE sha1='$docsha1' AND memberid='$memberid' LIMIT 1";
$update=mysql_query($sql);
if (!$update) {
// Update didn't work so fail
readit_error("Update did not work");
}
// If we're updating read_it change time on readit_time in the table
// current time if it is marked as read
// 0 if it is changed back to not read
if ($column == 'read_it') {
if($new == '1'){
$readit_time=time();
}else{
$readit_time=0;
}
$sql="UPDATE member_file
SET readit_time='$readit_time'
WHERE sha1='$docsha1' AND memberid='$memberid' LIMIT 1";
$update=mysql_query($sql);
if (!$update) {
// Update didn't work so fail
readit_error("Update time did not work");
}
}
}
// print nr of new users waiting to be accepter by an admin
function nr_new_users(){
$sql="SELECT count(*) FROM members WHERE accepted='0'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
$nr=$row['0'];
mysql_free_result($result);
if($nr == 0){
// No users so empty string
return "";
}else{
// Return nr of users
return " (".$nr.")";
}
}
// Return uploaddir
// In the future it will be possible to store files in subdirs
function uploaddir($docsha1){
global $uploaddir;
return $uploaddir;
}
// Generate hash
function generate_hash($passwd){
global $salt;
if(empty($salt)){
readit_error('You must set $salt in the config.php file');
}
return hash('sha512', $salt.$passwd);
}
?>