root/admin.lib.php @ 97

Revision 96, 18.2 kB (checked in by davea, 5 years ago)

Added list of 5 most recent entries to the admin main page, a link to view all past entries on the menu, and fixed some numpty's over zealous use of striptags()

Line 
1<?php
2/*
3 * blogs class - provides functions for blogs
4 */
5
6// RC's nasty horrible database library, really needs replacing with something more sane..
7$db_name = "blogs";
8$db_type = "pgsql";
9require_once("database.lib.php");
10// Some useful validation functions
11require_once("validation.lib.php");
12
13//stuff from blog.lib will be usefull
14require_once("blog.lib.php");
15
16//Our Blogs Class
17class admin {
18    var $id;        //Blog ID
19    var $userName;        //Blogger's User Name
20    var $realName;        //Blogger's Real Name
21    var $sessionError;      //login or session errors
22    var $shortDateFormat;    //Short date format
23    var $longDateFormat;    //Long date format
24    var $httpPath;        //http Path for files
25    var $adminPath;        //path to admin
26    var $blog;        //[temporary] holder for instance of blog class
27           
28    //Constructor - checks we've been given a valid username, and pulls in generic blog info
29    function admin()
30    {
31        $this->startSession();
32        $this->id = $_SESSION['id'];
33        $this->userName = $_SESSION['userName'];
34        $this->realName = $_SESSION['realName'];
35        $this->sessionError = '';
36        $this->shortDateFormat = "Y-m-d";
37        $this->longDateFormat = "r";
38        $this->httpPath = dirname($_SERVER['SCRIPT_NAME'])."/";
39        $this->adminPath = $this->httpPath."admin.php/";
40        if ($this->userName) {
41            $this->blog = new blogs($this->userName);
42        }
43    }
44   
45    //start / check our session
46    function startSession() {
47        //set the session time out in seconds
48        //1 hour
49        $maxSessionAge = 3600;
50       
51        //setup the session stuff
52        session_name("BlogSession");
53        session_set_cookie_params($maxSessionAge,dirname($_SERVER['SCRIPT_NAME'])."/");
54        session_start();
55        //get the host
56        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
57            $host = addslashes($_SERVER['HTTP_X_FORWARDED_FOR']);
58        }
59        else {
60            $host = addslashes($_SERVER['REMOTE_ADDR']);
61        }
62        //if we dont have a session, start one
63        if (!$_SESSION[time]) {
64            $_SESSION[time] = time();
65            $_SESSION[ip] = $host;
66        }
67        //close the session if its too old
68        elseif ((time()-$_SESSION[time]) > $maxSessionAge) {
69            session_unset();
70            $this->sessionError =_("Session Expired");
71            startSession();
72        }
73/*        //close the session if its move IP
74        elseif($_SESSION[ip] != $host)    {
75            session_unset();
76            $this->sessionError =_("IP Changed");
77            $this->startSession();
78        } */
79        //else we are happy, and we just update the session time
80        else     {
81            $_SESSION[oldTime] = $_SESSION[time];
82            $_SESSION[time] = time();
83        }
84        if ($this->sessionError) {
85            echo "<p class=\"invalid\">*** " . $this->sessionError . " ***</p>\n";
86        }
87    }
88    //logs people in
89    function login() {
90        $username = "";
91        $password = "";
92        if (isset($_POST['username']) && trim($_POST['username']) != "" && safeuname(trim($_POST['username']))) {
93            $username = trim($_POST['username']);
94        }
95        else {
96            $this->sessionError = _("Please check the username field");
97        }
98        if (isset($_POST['password']) && trim($_POST['password']) != "") {
99            $password = trim($_POST['password']);
100        }
101        else {
102            $this->sessionError = _("Please check the password field");
103        }
104        if($this->sessionError) {
105            $this->printLoginForm();
106        }
107        else {
108            $sql = db_query("SELECT id, name from users where enabled = true and username = '".$username."' and password = '".md5($password)."';");
109            $sqlNum = db_num_rows($sql);
110            if ($sqlNum != 1) {
111                $this->sessionError=_("Invalid Username or Password");
112                $this->printLoginForm();
113            }
114            else    {
115                $sqlRow = db_getrow($sql);
116                $_SESSION['id'] = $sqlRow['id'];
117                $_SESSION['userName'] = $username;
118                $_SESSION['realName'] = $sqlRow['name'];
119                $this->id = $_SESSION['id'];
120                $this->userName = $_SESSION['userName'];
121                $this->realName = $_SESSION['realName'];
122            }
123        }
124    }
125   
126    //admin menu
127    function menu() {
128        echo "<ul class=\"side-menu\">\n";
129        echo "<li><a href=\"".$this->adminPath."newentry"."\">Write new entry</a></li>\n";
130        echo "<li><a href=\"".$this->adminPath."showentries\">Edit entries</a></li>\n";
131        echo "<li><a href=\"",$this->adminPath."settings"."\">Settings</a></li>\n";
132        echo "</ul>\n";
133    }
134   
135    //destroys the session and presents you with a login screen
136    function logout ()
137    {
138        session_unset();
139    }
140   
141    //prints a login form
142    function printLoginForm()
143    {
144        echo "<div class=\"login\">\n";
145        echo "<h2>"._("Login")."</h2>\n";
146        echo "<div class=\"td\">\n";
147        if ($this->sessionError != "") {
148            echo "<p class=\"invalid\">*** " . $this->sessionError . " ***</p>\n";
149        }
150        echo "<form action=\"".$this->adminPath."login\" method=\"post\" id=\"commentform\">\n";
151        echo "<p>\n";
152        echo "<input type=\"text\" name=\"username\" id=\"username\" value=\"" . (($this->commentError != "") ? strip_tags(trim($_POST['username'])) : "") . "\" size=\"22\" maxlength=\"50\" tabindex=\"1\" />\n";
153        echo "<label for=\"username\">"._("Username")."</label>\n";
154        echo "</p>\n";
155        echo "<p>\n";
156        echo "<input type=\"password\" name=\"password\" id=\"password\" size=\"22\" maxlength=\"128\" tabindex=\"2\" />\n";
157        echo "<label for=\"password\">"._("Password")."</label>\n";
158        echo "</p>\n";
159        echo "<p>\n";
160        echo "<input name=\"submit\" type=\"submit\" id=\"submit\" tabindex=\"4\" value=\"Login\" />\n";
161        echo "</p>\n";
162        echo "</form>\n";
163        echo "</div>\n";
164        echo "</div>\n";
165    }
166
167    // post an entry to the db
168    function postEntry()
169    {
170        $category = '';
171        $subject = '';
172        $body = '';
173       
174        //sanitise category (make sure it IS a number!)
175        if (isset($_POST['category']) && trim($_POST['category']) != "" && (int)$_POST['category'] != 0) {
176            $category = (int)$_POST['category'];
177        } else {
178            $this->inputError = _("Undefined Category!");
179        }
180        //sanitise subject (make sure its not a number!)
181        if (isset($_POST['subject']) && trim($_POST['subject']) != "" && (int)$_POST['category'] != 0) {
182            $subject = addslashes(trim(strip_tags($_POST['subject'])));
183        } else {
184            $this->inputError = _("No entry subject!");
185        }       
186        //sanitise body
187        if (isset($_POST['body']) && trim($_POST['body']) != "") {
188            $body = addslashes(nl2br(trim(strip_tags($_POST['body']))));
189        } else {
190            $this->inputError = _("No entry body!");
191        }
192        //no errors, so continue..
193        if (!$this->inputError) {
194            //first we make our short subject
195            $shortsubject = $this->blog->makeCleanString($subject);
196            // need to check if there are any short titles like this one already
197            $sql = db_query("SELECT shortsubject from entries where user_id = ".$this->id." and (shortsubject = '".$shortsubject."' or shortsubject like '".$shortsubject."\\\_%') order by char_length(shortsubject) desc, shortsubject desc;");
198            $sqlNum = db_num_rows($sql);
199            //if so we grab the last one, and add 1 to it..
200            if ($sqlNum != 0) {
201                $sqlRow = db_getrow($sql);
202                (int)$newNum = array_shift(array_reverse(explode('_',$sqlRow['shortsubject'])));
203                $shortsubject .= '_'.++$newNum; //new non-colliding short subject
204            }
205            //shortsubject is now safe..
206            //insert our new entry
207            $sql = db_query("INSERT INTO entries (category, subject, body, user_id, shortsubject) VALUES ({$category},'{$subject}','{$body}','{$this->id}','{$shortsubject}')");
208            if (!$sql) {
209                error(2,"Database commit failed - ".db_error());
210            }
211            else {
212                $row = db_last($sql, "entries");
213                $this->blog->printEntry($row,false,false);
214            }
215        }
216        //re-display entry form if there are errors
217        else {
218            $this->printEntryForm($_POST,true);
219        }   
220    }
221   
222    //update an entry in the db, possibly the body or the post will be updated
223    function updateEntry($id)
224    {       
225        $category = '';
226        $subject = '';
227        $body = '';
228        $id = $this->blog->makeCleanString($id);
229        if (!$id) {
230            error(4,"If you dont give me a post how do you expect me to update it");
231        }
232        //sanitise category (make sure it IS a number!)
233        if (isset($_POST['category']) && trim($_POST['category']) != "" && (int)$_POST['category'] != 0) {
234            $category = (int)$_POST['category'];
235        } else {
236            $this->inputError = _("Undefined Category!");
237        }
238        //sanitise subject (make sure it's not a number!)
239        if (isset($_POST['subject']) && trim($_POST['subject']) != "") {
240            $subject = addslashes(trim(strip_tags($_POST['subject'])));
241        } else {
242            $this->inputError = _("No entry subject!");
243        }       
244        //sanitise body
245        if (isset($_POST['body']) && trim($_POST['body']) != "") {
246            $body = addslashes(nl2br(trim($_POST['body'])));
247        } else {
248            $this->inputError = _("No entry body!");
249        }
250        //no errors, so continue..
251        if (!$this->inputError) {
252            //check to see this post exists
253            $sql = db_query("SELECT id from entries where shortsubject = '".$id."' AND user_id='".$this->id."';");
254            $sqlNum = db_num_rows($sql);
255            //yes?, we can update it then..
256            if ($sqlNum == 1) {
257                $sql = db_query("UPDATE entries SET category = {$category}, subject = '{$subject}', body = '{$body}' WHERE shortsubject = '{$id}' AND user_id = '".$this->id."';");           
258                if (!$sql) {
259                    error(2,"Database commit failed - ".db_error());
260                }
261                else {
262                    $this->inputError = _("Updated!");
263                    $this->updateForm($id);
264                }
265            }
266            //cant update non-existant entrys
267            else {
268                 error(2,_("Cannot update entry, as it does not exist.".db_error()));
269            }
270        }
271        //redisplay entry form if there are errors
272        else {
273            $this->updateForm($id);
274        }
275    }
276    //update form
277    function updateForm($id)
278    {
279        $id = $this->blog->makeCleanString($id);
280        $sql = db_query("SELECT subject, category, body, shortsubject from entries where shortsubject = '".$id."' AND user_id = '".$this->id."';");
281        $sqlNum = db_num_rows($sql);
282        //yes? we can update it then..
283        if ($sqlNum == 1) {
284            $row = db_getrow($sql);
285            $this->printEntryForm($row,true,true);
286        } else {
287            error(2, _("Could not find the requested entry."));
288        }
289    }
290
291    //update settings
292    function updateSettings()
293    {
294        //to be written
295    }
296   
297    //print the blog Entry form...
298    function printEntryForm($row='',$show=false,$edit=false)
299    {
300        echo "<div class=\"entry\">\n";
301        if ($this->inputError != "") {
302            echo "<p class=\"invalid\">*** " . $this->inputError . " ***</p>\n";
303        }
304        echo "<h2>".((!$edit) ?_("Write Entry") : _("Edit Entry"))."</h2>\n";
305        echo "<form action=\"".$this->adminPath.((!$edit) ? "postentry" : "postupdate/{$row['shortsubject']}")."\" method=\"post\" id=\"entryform\">\n";
306        echo "<p>\n";
307        echo "<input type=\"text\" name=\"subject\" id=\"subject\" value=\"" . (($show) ? strip_tags(trim($row['subject'])) : "") . "\" size=\"22\" maxlength=\"50\" tabindex=\"1\" />\n";
308        echo "<label for=\"subject\">"._(Subject)."</label>\n";
309        echo "</p>\n";
310        echo "<p>\n";
311        echo "<select name=\"category\" id=\"category\">";
312        //pull in the list of catogories from the database
313        $sql = db_query("SELECT id, name FROM categories ORDER BY name ASC;");
314        while ($sqlRow = db_getrow($sql)) {
315            echo "<option value=\"{$sqlRow['id']}\"".(((int)$row['category'] == $sqlRow['id']) ? " selected=\"selected\"" : "").">{$sqlRow['name']}</option>\n";
316            }
317        echo "</select>";
318        echo "<label for=\"category\">"._("Category")."</label>\n";
319        echo "</p>\n";
320        echo "<p>\n";
321        echo "<textarea name=\"body\" id=\"body\" cols=\"50\" rows=\"10\" tabindex=\"3\">" . (($show) ? $row['body'] : "") . "</textarea>\n";
322        echo "</p>\n";
323        echo "<p>\n";
324        echo "<input name=\"submit\" type=\"submit\" id=\"submit\" tabindex=\"4\" value=\"Submit Entry\" />\n";
325        echo "</p>\n";
326        echo "</form>\n";
327        echo "</div>\n";
328    }
329
330
331    //print the blog settings form...
332    function printSettingsForm()
333    {
334        //pull in user's current settings from the database
335        $sql = db_query("SELECT name, title, description, css FROM users WHERE username='" . $this->userName . "'");
336        $settings = db_getrow($sql);
337        echo "<div class=\"entry\">\n";
338        echo "<h2>"._("Blog Settings")."</h2>\n";
339        echo "<form action=\"".$this->blogPath."postsettings\" method=\"post\" id=\"settingsform\">\n";
340        echo "<p>\n";
341        echo "<input type=\"text\" name=\"name\" id=\"name\" value=\"" . $settings[name] . "\" size=\"30\" maxlength=\"60\" tabindex=\"1\" />\n";
342        echo "<label for=\"name\">"._("Real name")."</label>\n";
343        echo "</p>\n";
344        echo "<p>\n";
345        echo "<input type=\"text\" name=\"title\" id=\"title\" value=\"" . $settings[title] . "\" size=\"30\" maxlength=\"60\" tabindex=\"2\" />\n";
346        echo "<label for=\"title\">"._("Title")."</label>\n";
347        echo "</p>\n";
348        echo "<p>\n";
349        echo "<input type=\"text\" name=\"description\" id=\"description\" value=\"" . $settings[description] . "\" size=\"30\" maxlength=\"60\" tabindex=\"3\" />\n";
350        echo "<label for=\"description\">"._("Description")."</label>\n";
351        echo "</p>\n";
352        echo "<p>\n";
353        echo "<input type=\"text\" name=\"css\" id=\"css\" value=\"" . $settings[css] . "\" size=\"30\" maxlength=\"255\" tabindex=\"4\" />\n";
354        echo "<label for=\"css\">"._("CSS")."</label>\n";
355        echo "</p>\n";
356        echo "<p>\n";
357        echo "<input type=\"password\" name=\"pass1\" id=\"pass1\" value=\"\" size=\"15\" maxlength=\"16\" tabindex=\"5\" />\n";
358        echo "<label for=\"pass1\">"._("Password")."</label>\n";
359        echo "</p>\n";
360        echo "<p>\n";
361        echo "<input type=\"password\" name=\"pass2\" id=\"pass2\" value=\"\" size=\"15\" maxlength=\"16\" tabindex=\"6\" />\n";
362        echo "<label for=\"pass2\">"._("Again")."</label>\n";
363        echo "</p>\n";
364        echo "<p>\n";
365        echo "<input name=\"submit\" type=\"submit\" id=\"submit\" tabindex=\"4\" value=\"Save Settings\" />\n";
366        echo "</p>\n";       
367        echo "</form>\n";
368        echo "</div>\n";   
369    }
370
371    function printEntries($amount=0, $title=TRUE)
372    {
373        $limit = ($amount > 0) ? " LIMIT $amount" : "";
374        $result = db_query("SELECT shortsubject,timestamp,subject FROM entries WHERE user_id = '".$this->id."' ORDER BY timestamp DESC $limit;");
375        if(db_num_rows($result)==0){
376            error(5, _("No entries found."));
377        } else {
378            if($title){
379                echo "<h2>"._("Edit Entries")."</h2>\n";
380            }
381            echo "<ul>\n";
382            while($row = db_getrow($result)){
383                echo "<li>".date("r", strtotime($row['timestamp']))." <a href=\"".$this->adminPath."update/".$row['shortsubject']."\">".$row['subject']."</a></li>\n";
384            }
385            echo "</ul>\n";
386        }
387    }
388
389/* Some functions to manage posts, users etc. */
390
391    function addUser($user) //user is the user adminning (a staff member?)
392    {
393        $username = '';
394        $password = '';
395        $type = 1;
396        $name = '';
397        $title = '';
398        $description = '';
399        $css = 'blog.css';
400        $enabled = False; // seems sensible..
401       
402        //if (check_auth($user)) {}
403        //sanitise username
404                if (isset($_POST['username']) && trim($_POST['username']) != "" && (int)$_POST['username'] == 0) {
405                           $username = $_POST['username'];
406                } else {
407                        $this->inputError = _("Bad Input - Username");
408                        $err = 1;
409                }
410
411        //sanitise password, assume it will be hashed before sending :)
412                if (isset($_POST['password']) && trim($_POST['password']) != "" && (int)$_POST['password'] == 0) {
413                        $password = $_POST['password'];
414                } else {
415                        $this->inputError = _("Bad Input - Password");
416                        $err = 1;
417                }
418
419        //sanitise type
420                if (isset($_POST['type']) && trim($_POST['type']) != "" && (int)$_POST['type'] > 0) {
421                        $type = (int)$_POST['type'];
422                } else {
423                        $this->inputError = _("Bad Input - Type");
424                        $err = 1;
425                }
426
427        //sanitise name
428                if (isset($_POST['name']) && trim($_POST['name']) != "" && (int)$_POST['name'] == 0) {
429                        $name = addslashes(urldecode($_POST['name']));
430                } else {
431                        $this->inputError = _("Bad Input - Realname");
432                        $err = 1;
433                }
434
435        //sanitise title
436                if (isset($_POST['title']) && trim($_POST['title']) != "" && (int)$_POST['title'] == 0) {
437                        $title = addslashes(urldecode($_POST['title']));
438                } else {
439                        $this->inputError = _("Bad Input - Title");
440                        $err = 1;
441                }
442
443        //sanitise description
444                if (isset($_POST['description']) && trim($_POST['description']) != "" && (int)$_POST['description'] == 0) {
445                        $description = addslashes(urldecode($_POST['description']));
446                } else {
447                        $this->inputError = _("Bad Input - Description");
448                        $err = 1;
449                }
450
451        //sanitise css
452                if (isset($_POST['css'])) { // if its not set its defaulted...
453            if (trim($_POST['css']) != "" && (int)$_POST['css'] == 0 && is_file($_POST['css'])) {
454                            $css = $_POST['css'];
455                    } else {
456                            $this->inputError = _("Bad Input - CSS location");
457                            $err = 1;
458                    }
459        }
460
461        //sanitise enabled -- not really sure about this. i think creation and enabling should be
462        // done seperately... ???
463                /*if (isset($_POST['enabled'])) { // if its not set its defaulted...
464                        if (trim($_POST['enabled']) != "" && (int)$_POST['enabled'] == 0)) {
465                                $css = $_POST['enabled'];
466                        } else {
467                                $this->inputError = _("Bad Input - Enabled");
468                                $err = 1;
469                        }
470                }*/
471
472        if ($err == 0) { // and insert...
473           
474            $query = "INSERT into USERS (username,password,type,name,title,description,css,enabled) VALUES ('{$username}','{$password}',{$type},'{$name}','{$title}','{$description}','{$css}',{$enabled});";
475            if (!db_query($query)) {
476                error(2,_("Database Insertion failed."));
477            } else {
478                print(_("New user added:")." ".$username); //pleh?
479            }
480        } else {
481            error(4,_("Bad Input."));
482        }
483    }
484
485    // ok this should take all the input and post it to addUser, passing in the current user and stuff... i think...
486    function addUserForm()
487    {
488        echo "<div class=\"adduser\">\n";
489            if ($this->inputError != "") {
490                echo "<p class=\"invalid\">*** " . $this->inputError . " ***</p>\n";
491        }
492        elseif (isset($_POST['submit'])) {
493            echo "<p>New user added.</p>\n";
494        }
495        echo "<h2>"._("Add User")."</h2>\n";
496        echo "<form action=\"".$this->blogPath."adduser\" method=\"post\" id=\"adduserform\">\n";
497        echo "<p>\n";
498        echo "<input type=\"text\" name=\"username\" id=\"username\" value=\"" . (($this->inputError != "") ? strip_tags(trim($_POST['username'])) : "") . "\" size=\"22\" maxlength=\"50\" tabindex=\"1\" />\n";
499        echo "<label for=\"username\">"._("Username")."</label>\n";
500    }
501}
Note: See TracBrowser for help on using the browser.