[go: up one dir, main page]

Menu

[r334]: / trunk / lib / common.php  Maximize  Restore  History

Download this file

625 lines (562 with data), 17.9 kB

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
<?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&amp;list=read_it&amp;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);
}
?>