Spiga

Zend Framework View Helper for Smarty Cycle

December 09, 08 by Gabi Solomon

As i stated in a recent post i am now starting to learn Zend Framework. And with all new things that you learn, you try to find the old ways ( at least i do :D ).

So today i was trying to find a method of creating a zebra table. The old way i used to this back when i was using smarty is by using the cycle custom function. Basically it will just alternate through a set of values to create the effect.

PHP:
  1. {section name=rows loop=$data}
  2. <tr bgcolor="{cycle values="#eeeeee,#d0d0d0"}">
  3.    <td>{$data[rows]}</td>
  4. </tr>
  5. {/section}

Then when i moved on and stop using smarty, i wrote a similar function for my template engine.

So now i am looking for a similar solution on Zend Framework. Luckily for me some bright fellows have already thought of me :D .
In the zend wiki there is a Zend_View_Helper_Cycle Component Proposal that does exacly what i was wishing for :D .

Heres an example of how you can use it:

PHP:
  1. <?php $cycle=$this->cycle(array("#F0F0F0","#FFFFFF"));?>
  2. <?php foreach ($this->books as $book):?>
  3.   <tr  style="background-color:<?=$cycle->next()?>">
  4.   <td><?=$this->escape($book['author']) ?></td>
  5. </tr>
  6. <?php endforeach;?>

The proposal has been approved for development in standard/incubator.
You can download it from here.

Cheers.

[php class] Open Inviter – Get contacts of friends of different networks

December 01, 08 by Gabi Solomon

Yet another great class found on the php classes website.
This one has been in my draft folder for a while (the place i keep my articles ideas ), and finally it came time to write about it (manage to put my laziness away and write it).

The class is called open Inviter and has received the rank of november 2008 Nominee for Innovation Award. I personally hope it will win it, i think it really deserves it.

Describtion

This package can be use to get the contacts of friends of different e-mail providers and social networks.

It can access the Web services servers of different networks to retrieve the contacts of friends of a given user.

Each network is accessed by the means of plug-in classes. Some plug-ins support sending invitation messages to friends to be added to the user contacts.

The class currently comes with plug-ins that support :
* AOL
* GMail
* GMX.net
* Windows Live (Hotmail)
* Katamail
* Lycos
* Mail.com
* Mail.ru
* Rambler.ru
* Rediff
* Yahoo!
* Yandex
* Facebook
* Hi5
* LinkedIn
* MySpace
* Orkut
* Twitter

The class is very easy to use, and comes with a very detailed example of how you can implement it.

[Class full description & download link]

Hope it helps you in your development.

Cheers.

Zend Framework modular directory structure

by Gabi Solomon

After a lot of thinking and going back and forth about this idea, i finally decided to start using ( learning at first ) zend framework.

The main decision was to go with an already built framework or an inhouse one. And although i really like reinventing the wheel sometimes, i said i will not do the same this time.

After deciding i wanted to use an exiting framework, i had 2 candidates in mind : CodeIgniter or zend framework. The plus for codeigniter was the fact that it went with a more familiar approach to MVC, and the plus for zend was the company behind it. The downside about zend, was for me at least, the size of it, and the fact that it seemed a lot to learn.

But i decided to take a chance and learn Zend. The main problem i had was how to start ( as all things are :D ). Because the have such a freedom in development, i was a little puzzled on how to structure my application.

The only thing i knew was that i wanted to go with a modular structure. From there i did a lot of googling, read and watched a few presentation about this topic and finaly came up with a structure wich is bassed much on Wil Sinclair proposal.

My Zend modular structure

I will try to explain it, why i chose it this way and what each folder contains.

1. Application

The main aplication folder
1.1 Config - Contains application configuration files ( ex: mysql details )
1.2 Controllers - General Controllers, that are common in all modules
1.3 Languages - Holds the language files
1.4 Layouts - This directory is for MCV based layouts.
1.5 Models - This directory holds the application models ( in put them here instead of the modules directory since i belive there are common to all application and its more better this way )
1.6 Modules - I really liked the idea of modules that zend used because it enables you to organize your controllers and views much better in a separate folder for different sections of a website ( for example the main website, editors area and admin panel )
1.7 Views - I also included a views folder in the main application because i though i could use it to store common views for the 3 modules.

2. Data

This folder holds various information that is temporary, like cache, session data etc.

3. Docs

This directory is for documentation automatically generated or hand written.

4. Library

This directory holds the library Zend Framework files and also other folders for your own library (extended from Zend or not). I have one called GSD that extends some zend classes.

5. Public

This directory would contain the public files for your application: index.php. index.php ( this will include the bootstrap.php file from your application/ directory) and the front end assets (css, javascript, images, flash etc )

6. Tests

This directory would hold the application tests. This is a cool feature about Zend that it has support for writing application tests to better test your code during development.

Final Words

Ok this is about it so far. I am still a beginer with zend, and this structure is what i have thought off so far, and it doesn't have some real application testing. Use it at your own expense :) )
I am sure as i start developing using zend that it will be modified.

Another bad thing about zend is that there aren't so much resources and real examples about it, this is why i will write about my journey with zend here. Hopefully somebody will benefit from it. :)

Cheers

[phpclass] dinamicParams – Calling function with named params

November 23, 08 by Gabi Solomon

A lot of time while developing a function or a method of a class you need to specify 1, 2 or 3 parameters as inputs for that function or method. But usually as you develop further you might end-up in the situation where you would want to add a new parameter to your function.

And so you might have coded a function that has 5 or more parameters, and although it works fine, eventually you will want to call that function and leave the first 4 parameters with the default value and only change the last one. I ended up here a lot of times, and normally in php there is nothing you can do.

A workaround would be to specify the params as a single array variable, but that is just making you write more code and it looks really bad ( at least in my opinion).

Well today i found a new method of doing this in php5 with the help of the Reflection API that is offer in php5. I will not get into to much details about what it does, you can read that in the documentation, basicly it provides a way to reverse-engineer classes, interfaces, functions and methods.

So i wrote a simple class that is going to solve that problem.

With the help of the Reflection API from php5 the class will allow you to call function and methods by providing the parameters as an array specifying names and values even if the original function or methods receives them in the normal fashion.

But enough talk, heres the example.

PHP:
  1. <?php
  2. require('dinamicParams.class.php');
  3.  
  4. class news {
  5.  
  6.     function fetch ( $id, $page = 0, $items_pp = 10, $order_by = 'date', $method = 'desc') {
  7.         echo "
  8.             id: $id,
  9.             page: $page,
  10.             items_pp: $items_pp,
  11.             order_by: $order_by,
  12.             method: $method
  13.         ";
  14.     }
  15.  
  16. }
  17.  
  18.  
  19.  
  20. $news = new news();
  21. $dinamicParams = new dinamicParams();
  22.  
  23. $dinamicParams->call(array($news, 'fetch'), array('order_by' => 'name'));

This will output :

id: , page: 0, items_pp: 10, order_by: name, method: desc

This class is based on this implementation of the reflection API.
It is available on phpclasses can be downloaded here

[php class review] Relink – Rewrite URLs based on mod_rewrite configuration

November 02, 08 by Gabi Solomon

view this article in romanian

I have an email subscription to phpclasses email newsletter, and read it to see what new classes have been added to the site. And once in a while i will find interesting and innovative classes. Like today when between the classes that won the Innovation award was one that caught my attention.

The class developed by Benjamin Falk that he called Relink is a very interesting and useful tool in my opinion.

Lets say that you have a website and after you build it you want to make some SEO for it. That usually involves modifying all the links in the website. And that is quite a task. But what if you are like me and know a few things about SEO but are no expert, and somewhere down the line you either hire a SEO expert or receive an expert advice and want to change all those links ? Another time spent on tedious task of find and replace. And if we are talking about a larger project than that could be quite a big time.

Well what this class enables you to do is to make your links dynamically generated based on your .htaccess configuration. Let be more specific, first you must initialize the class

PHP:
  1. require_once 'class.relink.php';
  2.  
  3. $htaccessFile    = './htaccess-example';
  4. $c_relink        = new RELINK($htaccessFile);
  5.  
  6. // If you leave the $htaccessFile empty it will automatically take the .htaccess file from the current directory.

Then everywhere in the script where you have a link you will put something like

PHP:
  1. echo '<a href="'.$c_relink-&gt;replaceLink('?page=blog').'">View blog</a> | ';
  2. echo '<a href="'.$c_relink-&gt;replaceLink('?page=blog&amp;mode=edit').'">Edit Blog</a> | ';
  3. echo '<a href="'.$c_relink-&gt;replaceLink('?info&amp;value=all').'">Show all information</a>';

I didn't use it in any projects so far but I think i will do it on my next project.
Hope this new class is as interesting to you as it was to me.

Cheers

PHP – convert Microsoft word doc to pdf

September 08, 08 by Gabi Solomon

A lot of people are searching for solution to do this conversion on the fly. I dont know any other programing languages except PHP so i will write only about how you can do this in PHP.

Now to do this there is 2 major situations:
1. Doing it on a windows Server
2. Doing it on a linux Server

In both cases the chanses are that you need to have root access to the server in order to do all the settings required for this conversion.

In case of windows you can use COM objects to acces either Word or OpenOffice and do the conversion. Here peek of a code to access OpenOffice API to do the conversion:

PHP:
  1. <?php
  2. function MakePropertyValue($name,$value,$osm){
  3. $oStruct = $osm->Bridge_GetStruct("com.sun.star.beans.PropertyValue");
  4. $oStruct->Name = $name;
  5. $oStruct->Value = $value;
  6. return $oStruct;
  7. }
  8. function word2pdf($doc_url, $output_url){
  9. //Invoke the OpenOffice.org service manager
  10. $osm = new COM("com.sun.star.ServiceManager") or die ("Please be sure that OpenOffice.org is installed.\n");
  11. //Set the application to remain hidden to avoid flashing the document onscreen
  12. $args = array(MakePropertyValue("Hidden",true,$osm));
  13. //Launch the desktop
  14. $oDesktop = $osm->createInstance("com.sun.star.frame.Desktop");
  15. //Load the .doc file, and pass in the "Hidden" property from above
  16. $oWriterDoc = $oDesktop->loadComponentFromURL($doc_url,"_blank", 0, $args);
  17. //Set up the arguments for the PDF output
  18. $export_args = array(MakePropertyValue("FilterName","writer_pdf_Export",$osm));
  19. //Write out the PDF
  20. $oWriterDoc->storeToURL($output_url,$export_args);
  21. $oWriterDoc->close(true);
  22. }
  23. $output_dir = "C:/dev/openofficeintegration/docconverter/";
  24. $doc_file = "C:/dev/openofficeintegration/docconverter/DpmR5Reqv1.20.doc";
  25. $pdf_file = "DpmR5Reqv1.20.pdf";
  26. $output_file = $output_dir . $pdf_file;
  27. $doc_file = "file:///" . $doc_file;
  28. $output_file = "file:///" . $output_file;
  29. word2pdf($doc_file,$output_file);
  30. ?>

Now in case of linux things get a little more tricky, not by much but they do. You cant user COM objects any more but you can still install OpenOffice and its API in extension with a python script.

PyODConverter, for Python OpenDocument Converter, is a Python script that automates office document conversions from the command line using OpenOffice.org.

The script does basically the same thing as the command line tool that comes with JODConverter but is much simpler. In fact the Python script was released for the people who use JODConverter only from the command line (not as a Java library or web service) and would like a simpler alternative.

To check out the full documentation and download the script go here.

Covertor for php5

As i was doing research to do this post i found out of yet another solution, but this is only available for php5, but it works for both lynux and windows. Its a php module written in C++ called Punno.

This project is a PHP5 module written in C++ that brings the OpenOffice.org UNO Programming API to the PHP userspace.

You can use it to write scripts that create, modify, read and save OpenOffice.org documents (Writer, Spreadsheet, Drawing). Also, you can export these documents in various formats, like PDF or HTML for example.

It can be installed on any Linux/Unix or Windows platform where PHP5 and OpenOffice.org are also available.

It is released under PHP License 3.01.

That is it.

Do you know of any other solutions to do a doc to pdf conversion using php ?

How to protect your php applications for free ?

August 25, 08 by Gabi Solomon

Did you developed a very cool application, and maybe thought about selling it ?
If you did you might have thought: How will i protect my code ?
Because the php code is visible and can be distributed really easy, once it has been downloaded once.

Well there are solutions to do this, but most of them are not free, and if your application is not a really expensive one it doesn't make sense to pay more on the software to protect the code then the actual selling price.

Well you are in luck, because there is a php class called PADL (PHP Application Distribution License System) that generates PHP application license keys.

This class can used to generate license style keys to control the distribution and functionality of PHP applications.

It generates license strings that can bind PHP applications to specific domains, specific servers, can only be executed during limited time period, or to restrictions placed on a home server within the license key.

The binding to server process attempts to use the server network card MAC address. This feature was tested on servers are Mac OS X (Darwin), Linux, Windows XP, although it may also work for FreeBSD, NetBSD, Solaris.

PADL also attempts to use information from $_SERVER variable to encode that server name, server IP, server application path and server application url to the license key. Part of the process also binds the IP Address from the $_SERVER variable if found, but it also attempts to parse the server config file (the same used to get the MAC address) for any more IPs.

The server binding can be disabled if required, and it also possible to block the key being generated for the localhost address (127.0.0.1).

The time limiting of the license uses a start period (and a given start offset to allow for time discrepancies) and an expiry date if required.

If required when validating a key it is also possible to dial home to check the license key on your own PADL License Server, examples are given.

The PHP_OS and PHP_VERSION of the php that the key was generated for is also encrypted into the key.

It is also possible to encrypt additional information into the license key to enable you to place restrictive features in your application to allow the creation of trialware or demoware.

This class is still in development however it is stable. A GUI is to follow.

This class received the Php Classes Innovation Award, and is ranked 98 in the same website, so this is why i highly recommend this class to protect your code.

Hope like this class as well,
Cheers

how to: Generating XML from PHP

August 15, 08 by Gabi Solomon

I had to do a small REST application on a project recently and i wanted to find a small easy way of returning the response in XML.

After a little searching find this rather old post ( but just what i was looking for ) on Simon Willison’s Weblog. It featured a small php class to generate XML.

Example Code

PHP:
  1. $array = array(
  2.     array('monkey', 'banana', 'Jim'),
  3.     array('hamster', 'apples', 'Kola'),
  4.     array('turtle', 'beans', 'Berty'),
  5. );
  6. $xml = new XmlWriter();
  7. $xml->push('zoo');
  8. foreach ($array as $animal) {
  9.     $xml->push('animal', array('species' => $animal[0]));
  10.     $xml->element('name', $animal[2]);
  11.     $xml->element('food', $animal[1]);
  12.     $xml->pop();
  13. }
  14. $xml->pop();
  15. print $xml->getXml();

XML returned

XML:
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <zoo>
  3.   <animal species="monkey">
  4.     <name>Jim</name>
  5.     <food>banana</food>
  6.   </animal>
  7.   <animal species="hamster">
  8.     <name>Kola</name>
  9.     <food>apples</food>
  10.   </animal>
  11.   <animal species="turtle">
  12.     <name>Berty</name>
  13.     <food>beans</food>
  14.   </animal>
  15. </zoo>

Attention

A little heads up, if your running php you might encounter this error:

Fatal error: Cannot redeclare class xmlwriter in /var/www/web4/cgi-bin/includes/XmlWriter.class.inc on line 6

Thats because php already has a built in php class called xmlwriter, to fix it all you need to do is rename it.

hope this helps somebody.
Cheers

How to upload & resize images in PHP with thumb creation

August 02, 08 by Gabi Solomon

Many times in my coding projects i had to do an upload form that will upload an image. This by it self is not so hard to do, and i bet many of you can write the code in under a minute :) ). But as we all know webspace is not free ( excluding free hosting ) and certainly not unlimited, so we must try and make the best use out of it and most of the time you will need to resize the images uploaded to a certain size, and maybe even make a thumb image.

This where the fun starts, every coder has his own methods of dealing with image resizing, as do I :D .
I came across a class on phpclasses.org called class.upload.php and fall in love with it :) ).

It is the ideal class to quickly integrate file upload and image manipulation in your site. That's all you need for a gallery script for instance.

It manages the uploaded file and allows you to do whatever you want with the file as many times as you want. If the file is an image, you can convert and resize it, rotate it, crop it in many ways; You can also add borders, frames, bevels, add of text labels and watermarks or apply graphic filters such as contrast or brightness correction, colorization, negative, threshold, greyscale, reflections and more. Transparency and true color are fully supported. JPEG, PNG, GIF and BMP are supported.

Security features and file management functions are provided. The class can also work on local files, which is useful for batch processing images online, and can circumvent open_basedir restrictions. Uploaded files can also be output directly to the browser.

The class is mature and well documented, already widely used around the world. From version 0.25, the class is fully internationalized. It is also compatible with PHP 4 and 5.

Example of usuage

PHP:
  1. $foo = new Upload($_FILES['form_field']);
  2. if ($foo->uploaded) {
  3.   // save uploaded image with no changes
  4.   $foo->Process('/home/user/files/');
  5.   if ($foo->processed) {
  6.     echo 'original image copied';
  7.   } else {
  8.     echo 'error : ' . $foo->error;
  9.   }
  10.   // save uploaded image with a new name
  11.   $foo->file_new_name_body = 'foo';
  12.   $foo->Process('/home/user/files/');
  13.   if ($foo->processed) {
  14.     echo 'image renamed "foo" copied';
  15.   } else {
  16.     echo 'error : ' . $foo->error;
  17.   }
  18.   // save uploaded image with a new name,
  19.   // resized to 100px wide
  20.   $foo->file_new_name_body = 'image_resized';
  21.   $foo->image_resize = true;
  22.   $foo->image_convert = gif;
  23.   $foo->image_x = 100;
  24.   $foo->image_ratio_y = true;
  25.   $foo->Process('/home/user/files/');
  26.   if ($foo->processed) {
  27.     echo 'image renamed, resized x=100
  28.           and converted to GIF';
  29.     $foo->Clean();
  30.   } else {
  31.     echo 'error : ' . $foo->error;
  32.   }
  33. }

Small problems i had with this class

Even though it is a great class that i use every time i need to do an upload, i had a few problems with it, and have toke me a while to solve. As a suggestion for debug do a print of "$foo->log" variable to see what happened during the preparation of the image.

1. Handling uploads from flash uploader

It took me a while to solve this one, since images uploaded with flash were not being re sized, but after a some debugging and searching i managed to figure out the cause: the mime type for the file was application/octet-stream so the class didnt treat it as an image.
Solution:
You can find it on the class forum

2. Handling very large images

This one really put me to the test, every time i uploaded an image that was large ( above 1,5 Mb ) it just show an empty page, not an error ... nothing. Couldn't figure it out. I looked in the php error log ... nothing. After like 2 hours of almost throwing my monitor out the window i managed to find a solution. It was because of the server, more exactly the memory limit. During the processing of large images, the script would use a lot of memory which would cause the script to stop once it reached the limit with no error message.
Solution:
Add this in your script:
ini_set ( "memory_limit", "40M")

Or in a .htaccess file:
php_value memory_limit 40M

That is it i dindt had any more troubles with this class, it is a pretty stable class witch didnt gave me to much trouble.

I hope you will enjoy it too.
Cheers.

How to Create a zip file with php on the fly

July 31, 08 by Gabi Solomon

For a future project I needed these days some easy to use zip or gzip class to create a zip file from files / folders inside a specified directory. A short search on Google has lead me to the Create ZIP File PHP class from Rochak Chauhan.

This class can create ZIP archives from lists of files.

The class provides means to add individual files or whole directories to the list of files packed into a ZIP archive.

The class can generate the packed archive as a string value.

The class can also output the necessary request response headers to serve the generated ZIP archive for download.

The supplied example demonstrates how to use the class to store the ZIP archive in a file, serve it for download and delete the file after it is served.

Example of usage

PHP:
  1. <?php
  2.  
  3. include_once("createZip.inc.php");
  4. $createZip = new createZip; 
  5.  
  6. $createZip -> addDirectory("dir/");
  7.  
  8. $fileContents = file_get_contents("img.jpg")
  9. $createZip -> addFile($fileContents, "dir/img.jpg")
  10.  
  11.  
  12. $fileName = "archive.zip";
  13. $fd = fopen ($fileName, "wb");
  14. $out = fwrite ($fd, $createZip -> getZippedfile());
  15. fclose ($fd);
  16.  
  17. $createZip -> forceDownload($fileName);
  18. @unlink($fileName);
  19. ?>