root/admin.lib.php

Revision 211, 36.4 kB (checked in by pwb, 2 years ago)

50 characters is too short a limit for entry titles, increasing it to 100

Line 
1 <?php
2 /*
3  * blogs class - provides functions for blogs
4  */
5
6 // Some useful validation functions
7 require_once("validation.lib.php");
8 // random other functions that aren't validation or db related
9 require_once("miscfunctions.lib.php");
10 //stuff from blog.lib will be useful
11 require_once("blog.lib.php");
12
13 //Our Blogs Class
14 class admin {
15     //Blog ID
16     var $id;
17     //Blogger's Details
18     var $userName;
19     var $realName;
20     //Errors
21     var $error;
22     //Date formats
23     var $shortDateFormat;
24     var $longDateFormat;
25     //Paths
26     var $httpPath;
27     var $adminPath;
28     var $blogPath;
29     var $basePath;
30     //[temporary] holder for instance of blog class
31     var $blog;
32             
33     //Constructor - checks we've been given a valid username, and pulls in generic blog info
34     function admin()
35     {
36         //set the error string first, so we dont wipe out any errors
37         $this->error = '';
38         //set the locale
39         setlocale(LC_ALL, 'en_GB');
40         //pull in the session stuff
41         $this->startSession();
42         //setup our environment
43         $this->id = $_SESSION['id'];
44         $this->userName = $_SESSION['userName'];
45         $this->realName = $_SESSION['realName'];
46         $this->shortDateFormat = "Y-m-d";
47         $this->longDateFormat = "r";
48         $this->httpPath = "/blog/";
49         $this->adminPath = $this->httpPath."admin/";
50         $this->basePath = "/blogs/";
51         if($this->httpPath[strlen($this->httpPath)-1]!="/") {
52             $this->httpPath .= "/";
53         }
54         //if we are logged in start a blog instance, and setup the blog path
55         if ($this->userName) {
56             $this->blog = new blogs($this->userName);
57             $this->blogPath = $this->basePath.$this->userName."/";
58         }
59     }
60     
61     //start / check our session
62     function startSession()
63     {
64         //set the session time out in seconds
65         $maxSessionAge = 10800; //1 hour
66         //setup the session stuff
67         session_name("BlogSession");
68         session_set_cookie_params($maxSessionAge,dirname($_SERVER['SCRIPT_NAME'])."/");
69         session_start();
70         //if we dont have a session, start one
71         if (!$_SESSION[time]) {
72             $_SESSION[time] = time();
73         }
74         //close the session if its too old
75         elseif ((time()-$_SESSION[time]) > $maxSessionAge) {
76             session_unset();
77             $this->error =_("Session Expired");
78             $this->startSession();
79         }
80         //else we are happy, and we just update the session time
81         else {
82             $_SESSION[oldTime] = $_SESSION[time];
83             $_SESSION[time] = time();
84         }
85     }
86     
87     //logs people in
88     function login()
89     {
90         global $BlogDB;
91         $username = "";
92         $password = "";
93         //sanitise username
94         if (isset($_POST['username']) && trim($_POST['username']) != "" && safeuname(trim($_POST['username']))) {
95             $username = trim($_POST['username']);
96         }
97         else {
98             $this->error = _("Please check the username field");
99         }
100         //sanitise password
101         if (isset($_POST['password']) && trim($_POST['password']) != "") {
102             $password = trim($_POST['password']);
103         }
104         else {
105             $this->error = _("Please check the password field");
106         }
107         //no errors?
108         if(!$this->error)
109         {
110             //try to pull in the users details
111             $sqlRow = $BlogDB->GetRow("SELECT id, name, password from users where enabled = true and username = '".$username."' limit 1;");
112
113             //check we returned a user
114             if (!$sqlRow) {
115                 $this->error =_("Invalid Username or Password");
116             }
117             else    {
118                 //check the password the user gave us agaisnt the one in the database
119                 if ($sqlRow['password']!=crypt($password, $sqlRow['password'])) {
120                     $this->error =_("Invalid Username or Password");               
121                 }
122                 else {
123                     //if everything matches dump some persistant details into the session
124                     $_SESSION['id'] = $sqlRow['id'];
125                     $_SESSION['userName'] = $username;
126                     $_SESSION['realName'] = $sqlRow['name'];
127                     $this->id = $_SESSION['id'];
128                     $this->userName = $_SESSION['userName'];
129                     $this->realName = $_SESSION['realName'];
130                 }
131             }
132         }
133         //return a state to indicate wether login was successful
134         if ($this->error) {
135             return false;
136         }
137         else {
138             return true;
139         }
140     }
141     
142     //admin menu
143     function menu() {
144         global $BlogDB;
145         echo "<ul class=\"side-menu\">\n";
146         echo "<li><a href=\"".$this->adminPath."newentry\">"._("Write new entry")."</a></li>\n";
147         echo "<li><a href=\"".$this->adminPath."showentries\">"._("Edit entries")."</a></li>\n";
148         echo "<li><a href=\"".$this->adminPath."settings\">"._("Settings")."</a></li>\n";
149         echo "<li><a href=\"".$this->adminPath."moderatecomments\">"._("Comments");
150         //count how many unmoderated comments there are
151         $result = $BlogDB->GetOne("SELECT count(comments.id) from comments join entries on comments.post = entries.id where moderated = false and entries.user_id = ".$this->id.";");
152         if($result){
153             echo "<span style=\"font-size: 0.8em; color: red\"> (".$result[0].")</span>";
154         }
155         echo "</a></li>\n";
156         echo "<li><a href=\"".$this->blogPath."\">"._("My blog")."</a></li>\n";
157         echo "</ul>\n";
158     }
159     
160     //destroys the session
161     function logout ()
162     {
163         session_unset();
164         header("Location: ".$this->blogPath);
165     }
166     
167     //prints a login form
168     function printLoginForm()
169     {
170         echo "<h2>"._("Login")."</h2>\n";
171         echo "<div class=\"td\">\n";
172         if ($this->error) {
173             echo "<div class=\"errorinfo\">"._("Error")." : " . $this->error . "</div>\n";
174         }
175         echo "<form action=\"".$this->adminPath."login\" method=\"post\" id=\"commentform\">\n";
176         echo "<p>\n";
177         echo "<input type=\"text\" name=\"username\" id=\"username\" value=\"" . (($this->error) ? strip_tags(trim($_POST['username'])) : "") . "\" size=\"22\" maxlength=\"50\" tabindex=\"1\" />\n";
178         echo "<label for=\"username\">"._("Username")."</label>\n";
179         echo "</p>\n";
180         echo "<p>\n";
181         echo "<input type=\"password\" name=\"password\" id=\"password\" size=\"22\" maxlength=\"128\" tabindex=\"2\" />\n";
182         echo "<label for=\"password\">"._("Password")."</label>\n";
183         echo "</p>\n";
184         echo "<p>\n";
185         echo "<input name=\"submit\" type=\"submit\" id=\"submit\" tabindex=\"4\" value=\"Login\" />\n";
186         echo "</p>\n";
187         echo "</form>\n";
188         echo _("Not got an account?")."<br /><a href=\"{$this->adminPath}signup\">"._("Sign Up Here!")."</a></div>";
189         echo "</div>\n";
190     }
191
192     // post an entry to the db
193     function postEntry()
194     {
195         global $BlogDB;
196         $category = '';
197         $subject = '';
198         $body = '';
199         //sanitise category (make sure it IS a number!)
200         if (isset($_POST['category']) && (int)$_POST['category'] != "" && (int)$_POST['category'] != 0) {
201             $category = (int)$_POST['category'];
202         } else {
203             $this->error = _("Undefined Category!");
204         }
205         //sanitise subject
206         if (isset($_POST['subject']) && trim($_POST['subject']) != "") {
207             //complain if the subject contains html or html like things rather than dumping it without warning
208             if (strip_tags($_POST['subject']) != $_POST['subject']) {
209                 $this->error = _("HTML is not allowed in the subject!");           
210             }
211             else {
212                 $subject = addslashes(trim($_POST['subject']));
213             }
214         } else {
215             $this->error = _("No entry subject!");
216         }       
217         //sanitise body
218         if (isset($_POST['body']) && trim($_POST['body']) != "") {
219             $body = trim($_POST['body']);
220             //we dont want to use nl2br if peeps are useing tinymce
221             if (!$this->blog->editor) {
222                 $body = nl2br($body);
223             }
224             $body = addslashes($body);
225         } else {
226             $this->error = _("No entry body!");
227         }
228         //no errors, so continue..
229         if (!$this->error) {
230             //first we make our short subject
231             $shortsubject = $this->blog->makeCleanString($subject,true);
232             //need to check if there are any short titles like this one already
233             $sql = $BlogDB->GetAll("SELECT shortsubject FROM entries WHERE user_id = {$this->id} AND shortsubject ~ '{$shortsubject}(_[0-9]{1,3}$|$)' ORDER BY char_length(shortsubject) DESC, shortsubject DESC LIMIT 1;");
234             //if so we grab the last one, and add 1 to it..
235             if (count($sql) != 0) {
236                 $sqlRow = array_shift($sql);
237                 // Put the matched _number into $matches[0] if there is one
238                 if (preg_match("/\_[0-9]{1,3}$/",$sqlRow['shortsubject'],$matches)) {
239                     // Remove the _ to get the number, add 1 and append
240                     $shortsubject .= '_' . ((int)substr($matches[0],1) + 1);
241                 } else {
242                     $shortsubject .= '_1';
243                 }
244             }
245             //shortsubject is now safe..
246             //insert our new entry
247             $sql = $BlogDB->Execute("INSERT INTO entries (category, subject, body, user_id, shortsubject) VALUES ({$category},'{$subject}','{$body}','{$this->id}','{$shortsubject}')");
248             if (!$sql) {
249                 error(2,_("Database commit failed")." - ".$BlogDB->ErrorMsg());
250             }
251             else {
252                 // $row = db_last($sql, "entries");
253                 $row = $BlogDB->GetRow("SELECT * FROM entries WHERE user_id = {$this->id} AND shortsubject='".$shortsubject."'");
254                 $this->blog->printEntry($row,false,false);
255             }
256         }
257         //re-display entry form if there are errors
258         else {
259             $this->printEntryForm($_POST,true);
260         }   
261     }
262     
263     //update an entry in the db
264     function updateEntry($shortSubject)
265     {       
266         global $BlogDB;
267         $category = '';
268         $subject = '';
269         $body = '';       
270         //sanitise and check for existance of a short subject
271         $shortSubject = $this->blog->makeCleanString($shortSubject);
272         if (!$shortSubject) {
273             error(4,_("If you dont give me a post how do you expect me to update it"));
274         }
275         //sanitise category (make sure it IS a number!)
276         if (isset($_POST['category']) && (int)$_POST['category'] != "" && (int)$_POST['category'] != 0) {
277             $category = (int)$_POST['category'];
278         } else {
279             $this->error = _("Undefined Category!");
280         }
281         //sanitise subject
282         if (isset($_POST['subject']) && trim($_POST['subject']) != "") {
283             //complain if the subject contains html or html like things rather than dumping it without warning
284             if (strip_tags($_POST['subject']) != $_POST['subject']) {
285                 $this->error = _("HTML is not allowed in the subject!");           
286             }
287             else {
288                 $subject = addslashes(trim($_POST['subject']));
289             }
290         } else {
291             $this->error = _("No entry subject!");
292         }       
293         //sanitise body
294         if (isset($_POST['body']) && trim($_POST['body']) != "") {
295             $body = trim($_POST['body']);
296             //we dont want to use nl2br if peeps are useing tinymce
297             if (!$this->blog->editor) {
298                 $body = nl2br($body);
299             }
300             $body = addslashes($body);
301         } else {
302             $this->error = _("No entry body!");
303         }
304
305         //no errors, so continue..
306         if (!$this->error) {
307             //check to see this post exists
308             $sql = $BlogDB->GetRow("SELECT id from entries where shortsubject = '".$shortSubject."' AND user_id='".$this->id."';");
309             //yes?, we can update it then..
310             if ($sql) {
311                 $sql = $BlogDB->Execute("UPDATE entries SET category = {$category}, subject = '{$subject}', body = '{$body}' WHERE shortsubject = '{$shortSubject}' AND user_id = '".$this->id."';");
312                 if (!$sql) {
313                     error(2,_("Database commit failed - ").$BlogDB->ErrorMsg());
314                 }
315                 else {
316                     echo "<div class=\"updateinfo\">"._("Updated!")."</div>\n";
317                     $this->updateForm($shortSubject);
318                 }
319             }
320             //cant update non-existant entrys
321             else {
322                  error(2,_("Cannot update entry, as it does not exist.".$BlogDB->ErrorMsg()));
323             }
324         }
325         //redisplay entry form if there are errors
326         else {
327             $this->updateForm($shortSubject);
328         }
329     }
330
331     //update form
332     function updateForm($shortSubject)
333     {
334         global $BlogDB;
335         //sanitise and check the short subject
336         $shortSubject = $this->blog->makeCleanString($shortSubject);
337         if (!$shortSubject) {
338             error(4,_("If you dont give me a post how do you expect me to decide which one you want to edit?"));
339         }
340         //try to grab the post
341         $row = $BlogDB->GetRow("SELECT subject, category, body, shortsubject from entries where shortsubject = '".$shortSubject."' AND user_id = '".$this->id."';");
342         //if it exists we can do stuff with it
343         if ($row) {
344             $this->printEntryForm($row,true,true);
345         }
346         //else give an error
347         else {
348             error(2, _("Could not find the requested entry."));
349         }
350     }
351 /*    currently not used.. if we dont want to bring back the delete link in printEntry from blog.lib we can get rid of this entirely
352     
353     //delete an entry
354     function deleteEntry($shortSubject)
355     {
356         //sanitise the short subject
357         $shortSubject = $this->blog->makeCleanString($shortSubject);
358         if (!$shortSubject) {
359             error(4,_("If you dont give me a post how do you expect me to delete it"));
360         }
361         //check to see this post exists
362         $sql = db_query("SELECT id from entries where shortsubject = '".$shortSubject."' AND user_id='".$this->id."';");
363         $sqlNum = db_num_rows($sql);
364         //yes?, we can delete it then..
365         if ($sqlNum == 1) {
366             db_query("DELETE FROM entries WHERE shortsubject = '{$shortSubject}' AND user_id = '".$this->id."';");           
367             echo "<p>"._("Entry deleted.")."</p>";
368         }
369         //can't delete non-existant entries
370         else {
371              error(2,_("Cannot delete entry, as it does not exist.".db_error()));
372         }
373     }
374 */
375     //update settings
376     function updateSettings()
377     {
378         global $BlogDB;
379         $name = '';
380         $title = '';
381         $description = '';
382         $css = 'blog.css';
383         $password = "";
384         //sanitise name
385         if (isset($_POST['name']) && trim($_POST['name']) != "") {
386             $name = addslashes(trim(strip_tags($_POST['name'])));
387         }
388         else {
389             $this->error = _("Bad Input - Realname");
390         }
391         //sanitise title
392         if (isset($_POST['title']) && trim($_POST['title']) != "") {
393             //complain if the title contains html or html like things rather than dumping it without warning
394             if (strip_tags($_POST['title']) != $_POST['title']) {
395                 $this->error = _("HTML is not allowed in the title!");           
396             }
397             else {
398                 $title = addslashes(trim($_POST['title']));
399             }
400         }
401         else {
402             $this->error = _("Bad Input - Title");
403         }
404         //sanitise description
405         if (isset($_POST['description']) && trim($_POST['description']) != "") {
406             //complain if the description contains html or html like things rather than dumping it without warning
407             if (strip_tags($_POST['description']) != $_POST['description']) {
408                 $this->error = _("HTML is not allowed in the description!");           
409             }
410             else {
411                 $description = addslashes(trim($_POST['description']));
412             }
413         }
414         else {
415             $this->error = _("Bad Input - Description");
416         }
417         //sanitise css
418         if (isset($_POST['css'])) { // if its not set its defaulted...
419             if (trim($_POST['css']) != "" && is_file($_POST['css'])) {
420                 $css = $_POST['css'];
421             }
422             else {
423                 $this->error = _("Bad Input - CSS location");
424             }
425         }
426         //sanitise password and encrypt
427         if ($_POST['pass1']) {
428             if ((isset($_POST['pass1']) && trim($_POST['pass1']) != "") && ($_POST['pass1']==$_POST['pass2'])) {
429                 $password = crypt($_POST['pass1']);
430             }
431             else {
432                 $this->error = _("Bad Input - Password");
433             }
434         }
435         // checkbox for comment moderation, either is or isnt
436         if ($_POST['moderate'] != "") {
437             $moderate = "true";
438         }
439         else {
440             $moderate = "false";
441         }   
442         // checkbox for editor, either is or isnt
443         if ($_POST['editor'] != "") {
444             $editor = "true";
445         }
446         else {
447             $editor = "false";
448         }
449         //if there are no errors
450         if (!$this->error) {
451             //construct the query
452             $query = "UPDATE USERS SET name='{$name}', title='{$title}', description='{$description}', css='{$css}', moderate={$moderate}, editor={$editor}";
453             //if the password is set add that too
454             if ($password) {
455                 $query .= ", password='{$password}'";
456