Dynamic Banner - js and css

Link: http://grepcode.com/file/repo1.maven.org/maven2/org.geomajas/geomajas-dojo-example-modules-shrinksafe/1.7.1/dojox/gfx/tests/test_linearGradient.html

This post provides code to create a dynamic banner which sources images from Flickr.

Using a dynamic banner has several advantages:

  • The banner is assembled dynamically, it is more engaging
  • The images aren’t stored or managed on local servers
  • The banner images can be changed by modifying the images at the source
  • It would be possible to customize the source of the images for demonstrations
  • Clicking on the banner displays the image credits

This is an extension of the code listed in link above. It is running nicely with dojo 1.3.0, tested under IE7, FF11&12, and Chrome 17.

The banner is 160px high, and 1024px wide, it is overlaid with an image which includes a gradient to fade the banner images from full color to white, using transparency. The banner includes an icon for the product on the far right.

CSS:

#header img,#header a
{
height:160px;
overflow:hidden;
}
#gradient-overlay
{
background:transparent url(images/banner.png) no-repeat;
height:160px;
width:1024px;
position:fixed;
}
#header
{
cursor:pointer;
height:160px;
width:100%;
margin:25px;
overflow:hidden;
}

This is the javascript to create the banner. The remaining code should be collected from the link above.

The image list received from flickr is accessed randomly, using the splice function. This allows each banner to be created differently. Images are added to the banner until the width exceeds 870px. Padding is added to the last image in the banner to accommodate the icon. The image credits are place in a dialog box.

Code:

function gotItems(items, request){
      var i,list = dojo.byId("header");
      if(list){
        var span=document.createElement("span");
        span.setAttribute("id","gradient-overlay");
        list.appendChild(span);
        var width,pick,credit_text='';
        var MAX_WIDTH=870;
        width=0;i=0;
        while (width<MAX_WIDTH)
        {
          index=Math.floor(Math.random()*items.length);
          pick=items.splice(index,1);
          if (pick.length>0)
          {
            var item=pick[0];
            var a = document.createElement("a");
            var image = document.createElement("img");
            a.setAttribute("href",flickrStore.getValue(item,"link"));
            a.setAttribute("title", flickrStore.getValue(item, "title"));
            list.appendChild(a);
            a.appendChild(image);
            image.setAttribute("src", flickrStore.getValue(item, "imageUrlMedium"));
            image.setAttribute("title", flickrStore.getValue(item, "title"));
            image.setAttribute("alt", flickrStore.getValue(item, "title"));
            width+=image.clientWidth;
            credit_text+=flickrStore.getValue(item,"description");
          }
          else
            break;
        }
        image.style.paddingRight='140px';
        var credit=document.createElement("div");
        new dijit.Dialog({
                      'id': 'dlgCredit',
                      'content':credit_text},
                      'credit');
        list.setAttribute('title','Click for image credits');
        list.setAttribute('onclick','dijit.byId("dlgCredit").show()');
        list.appendChild(credit);
      }
    }

The HTML creates the flickrStore and sets up the header div.

XML:

<div dojoType="dojox.data.FlickrStore" jsId="flickrStore"></div>
<div id="header"></div>

This post courtesy of Lyrix, Inc

dojox.data.FlickrStore - Source from favorites

Link: http://grepcode.com/file/repo1.maven.org/maven2/net.java.dev.weblets/weblets-exampleweblet/1.1/org/dojo/dojox/data/demos/demo_FlickrStore.html

I wanted to use a favorites list on Flickr (http://flickr.com) as a source for images.

dojo 1.3.0’s dojox.data.FlickrStore sources images from a public photo feed:

reg.register("default",function(_2f){return true;},_2d+"photos_public.gne");

Since I only wanted to change the feed URL, I used the following code to indicate that the request should be made to the favorites feed.

Code:

var reg=dojox.data.FlickrStore.urlRegistry;
  reg.unregister("default");
  reg.register("default",function(a){
    return true;
    },"http://api.flickr.com/services/feeds/photos_faves.gne");

Google OAuth and Contacts API - PHP Curl Examples

This code uses Zend Framework’s Zend_Json::decode method, however you can use json_decode if it is available on your version of PHP.

Create the authorization link
When this link is clicked, the site visitor is presented with a page from Google asking if they would like to allow your application access to their data. If they accept, Google will give them a code, which can then be used on the next request. This is run as an installed application, because there are times when data will be requested without user interaction.

PHP:

$sAuthURL=AUTH_URL;
$aParms=array('response_type'=>RESPONSE_TYPE,
        'client_id'=>CLIENT_ID,
        'redirect_uri'=>REDIRECT_URI,
        'scope'=>SCOPE);
$sLink=$sAuthURL.'?'.http_build_query($aParms);

Request an access and refresh token

PHP:

require_once 'Zend/Json.php';
        $sTokenURL=TOKEN_URL;
        $aParms=array(
                'code'=>$_POST['code'],
                'client_id'=>CLIENT_ID,
                'client_secret'=>CLIENT_SECRET,
                'redirect_uri'=>REDIRECT_URI,
                'grant_type'=>AUTHORIZATION_CODE);
        $cURL=curl_init();
        curl_setopt($cURL,CURLOPT_URL,$sTokenURL);
        curl_setopt($cURL,CURLOPT_SSL_VERIFYPEER,TRUE);
        curl_setopt($cURL,CURLOPT_POSTTRUE);
        curl_setopt($cURL,CURLOPT_RETURNTRANSFERTRUE);
        curl_setopt($cURL,CURLOPT_POSTFIELDS,$aParms);
        $cResponse=Zend_Json::decode(trim(curl_exec($cURL)));
        curl_close($cURL);                
        $sAccessToken=$cResponse['access_token'];
        $sRefreshToken=$cResponse['refresh_token'];

Use the refresh_token to request a new access_token

PHP:

$sTokenURL=TOKEN_URL;
                                $aParms=array(
                                        'refresh_token'=>$sRefreshToken,
                                        'client_id'=>CLIENT_ID,
                                        'client_secret'=>CLIENT_SECRET,
                                        'grant_type'=>REFRESH_TOKEN);
                                $cURL=curl_init();
                                curl_setopt($cURL,CURLOPT_URL,$sTokenURL);
                                curl_setopt($cURL,CURLOPT_SSL_VERIFYPEER,TRUE);
                                curl_setopt($cURL,CURLOPT_POSTTRUE);
                                curl_setopt($cURL,CURLOPT_RETURNTRANSFERTRUE);
                                curl_setopt($cURL,CURLOPT_POSTFIELDS,$aParms);
                                require_once 'Zend/Json.php';
                                $cResponse=Zend_Json::decode(trim(curl_exec($cURL)));
                                $sError=curl_error($cURL);
                                curl_close($cURL);
                                $sAccessToken=$cResponse['access_token'];


Request the contact data

PHP:

$sContactsURL=CONTACTS_URL.'?access_token='.$sAccessToken;
                $cURL=curl_init();
                curl_setopt($cURL,CURLOPT_URL,$sContactsURL);
                curl_setopt($cURL,CURLOPT_RETURNTRANSFERTRUE);
                $cResponse=trim(curl_exec($cURL));
                $sError=curl_error($cURL);
                curl_close($cURL);

Parse the data from Google
This code also Zend_Gdata to handle the parsing.

PHP:

$phone_only=false;
 
include 'Zend/Gdata.php';
 
$gdata=new Zend_Gdata();
$feed=$gdata->importString($cResponse);
 
foreach ($feed as $entry) {
        // Thanks to: <a href="http://www.ibm.com/developerworks/opensource/library/x-phpgooglecontact/index.html">http://www.ibm.com/developerworks/opensource/library/x-phpgooglecontact/index.html</a>
        $xml simplexml_load_string($entry->getXML());
        $obj = new stdClass;
        $obj->id $entry->id->text;
        if (false===($iSlash=strpos($entry->title->text,'/')))
                $obj->name=$entry->title->text;
        else
                $obj->name substr($entry->title->text,0,$iSlash);
        if (empty($obj->name)) continue;
        $name explode(' ',$obj->name,3);
        $obj->first_name $obj->middle_name $obj->last_name '';
        switch (count($name))
        {
                case 1
                        $obj->first_name $obj->name;
                        break;
                case 2
                        $obj->first_name $name[0];
                        $obj->last_name $name[1];
                        break;
                case 3:
                        $obj->first_name $name[0];
                        $obj->middle_name $name[1];
                        $obj->last_name $name[2];
                        break;
        }
        $obj->phoneNumber array();
        $obj->phone array();
        foreach ($xml->phoneNumber as $p
        {
                $type preg_replace('/^[^#]+#(.*)$/','\1',(string) $p['rel']);
                $obj->phoneNumber[] = (string) $p.' ('.$type.')';
                $obj->phone[$type] = array ('phone' => preg_replace('/\D/','',(string) $p), 'type' => strtolower($type) );
        }
        if (empty($obj->phone) && $phone_only) continue;
        $results[$obj->last_name] = $obj;  
}
ksort($results);


This post courtesy of Lyrix, Inc. http://mobiso.com

Apache IE8 HTML entities filter

Link: http://stackoverflow.com/questions/3322820/find-replace-htmlentities-using-the-standard-linux-toolchain

One of the pages in a web application displays text log file output in popup browser windows.

If that output includes this statement:

XML:

<?xml version="1.0" encoding="utf-8"?>

IE8 will try to parse the content as XML, and it will show an error:

The XML page cannot be displayed
Cannot view XML input using style sheet.
Please correct the error and then click the Refresh button, or try again later.
Invalid at the top level of the document. Error processing resource:

I didn’t want to add any scripting to the pages, since they’re text, and I didn’t want to make any coding changes. One solution is to use an Apache output filter to convert the text into HTML entities, and force the document type to text/html.

Code:

ExtFilterDefine htmlentities mode=output cmd="/usr/bin/php -R 'echo htmlentities(fgets(STDIN));'"
 
<FilesMatch "\.txt$">
  ForceType text/html
  SetOutputFilter htmlentities
</FilesMatch>

This is definitely a quick solution that may not be ideal for every situation, or could be refined.

The documents aren’t HTML, they are text. They don’t have any tags in them, and those that are there should not be treated as tags, but as text. Forcing the type to text/plain didn’t work.

Regardless, this is one way you can convert characters into HTML entities without modifying your code.

Different solutions:

  • Extend the filter to add the HTML tags necessary for a true text/html document
  • Modify the code to convert the document to HTML
  • Install recode (see link above)
  • Do something entirely different

Image - Round corners, add a credit

Link: http://www.imagemagick.org/Usage/thumbnails/#rounded

A script that uses ImageMagick to round the corners of an image, apply a credit, and optionally resize it. This script leaves the interim images, you could also delete them. The image credit is also written to a text file.

Original image

Credited Image

Code:

#!/bin/bash
if [ "$#" -lt 2 ]; then
        echo "usage: $0 <image file> <credit> [<resize>]"
else
ORIGINAL_IMAGE=$1
BASE_FILENAME=`basename $1 .jpg`
echo "$2" > $BASE_FILENAME.credit
convert $BASE_FILENAME.jpg \( +clone -alpha extract -draw 'fill black polygon 0,0 0,5 5,0 fill white circle 5,5, 5,0' \( +clone -flip \) \
    -compose Multiply -composite \( +clone -flop \) -compose Multiply -composite \) -alpha off  \
    -compose CopyOpacity -composite $BASE_FILENAME.rounded.png
convert -background white $BASE_FILENAME.rounded.png  +flatten $BASE_FILENAME.rounded.jpg
convert -background '#00000080' -pointsize 12 -fill white label:"$2" miff:- | \
    composite -gravity south -geometry +0+3 - \
    $BASE_FILENAME.rounded.jpg $BASE_FILENAME.credited.jpg
if [ "$#" -gt 2 ]; then
    mogrify -resize $3 $BASE_FILENAME.credited.jpg
fi
fi

Tested with:

convert -version
Version: ImageMagick 6.5.4-2 2009-07-08 Q16 OpenMP http://www.imagemagick.org
Copyright: Copyright © 1999-2009 ImageMagick Studio LLC

:: Next >>