Browse Source

Microblog now uses JSON to store posts.
Various bugfixes have also been made.

teo greenwood 10 years ago
parent
commit
9f5551d4e5
6 changed files with 126 additions and 87 deletions
  1. 1 0
      css/screen.css
  2. 3 3
      index.php
  3. 70 36
      sys/admin/mbengine.inc
  4. 3 3
      sys/blogroll.inc
  5. 48 44
      sys/microblog.inc
  6. 1 1
      sys/rss/microblog.php

+ 1 - 0
css/screen.css

@@ -166,6 +166,7 @@ button#clickme:active {
 }
 .cooltext {
  background-color: #333;
+ width: 100%;
 }
 #Submissions input, #Submissions textarea {
  width: 95%;

+ 3 - 3
index.php

@@ -4,18 +4,18 @@
   <?php
    //SRSBIZNUSS below - you probably shouldn't edit this unless you know what you are doing
    //GET validation/sanitation and parameter variable definitions below
-   if (!$_SERVER["HTTPS"]) {
+   if (!empty($_SERVER["HTTPS"])) {
     $protocol = "http";
    } else {
     $protocol = "https";
    }
-   if (!$_GET['nav']) {
+   if (empty($_GET['nav'])) {
     $nav = '';
    }
    else {
     $nav = $_GET['nav'];
    }
-   if (!$_GET['post']) {
+   if (empty($_GET['post'])) {
     $post = '';
    }
    else {

+ 70 - 36
sys/admin/mbengine.inc

@@ -1,33 +1,50 @@
 <?php
-  //TODO have include file here for string size validation function
-  //Microblog Posting engine - also used to display a form for submitting stories
-  if (!empty($_POST["title"])) {//First check for a title in your POST data. If so, assume we're posting something new
+  //TODO have include file here for string size validation function on titles, XSS Prevention (?)
+
+  // Function for creating a post, used twice in the code below (thus it is encapsulated).
+  function write_post($fh=null) {
+    //Pull in config due to function scoping
+    extract(json_decode(file_get_contents('config/main.json'),true));
     $errors = array();//Create empty error array
     //Validation checks
     $url = stripslashes($_POST["URL"]);
-    if (empty($_POST['URL'])) {$errors[] = "No url provided.";}
-    else if (!filter_var($url,FILTER_VALIDATE_URL)) {$errors[] = '"'.$url.'" is not a valid ASCII URL.';}
-    if (!empty($_POST["IMG"]) && !filter_var(stripslashes($_POST["IMG"]),FILTER_VALIDATE_URL)) {$errors[] = 'Image "'.$url.'" is not a valid ASCII URL.';}
-    if (!empty($_POST["AUD"]) && !filter_var(stripslashes($_POST["AUD"]),FILTER_VALIDATE_URL)) {$errors[] = 'Audio "'.$url.'" is not a valid ASCII URL.';}
-    if (empty($_POST["comment"]) && empty($_POST["IMG"]) && empty($_POST["AUD"])) {$errors[] = "Post content is blank, Please add a comment or media to the posting.";}
-    //TODO Need to do extra validation here to prevent folks from doing something stupid like inserting executable code or large hex dumps of files
-    if (!count($errors)) {//All POST Vars needed to construct a coherent posting are here, let's format our data and write this thing
+    if (empty($_POST['URL'])) {
+      $errors[] = "No url provided.";
+    } else if (!filter_var($url,FILTER_VALIDATE_URL)) {
+      $errors[] = '"'.$url.'" is not a valid ASCII URL.';
+    }
+    if (!empty($_POST["IMG"]) && !filter_var(stripslashes($_POST["IMG"]),FILTER_VALIDATE_URL)) {
+      $errors[] = 'Image "'.$url.'" is not a valid ASCII URL.';
+    }
+    if (!empty($_POST["AUD"]) && !filter_var(stripslashes($_POST["AUD"]),FILTER_VALIDATE_URL)) {
+      $errors[] = 'Audio "'.$url.'" is not a valid ASCII URL.';
+    }
+    if (!empty($_POST["VID"]) && !filter_var(stripslashes($_POST["VID"]),FILTER_VALIDATE_URL)) {
+      $errors[] = 'Video "'.$url.'" is not a valid ASCII URL.';
+    }
+    /*TODO Need to do extra validation here to prevent folks from doing something stupid
+    (like inserting executable code or large hex dumps of files). FILTER_VALIDATE_URL should catch
+    most of this, but especially on the title and commentary I can't be sure.*/
+    if (!count($errors)) {//All POST Vars needed to construct a coherent posting are here, let's go 
       include_once("config/users.inc");//Import userland functions to figure out who's posting
       $postBody = array(
         "title"   => stripslashes($_POST["title"]),
         "url"     => $url,
         "image"   => stripslashes($_POST["IMG"]),
         "audio"   => stripslashes($_POST["AUD"]),
+        "video"   => stripslashes($_POST["VID"]),
         "comment" => stripslashes($_POST["comment"]),
         "poster"  => $poster
-      );
-      $tdtime = new DateTime(null, new DateTimeZone($timezone));
-      $today = $tdtime->format('m.d.y');
-      $now = $tdtime->format('H:i:s');
-      $newsdir = $_SERVER["DOCUMENT_ROOT"].'/'.$basedir.$microblogdir;
-      @mkdir($newsdir.$today);
-      $fh = fopen($newsdir.$today."/".$now, 'w');
-      if (!$fh) die("ERROR: couldn't write $newsdir$today/$now to $newsdir$today, check permissions");
+      );//XXX Note here that if editing, it changes poster to whoever last edited the post
+      if(empty($fh)) {//If none was passed in, we need to make one
+        $tdtime = new DateTime(null, new DateTimeZone($timezone));
+        $today = $tdtime->format('m.d.y');
+        $now = $tdtime->format('H:i:s');
+        $newsdir = $_SERVER["DOCUMENT_ROOT"].'/'.$basedir.$microblogdir;
+        @mkdir($newsdir.$today);
+        $fh = fopen($newsdir.$today."/".$now, 'w');
+        if (!$fh) die("ERROR: couldn't write $newsdir$today/$now to $newsdir$today, check permissions");
+      }
       fwrite($fh,json_encode($postBody));
       fclose($fh);
     } else {//Print errors at the top, since we didn't have what we needed from POST
@@ -36,19 +53,35 @@
       $message .= '</ul>POST Variable Dump below:<br /><em style="color: red; font-size: .75em;">'.print_r($_POST, true).'</em>';
       echo $message;
     }
-  } elseif (!empty($_POST["id"])) {//If no title is supplied, let's see if we're editing/deleting a post.
-    if (empty($_POST["content"])) {//BLANKING IN PROGRESS
-      $res = unlink($_POST["id"]);
-      if (!$res) die("ERROR: couldn't delete ".$_POST['id'].", check permissions");
-      echo "Deleted ".$_POST["id"]."<br />";
-    } else {//Attempt editing, first detecting whether content is json
-      $fh = fopen($_POST["id"], 'w');
-      if (!$fh) die("ERROR: couldn't write to ".$_POST['id'].", check permissions");
-      if(is_null(json_decode($_POST["content"]))) {$content = stripslashes($_POST["content"]);}//Do some munging if it's just raw text
-      else {$content = $_POST["content"];}//JSON should be formatted correctly already
-      fwrite($fh,$content);//Just write the blob ,TODO validation
-      fclose($fh);
-      echo "Edited ".$_POST["id"]."<br />";
+  }
+
+  //Microblog Posting engine - also used to display a form for submitting stories
+  if($_SERVER['REQUEST_METHOD'] == 'POST') {//Don't do anything unless we are POSTing 
+    if(empty($_POST["id"])) {//See if we need to post something new
+      write_post(); 
+    } else {//OK, so we've established that the post has an ID. Let's see if we're editing/deleting a post.
+      if (!empty($_POST["action"]) && $_POST["action"] == 'Delete') {//BLANKING IN PROGRESS
+        $res = unlink($_POST["id"]);
+        if (!$res) {
+          header("HTTP/1.1 500 Internal Server Error");
+          die("ERROR: couldn't delete ".$_POST['id'].", check permissions");
+        }
+        echo "Deleted ".$_POST["id"]."<br />";
+      } else {//Attempt editing, first detecting whether content is json
+        $fh = fopen($_POST["id"], 'w');
+        if (!$fh) {
+          header("HTTP/1.1 500 Internal Server Error");
+          die("ERROR (500): couldn't open ".$_POST['id'].", check permissions");
+        }
+        if(empty($_POST["type"]) && !empty($_POST["content"])) {//Do some munging if it's just raw text
+          $content = stripslashes($_POST["content"]);
+        } else {//Process the JSON Post, write to file
+          write_post($fh);
+        }
+        fwrite($fh,$content);//Just write the blob ,TODO validation
+        fclose($fh);
+        echo "Edited ".$_POST["id"]."<br />";
+      }
     }
   }
   //DOM below
@@ -57,11 +90,12 @@
  <div id="submissions">
   <p class="title">Submissions:</p>
   <form id="Submissions" method="POST">
-   Title<br /><input class="cooltext" type="text" name="title" />
-   URL<br /><input class="cooltext" type="text" name="URL" />
-   Image<br /><input class="cooltext" type="text" name="IMG" />
-   Audio<br /><input class="cooltext" type="text" name="AUD" />
-   Comments:<br /><textarea class="cooltext" name="comment">Potzrebie</textarea>
+   Title *<br /><input class="cooltext" type="text" name="title" placeholder="Iowa Man Destroys Moon" />
+   URL *<br /><input class="cooltext" type="text" name="URL" placeholder="https://oneweirdtrick.scam" />
+   Image<br /><input class="cooltext" type="text" name="IMG" placeholder="https://gifdump.tld/Advice_Dog.jpg" />
+   Audio<br /><input class="cooltext" type="text" name="AUD" placeholder="https://soundclod.com/static.mp3"/>
+   Video<br /><input class="cooltext" type="text" name="VID" placeholder="https://youvimeo.tv/infomercial.mp4" />
+   Comments:<br /><textarea class="cooltext" name="comment" placeholder="Potzrebie"></textarea>
    <input class="coolbutton" type="submit" value="Publish" text="Publish" />
   </form>
  </div>

+ 3 - 3
sys/blogroll.inc

@@ -7,7 +7,7 @@
 </p>
 <?php
 
-if ($_GET['post'] != "") {
+if (!empty($_GET['post'])) {
     $post=urldecode($_GET['post']);
     $statz = stat($post);
     $uid = $statz['uid'];
@@ -29,7 +29,7 @@ if ($_GET['post'] != "") {
 } else {
 
 $offset=0;
-if ($_GET['index'] != "" && !is_int($_GET['index'])) {
+if (!empty($_GET['index']) && !is_int($_GET['index'])) {
 	$offset = 10*$_GET['index'];
 }
 
@@ -87,7 +87,7 @@ if ($older) {
 	echo "<a href=\"".$_SERVER["PHP_SELF"]."?nav=3&index=$offset\">Older Posts</a>";
 }
 echo "</td><td style=\"text-align: right;\">";
-if ($_GET['index'] != "") {
+if (!empty($_GET['index'])) {
 	$offset=$_GET['index']-1;
 	if ($offset == 0) {
 		echo "<a href=\"".$_SERVER["PHP_SELF"]."?nav=3\">Newer Posts</a>";

+ 48 - 44
sys/microblog.inc

@@ -1,13 +1,5 @@
-<!--Scripts below allow audio player JS to show up with fancy little player-->
-<script type="text/javascript" src="sys/fileshare/include/audio-player.js"></script>
-<script type="text/javascript">
-	AudioPlayer.setup("sys/fileshare/include/player.swf", {
-	width: 290,
-	transparentpagebg: "yes",
-	});
-</script>
 <?php
-  if ($editable) {
+  if ($editable) { //Insert the Only JS the project should have, all it does is toggle a div
     echo "
       <script type=\"text/javascript\">
         function switchMenu(obj) {
@@ -25,26 +17,19 @@
   //Set important times - $tdtime is today's date, $oldtime is the oldest known date a tCMS install had nuze for - defaults to today then searches microblog dir for entries to set date
   $tdtime = new DateTime(null, new DateTimeZone($timezone));
   $oldtime = clone $tdtime;
-  //limit results of directory read to first entry
-  function &oldtimer($timezone, $basedir, $microblogdir) {
-    if ($handle = opendir($_SERVER["DOCUMENT_ROOT"].'/'.$basedir.$microblogdir)) {
-      while (false !== ($entry = readdir($handle))) {
-        if ($entry != "." && $entry != "..") {
-          $oldtime = DateTime::createFromFormat('m.d.y', $entry, new DateTimeZone ($timezone));
-          closedir($handle);
-          return($oldtime);
-        }
-      }
-    }
-  };
-  $oldtime = &oldtimer($timezone, $basedir, $microblogdir);
+  //limit results of directory read to first entry -- much faster than doing it with PHP once you get a large filelist. 
+  exec("ls -tr1 ".$_SERVER["DOCUMENT_ROOT"].'/'.$basedir.$microblogdir." |head -1", $cmd_out);
+  if(!empty($cmd_out[0])) {
+    $oldtime = $oldtime = DateTime::createFromFormat('m.d.y', $cmd_out[0], new DateTimeZone($timezone));
+  }
   $oldtime->sub(new DateInterval('P1D'));
-  //$today and $tmrw refer to times relative to what is passed by GET params - $today is the date requested by GET, $tmrw is bool designating whether $today is something other than $tdtime 
-  //error indicates whether you supplied a bogus GET param for date.
+  /*$today and $tmrw refer to times relative to what is passed by GET params -
+  $today is the date requested by GET, $tmrw is bool designating whether $today is something other than $tdtime 
+  error indicates whether you supplied a bogus GET param for date.*/
   $tmrw = 0;
   $error = 0;
   $today = clone $tdtime;
-  if ($_GET["date"] != "") {
+  if(!empty($_GET["date"])) {
     $today = DateTime::createFromFormat('m.d.y', $_GET["date"], new DateTimeZone ($timezone));
     //Catch bogus input, set $tmwr to TRUE if $today was set to something other than today's date
     if (!filter_var($_GET["date"],FILTER_VALIDATE_REGEXP,array('options' => array('regexp' => "/^(0[1-9]|1[012])[.](0[1-9]|[12][0-9]|3[01])[.]\d\d/")))) {
@@ -59,13 +44,18 @@
       $tmrw = 1;
     }
   }
-  //Catch if day in question has no news - If not, display day before (or before that if still no news. $oldtime used here to tell when to stop looping back)
+  /*Catch if day in question has no news -
+  If not, display day before (or before that if still no news.
+  $oldtime used here to tell when to stop looping back)*/
   if (!$error) {
     while (empty($todaysnews)) {
-     $yesterday = clone $today;
-     $yesterday->sub(new DateInterval('P1D'));
-     //Detect if We're at the end of postings
-     if ($yesterday < $oldtime) {
+      $todaysnews = ""; //Set it to be something empty to prevent logspam
+      $yesterday = clone $today;//This may look strange, but it'll make sense later
+      $tomorrow = clone $today;
+      $tomorrow->add(new DateInterval('P1D'));
+      $yesterday->sub(new DateInterval('P1D'));
+      //Detect if We're at the end of postings
+      if ($yesterday < $oldtime) {
         echo " (".$today->format('m.d.y')."):</p><hr />";
         echo "For me, it was a beginning, but for you it is the end of the road.<br /><hr />\n";
         if ($oldtime != $tdtime) {
@@ -76,11 +66,15 @@
         $todaysnews = "end";
       }
       if ($todaysnews != "end") {
-        //Get news from directory if any exists for that day
+        //Get news from directory if any exists for that day, glob will return empty if nothing is in dir
         $todaysnews = glob($_SERVER["DOCUMENT_ROOT"].'/'.$basedir.$microblogdir.$today->format('m.d.y')."/*");
         //Set display date for today's news, set $today to be yesterday in order to get while loop to recurse correctly
         $realtime = $today->format('m.d.y');
-        $today = clone $yesterday;
+        if(!empty($_GET['fwd']) && $_GET['fwd']) {//Check whether we are traversing forward or backward in time
+          $today = clone $tomorrow;
+        } else { //Default to going back
+          $today = clone $yesterday;
+        }
         //Finish by setting times for Yesterday and Tomorrow so that they can be used in links below
         $tomorrow = clone $yesterday;
         $tomorrow->add(new DateInterval('P2D'));
@@ -97,27 +91,27 @@
         $json = json_decode($fc);
         if(is_null($json)) {
           echo $fc;
-        } elseif (isset($json->title) && isset($json->url) && isset($json->poster)) {
+        } elseif (!empty($json->title) && !empty($json->url) && !empty($json->poster)) {
           $out = '<h3 class="blogtitles">
                     <a href="'.$json->url.'">'.$json->title.'</a>
                     <a class="usericon '.$json->poster.'" title="Posted by '.$json->poster.'"></a>
                   </h3>';
-          if(isset($json->image)) {
+          if(!empty($json->image)) {
             $out .= '<img class="mblogimg" src="'.$json->image.'" />';
           }
-          if(isset($json->audio)) {
+          if(!empty($json->audio)) {
             $out .= '<audio src="'.$json->audio.'" controls>
                        Download Audio 
                        <a href="'.$json->audio.'">Here</a><br />
                      </audio>';
           }
-          if(isset($json->video)) {
+          if(!empty($json->video)) {
             $out .= '<video src="'.$json->video.'" controls>
                        Download Video
                        <a href="'.$json->video.'">Here</a><br />
                      </video>';
           }
-          if(isset($json->comment)) {
+          if(!empty($json->comment)) {
             $out .= $json->comment;
           }
           $out .= '<hr />';
@@ -125,14 +119,24 @@
         } #Note that if nothing works out here, I'm just opting not to show anything.
         if ($editable) {
           $id=basename($i);
-	  echo "
+	  $editblock = "
             <a style=\"display: inline-block;\" onclick=\"switchMenu('$id');\">[Edit]</a>
             <div style=\"display: none;\" id=\"$id\">
              <form style=\"display: inline\" method=\"POST\">
               <input type=\"hidden\" name=\"id\" value=\"$i\" />
-              <input type='hidden' name='action' value='Edit' />
-              <textarea class=\"mbedit_text\" name=\"content\">$fc</textarea>
-              <input class=\"coolbutton mbedit_button\" type=\"submit\" Value=\"Edit\" />
+              <input type='hidden' name='action' value='Edit' />";
+          if(is_null($json)) {
+            $editblock .= "<textarea class=\"mbedit_text\" name=\"content\">$fc</textarea>";
+          } else {
+          $editblock .= '<input type="hidden" name="type" value="JSON" />
+            Title: <input class="cooltext" type="text" name="title" value="'.$json->title.'" /><br />
+            URL: <input class="cooltext" type="text" name="URL" value="'.$json->url.'" /><br />
+            Image: <input class="cooltext" type="text" name="IMG" value="'.$json->image.'" /><br />
+            Audio: <input class="cooltext" type="text" name="AUD" value="'.$json->audio.'" /><br />
+            Video: <input class="cooltext" type="text" name="VID" value="'.$json->video.'" /><br />
+            Comments: <textarea class="cooltext" name="comment">'.$json->comment.'</textarea>';
+          }
+          $editblock .= "<input class=\"coolbutton mbedit_button\" type=\"submit\" Value=\"Edit\" />
              </form>
              <form style=\"display: inline\" method=\"POST\">
               <input type=\"hidden\" name=\"id\" value=\"$i\" />
@@ -141,13 +145,13 @@
              </form>
             </div>
             <hr class=\"clear\" />";
+          echo $editblock;
         }
-        echo "\n";
       }
-      echo "<a style=\"float: left;\" title=\"skips empty days\" href=\"".$_SERVER["PHP_SELF"]."?nav=2&date=".$yesterday."\">Yesterday's News</a>\n";
+      echo "<a style=\"float: left;\" title=\"skips empty days\" href=\"?nav=2&date=".$yesterday."&fwd=0\">Older Entries</a>\n";
     }
     if ($tmrw) {
-      echo "<a style=\"float: right;\" href=\"".$_SERVER["PHP_SELF"]."?nav=2&date=".$tomorrow."\">Tomorrow's News</a>\n";
+      echo "<a style=\"float: right;\" href=\"?nav=2&date=".$tomorrow."&fwd=1\">Newer Entries</a>\n";
     }
   }
 ?>

+ 1 - 1
sys/rss/microblog.php

@@ -51,7 +51,7 @@
                  <pubDate>'.$storyPubDate.'</pubDate>
                  <author>'.$email.' ('.$author.')</author>
                 </item>';
-    } elseif (isset($json->title) && isset($json->url) && isset($json->poster)) {
+    } elseif (!empty($json->title) && !empty($json->url) && !empty($json->poster)) {
         if(isset($tcmsUsers[$json->poster])) {
             $email = $tcmsUsers[$json->poster]["email"];
             $author = $tcmsUsers[$json->poster]["fullName"];