Category Archives: Programming

Programming articles

handle subdomains with .htaccess / rewrite rule

Hi,

you are doing a web app or something that requires the creation of a subdomain for a account/user feature/action and don’t know how to do it? i will give you some tips about it :)

normally, when you create a subdomain, you do it in your dns files/manager adding a CNAME record, that redirect to a new folder under your account or server. this is the normal process but is not dynamic/flexible to create subdomains on the fly, why require to touch server configuration files in the best of the cases (if you have a vps or a dedicated, why if you are on a shared account you need to use the control panel of your hosting company to do this).

in this case, we will be able to dynamically create/edit/delete any subdomain on the fly, using some persistence method to save the existent domains (like DB, files, variables etc..)

first of all, the biggest requirement is to config   your domain as a wildcard domain, so any prefix added to the domain will be taken as valid. if you have access to the apache configuration files, open the one that have the virtualhost declaration of the domain and add the line:

ServerAlias *.your-domain-name.com

save and restart apache. if you are on a shared account, ask your hosting provider to do it, most of them will do it.

after this, we will create a .htaccess on the root of your web directory of the domain and paste this content in it:

   Options +FollowSymLinks
   Options +Indexes
   RewriteEngine On
   RewriteBase /

   RewriteCond %{HTTP_HOST} !www.your-domain-name.com$ [NC]
   RewriteCond %{HTTP_HOST} ^(www.)?([a-z0-9-_]+).your-domain-name.com [NC]
   RewriteRule (.*) \/index.php?subdomain=%1 [QSA,L]

this code, will do the following:

1) check the the domain is not the domain + www prefix

2)check that the domain is a valid string (numbers, sign – _ and letters)

3) redirect to the index.php passing the subdomain as a GET parameters

this has been coded to send the subdomain as a get parameter to the php script, there you can check if the subdomain exists agains a db or any other persistent data as config files and do the necessary actions. of course that this subdomain detection can be done with php, but if you are in some conflict with other code, this solution could be handy, clean and effective.

i hope it help you in some way.

Regards,

Shadow.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Related Post

Crop images with mootools

Hi,

i’m still with the images stuff :)

now i needed to integrate a crop image script using js. so i started to look for a premade solution. you can find several of them here, here and here. i was looking for a mootools based solution and i found 4. for my surprise,one didn’t exist anymore,  one of them didn’t worked with mootools 1.2, the others was too complicated and not flexible and none offer what i really needed, that was able to offer “mirrors” as preview of the crop in 2 different sizes. in my adventure, i tried to fix the first one (MooCrop) porting it to 1.2 but i leave it why it would take me too much work, then i tried to modify cwCrop but the code structure seems to be less flexible, and finally i decided to go with uvumiCrop, as it already have a mirror function and just need to be converted into a multi-div function.

so for those who want the mirror feature in the uvumiCrop script, here are the functions and code you need to replace:

Add this to the class var declaration

previewImageArray:new Array(),

On some place around line 102, paste this

this.previewImageArray = new Array();

replace with this from lines 285 to 354

if(this.options.preview){
 if(isArray(this.options.preview)){
 var previewImgObjArray=new Array();
 this.options.preview.each(function (item,index){
 var initWidth= $(item).getStyle('width');
 var initHeight= $(item).getStyle('height');
 //we put the preview in a wrapper div with a fixed height, because preview height and width may change.
 var previewWrapperObj = new Element('div',{
 styles:{
 height:initHeight
 }
 }).wraps($(item));

 //Setting the preview container
 $(item).setStyles({
 display:'block',
 position:'relative',
 width:initWidth,
 height:initHeight,
 overflow:'hidden',
 margin:'auto',
 fontSize:0,
 lineHeight:0,
 opacity:1,
 visibility: 'visible'
 });

 //cloning the original image for the preview
 var previewImageObJ = this.target.clone();
 previewImageObJ.set('id','imgObj_'+index);
 previewImageObJ.removeProperties('width','height').setStyle('position','absolute').inject($(item));
 previewImgObjArray.push(new Array('imgObj_'+index,item,initWidth,initHeight));
 }.bind(this));
 this.previewImageArray=previewImgObjArray;
 }else{
 if($(this.options.preview)){
 this.preview = $(this.options.preview);
 //we put the preview in a wrapper div with a fixed height, because preview height and width may change.
 this.previewWrapper = new Element('div',{
 styles:{
 height:this.previewSize.y+2*this.preview.getStyle('border-width').toInt()+this.preview.getStyle('margin-top').toInt()+this.preview.getStyle('margin-bottom').toInt()
 }
 }).wraps(this.preview);
 }else{
 var previewWrapper = new Element('div',{
 'class':'preview'
 }).inject(this.toolBox,'top');
 this.preview = new Element('div').inject(previewWrapper)
 }

 //Setting the preview container
 this.preview.setStyles({
 display:'block',
 position:'relative',
 width:this.previewSize.x,
 height:this.previewSize.y,
 overflow:'hidden',
 margin:'auto',
 fontSize:0,
 lineHeight:0,
 opacity:0
 });

 //cloning the original image for the preview
 this.previewImage = this.target.clone();
 this.previewImage.removeProperties('width','height').setStyle('position','absolute').inject(this.preview);
//            this.addEvent('onPreview',this.updatePreview.bind(this));
 }
 this.addEvent('onPreview',this.updatePreview.bind(this));
 }

replace updatePreview function with this code below:

//Function to update the preview
 updatePreview: function(top,left,width,height){
 if(this.previewImageArray.length>0){
 this.previewImageArray.each(function (item,index){
 if(height*item[2].toInt()/width<item[3]){
 $(item[1]).setStyles({
 width:item[2],
 height:(item[3].toInt()*height/width).toInt()
 });
 $(item[0]).setStyles({
 width:(this.target_coord.width*item[2].toInt()*this.scaleRatio/width).toInt(),
 height:'auto',
 top:-(top*item[2].toInt()/width).toInt(),
 left:-(left*item[2].toInt()/width).toInt()
 });
 }else{
 $(item[1]).setStyles({
 height:item[3],
 width:item[3]
 });
 $(item[0]).setStyles({
 height:(this.target_coord.height*item[3].toInt()*this.scaleRatio/height).toInt(),
 width:'auto',
 top:-(top*item[3].toInt()/height).toInt(),
 left:-(left*item[3].toInt()/height).toInt()
 });
 }
 }.bind(this));
 }else{
 if(height*this.previewSize.x/width<this.previewSize.y){
 this.preview.setStyles({
 width:this.previewSize.x,
 height:(this.previewSize.x*height/width).toInt()
 });
 this.previewImage.setStyles({
 width:(this.target_coord.width*this.previewSize.x*this.scaleRatio/width).toInt(),
 height:'auto',
 top:-(top*this.previewSize.x/width).toInt(),
 left:-(left*this.previewSize.x/width).toInt()
 });
 }else{
 this.preview.setStyles({
 height:this.previewSize.y,
 width:(this.previewSize.y*width/height).toInt()
 });
 this.previewImage.setStyles({
 height:(this.target_coord.height*this.previewSize.y*this.scaleRatio/height).toInt(),
 width:'auto',
 top:-(top*this.previewSize.y/height).toInt(),
 left:-(left*this.previewSize.y/height).toInt()
 });
 }
 }
 },

and the isArray() function used at the beginning of the code:

function isArray(obj) {
 return obj.constructor == Array;
}

so, now in the initialization of the uvumiCrop object, you set the preview property as a array ( new Array(‘id1′,’id2′) ) with the id’s of the divs that will be used as mirrors. is important that you set the width and height of each div before you create the uvumiCrop object. this code will maintain the original behavior of the original script, you can still have the floating mirror and the unique mirror.

is also important to mention that i changed the code so the container don’t get the width and height deformed and work as a container hiding the rest of the image. is done like this so the user can know really how it will look after the crop process.

i have sent this post to the developer, so maybe he include it on the next release :D

i hope you find this useful and save you some time :D

Regards,

Shadow.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Related Post

PHP resize solution: phpThumb

Hi,

on the web app i have been working this past months, we allow the users to upload avatar photos, and some other pictures that are shown at the site. so, i implemented the code i always use to resize the images. it have done the job well on the testing phase but we found that we have bad quality images when the users uploaded their photos. so i looked for a solution and i found phpThumb. this class/script generate resized images in a quickly and easy way. it comes in 2 flavors, in a ready to use script where you pass the parameters of where is the source image, destination, measures etc.. and will print you the image (can be used in img tags as source). and also you have the class where you can manually convert the files and save it on a file or print it etc..

the class use as input the location of the source image, the binary data or a GD resource. also, phpThumb will try to use imagemagick if is installed on the server (that will give you a better quality image) and if is not available, will use GD automatically. i have tried it and i need to say that the best configuration i made to get the best quality image possibly was:

 $phpThumb->setParameter('output_interlace',true);
 $phpThumb->setParameter('config_output_format', 'png');
 $phpThumb->setParameter('fltr', 'q|95');
 $phpThumb->setParameter('config_imagemagick_path', '/usr/bin/convert');

i have tried to use jpeg format, but sometimes i get some ugly and pixelated grey background at the thin lines of the image (like words etc..) so the best option was to use png.

you can download phpThumb from here

Regards,

Shadow.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Related Post

Simulate User Testing: Selenium IDE

Hi,

long time since my last post right? sorry about that, too much work and things happening lately :) .

this time i’m here to share the discover of a great tool that a friend of mine told me some days ago. is called selenium IDE. this tools  comes in several formats, but what i’m interested in the FF addon version. this addon let you record user actions in a website, as login into a site, submit a form, click a link etc.. all of this can be recorded and reproduced anytime. this is useful why you can create a test suite of diferent’s actions for your app, and after you added some change or feature, you can run the test’s and know if something is not working.

selenium also accept scripting,in a markup language like xml where you can manually define actions, as waiting for some DOM object to show up, or some value to get set to  launch an action.

i recommend you to take a look at it, will save you time and headaches in the future :)

you can download it from here.

Regards,

Shadow.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Related Post

Autocomplete plugin for mootools

Hi,

recently building a app i was need to suggest data to the user when trying to fill a input. so i look for a js script for this. i usually use mootools for my development in js, so looking for a plugin i found this: Meio.Autocomplete plugin for mootools

is a really nice plugin, between their features, support the inbuilt ajax calls using the Request.JSON method from the mootools framework. also support to set up filter for the returned data, the set of field parameter to look for the input by the user, the minimum of characters that the user need to enter to start looking for it, delay between the ajax call and the search in the data and many other properties. you can also customize the look and feel of how the options are displayed.

from their web page you can download the source code and the compressed version for production environments. also there you can see plenty of documentation explaining each property of the plugin and several examples to see and try online.

i hope it help you in some way :)

Regards,

Shadow.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Related Post

Creating images with GD in php

Hi,

GD is a php extension that let you create images using code.between the images format are jpg, gif, pnf, swf,tiff and jpeg200. GD let you create images from 0, you can grab a image (from a full path or from a url) and edit them, draw things in it or mix it with other images, also you can write strings in different colors and fonts (it support ttf fonts).

i will share some examples manipulating images using GD:

1 color image:

 $im  = imagecreate (150, 30); // create a blank image
 $bgc = imagecolorallocate ($im, 255, 255, 255); // create a background color
 imagefilledrectangle ($im, 0, 0, 150, 30, $bgc); // draw a rectangle of the size of the image with the background color

resize image:

// Load the images
$thumb = imagecreate($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);
// Resize the images
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
// Showing the resized image
imagejpeg($thumb);

Mix 2 images:

// Create image instances
$dest = imagecreatefromgif('php.gif');
$src = imagecreatefromgif('php.gif');
// Copy and merge
imagecopymerge($dest, $src, 10, 10, 0, 0, 100, 47, 75);
// Output and free from memory
header('Content-Type: image/gif');
imagegif($dest);

i hope this help you in some way :D

Regards,

Shadow.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Related Post

pChart php class to build charts

pChart Logo

pChart Logo

Hi,

today i wanted to talk about a class that i have been using a lot lately and  i have worked with it for the past months, called pChart. this class let you create charts from stream data. the class let you create line, curve, cake/basic pie, bar,stacked,radar, 3d pie,radar, and scatter charts, and in this list i’m sure i’m forgetting some of them. the process to create the chart is very simple

pChart Creation Process

pChart Creation Process

as you see in the graph, the process consist in get the data from some stream, something that there is not mentioning is that the data retrieved, if is not a csv that the class have inbuilt functions to parse it, you need to prepare it, ordering in a specific way depending the type of chart you are using (if is a line bar, you need to define the serie name’s for each axis and the values for it). after you have the data, set the style, as the background, the font type and size (it support ttf fonts) and the scale. and then you are ready to draw the chart, that the returned data can be printed to the user directly, of course first setting a image type stream with the header() function or write it in a file.

below, you can see some example code:

// Standard inclusions
include(“pChart/pData.class”);
include(“pChart/pChart.class”);
// Dataset definition
$DataSet = new pData; // initialize the data parser object
$DataSet->ImportFromCSV(“Sample/bulkdata.csv”,”,”,array(1,2,3),FALSE,0); //get the data input from a csv file
$DataSet->AddAllSeries();
$DataSet->SetAbsciseLabelSerie();
$DataSet->SetSerieName(“January”,”Serie1″);
$DataSet->SetSerieName(“February”,”Serie2″);
$DataSet->SetSerieName(“March”,”Serie3″);
$DataSet->SetYAxisName(“Average age”);
$DataSet->SetYAxisUnit(“µs”);
// Initialise the graph
$Test = new pChart(700,230); //setting the widht and height of the chart
$Test->setFontProperties(“Fonts/tahoma.ttf”,8);  //the font used for the chart and the font size
$Test->setGraphArea(70,30,680,200);  //the width, height, x and y position of the area where the graph will be drawn
$Test->drawFilledRoundedRectangle(7,7,693,223,5,240,240,240);
$Test->drawRoundedRectangle(5,5,695,225,5,230,230,230);
$Test->drawGraphArea(255,255,255,TRUE);
$Test->drawScale($DataSet->GetData(),$DataSet->GetDataDescription(),SCALE_NORMAL,150,150,150,TRUE,0,2);
$Test->drawGrid(4,TRUE,230,230,230,50);
// Draw the 0 line
$Test->setFontProperties(“Fonts/tahoma.ttf”,6);
$Test->drawTreshold(0,143,55,72,TRUE,TRUE);
// Draw the line graph
$Test->drawLineGraph($DataSet->GetData(),$DataSet->GetDataDescription());
$Test->drawPlotGraph($DataSet->GetData(),$DataSet->GetDataDescription(),3,2,255,255,255);
// Finish the graph
$Test->setFontProperties(“Fonts/tahoma.ttf”,8);
$Test->drawLegend(75,35,$DataSet->GetDataDescription(),255,255,255);
$Test->setFontProperties(“Fonts/tahoma.ttf”,10);
$Test->drawTitle(60,22,”example 1″,50,50,50,585);
$Test->Render(“example1.png”);

and this is the result

pChart Example

pChart Example

you can download the class from here, you can find documentation and the classes definition at here, and here several examples of how to create different types of graphs

i hope this help you in some way :D .

Regards,

Shadow.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Related Post

Basic CSS tricks

Hi,

today i wanted to share some basic CSS tricks :)

Dont resize textarea on chrome and safari

the textarea can be resized on chrome and safari, and even that seems to be a nice feature, when you have a limited and strict layout, this could screw up the things. to avoid this, just add this css code to your stylesheet:

textarea{

resize: none;

}

Scrollbars for DOM

sometimes you need to show content in a small space, not enough maybe for the content, so it come useful some scroll bars, for that, add the overflow property:

overflow: scroll;

Static background like twitter

you always wanted a background like the twitter accounts have right? is easy as like this:

backgroun-attachement: fixed;

Text lowercase, uppercase or capital

if you have a stream of data and is not well formatted, you can user this properties to do it :

text-transform: uppercase // MY TEXT

text-transform: lowercase // my text

text-transform: capitalize //My Text

Input button or submit with a custom image

maybe you have designed a image button, and want to apply it to a input submit or button, for that, you can use this code:

background: transparent url(image.png) 0 0 no-repeat; //your background image
border: none; //setting border to none
overflow: hidden; // all the excess of data or text is hide
text-indent: -3000px;  //moving the text inside the button outside the field of view

i hope this help you in some way :D

Regards,

Shadow.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Random Posts

    Simple text replacement using javascript

    Hi,

    just a quick code snippet to filter any text inserted by the user, useful for only numbers (and symbols) fields like for the user phone in a form.

    function checkLetters(elem){
    var val=elem.value;
    elem.value=val.replace(/[a-z]+/gi,”");
    }

    you can add this function to any input like this:

    onkeypress=”checkLetters(this);”

    a very basic and simple code example, but very useful some times :)

    Regards,

    Shadow.

    [Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

    Related Post

    Open Source Web E-learning & Conference Platform: Big Blue Button

    Hi,

    some months ago, working over a project and designing the architecture and technical spects, we got a moment where we needed to get or build a streaming platform.  the problem was, that the streaming platform will needed to have a Q&A module, a way to share the desktop or ppt and other features. then searching in the web, i found Big Blue Button.

    this open source project aims to build a free E-learning and Conference platform, from their web can be read as:

    Our vision is that starting a web conference should be as easy as clicking a single metaphorical big blue button. As an open source project, we believe it should be easy for others to embrace and extend. And while web conferencing means many things to many people — our focus is to make the best web conferencing system for distance education.

    the software is a conjunction of different technologies as java, flash, red5 etc.. to provide the streaming of the content to the users, is a big project, stable for now that really make the work. the only problem is that is not as-easy to install and configure than use it. for use it you just need a flash-compatible browser, but at the installation part, you need a dedicated server, linux-based, and follow a lot of configurations and installation process. i think is not for all the people but is a perfect project to customize /integrate in your own web application. also, the license of BBB is LGPL so can be integrated in any closed source project.

    if you want, can try a live demo here

    i hope it help you in some way :D

    Regards,

    Shadow.

    [Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

    Related Post