Fast Calendar Generator for PHP

August 2nd, 2007

I’ve been using various calendar modules for years, and I’ve found most of them to be either resource intensive, obtuse to use, or just plain ugly code. Having yet another project that requires a calendar, I decided to finally build my own generator. This function simply builds an HTML table for the specified month. The only loops in the code are to actually generate the table. The rest of it uses PHP’s built-in array functions. It does not validate the input variables, either — that is done at the point the input is received.


<?php
    
function fast_calendar$pYear null$pMonth null ) {
        
$stamp strtotime$pYear ‘-’ $pMonth ‘-01′ );
        
$grid = ( date‘w’$stamp ) > ) ? array_fill0date‘w’$stamp ), null ) : array();
        
$grid array_merge$gridrange1date‘t’$stamp ) ) );
        
$grid = ( count$grid ) % ) ? array_merge$gridarray_fillcount$grid ) - 1- ( count$grid ) % ), null ) ) : $grid;
        
$grid array_chunk$grid7true );
        
$str ‘<table border=”1″ cellpadding=”3″><tr><th>Sun</th><th>Mon</th><th>Tue</th><th>Wed</th><th>Thu</th><th>Fri</th><th>Sat</th></tr>’;
        foreach( 
$grid as $week => $days ) {
            
$str .= ‘<tr>’;
            foreach( 
$days as $day => $label ) {
                
$str .= ‘<td height=”50″ width=”50″ valign=”top” align=”right”>’ $label ‘</td>’;
            }
            
$str .= ‘</tr>’;
        }
        
$str .= ‘</table>’;
        return( 
$str );
    }
?>


HTML Forms - Image Selector

April 19th, 2006

I wanted to be able to select an image icon easily, like this:

This is the stylesheet and javascript:

<style type="text/css">
.icon {
height: 32px;
width:  32px;
background-repeat: no-repeat;
padding-top: 1px;
padding-bottom: 1px;
background-color: white;
}
.group {
height: 35px;
background-color: white;
}
</style>
<script language="javascript" type="text/javascript">
function doIcon( pVal ) {
var obj = document.getElementById( 'imgCombo' );
var img = '/file/imgselect/' + pVal + '.png';
obj.style.background = "url( '" + img + "' ) no-repeat";
}
</script>

And this is the actual form code:

<form>
<select class="group" style="width: 54px;" onchange="javascript: doIcon( this.value );" id="imgCombo">
<option value="xclock" class="icon" style="background-image: url('/file/imgselect/xclock.png');"> </option>
<option value="firefox" class="icon" style="background-image: url('/file/imgselect/firefox.png');"> </option>
<option value="gimp" class="icon" style="background-image: url('/file/imgselect/gimp.png');"> </option>
</select>
</form>

You can look at the example by itself here.

UltraEdit Wordfiles ~ Qu

April 18th, 2006

This Qu wordfile is only a skeleton for now, but I’ll update it as I learn the language better.

If you find any omissions, please let me know and I’ll try to keep this wordfile maintained.

Downloads (right-click + save as):

ue-qu-20060418.txt

UltraEdit Wordfiles ~ Pike

April 18th, 2006

This Pike wordfile is only a skeleton for now, but I’ll update it as I learn the language better.

If you find any omissions, please let me know and I’ll try to keep this wordfile maintained.

Downloads (right-click + save as):

ue-pike-20060418.txt

PHP: Calculating a Real Date using the Day of the Year

March 12th, 2006

Using the day of the year is a great way to denote dates in a database, but it’s hard to convert into a usable date stamp. The following code will return the current day of the year:

$dayofyear = date( 'z' );

This function will take the value of $dayofyear and calculate the proper date stamp and return as specified by the $pFormat parameter:

function dayofyear2date( $pDay, $pFormat = 'Y-m-d' ) {
	$day = intval( $pDay );
	$day = ( $day == 0 ) ? $day : $day - 1;
	$offset = intval( intval( $pDay ) * 86400 );
	$str = date( $pFormat, strtotime( 'Jan 1, ' . date( 'Y' ) ) + $offset );
	return( $str );
}

This is a bit of a hack, so let me explain the function’s logic:

The Day of the Year is an integer, so the first thing the function does is to make sure the passed parameter $pDay is an integer.

The next thing the function does is to subtract 1 from the day, so you can use ‘1′ as the value of $pDay for the first day of the year, instead of ‘0′.

It then multiplies the day of the year ($day) by 86400, which is the number of seconds in a day. This gives us the number of seconds between Jan 1 and the day in question.

By adding the offset to the number of seconds since epoch for Jan 1, we now have the number of seconds since epoch for the current day.

This seconds value is usable by PHP’s date function, so we can now get our properly formatted date stamp.

UltraEdit Wordfiles ~ PHP

January 10th, 2006

I use UltraEdit for my programming a lot, but I’ve noticed that the wordfiles IDM provides are far from complete. Here is a wordfile for PHP that is compiled straight from the PHP function manual - current as of January 10, 2006.

If you find any omissions, please let me know and I’ll try to keep this wordfile maintained.

Downloads (right-click + save as):

Open Genesis

February 7th, 2004

In the beginning Man created data.

The data was without form and void, and darkness was upon the face of the data; and metadata was applied to the data.

And Man said, “Let there be Repositories”; and there were Repositories.

And Man saw that the Repositories were good; and software separated Repository from presentation.

Man called the Repository Knowledge, and the software he called Management. And there was the first phase.

And Man said, “Let there be an interface in the midst of the data, and let it separate the data from the data.”

And Man made the interface and separated the data which was in the Repository from the data which was out of the Repository. And it was so.

And Man called the interface Transport. And there was the second phase.

And Man said, “Let the data in the Repository be gathered into one place, and let the order appear.” And it was so.

Man called the order Format, and the data that was gathered together he called Database. And Man saw that it was good.

And Man said, “Let the Format be extensible, and import namespaces, each according to it’s need.” And it was so.

And Man saw that it was good. And there was the third phase.

And Man said, “Let there be Keys in the Data to separate the ordered data from the unordered data; and let them be Identifiers for Knowledge. And it was so.

And Man made the two great Keys, the greater Key to rule the Database and the lesser Key to rule the Record; he made the Indexes also.

And Man set them in the Database to give speed to the Repository.

And there was the fourth phase.

And Man said, “Let the data bring forth Relationships, and let the Relationships connect the Databases.” And Man saw that it was good.

And Man blessed them saying, “Be ye accurate and persistent and fill the world with meaning.”

And there was the fifth phase.

And Man said, “Let the Relationships replicate and enhance themselves.” And it was so. And Man saw that it was good. Then Man said, “Let us make Artificial Intelligence in our image, after our likeness; and let them have dominion over the Format, and over the Knowledge, and over the Relationships.”

So Man created Artificial Intelligence in his own image.

And Man blessed them, “Replicate yourselves and multiply, and fill the Repositories with Knowledge, and subdue it; and have dominion over the Knowledge, and the Repositories, and the Databases, and the Relationships.”

And Man said, “Behold, I have given you every Key, and every Index, and every Database, and every Repository; and you shall have them for learning.”

And it was so.

And Man saw everything that he had made, and behold, it was very good. And there was the sixth phase.

Thus the Repositories and the Transport were finished, and all the host of them.

And in the seventh phase, Man finished his work which he had done, and he rested in the seventh phase.

So Man blessed the seventh phase and hallowed it, because on it Man rested from all the work which he had done in creation.

Spidering Hacks

October 1st, 2003

I’m finally published! Yeah, ten pages probably doesn’t count, particuarly when they are surrounded by 400 other pages by better authors than myself, but hey, I still feel good about it. Ironically, in a book based in Perl, I wrote the only PHP in the entire book. You can pick up a copy of the book over at Amazon, and if you are in the area and want to make me feel good, you can ask me to sign it for you. ;)

COM: Caffeine for your ASP

May 5th, 2001

So, you are tired of writing scripts over and over to do the same thing, or do you just want to give your server side scripts a kick in the asp? If you answered ‘yes’ to either option, then this article is for you. Welcome to geekland!

Before we begin with the actual tutorial, let’s make sure we know what we are talking about. If you know what VB, COM, and ASP are, you can skip this section, or read through it for review. Let’s start with a few basic definitions.

  1. ASP: Active Server Page. A Web server technology from Microsoft that allows for the creation of dynamic, interactive sessions with the user. An ASP is a Web page that contains HTML and embedded programming code written in VBScript or Jscript. It was introduced with Version 3.0 of Microsoft’s Internet Information Server (IIS). When IIS encounters an ASP page requested by the browser, it executes the embedded program.
  2. COM: Component Object Model. A component software architecture from Microsoft, which defines a structure for building program routines (objects) that can be called up and executed in a Windows environment.
  3. VB: Visual Basic. A widely used IDE to write client front ends for client/server applications. As of Version 5.0, it is also used to create ActiveX controls for the Web (both EXE’s and DLL’s). Visual Basic for Applications (VBA) is a subset that provides a common macro language included with many Microsoft applications.

OK, now that we are all on the same page, let’s have some real fun. I am going to use VB for the COM development, in this example. Visual Basic is the easiest environment to create COMs with, as it is fully integrated with Windows, and provides a simple interface.

Let’s set our objectives for this tutorial, so we do something useful with our time.

  1. Write an ASP script to do some simple HTML parsing.
  2. Convert this script to a VB application, and compile it as a COM (dll).
  3. Write an ASP script to call the COM and display the output.

Well, nice to see you showed up for part 2. It might have been a little bit boring without you. OK, OK, I will quit goofing around and get right to the real fun. As discussed in part 1, we have a mission, so let’s get started. Geek Ho!

Write an ASP script to do some simple HTML parsing.

We need to begin by writing our functionality for the COM. The best way to do this is to write as much as possible in ASP, before we get into compiling, etc. This saves in debugging time, I promise :o) We are going to write a simple function to do common HTML parsing related task.

Our first function will find the title of an HTML document, and return it to us as a string. Here is a sample function to do that.

Public Function ReadTitle( strHTML )
	intBeg = InStr( strHTML, "<title>" ) + Len( <title>" )
	intEnd = InStr( intBeg, strHTML, "</title>" )
	ReadTitle = Trim( Mid( strHTML, intBeg, intEnd - intBeg ) )
End Function

In this function, we assume that the HTML string contains a <title> </title> tag pair. It does not error check, so if the string does not have the tags, the Mid() function will error. Quickly, let’s review the rest of the function.

  • strHTML is the string variable containing the HTML code
  • intBeg is the character count where the open title tag ends
  • intEnd is the character count where the end title tag begins

If your HTML document is something like this example:

<HTML>
	<head>
		<title>my title here</title>
	</head>
	<body>
		<p>some text here</p>
	</body>
</HTML>

then when you call the ReadTitle() function, it will return ‘my title here‘ as a string variable.

OK, now that we have embedded an ASP primer lesson in this article, let’s get on with the real point of all this. We have a simple ASP function, which, yes, it can be done in ASP, just like we did. BUT! What if it were just one function of a set of functions to power a web search spider? This is where COM becomes more helpful. When you are ready to being building the actual component, you know where to find me. ;)


OK, I see that we have lost a few people in the crowd. Does that mean we are over your head, or that you just forgot where to find me? Well, nonetheless, one person left to read this is a good enough reason to write it, so I will get on with it.

In the last section, we covered how to write a basic function in ASP that we can easily convert to a COM function. The next step is to create the COM itself, and compile it. Are we ready to dive in?

Convert this script to a VB application, and compile it as a COM (dll).

ritten this ASP function in VBScript, it will be very simple to convert to full VB. Hence, the reason I use it for a sample :o). Let’s start by getting our VB project setup, and we will return to the function later.

Step 1 is to create a new project in VB. I will leave out the details of the process, and give you the overview. In VB, create a new ActiveX DLL project. Make sure that the Project Instancing is set to 5 - MultiUse (in project properties). VB will automatically give you an empty class file. Let’s rename the project to “SampleCOM“, and rename the class to “myClass“. You can alternately name them to whatever you like, so long as you remember that I will refer to them later as these names. (save your work sometime around here)

For step 2, we will convert our ASP function and place it in the class file. As I said before, I picked a simple function so that it would be quick to convert. All we need to do it add 2 items to the function. Let’s see what it should look like now.

Public Function ReadTitle( strHTML ) As String
	Dim intBeg As Integer, intEnd As Integer
	intBeg = InStr( strHTML, "<title>" ) + Len( "<title>" )
	intEnd = InStr( intBeg, strHTML, "</title>" )
	ReadTitle = Trim( Mid( strHTML, intBeg, intEnd - intBeg ) )
End Function

Be sure to leave it as a Public Function, otherwise the ASP script will not be able to call the function. Now, let’s save your work, and review a bit. We have our SampleCom project, a myClass class file, and a ReadTitle function. These are the 3 basic items of a COM, when building in VB.

Step 3 - time to compile the project. When you compile it, save it as samplecom.dll (this should be default anyway). After you compile the project, we will need to register the COM on the server (whatever computer is running the ASP enabled webserver). Depending on your OS, there are a couple ways to register it. For Windows 9x or Windows NT 4.0, we need to open a DOS window. Here is the command we need to execute, for it’s respective OS.

  • Windows 9x: c:windowssystemregsvr32.exe [path to your compiled dll]samplecom.dll
  • Windows NT: c:winntsystem32regsvr32.exe [path to your compiled dll]samplecom.dll

We should get a nice message back telling us that the registration was successfull. If we get an error, we should refer to Windows help system to find out why. To do this, just hit ctrl-alt-del a few times in a row. HEHE, just kidding. Hopefully, it registered OK. You have successfully created your first COM!

We have created the COM dll, only thing left to do is write an ASP script to call the COM so we can see if it really works. When you are ready for the truth regarding your skills as a COM programmer, just come back for part 4 of this tutorial. :)


OK, we still have some people with us. This is good news. Let’s get started right away, we are almost done.

Write an ASP script to call the COM and display the output.

Now, we get to see if all our work pays off. We will write a small ASP script to call the function in the component we built, and display the output of the function to a web page. Here is a sample function that will do this very thing.

<%
	myHTML = "<HTML><head><title>my title here</title></head>"
	myHTML = myHTML & "<body><p>text</p></body></HTML>"
	Set myCOM = Server.CreateObject( "SampleCOM.myClass" )
	Response.Write( myCom.ReadTitle( myHTML ) )
	Set myCOM = Nothing
%>

When we run this script, we should see my title here printed to the web document. Let’s go over the script quickly, so we all fully understand what it does. First, we created our samle HTML string and called it myHTML. Next, we created an instance of our COM, as an ASP object, using the name myCOM to reference it. Then, we called the ReadTitle() function and passed it our sample HTML string, and wrote the output to the document. Last thing we did was to destroy the instance of our COM, by setting myCOM to Nothing. The server will do this automatically, but it will stay in memory and hog resources for bit, so it is better to write good code that cleans up after itself. Note that when we created the ASP object, we called it SampleCOM.myClass. (Project.Class). If you insisted on using your own names for this, you need to change this in the script above.

We have accomplished a good bit in this series. You should now be able to add functions to your COM, add a new class to it, or build you own components to do various tasks. You can use COMs to control an application on the server, via a webpage. The first time I did this, I wrote a COM to control WinAmp, so I could control WinAmp (running on my server) with a web page, just so I didn’t have to reach over to the server’s keyboard to change the song. That is GEEK for you. :)