RSS displayed with PHP – Updated!

A week ago I posted about using PHP to display an RSS feed. We moved to a new server that did not have DOM enabled, so I have updated my code to use curl instead of DOMDocument.  Either method does work, but this is nice and clean.  See below for my new code:


<html>
<head>
<link rel="stylesheet" href="/alert-rss.css" media="all">
</head>

<body>

<?php

//set timezone
date_default_timezone_set('America/New_York');

//set RSS feed
$handle = curl_init('https://url-of-rss-feed.com');

curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($handle, CURLOPT_FOLLOWLOCATION, TRUE); 
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($handle, CURLOPT_ENCODING, 'identity');

//get RSS feed from $handle
$response = curl_exec($handle);

curl_close($handle);

$xml = simplexml_load_string($response, "SimpleXMLElement", LIBXML_NOCDATA);
$json = json_encode($xml);
$data = json_decode($json, true);

//load feed
$feeds =  array();

//load only required feed items
if(isset($data['channel']['item'])) {
    foreach($data['channel']['item'] as $item) {
        $feeds[] =  array(
            'title' =>  $item['title'],
            'desc'  =>  $item['description'],
            'date'  =>  $item['pubDate'],
        );
    }
}

//set the internal point of the array to last element
end($feeds);

//pull key of array at pointer so we only display one entry
$key = key($feeds);

//set variables to display data from array
$title = $feeds[$key]['title'];
$description = $feeds[$key]['desc'];
$date = date('l F d, Y g:ia', strtotime($feeds[$key]['date']));

//set $end_date for when RSS expires - calculation entered as (hours*secondsperhour)
$end_date = date('l F d, Y H:i', strtotime($feeds[$key]['date']) + (18*3600));

//set how date variables are calculated for comparison purposes
$today = date('l F d, Y H:i');
$today_calc = strtotime($today);
$end_date_calc = strtotime($end_date);

//display what we have found if it is current
if($today_calc < $end_date_calc) {
	echo '<div id="blinky-div"><p><strong>'.$title.'</strong><br />';
	echo '<small><em>Posted on '.$date.'</em></small></p>';
	echo '<p>'.$description.'</p></div>';
//hide div if there is no current data
} else {
	    echo '<div style="display: none;">No current RSS</div>';
}
?>

</body>
</html>
Posted in Upgrade, Web/Internet | Comments Off on RSS displayed with PHP – Updated!

Display RSS feed as alert using PHP

Our school district had a need where we wanted to have the no school notice show on all of our district pages when an alert is sent out.  I wanted to automate the process so that there wouldn’t need to be any intervention last minute.  The alert system we use, Alert Solutions, has an option to output to an RSS feed.  By using this and a small amount of PHP, I was able to get the alerts to show up on the site automatically and display for 18 hours without any special intervention other than when the admin makes the notification, they have to remember to check the “RSS” box as well. 

The issue became that the RSS feed never lets go of any posts, and on top of that, it outputs the oldest at the top.  To fix this, we look for the number of keys, then pull only the latest key.  This means that we are only looking at the most recent entry.  If it is less than 18 hours old, it is displayed automatically.  Otherwise the div is set to display:none; and doesn’t show.

Below is the code I used.


<html>
<head>
<link rel="stylesheet" href="/alert-rss.css" media="all">
</head>

<body>

<?php
	//Set timezone and load array with only the fields we need
	date_default_timezone_set('America/New_York');
	$rss = new DOMDocument();
	$rss->load('https://url-of-rss-feed.com');
	$feed = array();
	foreach ($rss->getElementsByTagName('item') as $node) {
		$item = array ( 
			'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
			'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
			'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue,
			);
		array_push($feed, $item);
	}
	
	
	//Find the last entry array key so we only display current RSS feed
	end($feed);
	$key = key($feed);
	
	//Set variables to pull appropriate data from array
	$title = str_replace(' & ', ' &amp; ', $feed[$key]['title']);
	$description = $feed[$key]['desc'];
	$date = date('l F d, Y H:ma', strtotime($feed[$key]['date']));

	//Set $end_date for when RSS expires.  Calculation entered as (hours*secondsperhour).
	$end_date = date('l F d, Y H:ma', strtotime($feed[$key]['date']) + (18*3600));

	//Set how today is calculated for comparison purposes
	$today = date('l F d, Y H:ma');

	//Display what we have found if it is current
	if($today < $end_date) {
		echo '<div id="blinky-div"><p><strong>'.$title.'</strong><br />';
		echo '<small><em>Posted on '.$date.'</em></small></p>';
		echo '<p>'.$description.'</p></div>';
	//Hide DIV if there is no current data
	} else {
		    echo '<div style="display: none;">No current RSS</div>';
	}

?>

</body>
</html>

 

And here is the CSS I used:

@keyframes blink { 
    50% {
   	border-color: #ff0000; 
   	border-style: solid;
   	border-width: 4px;
   	}
   	0% {
   	border-color: #fff; 
   	border-style: solid;
   	border-width: 4px;
   	} 
}
#blinky-div {
    animation-name: blink ;
    animation-duration: .5s ;
    animation-timing-function: step-end ;
    animation-iteration-count: infinite ;
    animation-direction: alternate ;
}
Posted in Computers and Hardware, Technology, Web/Internet | Comments Off on Display RSS feed as alert using PHP

Clean your DHW tankless coil

We have hard water and we heat our water with an oil boiler and a tankless coil.  This is, admittedly, a very inefficient method of heating water but it came with the house so we are making it work.  Once a year we need to have the coil cleaned so that we get full output again.  In the past, our service company covered this under our contract, now they don’t so I have taken to doing it myself.  Here’s how I do it:

Wayne WaterBUG pump (any plastic submersible utility pump works) – $100
Washer hoses (pair) – $15
2 gallons of white vinegar – $6
New 5 gallon bucket – $3

For a total of $124 plus tax, I have everything I need to perform the cleaning.  Considering it was going to be $200 to have it done professionally, this was good.  Also, next time it is only $6 for the vinegar.

Of note, I already had the tankless coil isolator valves plumbed in, if you don’t have these you will need them and they cost about $60 for the set.

Procedure: Turn off boiler, let it cool down to at 110F or cooler.  Put pump in 5 gallon bucket.  Fill bucket with 2 gallons of vinegar.  Hook one hose from top of pump to one end of the coil.  Hook other hose from remaining coil hookup and put the loose end into the bucket.  Turn isolator valves off from water main and on to the pump and exit hose.  Plug in pump, let it run for 1-2 hours.  After that, I drained the vinegar and did the same process with clean water for a few minutes to get all the vinegar out.

It worked perfectly for us and is a known DIY solution, but I thought I’d share it here for you folks!

Posted in Home and Homestead, Wood Heat/HVAC | Comments Off on Clean your DHW tankless coil

Driveway alignment, do it yourself!

I’ve always been under the assumption that alignments should only be done by professionals on an alignment rack.  While I do still believe that this will give the best results, in a pinch, it can be done in the driveway as long as you are looking for zeroing out your toe adjustment.  It worked well for me as my Subaru Forester prefers zero toe-in anyway.

Simply use a piece of string and attach it somewhere behind the rear wheels (license plate or trailer hitch works well).  Then bring the string half way up the rear wheel and up to the front of the car, half way up the front wheels.  Adjust the tie rod end until the front tire touches the string at both points it crosses the rubber (front and rear of the front tire).

Here is someone else who uses this method and made a great YouTube video displaying how this works: https://www.youtube.com/watch?v=AuYsd7SUwTA

Posted in Cars, Trucks and Tractors, Hobbies, Home and Homestead | Comments Off on Driveway alignment, do it yourself!

Biking update

Since the last post I have:

– Replaced old bashguard with new BBG
– Replaced crankset with Shimano FC-M361 165mm crank
– Replaced front 3x gears with 1x 32 tooth N/W (Blackspire Snaggletooth)
– Removed front derailleur and added an N-Gear Jump Stop
– New chain
– Lezyne air pump
– Green Guru Saddle Bag and Frame bag
– Removed reflectors, added reflective tape for visibility

I’ve been riding my new 1×8 setup for a few months now and I have to say, I’m sold.  I really love the simplicity and don’t feel like I’m really missing out on anything.  With my shorter 165mm crank arms, I don’t really spin out until above 25mph, which is more than plenty on a trail bike.  I would like some lower gearing, and I plan on replacing my 11-30 cassette for an 11-34.  I can definitely see where an 11-40 10spd or 11spd would come in handy, but I think I can make plenty of action happen on the old 8.

I’ve even been adding some trail around the homestead, that has been really fun and the kids enjoy it too!  I do need to get over to the Wilder Hill Trails here in town as well as the Freedom Trails behind MSLC in Skowhegan.

Posted in Hobbies, Home and Homestead, Upgrade | Comments Off on Biking update

Excited about biking

I’m stoked to get back into the mountain biking scene.  I haven’t done much of it since graduating college 10 years ago.  I’ve been tuning up my bike, a 2005 Giant Rincon.  I need to adjust the front derailleur and lube the chain.  That’s pretty much all that’s left.  But I’ve already done a lot.  So far I have:

– Trimmed my custom bash guard (140g down to 80g)
– Upgraded from heavy 635g cable lock to 40g for two Hiplok Z-Loks
– New grips (Lizard Skins – Moab)
– Removed kickstand
– Trimmed and marked height on seat post

I can’t wait to try out the new local trails, Wilder Hill Trails in Norridgewock.

Posted in Health, Hobbies, Home and Homestead, Upgrade | Comments Off on Excited about biking

Jump Pack Meme!

My jump pack starts all the cars in the yard, and they're like, I'm too weak to start.  Damn right, you're too weak to start.  Clamp on, and you'll get a charge.

My jump pack starts all the cars in the yard…

Posted in Memes | Comments Off on Jump Pack Meme!

Webcams on Raspberry Pi

Webcams on Raspberry Pi is like salsa and chips – they just belong together.  But sometimes making that happen isn’t straight forward.  I’ve done it two ways and figured I would share with anyone else wanting an easy way to run a webcam on Raspberry Pi.  The first way is for a standard USB webcam, the second way is for any of the “Raspberry Pi Cameras.”  To automate any of these processes, use crontab and call the command every minute, hour, or whenever you want.  For me I make a shell file with the command(s) in it, then call that in crontab.  This makes like easier, especially when using multiple commands like with ImageMagick, so that things happen in the right order.  Also, if you need to make changes to the script you are only editing that one shell file rather than every line in crontab!


Make USB webcam work on Pi:

First install fswebcam: sudo apt-get install fswebcam

Then you can run a command to take a picture from the camera.  In my case I wanted to save it in the “html” folder so I could share it with the world.  This directory could be changed to wherever you want it saved.  Here is the command I was using: fswebcam –jpeg 95 –save /var/www/html/current.jpg -S 20 -r 1280×720

If you would like to scale the image down you can add the –scale flag like this: fswebcam –jpeg 25 -S 20 -r 1280×720 –scale 640×360 –save /var/www/html/current.jpg

If you would like to change the default banner (or remove it), as well as many other options, check out the fswebcam manual.

To get the files to host using Apache you will need to fix permissions so “pi” can write to those folders (directions from raspberrypi.org):

On normal situation, http daemon run as some user and group, www-data on debian (raspbian).
Standard html files are stored on /var/www/, owned by root:root, with permissive permission, all can read, but only root can write.
To ordinary user write to /var/www need to takeover it. Supposed the use is pi.
sudo chown -R pi:www-data /var/www
Also, need to set user and group permission:
sudo chmod u+rxw,g+rx-w,o-rwx /var/www
Now, /var/www can be read,write and chdir by user pi, group www-data can chdir and read. Other not have access.
sudo chmod g+s /var/www
Any new file created on /var/www belong to group www-data.
If have files on /var/www, change user and group, and allow to group www-data read.
For file chmod u+rw,g+r-xw,o-rwx
For directory chmod u+rwx,g+rx-w,o-rxw
Now, user pi can manipulate files on /var/www and httpd can read, but not write.

If you would like to make an archive of your webcam images, we can do that too!

First you will need to make a shell file that you will be executable, sudo chmod +x shellfilename.sh

Then open the new shell file in nano (or other editor) and put in your code.  This shell file code below will copy the current.jpg file to an archive folder with $DATE in the filename.

#!/bin/bash

DATE=$(date +”%Y-%m-%d_%H%M”)

cp /var/www/html/current.jpg /home/pi/webcam/$DATE.jpg


Make Raspberry Pi Camera function as webcam:

For the Raspberry Pi camera to work you will need to use Raspistill.  This is pre-installed with Rasbian, but if you want text on your image (like the default banner in fswebcam) you will need to install ImageMagick, sudo apt-get install imagemagick

Now run the terminal command to take a picture, for us we used: raspistill -w 640 -h 480 -hf -vf -o /var/www/html/buffer.jpg

For more commands, check out the Raspberry Pi Camera Manual.

Now we want to take the new image and add our banner.  This code will take the buffer.jpg image and add the label, timestamp, and banner color behind the text, then save the file as current.jpg.

/usr/bin/convert /var/www/html/buffer.jpg -fill ‘#0008’ -draw ‘rectangle 0,455,640,474’ -pointsize 14 -fill white -annotate +5+470 “TITLE OF WEBCAM” -annotate +505+470 %[exif:DateTimeOriginal] /var/www/html/current.jpg

When drawing the banner box, the coordinates are a,b,c,d where a is the left edge of the box, b is the top of the box, c is the right edge of the box, and d is the bottom of the box.

For more information on ImageMagick, check out the terminal commands in the ImageMagick manual.


Now you want to display this new image in a web page, right?  But isn’t it cooler if it auto-refreshes?  I think so.  Here is the very simple, but very effective, code that I like to use:

<html>
<head>
<script>
var webcamimage;
var imgBase=”current.jpg?”
var c = 0;
function count()
{
webcamimage.src=imgBase+(++c);
}
function init()
{
webcamimage = document.getElementById(“webcamimage”);
if( webcamimage )
{
setInterval(“count()”,10000);
}
}
window.onload = init;
</script>
<title>Current Weather in Skowhegan, ME</title>
</head>

<body>

<img alt=”Web Camera Image” id=”webcamimage” src=”current.jpg” />
</body>
</html>

Posted in Computers and Hardware, Technology, Web/Internet | Comments Off on Webcams on Raspberry Pi

32 a big year

It seems I always hear about people turning 30 or 40 and how big of a deal it is.  For me when I turned 30, I didn’t think anything of it.  However, turning 32 this year seemed to resonate more.  Not a bad thing, but I just noticed.  For instance, no longer am I able to register my age in 5 bits, I am now into a 6 bit register!  (31 in binary is 11111, 32 in binary is 100000).

I’m curious how many other tech-minded folks have thought about this.

Posted in Ponderings | Comments Off on 32 a big year

Digital security more important now than ever

There has been an enormous up-tick in hacking attempts, at least on web space that I manage as well as the servers at my day job.  This means that more than ever, people need to be diligent about running all security updates on their OS as well as application updates (especially plugins like Java and Flash).  It also means that for web devs like myself, it’s time to bite the bullet and buy SSL certs for any websites containing multiple logins and user data.  For me, this means SSGuitar.com.  As of January 20th 2017 SSGuitar is completely SSL’d.  I love encryption.

Posted in Computers and Hardware, Technology, Web/Internet | Comments Off on Digital security more important now than ever