No public Twitter messages.

Solar e-mail helper that stops spammers

August 19th, 2009 by Ray in Cookbook, PHP/MySQL, Solar | Tags: , , | No Comments

Tonight I created a helper for Solar that encodes mailto href addresses so SPAMers that scrape HTML pages will never get your addresses.

To use this helper, just do the following in your views/layouts:

echo $this->email('someuser@somehost.com', 'Ray');

Here is the helper code:

<?php

/**
 * Generates an encoded mailto href to stop spammers from scrapping email
 * addresses from your web pages.  This code is based on the PHP example
 * from http://rumkin.com/tools/mailto_encoder/
 *
 * @category Whitebox
 * @package Whitebox_View
 * @author Raymond J. Kolbe <rkolbe@gmail.com>
 */
class Whitebox_View_Helper_Email extends Solar_View_Helper {
    /**
     * The encoded email address.
     *
     * @var string
     */
    protected $_encoded_string = '';

    /**
     * The encoded index used to decode $_encoded_string/
     *
     * @var string
     */
    protected $_encoded_indexes = '';

    /**
     * Generates an encoded mailto href to stop spammers from
     * scrapping email addresses off your web pages.  Returns
     * an inline javascript code block that allows web browser
     * to read the mailto href.
     *
     * If javascript is disabled in the web browser, only the
     * link text is shown to the user.
     *
     * @param string $spec The email address (e.g. rkolbe@gmail.com)
     * @param string $text Href
     * @param array $attribs An array of href attributes
     * @return string An inline string of javascript to handle the
     * encoded mailto href
     */
    public function email($spec, $text = null, $attribs = null) {
        // escape the email address
        $spec = $this->_view->escape($spec);

        // build attribs, after dropping any 'href' attrib
        $attribs = (array) $attribs;
        unset($attribs['href']);
        $attribs = $this->_view->attribs($attribs);

        $this->_obfuscate("<a href=\"mailto:$spec\"$attribs>$text</a>");

        $script = $this->_getScript();
        $script .= '<noscript>'.$text.'</noscript>';

        return $script;
    }

    /**
     * Takes a given href and obfuscates it.
     *
     * @param string $link A full mailto href
     * @return void
     */
    protected function _obfuscate($link) {
        $scrambled_chars = str_shuffle($link);
        $this->_encoded_string = $this->_escapeString($scrambled_chars);

        $string_indexes = '';
        for ($i = 0; $i < strlen($link); $i++) {
            $index = strpos($scrambled_chars, substr($link, $i, 1)) + 48;
            $string_indexes .= chr($index);
        }

        $this->_encoded_indexes = $this->_escapeString($string_indexes);
    }

    /**
     * Returns a block of javascript used to decode the mailto href.
     * This only allows web browsers to see the mailto address.
     *
     * @param void
     * @return string An inline block of javascript
     */
    protected function _getScript() {
        return $this->_view->scriptInline('<!--
            chars = "'.$this->_encoded_string.'";
            indexes = "'.$this->_encoded_indexes.'";
            href = "";

            for(j = 0; j < indexes.length; j++){
                href += chars.charAt(indexes.charCodeAt(j) - 48);
            }

            document.write(href);
            // -->');
    }

    /**
     * Prepares (escapes) a string for javascript.
     *
     * @param string $string The string to escape
     * @return string The escaped string
     */
    protected function _escapeString($string) {
        $string = str_replace("\\", "\\\\", $string);
        $string = str_replace("\"", "\\\"", $string);

        return $string;
    }
}

Table view helper it out!

July 25th, 2009 by Ray in Cookbook, PHP/MySQL | Tags: , , | No Comments

Table view helper has been released! Since my last post about writing a helper such as this, a lot has changed. I hope to have API docs up soon. In the meantime you can download the code and check out the examples at its new project page.


Table helper

July 9th, 2009 by Ray in PHP/MySQL, Solar | Tags: , | No Comments

Thought I would give you all a sneak peek at the table helper class I am working on. I’m not a big fan of table helper classes but I kind of found a use for a helper such as this for one of my projects–plus it’s neat.

$table = new Table();

$table->setCssId('my_table');
$table->addCssClasses('default big_text');

$thead = $table->addGroup('thead')->addCssClass('thead_tag_css_class');

$row1 = $thead->addRow()->addCssClass('sample_css_heading');
$row1->addHeadingCell('Name');
$row1->addHeadingCell('Sex');
$row1->addHeadingCell('Position');
$row1->addHeadingCell('Top 2 favorite colors')->colSpan(2);

// rows that are not instantiated from addGroup() are added to tbody
$row2 = $table->addRow();
$row2->addDataCell('Adam Smith');
$row2->addDataCell('Male');
$row2->addDataCell('Economist');
$row2->addDataCell('Black');
$row2->addDataCell('White');

$tfoot = $table->addGroup('tfoot');

// empty data cells make sure we are compliant
// empty cells default to &nbsp;
$row3 = $tfoot->addRow();
$row3->addDataCell('example footer data');
$row3->addDataCell();
$row3->addDataCell();
$row3->addDataCell();
$row3->addDataCell();

// we can also just call print $table;
print $table->display()

Produces…

<table id="my_table" class="default big_text">
    <thead class="thead_tag_css_class">
            <tr class="sample_css_heading">
        <th>
            Name
        </th>
        <th>
            Sex
        </th>
        <th>
            Position
        </th>
        <th colspan="2">
            Top 2 favorite colors
        </th>
    </tr>
    </thead>
    <tfoot>
            <tr>
        <td>
            example footer data
        </td>
        <td>
            &nbsp;
        </td>
        <td>
            &nbsp;
        </td>
        <td>
            &nbsp;
        </td>
        <td>
            &nbsp;
        </td>
    </tr>
    </tfoot>
    <tbody>
            <tr>
        <td>
            Adam Smith
        </td>
        <td>
            Male
        </td>
        <td>
            Economist
        </td>
        <td>
            Black
        </td>
        <td>
            White
        </td>
    </tr>
    </tbody>
</table>

I still have some refactoring/testing/fixing to do but I hope to release this package soon under the GPLv3. I have also been throwing the idea around of being able to have this class generate CSS tables–e.g. fetchCssTable() and displayCssTable() (something like that) that would return both a CSS stylesheet and the proper div tags for the table itself.

Once I’m happy with this package I will also convert it over to Solar since it lacks this type of helper.


Savant3 URI Plugin

June 14th, 2009 by Ray in PHP/MySQL, Solar | Tags: , , | No Comments

I started working on a small project last weekend for a [H]ard|Forum member that would allow viewing maillog log info from a web site. I wanted to make an app that would have a small footprint and would be easy to manage (code base wise as well as UI). My first instinct was to use a MVC framework like Solar or Zend but those two have more features than what I needed for this project. Remember, I wanted a small footprint.

I decided to give Savant3 a shot. This at least allows me to separate my controller logic from my view logic. I only had one controller and one template so code overhead wasn’t an issue.

One of the things missing from this system was a way to easily handle URIs/URLs. Since Savant3 is a template engine, I wouldn’t necessarily expect a URI handler. However, I felt that having a plugin that handles URIs was worth the effort, even with a project of this size.

Since the plugin code is still a bit messy (missing inline docs, needs a little bit of refactoring, etc) I can only show you usage examples for now. I plan on cleaning up the code and releasing the plugin on this site shortly.

Here is how one might use this URI plugin in a Savant3 template:

// builds the URI based off of the current URL
$uri = $this->uri()->fromCurrentUrl();

// allows setting query info
$uri->query = 'order=name_asc';

// this adds to the query, it does not overwrite it
$uri->query = 'page=2';

// returns only the query portion: '?order=name&page=2'
$uri->get();

// this will update page to 'page=3'
$uri->query = 'page=3';

// again we only return the query portion: '?order=name&page=3'
$uri->get();

// we can also set a full query as well and we can provide keys without values
$uri->query = 'order=name_desc&page=3&submitted'

// currently there is not a way to remove a single piece of the query
// we have to reset the whole query and rebuild it
unset($uri->query);

// passing 'true' to get() gives us the whole URI
// for example: http://white-box.us/somedir/index.php
$uri->get(true);

The rest of the functionality works much like Solar_Uri (currently w/the exception of path and query behavior), being able to set each piece of the URI before returning a newly built URI.


Modifying Solar_View_Helper_Form

May 23rd, 2009 by Ray in Cookbook, PHP/MySQL, Solar | Tags: , | No Comments

Solar comes packed with many different view helpers that will make your life easier, such as inserting images, creating links, and generating forms. However, sometimes a generic helper doesn’t cut it for custom behavior in a project. For example, I wanted to change the way form field hints (field descriptions) and error messages were displayed for the registration form at http://fahwebmon.white-box.us. Note that I am using Solar_View_Helper_Form::auto() to generate my form automagically. The only downside to this is that you do not have control over where errors are displayed on a page.

Read the rest of this entry »


BBCode PHP Syntax Highlighting For Lazy People

April 26th, 2009 by Ray in Cookbook, PHP/MySQL | Tags: , | No Comments

While working on one of my little side projects, I came across a problem where I wanted to highlight bbcode syle php tags in my text (e.g. [PHP] echo “code goes here”; [/PHP]).

Being lazy and using regex (I love it!), I came up with the following solution:

// test text w/embedded code
$text = "This is a sample text string with PHP style tags. [PHP] echo 'Hello'; [/PHP]

// and I made sure to make this case insensitive.
$pattern = "/\[PHP\](.*)\[\/PHP\]/Uis";

// the magic!
$matchCount = preg_match_all($pattern, $text, $matches, PREG_SET_ORDER);
if ($matchCount !== false && $matchCount > 0) {
    foreach ($matches as $match) {
        // highlight_string forces us to start with at least the php opening tag
        $highlightedCode = highlight_string('<?php'.$match[1].'?>', true);

        // finally, replace the original non-highlighted text with the highlighted text
        $text = preg_replace($pattern, $highlightedCode, $text, 1);
    }
}

echo $text;

Just FYI, this was a quick one-off and wasn’t intended to scale with other bbcode style tags. Also, in my real code, the [PHP] tags are lowercase. The only reason they are uppercase is because the syntax highlighter in Wordpress isn’t smart enough to distinguish the tags in my code and tags to signify syntax highlighting.


Solar Cli

November 1st, 2008 by Ray in Cookbook, Solar | Tags: , , | 1 Comment

Overview

One of the nice things Solar has to offer is its CLI (Command Line Interface), which can be used to accomplish tasks that would otherwise eat up valuable time, such as creating applications, models, tests, documentation, and unit tests. In this entry, I will be showing you how to use the current (Solar v1.0.0 alpha2) CLI, detailing commands, available options, parameters, and usage examples. So make sure that you have a fresh pot of coffee and let’s get to it!

Read the rest of this entry »


Protected: Big Bang with Solar – Part 2

October 1st, 2008 by Ray in Solar, Tutorials | Tags: , | Enter your password to view comments

This post is password protected. To view it please enter your password below:



Virtual hosts and multiple Solar projects

September 27th, 2008 by Ray in Cookbook, Solar | Tags: , | No Comments

In the first part of the series, Big Bang with Solar, I showed you how to download and install Solar for a single project. What I didn’t show you is a way to set up Solar for multiple virtual hosts under Apache, which is what I will be showing you today in our example.

For our example we will use the fictional web sites polygon-ex.com and square-ex.com. If these sites actually exist I apologize in advance for using the names without permission…please forgive me ;-)

Read the rest of this entry »


Big Bang with Solar – Part 1

September 25th, 2008 by Ray in Cookbook, Solar | Tags: , | No Comments

So you have read the manual and browsed the Solar wiki. Now you want to get your hands dirty with setting up your own project. Good news, you’ve found the right place. In this series, I plan to show you, step-by-step, how to set up your very own project using Solar.

To make sure we stay on track, here is the scope for part 1 of the series.

  • Download and Install Solar
  • Determine our project guidelines
  • Configure Apache using Virtual Hosts
  • Set up our bootstrap and configuration file
  • Create a “Hello World” example application

Read the rest of this entry »