· 8 years ago · May 15, 2018, 03:36 PM
1<?php
2class Blog {
3
4 /*
5 Name: KoalaBlog (Kblog)
6 Author: Koala
7 Description: A simple blog based on Kcms
8 Version: 1.0 alpha
9
10 Database: Mysql
11 Table: b_posts
12
13 Elements: id [int] [auto_increment]
14 titolo [varchar]
15 contenuto [longtext]
16 data [varchar]
17 */
18
19 /*
20 ### HERE START THE SCRIPT ###
21 ### DON'T CHANGE IF U DON'T KNOW PHP ###
22 */
23
24 /*
25 ## SQL 4 THE DATABASE
26
27 CREATE TABLE IF NOT EXISTS `b_posts` (
28 `id` int(11) NOT NULL AUTO_INCREMENT,
29 `titolo` varchar(250) NOT NULL,
30 `contenuto` longtext NOT NULL,
31 `data` varchar(250) NOT NULL,
32 PRIMARY KEY (`id`)
33 ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=24 ;
34
35 */
36
37 var $art_unit = NULL;
38 var $is_admin = false;
39 var $css = " <style>
40 /*
41 ##### KOALA BLOG CSS #####
42 */
43
44 .kblog_post {
45 border: 1px solid black;
46 margin: 5px;
47 padding: 5px;
48 }
49
50 .kblog_post blockquote {
51 margin-top: -20px;
52 margin-bottom: -20px;
53 }
54
55 .kblog_post_cont {
56 margin-left: 20px;
57 border-left: 3px solid black;
58 padding: 10px;
59 margin-bottom: -20px;
60 }
61
62 .kblog_post:hover {
63 background-color: #E6E6E6;
64 }
65
66 .kblog_post_more {
67 color: #000000;
68 border: 1px solid black;
69 text-align: center;
70 padding: 10px;
71 width: 50%;
72 margin-left: auto;
73 margin-right: auto;
74 margin-bottom: 10px;
75 }
76
77 .kblog_post_more:hover {
78 background-color: #E6E6E6;
79 }
80
81 .kblog_post_cont img {
82 max-width: 90%;
83 max-height: 90%;
84 }
85
86 </style>
87 ";
88
89
90 public function main($data, $title) {
91 session_start();
92
93 $data = str_replace("<head>", "<head>".$this->css, $data);
94
95 if (isset($_SESSION['is_logged']) && $_SESSION['is_logged'] === true) {
96 $this->is_admin = true;
97 }
98
99 if (isset($_POST['write'])) {
100 if (!isset($_POST['content']) || !isset($_POST['title']) || !isset($_POST['sid']) || $_POST['content'] == "" || $_POST['title'] == "") {
101 die("You must complete all fields (or you aren't logged)");
102 }
103
104 if ($_REQUEST['sid'] != session_id() || !$this->is_admin === true) {
105 die("Are you trying to hacking KCms?");
106 }
107
108 $this->InsertArticle($_REQUEST['content'], $_POST['title']);
109 }
110
111 if (isset($_GET['action']) && $_GET['action'] == "delete" && isset($_GET['deleteid'])) {
112 if($this->is_admin === true) {
113 $delete_id = abs(intval($_GET['deleteid']));
114 mysql_query("DELETE FROM b_posts WHERE id='{$delete_id}'") or die (mysql_error());
115 }
116 }
117
118 if($title == "Kblog") {
119 if(isset($_GET['limit']) && ctype_digit($_GET['limit'])) {
120 $this->DoPage(abs(intval($_GET['limit'])));
121 }
122 else {
123 $this->DoPage();
124 }
125 $data = str_replace("<p>[articles here]</p>", $this->art_unit, $data);
126 }
127 return $data;
128 }
129
130 private function DoPage($limit = 2) {
131 global $theme, $css;
132
133 //Admin section
134 if($this->is_admin === true) {
135 $this->art_unit .= "<b>Welcome Admin!</b> -> <a style=\"cursor: pointer;\" onClick=\"change_divst('post_create')\"><u>Create</u></a><hr />";
136 $this->art_unit .= "<div id='post_create' style='display: none;'>\n";
137 $this->art_unit .= "<form method='POST'>\n";
138 $this->art_unit .= "<input type='hidden' name='write'>";
139 $this->art_unit .= "<input type='hidden' value='".htmlspecialchars(session_id())."' name='sid'>";
140 $this->art_unit .= "<label>Title: </label><input type='text' name='title'><br />\n";
141 $this->art_unit .= "<textarea cols=60 rows=8 name='content'></textarea><br />\n";
142 $this->art_unit .= "<input type='submit' value='Add'>";
143 $this->art_unit .= "</form><hr />";
144 $this->art_unit .= "</div>";
145 }
146
147 //List of posts.
148 if(isset($_GET['postid'])) {
149 $_GET['postid'] = (ctype_digit($_GET['postid'])) ? $_GET['postid'] : NULL;
150 if($_GET['postid'] != NULL) {
151 $row = mysql_fetch_array(mysql_query("SELECT * FROM b_posts WHERE id='".$_GET['postid']."'"), MYSQL_ASSOC);
152 $delete_post_link = ($this->is_admin === true) ? "- [ <a href='read.php?id=". $this->getIdfromName("Kblog") ."&action=delete&deleteid={$row['id']}'>DELETE</a> ]" : "";
153 $this->art_unit .= " <div class='kblog_post'>
154 <div class='kblog_post_title'> <h2>{$row['titolo']}</h2></div>
155 <div class='kblog_post_cont'> ". nl2br($row['contenuto']) ." </div>
156 <div class='kblog_post_date'> <h6 align='right'>Date: {$row['data']} {$delete_post_link}</h6> </div>
157 </div>
158 ";
159 }
160 }
161 elseif($this->is_admin === true && !isset($_GET['postid'])) {
162 $query = mysql_query("SELECT * FROM b_posts ORDER BY id DESC LIMIT {$limit}") or die (mysql_error());
163 $max = mysql_fetch_array(mysql_query("SELECT COUNT(*) AS max FROM b_posts"), MYSQL_ASSOC) or die (mysql_error());
164 while($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
165 $delete_post_link = "- [ <a href='read.php?id=". $this->getIdfromName("Kblog") ."&action=delete&deleteid={$row['id']}'>DELETE</a> ]";
166
167 $this->art_unit .= " <div class='kblog_post'>
168 <div class='kblog_post_title'> <h2>{$row['titolo']}</h2></div>
169 <div class='kblog_post_cont'> ". $this->cutHtmlText(nl2br($row['contenuto']), 300, "...") ." </div>
170 <div class='kblog_post_date'> <h6 align='right'>Date: {$row['data']} - [ <a href='read.php?id=". $this->getIdfromName("Kblog") ."&postid={$row['id']}'>CONTINUA</a> ] {$delete_post_link}</h6> </div>
171 </div>
172 ";
173 }
174 }
175 else {
176 $query = mysql_query("SELECT * FROM b_posts ORDER BY id DESC LIMIT {$limit}") or die (mysql_error());
177 $max = mysql_fetch_array(mysql_query("SELECT COUNT(*) AS max FROM b_posts"), MYSQL_ASSOC) or die (mysql_error());
178 while($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
179 $this->art_unit .= " <div class='kblog_post'>
180 <div class='kblog_post_title'> <h2>{$row['titolo']}</h2></div>
181 <div class='kblog_post_cont'> ". $this->cutHtmlText(nl2br($row['contenuto']), 300, "...") ." </div>
182 <div class='kblog_post_date'> <h6 align='right'>Date: {$row['data']} - [ <a href='read.php?id=". $this->getIdfromName("Kblog") ."&postid={$row['id']}'>CONTINUA</a> ]</h6> </div>
183 </div>
184 ";
185 }
186 }
187
188 //Link a fine pagina per far mostrare ancor più contenuti.
189 if(isset($max) && $max['max'] > $limit) {
190 $this->art_unit .= "<div class='kblog_post_more'><a href='read.php?id=". $this->getIdfromName("Kblog") ."&limit=". $limit*2 ."'>MORE POSTS</div>";
191 }
192
193 //Adding script
194 $this->art_unit .= " <script language='javascript'>
195 function hide_div(id)
196 {
197 document.getElementById(id).style.display = 'none';
198 document.cookie=id+'=0;';
199 }
200 function show_div(id)
201 {
202 document.getElementById(id).style.display = 'block';
203 document.cookie=id+'=1;';
204 }
205 function change_divst(id)
206 {
207 if (document.getElementById(id).style.display == 'none')
208 show_div(id);
209 else
210 hide_div(id);
211 }
212
213
214 </script>
215 <script type='text/javascript' src='tinymce/jscripts/tiny_mce/tiny_mce_dev.js'></script>
216 <script type='text/javascript'>
217 tinyMCE.init({
218 mode : 'textareas',
219 theme : 'advanced',
220 plugins : 'autolink,lists,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template',
221
222 theme_advanced_buttons1 : 'save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect',
223 theme_advanced_buttons2 : 'cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor',
224 theme_advanced_buttons3 : 'tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen',
225 theme_advanced_buttons4 : 'insertlayer,moveforward,movebackward,absolute,|,styleprops,spellchecker,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,blockquote,pagebreak,|,insertfile,insertimage',
226 theme_advanced_toolbar_location : 'top',
227 theme_advanced_toolbar_align : 'left',
228 theme_advanced_statusbar_location : 'bottom',
229 theme_advanced_resizing : true,
230
231 skin : 'o2k7',
232 skin_variant : 'black',
233
234 template_external_list_url : 'tinymce/jscripts/tiny_mce/template_list.js',
235 external_link_list_url : 'tinymce/jscripts/tiny_mce/link_list.js',
236 external_image_list_url : 'tinymce/jscripts/tiny_mce/image_list.js',
237 media_external_list_url : 'tinymce/jscripts/tiny_mce/media_list.js'
238 });
239 </script>
240 <link rel=\"stylesheet\" href=\"themes/{$theme}/{$css}\" type=\"text/css\">\n
241 ";
242 }
243
244 private function getIdfromName($name) {
245 $res = mysql_query("SELECT id FROM kcms WHERE title='{$name}'") or die(mysql_error());
246 $r = mysql_fetch_row($res);
247 return $r[0];
248 }
249
250 private function InsertArticle($cont, $title) {
251 mysql_query("INSERT INTO b_posts(titolo, contenuto, data) VALUES ('{$title}','{$cont}','". date("m/d/Y") ."')") or die(mysql_error());
252 }
253
254 /**
255 * Truncates html text.
256 *
257 * Cuts a string to the length of $length and replaces the last characters
258 * with the ending if the text is longer than length.
259 * Can strip tags or controlo their closure
260 *
261 * @param string $html Html string to truncate.
262 * @param integer $length Length of returned string, including ellipsis.
263 * @param string $ending Ending to be appended to the trimmed string.
264 * @param boolean $strip_tags If true, html tags are replaced by nothing
265 * @param boolean $cut_words If false, returned string will not be cut mid-word
266 * @return string Trimmed string.
267 */
268 private function cutHtmlText($html, $length, $ending, $strip_tags = false, $cut_words = false, $cut_images = false) {
269
270 /*
271 regular expressions to intercept tags
272 */
273 $opened_tag = "<\w+\s*([^>]*[^\/>]){0,1}>"; // i.e. <p> <b> ...
274 $closed_tag = "<\/\w+\s*[^>]*>"; // i.e. </p> </b> ...
275 $openended_tag = "<\w+\s*[^>]*\/>"; // i.e. <br/> <img /> ...
276 $cutten_tag = "<\w+\s*[^>]*$"; // i.e. <img src=""
277 $reg_expr_img = "/<img\s*[^>]*\/>/is";
278 /*
279 Check: if text is shorter than length (tags excluded) return $html
280 with or without tags
281 */
282 $reg_expr = "/$opened_tag|$closed_tag|$openended_tag/is";
283 $text = preg_replace($reg_expr, '', $html);
284 if (strlen($text) <= $length) {
285 if(!$strip_tags) {
286 if($cut_images) {
287 $html = preg_replace($reg_expr_img, "", $html);
288 }
289 return $html;
290 }
291 else return $text;
292 }
293
294 /*
295 else if $strip_tags s false...
296 */
297 if(!$strip_tags) {
298
299 // splits all html-tags to scanable lines
300 $reg_expr = "/(<\/?\w+\s*[^>]*\/?>)?([^<>]*)/is";
301 preg_match_all($reg_expr, $html, $lines, PREG_SET_ORDER);
302 /*
303 now
304 - in $lines[$i] are listed all the matches with the regular expression:
305 $lines[0]: first match
306 $lines[1]: second match ...
307
308 - $lines[$i][0] contains the wide matching string
309 - $lines[$i][1] contains the matching with (<\/?\w+\s*[^>]*\/?>), that is opened or
310 closed ore openclosed tags
311 - $lines[$i][2]contains the matching with ([^<>]*) that is the text inside the tag
312 or between a tag and another
313 */
314 $total_length = 0;
315 $tags_opened = array();
316 $partial_html = '';
317
318 foreach ($lines as $line_matchings) {
319 /*
320 $line_matchings[1] contains tags
321 $line_matchings[2] contains text contained in tags
322
323 Check: what kind of tag is? open, close, openclose?
324 */
325 if (!empty($line_matchings[1])) {
326 $strip_this_tag = 0;
327 $reg_expr_oc = "/".$openended_tag."$/is";
328 $reg_expr_o = "/<(\w+)\s*([^>]*[^\/>]){0,1}>$/is";
329 $reg_expr_c = "/<\/(\w+)>$/is";
330 // search img tags
331 if(preg_match($reg_expr_img, $line_matchings[1]) && $cut_images) {
332 $strip_this_tag = 1;
333 }
334 // search openended tags
335 elseif (preg_match($reg_expr_oc, $line_matchings[1])) {
336 // nothing: doesn't encrease the count of characters
337 // and doesn't need a closure
338 }
339 // search opened tags
340 elseif(preg_match($reg_expr_o, $line_matchings[1], $tag_matchings)) {
341 // open tag
342 // add tag to the beginning of $open_tags list
343 array_unshift($tags_opened, strtolower($tag_matchings[1]));
344 }
345 // search closed tags
346 elseif(preg_match($reg_expr_c, $line_matchings[1], $tag_matchings)) {
347 // close tag
348 // delete tag from $open_tags list (as it has been already closed)
349 $pos = array_search($tag_matchings[1], $tags_opened);
350 if ($pos !== false) {
351 unset($tags_opened[$pos]);
352 }
353 }
354 // add html-tag to $truncate'd text
355 if(!$strip_this_tag) $partial_html .= $line_matchings[1];
356
357 }
358 /*
359 Calculate the lenght of the text inside tags and replace considering html entities one size characters
360 */
361 $reg_exp_entities = '/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i';
362 $content_length = strlen(preg_replace($reg_exp_entities, ' ', $line_matchings[2]));
363
364 if ($total_length+$content_length> $length) {
365
366 $left = $length - $total_length;
367 $entities_length = 0;
368
369 // search for html entities (l'entities conta come un carattere, ma nell'html ne uccupa di più, quindi dobbiamo fare in modo di includere completament l'entities, cioè il suo codice e contarlo interamente come un singolo carattere: scaliamo uno da $left ed aggiungiamo $entities_length all alunghezza della substring)
370 if(preg_match_all($reg_exp_entities, $line_matchings[2], $entities, PREG_OFFSET_CAPTURE)) {
371 // calculate the real length of all entities in the legal range
372 foreach ($entities[0] as $entity) {
373 if ($entity[1]+1-$entities_length <= $left) {
374 $left--;
375 $entities_length += strlen($entity[0]);
376 }
377 else {
378 // no more characters left
379 break;
380 }
381 }
382 }
383
384 $partial_html .= substr($line_matchings[2], 0, $left+$entities_length);
385 // maximum lenght is reached, so get off the loop
386 break;
387
388 }
389 else {
390 $partial_html .= $line_matchings[2];
391 $total_length += $content_length;
392 }
393
394 // if the maximum length is reached, get off the loop
395 if($total_length>= $length) break;
396
397 }
398 }
399 else {
400 // considero solamente il testo puro
401 $partial_html = substr($text, 0, $length);
402 }
403
404 // if the words shouldn't be cut in the middle...
405 if (!$cut_words) {
406 //search the last occurance of a space or an end tag
407 $spacepos = strrpos($partial_html, ' ');
408 $endtagpos = strrpos($partial_html, '>');
409 if(isset($spacepos) || isset($endtagpos)) {
410 //cut the text in this position
411 $cutpos = ($spacepos<$endtagpos)? ($endtagpos+1) : $spacepos;
412 $partial_html = substr($partial_html, 0, $cutpos);
413 }
414 }
415
416 // add the ending characters to the partial text
417 $partial_html .= $ending;
418
419 /*
420 Se non ho strippato i tag devo chiudere tutti quelli rimasti aperti
421 */
422 if(!$strip_tags) {
423 // close all unclosed html tags
424 foreach ($tags_opened as $tag) {
425 $partial_html .= '</' . $tag . '>';
426 }
427 }
428
429 return $partial_html;
430
431 }
432}
433?>