Project BETA: New England Landmark Realty

New Website

I just finished the private beta for the New England Landmark Realty website.  Here it is:

New New England Landmark Realty Website

This will be going up at www.newenglandlandmarkrealty.com eventually, but not until after we get enough feedback.

Some of the new features include:

  • indexed and indexable MLS listings from both NNEREN and VREIN MLS IDX databases,
  • MUCH better SEO,
  • new design with slide show,
  • Old Website

    featured properties,

  • NELR property virtual tours and slide show movies,
  • back end analytics so they can actually see how the website is working.

Anyways, head over there and let me know what you think in the comments below.

The Twitter API

I’ve been messing with the Twitter API for the first time in the last few hours, and I’ve learned a TON.  I know – I’m jumping on the bandwagon late, but oh well.  I managed to create a script to retweet “stuff” based on the search functionality and I made a script to automatically follow people that post specific things.  I also managed to get my account suspended in like 2 hours due to suspicious activity – whoops.  I guess you live, you learn.  Basically everything for status updates and following uses CURL, which looks a little something like this:

<?php
 $username = "<username>";
 $password = "<password>"; t t
 $message = "<message content>";
 $url = '<API URL>';
 $curl_handle = curl_init();
 curl_setopt($curl_handle, CURLOPT_URL, "$url");
 curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
 curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($curl_handle, CURLOPT_POST, 1);
 curl_setopt($curl_handle, CURLOPT_POSTFIELDS, "status=$message");
 curl_setopt($curl_handle, CURLOPT_USERPWD, "$username:$password");
 $buffer = curl_exec($curl_handle);
 curl_close($curl_handle);
?>

If you’re looking for more info on how to use twitter, check out this eSeries.  It’s a good resource.

So, have questions?  Let me know.  I’m hoping to do a twitter series soon!

Tidbit Tuesday on PHP: Simple MySQL Database Insert Function

This builds on a function I did last week: db_query(). You can send any array straight to a MySQL database and it’ll even check to make sure the column actually exists.  Oh, and it returns the id of the record you just added in case you needed it.

<?php
   function db_array_insert($cfg_array, $table, $array) {
      require_once("dbQuery.function");

      $sql = "show columns from ".$table
      $tableArray = db_query($cfg_array, $sql);
      $inputString = "";

      foreach($tableArray as $key => $value) {
         if (array_key_exists($value[0], $array) && $value[0])
            $inputString .= "'".addslashes($array[$value[0]])."', ";
         else
            $inputString .= "'', ";
      }

      $inputString = substr($inputString, 0, -2);
      $sql = "insert into $table values(".$inputString.")"
      db_query($cfg_array, $sql);

      return mysql_insert_id();
   }

   $insert_array = array(
      "column_1" => "something_1",
      "column_2" => "something_2"
   );

   $cfg_array = array(
      "db_loc" => 'www.databaselocation.com',
      "db_user" => 'some user'
      "db_pass" => 'some password'
      "db_name" => 'database_name_here'
   );

   db_array_insert($cfg_array, "some_table", $insert_array); //and use it.
?>

So what do you think?  Having a problem?  Just let me know in the comments.

Tidbit Tuesday on PHP: Simple MySQL Database Query Function

It’s always great to create functions for those things you do a lot.  Probably the single most common function I execute is database calls.

Here is a simple script for hitting up your MySQL database with a query:

<?php
   if(!function_exists(dbQuery)) {
      function db_query($cfg_array, $query) {
         $connection =
            mysql_connect(
               $cfg_array['db_loc'],$cfg_array['db_user'],$cfg_array['db_pass']
            ) or die(mysql_error());

         mysql_select_db($cfg_array['db_name'],$connection)
            or die(mysql_error()." >> ".$query);
         $result = mysql_query($query,$connection)
            or die (mysql_error()." >> ".$query);
         $i = 0;

         if($result != 1) {
            while ($data_array = mysql_fetch_array($result)) {
               foreach($data_array as $key => $value) {
                  $tableArray[$i][$key] = stripslashes($data_array[$key]);
               }

               $i++;
            }

            return $tableArray;
         }
      }
   }
?>

You should be able to just copy and paste this as a function and call it in one of two ways:

$cfg_array = array(
   "db_loc" => 'www.databaselocation.com',
   "db_user" => 'some user'
   "db_pass" => 'some password'
   "db_name" => 'database_name_here'
);

$query = "SELECT * FROM 'table' WHERE some_column = 'something'";

db_query($cfg_array, $query); // This will return an array with the table in it.

$query = "UPDATE/DELETE/ETC * FROM 'table' WHERE some_column = 'something'";

db_query($cfg_array, $query); // This will return return an empty array, but still works.

I use this function in EVERYTHING.  I also have some other functions that use this as its base.  Someday I’ll turn it into a class.

So, what do you think?

Tidbit Tuesday on PHP: Holiday Notices for Business Sites

This is a handy script for managing an out of office message on your website.  I find this very useful on business websites when you’re tired of making that one little change to let people know when the office will be shut down.  With about 15 minutes of extra work, you only need to do it once a year.

Let’s say for instance we’re doing all of the major U.S. Holidays in 2010, observing weekend Holidays with a day off on either side of the weekend.  This means first we need to determine what those dates are.  I just happen to have looked up the six most common, listed below:

  • New Year’s Eve – January 1st
  • Memorial Day – May 31st
  • Independence Day – July 5th (July 4th is Sunday)
  • Labor Day – September 6th
  • Thanksgiving – November 25th and 26th
  • Christmas – December 24th (December 25th is a Saturday)

Now that we know our dates, we can build them into an array:

$date_array = array(
   "New Yearís Eve" =>
      array("leaving" => "2010-12-31", "returning" => "2011-01-03"),
   "Memorial Day" =>
      array("leaving" => "2010-05-31", "returning" => "2010-06-01"),
   "Independence Day" => // July 4th is a Sunday
      array("leaving" => "2010-07-05", "returning" => "2010-07-06"),
   "Labor Day" =>
      array("leaving" => "2010-09-06", "returning" => "2010-09-07"),
   "Thanksgiving" =>
      array("leaving" => "2010-11-025", "returning" => "2010-11-029"),
   "Christmas" => // December 25th is a Saturday
      array("leaving" => "2010-12-24", "returning" => "2010-12-27"),
 );

The date array can easily be stored in a database or be made up of more complicated functions that would calculate the holidays across multiple years with some basic logic.  Maybe we’ll cover the latter part in another post some day.

Now we need to build the function itself.  This function will be run every time the page loads.  You can even include the function in a separate file to be included on multiple pages:

function holiday_message($date, $date_array) {
   $date = strtotime($date); // Reformat the date so we can do math on it.
   foreach($date_array as $key => $value) {
      $leaving = strtotime($value['leaving']);
      $returning = strtotime($value['returning']);
      $early_warning = $leaving - 86400 * 7;
      // If the date is between (7 days before) leaving and returning
         if($date > $early_warning && $date < $returning) {
            echo
               "We will be observing ".$key." from ".date("Y-m-d", $leaving).
               " until ". date("Y-m-d", $returning).".
               When we return we will be more than happy to assist you.";
         }
   }
}

Now we just need to execute this function anywhere on the page:

holiday_message(date("Y-m-d H:i:s"),$date_array);

This code can be customized in numerous different ways, so the the message is more formal, or works for your specific situation.  You can also change the way days are stored or calculated, like the example above.  This is a core to get you started.  Where can you go from here?

PHP Function Friday: function

So, I’ve decided to start including a new post every Friday – kind of as a discipline thing. I’m going to write a post on a PHP function every Friday. I’m not just going to regurgitate the post in the official PHP manual, but I’m going to list my experience with it along with some creative ways to use it.

With out any further adieu, I’m posting on the first official building block (which isn’t technically a function, but I digress) ‘function’:

PHP Function and Syntax

function <function name>(<parameters>) {
   /*add code here*/
}

PHP Manual Entry

Check here for version information, or anything I may have missed:

http://www.php.net/manual/en/functions.user-defined.php

Notes and Use

This is great for building blocks of code that you repeat a lot.  I like to use it when duplicating XML/HTML code, such as links or form elements, which I will outline below.  Functions, both custom and built in, are the primary building blocks of a good program.  Everything else is just procedural.

Also, on a side note: PHP Coding Standards is a good read if you’re really geeky.

An important thing to keep in mind about making custom functions is that someone has probably already made it if it doesn’t already exist in the built in functions for PHP.  Feel free to jump online and see if someone has already made a function to do what you’re trying to do.  I like to use the site HotScripts.com, which has both free and commercial PHP scripts available.  Chances are: if I need it, they have it.  It saves me a ton of time.

Note in the examples that I precede the function with some explanation of what it does, the author, etc.  This isn’t needed, but it’s a REALLY good habit.

Other Functions Referenced in Examples

Examples

Here’s the meat.  Let’s make some stuff work.

Creating Image Links

/*
 *  Author: James Thompson, jtGraphic.net
 *
 *  Description
 *  ------------------------------------
 *  This function is for displaying image links in HTML.  It's less typing,
 *  and easier to remember what needs to be slashed out.  An image
 *  with the same name as the file name of the page you're linking to needs to
 *  be placed on the server in the same path as the internal variable
 *  '$image_path' and the same extension as '$image_ext'.
 *
 *  Arguments
 *  ------------------------------------
 *  $url - URL of the link
 *  $extra_tag_html - this is any extra HTML, like class, id, or style
 *
 */

/* Build the function. */

	function create_html_link($name, $extra_tag_html) {
		/* Define internal variables. */
			$image_path = "images/";
			$image_ext   = ".jpg";

		/* Output the HTML. */
			echo
				"<a href="".$name.".php" ".$extra_tag_html.">
					<img src="".$image_path.$name.$image_ext."" />
				</a>";
	}

/* Execute the function. */

	create_html_link("home", "class="normal_link"");
	create_html_link("about", "class="normal_link"");
	create_html_link("contact", "class="normal_link"");

Calculate the Number of Days Since Some other Date

/*
 *  Author: James Thompson, jtGraphic.net
 *
 *  Description
 *  ------------------------------------
 *  Simple.  This calculates the number of days since X date.
 *
 *  Arguments
 *  ------------------------------------
 *  $date - the date in this format: 'YYYY-MM-DD HH:MM:SS'
 *
 */

/* Build the function. */

	function num_days_since($date) {
		/* Do some time math. */
			$date = strtotime($date);
			$now = time();
			$difference = $now - $date;
			$days = $difference / 86400;

		/* Output the Value. */
			return $days;
	}

/* Execute the function. */

	/* Should return 0 */
		echo num_days_since(date("Y-m-d H:i:s"));
	/* Someone's birthday at 6:02:55AM on Oct 23, 1974 */
		echo num_days_since("1974-10-23 06:02:55");
	/* Since Jan 1, 2009 - no need for time */
		echo num_days_since("2009-01-01");

Examples Elsewhere on this Site:

Holiday Notices

Conclusion

So that’s the basics.  Functions can be very powerful in reducing the code on your websites.  If you’d like to see some more custom functions, check out my Tidbit Tuesdays on PHP If you have questions, let me know in the comments.

Pathfinding in PHP

I’ve been playing around with doing some A* pathfinding scripts.  I was looking around on the web and didn’t find any anywhere, so I decided to make my own rudimentary one.  I’m going to be expounding on this later.  I thought about looking into the A* method and a few others.  Feel free to take the sample below.  Here is a demo too.

<style>
 * {
 margin: 0px;
 padding: 0px;
 }
</style>
<body style="margin: 13px 0px 0px 0px; background: #000;">
<?php
 /* Set the size of our target area */
 $range = 3;

 /* Build the pathfinding function */
 function pathfind($current_square_x, $current_square_y, $map, $steps, $target) {
 /* Give the function a step limit.  We don't want to create an endless loop. */
 $max_steps = 100;

 /* Define the next steps */
 $next_steps[$current_square_y + 1]    [$current_square_x + 1]    = "";
 $next_steps[$current_square_y + 1]    [$current_square_x]     = "";
 $next_steps[$current_square_y + 1]    [$current_square_x - 1]    = "";
 $next_steps[$current_square_y - 1]    [$current_square_x + 1]    = "";
 $next_steps[$current_square_y - 1]    [$current_square_x]        = "";
 $next_steps[$current_square_y - 1]    [$current_square_x - 1]    = "";
 $next_steps[$current_square_y]        [$current_square_x + 1]    = "";
 $next_steps[$current_square_y]        [$current_square_x - 1]    = "";

 /* Do some math to find the distance from here (as the crow flies) to the target) */
 $height = sizeof($map);
 $width = sizeof($map[0]);
 $minimum = sqrt(($width * $width) + ($height * $height));

 /* Find the closest tile */
 foreach($next_steps as $y_key => $y_value) {
 foreach($y_value as $x_key => $x_value) {
 if(
 isset($map[$y_key][$x_key]) &&
 $map[$y_key][$x_key] != "closed" &&
 $map[$y_key][$x_key] != "start" &&
 $steps < $max_steps
 ) {
 if($map[$y_key][$x_key] != "traversed") {
 $width  = abs($x_key - $target['x']) + 1;
 $height = abs($y_key - $target['y']) + 1;
 $c = round(sqrt(($width * $width) + ($height * $height)),2);

 if($c < $minimum) {
 $minimum = $c;
 $lowest_distance_position = $x_key."x".$y_key;
 }
 }
 }
 }
 }

 /* Start the next calculation from the closest tile */
 $position = explode("x",$lowest_distance_position);

 if(
 isset($map[$position[1]][$position[0]]) &&
 !($position[0] == $target['x'] && $position[1] == $target['y'])
 ) {
 $map[$position[1]][$position[0]] = "traversed";

 $path[$position[0]."x".$position[1]] =
 pathfind($position[0], $position[1], $map, $steps + 1, $target);

 if($path) {
 return $path;
 break;
 }
 }

 return array($position[0]."x".$position[1] => "target");
 break;
 }

 /* Convert the three based array to a step based array. */
 function build_path($path_array, $step_number) {
 if(sizeof($path_array) > 0 && is_array($path_array)) {
 foreach($path_array as $key => $value) {
 $this_path[$step_number] = $key;

 if(sizeof($path_array[$key]) > 0) {
 $built_path =
 array_merge(
 $this_path,
 build_path($path_array[$key], $step_number++)
 );
 return $built_path;
 }
 }
 } else {
 return array();
 }
 }

 /* Set the map size. */
 $map_size_x = 43;
 $map_size_y = 22;

 /* Build the blank map. */
 for($y = 0; $y < $map_size_y; $y++) {
 for($x = 0; $x < $map_size_x; $x++) {
 $map[$y][$x] = "open";
 }
 }

 /* Set special sections of the map. */
 $map[15][25] = "closed";
 $map[16][25] = "closed";
 $map[17][25] = "closed";
 $map[18][25] = "closed";
 $map[19][25] = "closed";
 $map[20][25] = "closed";
 $target['x'] = 39;
 $target['y'] = 18;
 $start['x'] = 1;
 $start['y'] = 1;

 $path = pathfind($start['x'], $start['y'], $map, 0, $target);
 $built_path = build_path($path, 1);

 /* Output the final map. */
 echo "<table style="margin: 0px auto;">";

 foreach($map as $y_key => $y_value) {
 echo "<tr>";

 foreach($y_value as $x_key => $x_value) {
 if($x_value == "closed") {
 $background = "F99";
 } elseif ($x_value == "path") {
 $background = "9F9";
 } elseif ($x_key == $start['x'] && $y_key == $start['y']) {
 $background = "559";
 } elseif (
 $x_key < $target['x'] + $range &&
 $x_key > $target['x'] - $range &&
 $y_key < $target['y'] + $range &&
 $y_key > $target['y'] - $range
 ) {
 $background = "900";
 } elseif(in_array($x_key."x".$y_key,$built_path)) {
 $background = "353";
 } else {
 $background = "333";
 }

 echo
 "<td
 style="
 background: #".$background.";
 width: 20px;
 height: 20px;
 text-align: center;
 ">
 </td>";
 }

 echo "</tr>";
 }

 echo "</table>";
?>
<pre>
 <?php
 //print_r($path);
 ?>
</pre>
</body>