PHP and javascript snippets you can copy and paste.

Tuesday, April 17, 2007

js_map_keyPress(actualKeyPress,keyPressToMatch,callback)

/**
* Maps a key press to a function.
*
* @param int actualKeyPress.
* @param int keyPressToMatch.
* @param object callback.
*/
function js_map_keyPress(actualKeyPress,keyPressToMatch,callback){
if(actualKeyPress==keyPressToMatch){
callback();
}
}

js_get_keyCode(e)

/**
* Returns the key code of a key press.
*
* @param object e.
* @return key code.
*/

function js_get_keyCode(e){

if(e.event){ // IE
keyCode = e.keyCode;
}
else if(e.which){
keyCode = e.which;
}
return keyCode;

}

Sunday, April 15, 2007

js_create_socialBookmarks(container,path_to_icons)

/**
* Creates links to social bookmarking sites.
*
* @param object container - div, span etc element to hold links.
* @param string path_to_icons - path to where the social bookmarking sites icons are.
*/

function js_create_socialBookmarks(container,path_to_icons){

var page = window.location;
var title = window.document.title;

links = new Array();

if(!path_to_icons || path_to_icons=='undefined'){
path_to_icons = './';
}

// Digg.
link = document.createElement('A');
link.href = "http://digg.com/submit?phase=2&url=" + escape(page) + "&title=" + escape(title);
link.setAttribute('title','Digg');
img = document.createElement('IMG');
img.setAttribute('src', path_to_icons + 'digg.png');
img.setAttribute('border','0');

img.setAttribute('alt','digg');
link.appendChild(img);
links[links.length] = link;

// Delicious.
link = document.createElement('A');
link.href = "http://del.icio.us/post?url=" + escape(page) + "&title=" + escape(title);
link.setAttribute('title','del.icio.us');
img = document.createElement('IMG');
img.setAttribute('src', path_to_icons + 'delicious.png');
img.setAttribute('border','0');
img.setAttribute('alt','del.icio.us');
link.appendChild(img);
links[links.length] = link;

// Stumbleupon.
link = document.createElement('A');
link.href = "http://www.stumbleupon.com/url/" + escape(page);

link.setAttribute('title','StumbleUpon');
img = document.createElement('IMG');
img.setAttribute('src', path_to_icons + 'stumbleupon.png');
img.setAttribute('border','0');
img.setAttribute('alt','StumbleUpon');
link.appendChild(img);
links[links.length] = link;

// Reddit.
link = document.createElement('A');
link.href = "http://reddit.com/submit?url=" + escape(page) + "&title=" + escape(title);
link.setAttribute('title','Reddit');
img = document.createElement('IMG');
img.setAttribute('src', path_to_icons + 'reddit.png');
img.setAttribute('border','0');
img.setAttribute('alt','Reddit');
link.appendChild(img);

links[links.length] = link;

// Technorati
link = document.createElement('A');
link.href = "http://technorati.com/faves?add=" + escape(page);
link.setAttribute('title','Technorati');
img = document.createElement('IMG');
img.setAttribute('src', path_to_icons + 'technorati.png');
img.setAttribute('border','0');
img.setAttribute('alt','Technorati');
link.appendChild(img);
links[links.length] = link;

// Furl.
link = document.createElement('A');
link.href = "http://www.furl.net/storeIt.jsp?u=" + escape(page) + "&t=" + escape(title);
link.setAttribute('title','Furl');
img = document.createElement('IMG');

img.setAttribute('src', path_to_icons + 'furl.png');
img.setAttribute('border','0');
img.setAttribute('alt','Furl');
link.appendChild(img);
links[links.length] = link;

// Slashdot.
link = document.createElement('A');
link.href = "http://slashdot.org/bookmark.pl?title=" + escape(title) + "&url=" + escape(page);
link.setAttribute('title','Slashdot');
img = document.createElement('IMG');
img.setAttribute('src', path_to_icons + 'slashdot.png');
img.setAttribute('border','0');
img.setAttribute('alt','Slashdot');
link.appendChild(img);

links[links.length] = link;

// Blinklist.
link = document.createElement('A');
link.href = "http://www.blinklist.com/index.php?Action=Blink/addblink.php&Url=" + escape(page) + "&Title=" + escape(page);
link.setAttribute('title','BlinkList');
img = document.createElement('IMG');
img.setAttribute('src', path_to_icons + 'blinklist.png');
img.setAttribute('border','0');
img.setAttribute('alt','BlinkList');
link.appendChild(img);
links[links.length] = link;

var max = links.length-1;

for(i=0;i<max;i++){

container.appendChild(links[i]);
}

}

Saturday, April 14, 2007

js_ajax.js

// Credit: http://www-128.ibm.com/developerworks/xml/library/x-ajaxxml3/index.html?ca=dnw-812
function ajx_process_reqChange() {

if (req.readyState == 4){
if(req.status!=200){
if(typeof(onfailure)=='function'){
onfailure();
}
}
else{
if(typeof(onsuccess)=='function'){
onsuccess();
}
}
}

}

function js_ajax_load_url( url, successCallback, failureCallback){

if(window.XMLHttpRequest) {
try {

req = new XMLHttpRequest();
}
catch(e) {
req = false;
}
}
else if(window.ActiveXObject) {
try {
req = new ActiveXObject('Msxml2.XMLHTTP');
}
catch(e) {
try {
req = new ActiveXObject('Microsoft.XMLHTTP');
}
catch(e) {
req = false;
}

}
}
if(req) {
onfailure = failureCallback;
onsuccess = successCallback;
req.onreadystatechange = ajx_process_reqChange;
req.open('GET', url, true);
req.send('');
}

}

var req = null;
var onfailure = null;
var onsuccess = null
req = null;

//-------------------------------------------------------------------------
// Example:

[html]
[head]
[script language="Javascript" src="js_ajax.js"][/script]

[script language="Javascript"]

function onsuccessCallback(){
alert(req.responseText);
}

function onfailureCallback(){
alert('failed');
}

window.onload = registerEvents;

function registerEvents(e){
js_ajax_load_url('test.php', onsuccessCallback, onfailureCallback)
}

[/script]
[/head]
[body]
[/body]
[/html]

Friday, April 13, 2007

net_upload_photosToFlickr($yourFlickrEmailAddress,$pathsToPhotos)

/**
* Uploads photos to Flickr.
*
* @param string $yourFlickrEmailAddress - email address used to upload photos to Flickr. Ref: http://flickr.com/account/uploadbyemail/
* @param array $pathsToPhotos - array of paths to photos eg array('/mypath/photo1.jpg',/mypath/photo2.jpg' ...)
* @return bool.
*/


// http://phpmailer.sourceforge.net/
require_once('phpmailer/class.phpmailer.php');

function net_upload_photosToFlickr($yourFlickrEmailAddress,$pathsToPhotos){

$mailer = new PHPMailer();
$mailer->AddAddress($yourFlickrEmailAddress);
if(!empty($pathsToPhotos)){
while(list($key,$pathToPhoto)=each($pathsToPhotos)){
$mailer->AddAttachment($pathToPhoto);
}
}

return ($mailer->send()){


}

Thursday, April 12, 2007

js_is_image(ext)

/**
* Returns true if ext is an image extension.
*
* @param string ext.
* return bool
*/
function js_is_image(ext){

var imgExtsArr = new Array();
imgExtsArr.png = true;
imgExtsArr.jpg = true;
imgExtsArr.gif = true;
imgExtsArr.jpeg = true;

return imgExtsArr[ext];

}

js_php_parse_url(url)

/**
* Javascript equivalent of PHP 'parse_url' function.
*/
function js_php_parse_url(url){

url = new String(url);

ret = new Array();

// Domain name and scheme
var regexp = new RegExp("([a-z0-9]+)\:\/\/([\.a-z0-9\-\_]+)", "i");
result = regexp.exec(url);
if(result){
ret.scheme = result[1];
ret.domain = result[2];
}

// Path
regexp.compile("[a-z]+\:\/\/[\.a-z0-9]+\/([a-z0-9\/\.\-\_]+)\/", "i");
result = regexp.exec(url);
if(result){
ret.path = result[1] + '/';
}

// file name

regexp.compile("[a-z]+\:\/\/[\.a-z0-9]+\/([a-z0-9\/\.\-\_]+)", "i");
result = regexp.exec(url);
if(result){
ret.filename = result[1];
}
else{
ret.filename = url;
}

// Ext.
temp = ret.filename.split('.');
ret.ext = temp[1];


// Port

regexp.compile("[a-z]+\:\/\/[\.a-z]+\:([0-9]+)", "i");
result = regexp.exec(url);
if(result){
ret.port = result[1];

}

// Query
temp = url.split('?');
if(temp[1]){
ret.query = temp[1];
}

return ret;

}

Wednesday, April 4, 2007

file_do_download($fileName)

/**
* Downloads a file.
*
* @param fileName.
*/

function file_do_download($fileName, $mimeType){

header("Content-type: $mimeType");
$baseName = basename($fileName);
header("Content-disposition: attachment; filename=$baseName");
echo $data;
die(); // required

}

xml_replace_nodeContent( &$node, &$new_content )

/**
* Replaces node contents.
*
* Needed as a workaround for bug/feature of set_content.
* This version puts the content
* as the first child of the new node.
* If you need it somewhere else, simply
* move $newnode->set_content() where
* you want it.
* Credit: http://www.php.net/manual/en/function.domnode-set-content.php
*/

function xml_replace_nodeContent( &$node, &$new_content )
{

$dom =& $node->owner_document();

$newnode =& $dom->create_element( $node->tagname );

$newnode->set_content( $new_content );

$atts =& $node->attributes();
foreach ( $atts as $att )
{
$newnode->set_attribute( $att->name, $att->value );
}


$kids =& $node->child_nodes();
foreach ( $kids as $kid )
{
if ( $kid->node_type() != XML_TEXT_NODE )
{
$newnode->append_child( $kid );
}
}

return $newnode;

}

arr_add_elementToStart($a,$el)

/**
* Adds an element to the start of an array.
* @param array $a
* @param mixed $el
*/

function arr_add_elementToStart($a,$el){
$aRev = array_reverse($a);
array_push($aRev, $el);
return array_reverse($aRev);
}

fnc_call($funcName)

/**
* Enables a function to be passed as a parameter
*
* @param string $funcName.
* @param string $fn.
* $param array $params - params to pass to $fn.
* @return array - return values of each call to $fn.
*/
function fnc_call($funcName){

$args = func_get_args();
array_shift($args);
$classNameMethod = explode('::',$funcName);
if(isset($classNameMethod[1])){
$funcName = $classNameMethod;
}
return call_user_func_array($funcName,$args);

}

// Example
/*

require_once('fnc_call.php');

function add($a,$b){
return $a + $b;
}

function test($addFn, $a, $b){
print_r(fnc_call('add',$a ,$b));
}

test('add', '4', '5');

?>
*/

Tuesday, April 3, 2007

sec_quote_SQLStr($sql)

/**
* Converts an array to url string.
*
* @param string $sql.
* @param object $path.
* @param int $index - defaults to 0.
* @return string.
*/
function sec_quote_SQLStr($sql){

if (get_magic_quotes_gpc()) $value = stripslashes($sql);

$value = "'" . mysql_real_escape_string($sql) . "'";

return $value;

}

net_convert_arrayToUrlStr($arr)

/**
* Converts an array to url string.
*
* @param object $xpathObj.
* @param object $path.
* @param int $index - defaults to 0.
* @return array.
*/

function net_convert_arrayToUrlStr($arr){

$s = '';

if(is_array($arr) && !empty($arr)){
while(list($key,$val)=each($arr)){
$s .= urlencode($key) . '=' . urlencode($val) . '&';
}

// remove trailing '&'
$s = substr($s, 0, -1);

}


return $s;

}

xml_get_nodeChildren($xpathObj,$path,$index=0)

/**
* Gets the children of a node.
*
* @param object $xpathObj.
* @param object $path.
* @param int $index - defaults to 0.
* @return array.
*/

function xml_get_nodeChildren($xpathObj,$path,$index=0){

$nodes = $xpathObj->xpath_eval($path);
$nodeSet = $nodes->nodeset;
return isset($nodeSet[$index])?$nodeSet[$index]->children():array();

}

xml_get_XMLStrFromXPath($xpathObj,$path,$index=0)

/**
* Gets xml string from xpath object.
*
* @param object $xpathObj.
* @param object $path.
* @param int $index - defaults to 0.
* @return object.
*/

function xml_get_XMLStrFromXPath($xpathObj,$path,$index=0){
$nodes = $xpathObj->xpath_eval($path); // php 4
$nodeSet = $nodes->nodeset;
return isset($nodeSet[$index])?$nodeSet[$index]->dump_node():null;
}

xml_remove_elementsByTagName($parentNode,$tagName)

/**
* Removes elements by tag name.
*
* @param object $parentNode.
* @param object $tagName.
* @return object.
*/

function xml_remove_elementsByTagName($parentNode,$tagName){

$nodes = $parentNode->get_elements_by_tagname($tagName);

if(count($nodes)>0){
while(list($key,$node)=each($nodes)){
$parentNode->remove_child($node);
}
}

return $parentNode;

}

xml_append_childNode($parentNode,$childNode)

/**
* Appends a child node to a node.
*
* @param object $parentNode.
* @param object $childNode.
* @return object.
*/

function xml_append_childNode($parentNode,$childNode){

$doc = domxml_new_doc("1.0");
$newNode = $doc->create_element("import");
$clonedNode=$parentNode->clone_node(true);
$clonedNode->append_child($childNode->clone_node(true));
return $parentNode->append_child($clonedNode);

}

xml_create_elementWithText($doc, $name, $value)

/**
* Creates an xml element with text.
*
* @param object $doc.
* @param string $name.
* @param string $value.
* @return object.
*/

function xml_create_elementWithText($doc, $name, $value){

$el = $doc->create_element($name);
$textNode = $doc->create_text_node($value);
$el->append_child($textNode);

return $el;

}

xml_clone_xpathToNewDOM($origXPath,$path)

/**
* Appends a node returned by an xpath object to a new DOM.
*
* @param object $origXPath.
* @param string $path
* @return object.
*/

function xml_clone_xpathToNewDOM($origXPath,$path){

$newDOM = domxml_new_doc("1.0");
$temp = $newDOM->create_element("import"); //otherwise get errors in PHP4
$origNode = getNode($origXPath,$path);

$newNode=$origNode->clone_node(true);
$newDOM->append_child($newNode);

return $newDOM;

}

Monday, April 2, 2007

xml_create_node($xml)

/**
* Creates an xml node.
*
* @param string $xml.
* @return object.
*/

function xml_create_node($xml){
$DOM = createDOM($xml);
return $DOM->root();
}

xml_create_xpath($DOM)

/**
* Creates an xpath object.
*
* @param object $DOM
* @return object.
*/
function xml_create_xpath($DOM){
return $DOM->xpath_new_context();
}

xml_create_DOM($xmlStr)

/**
* Creates a DOM from an xml string.
*
* @param string $xmlStr.
* @return object.
*/

function xml_create_DOM($xmlStr){
// Create DOM object of $xmlStr.
return domxml_open_mem($xmlStr);
}

xml_get_attribValue($node, $name, $default)

/**
* Gets the value of an attribute.
*
* @param object $node.
* @param string $name - the name of the attribute.
* @param string $default - the default value to return if attribute not found.
* @return string.
*/

function xml_get_attribValue($node, $name, $default){
if(is_object($node)){
$val = $node->get_attribute($name);
}
else{
$val = $default;
}
return $val;
}

xml_get_nodeSet($xpathObj,$path,$index=0)

/**
* Gets a nodeset.
*
* @param object $xpathObj.
* @param string $path.
* @param int $index - defaults to 0.
* @return string.
*/

function xml_get_nodeSet($xpathObj,$path,$index=0){
$nodes = $xpathObj->xpath_eval($path); // php 4
return $nodes->nodeset;
}