Short Tag – Web Development Blog

Restart XULRunner application with XPCOM

The following code will restart the XULRunner application it is used in:

var appStartup = Components.classes["@mozilla.org/toolkit/app-startup;1"]
.getService(Components.interfaces.nsIAppStartup);

appStartup.quit(Components.interfaces.nsIAppStartup.eRestart |
Components.interfaces.nsIAppStartup.eAttemptQuit);

Initialize nsIAppStartup interface with the first line of code. With the second line of code I call the function called “quit”.

var appStartup = Components.classes["@mozilla.org/toolkit/app-startup;1"]
.getService(Components.interfaces.nsIAppStartup);

appStartup.quit(Components.interfaces.nsIAppStartup.eRestart |
Components.interfaces.nsIAppStartup.eAttemptQuit);

Make cPanel Api2 Requests with Jquery and Javascript

First, include jQuery in your page:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

Here is the API 2 of cPanel:
http://docs.cpanel.net/twiki/bin/view/ApiDocs/Api2/WebHome

Find the modules and function names you need, and use them when calling the function below.

Copy the following function to your webpage:

function cpanel_call(module, fct, domain, user, password, secure, port, json, callback, return_as, async)
{
var protocol = secure ? "https" : "http";
var data_type = json ? 'json-api' : 'xml-api';

var authStr = "Basic " + Base64.encode(user + ":" + password);
var url = protocol + "://" + domain + ":" + port + "/" + data_type + "/cpanel?user=" + user + "&cpanel_xmlapi_module=" + module + "&cpanel_xmlapi_func=" + fct + "&cpanel_xmlapi_version=2&domain=" + domain;

jQuery.ajax({
"type" : "GET",
"username" : user,
"password" : password,
"url" : url,
"async" : false,
"dataType" : return_as ? return_as : "text",
headers : {"Authorization" : authStr},
beforeSend : function(xhr)
{
xhr.setRequestHeader("Authorization", authStr);
},
success : function(msg, textStatus, xhr){

if (callback)
callback.apply(this, [msg]);

},
error : function(){
alert("Connection Error!");
}
});
}

Use the function like this:


cpanel_call(cpanel_module_name, cpanel_fct_name, domain, cp_user, cp_password, port, json, function(msg){
//do whatever you want, when it finished
}, return_as, async);

The answer from the server will be found in the msg variable received by the callback function. You will receive it in the format specified by return_as parameter. See the parameter explanation below.

Parameter explanation:
cpanel_module_name – the cPanel module you would like to call from API2
cpanel_fct_name – a cPanel function from the module above
domain – the domain of your host
cp_user – cPanel username
cp_password – cPanel password
port – cPanel port, usually 2082 for unsecure and 2083 for secure
json – specifies the format of the received data, set “json” for json, set “xml” or leave it empty for xml
function(){ – a callback function, this is executed after the cpanel request has been executed
return_as – the format format for returning data, set “text” or leave it empty to return as text, “json” for a JSON object, “xml” for an xml object
async – the call should be synchronous or asynchronous? Set false for synchronous and true for asynchronous

Example, list all Addon Domains from cPanel:

cpanel_call("AddonDomain", "listaddondomains", "my_domain.com", "my_user", "my_pass", 2082, "xml", function(msg){
alert("msg"); //this is what the server returned
}, "text", false);

One last thing! My function uses a BASE64 encode class, from: webtoolkit.info! Copy the function from below or from their website: http://www.webtoolkit.info/javascript-base64.html. Make sure your page contains this function, otherwise my function won’t work.


/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*  Class Needed for authentication
*
**/

var Base64 = {

// private property
_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

// public method for encoding
encode : function (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;

input = Base64._utf8_encode(input);

while (i < input.length) {

chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);

enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;

if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}

output = output +
this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

}

return output;
},

// public method for decoding
decode : function (input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;

input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

while (i < input.length) {

enc1 = this._keyStr.indexOf(input.charAt(i++));
enc2 = this._keyStr.indexOf(input.charAt(i++));
enc3 = this._keyStr.indexOf(input.charAt(i++));
enc4 = this._keyStr.indexOf(input.charAt(i++));

chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;

output = output + String.fromCharCode(chr1);

if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}

}

output = Base64._utf8_decode(output);

return output;

},

// private method for UTF-8 encoding
_utf8_encode : function (string) {
string = string.replace(/\r\n/g,"\n");
var utftext = "";

for (var n = 0; n < string.length; n++) {

var c = string.charCodeAt(n);

if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) & (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}

}

return utftext;
},

// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
var string = "";
var i = 0;
var c = c1 = c2 = 0;

while ( i < utftext.length ) {

c = utftext.charCodeAt(i);

if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if((c > 191) & (c < 224)) {
c2 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i+1);
c3 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}

}

return string;
}

}

If you set up everything correctly the alert above should show the xml that cPanel API returned. If you find something that is hard to understand please post it below in the comment box and I will try to answer as soon as possible!

Xul and XPCOM: Delete files

Here is a little handy function for removing files with Javascript on Mozzila platform:

function delete_file_by_path(path)
{
var file = Components.classes['@mozilla.org/file/local;1']
.createInstance(Components.interfaces.nsILocalFile);
file.initWithPath(path);
if (file.exists())
file.remove(false);
}

Create a new instance of nsILocalFile, and the use the initWithPath function to initialize the file, and the delete the file is exists.

Php .Htaccess Set default timezone

When getting an error like this:

© Warning: date(): It is not safe to rely on the system’s timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected ‘America/Location’ for ‘EST/-5.0/no DST’

It means you have to set the default timezone of your server.
1.) You can do this by changing php.ini
[Date]
; Defines the default timezone used by the date functions
date.timezone = America/Location

2.) You can set it up in htaccess
SetEnv TZ America/Location

3.) You can change it in php
date_default_timezone_set(“America/Location”);

The entire list of  timezones can be found on the PHP site:
http://www.php.net/manual/en/timezones.php

Replace America/Location with your server’s timezone.

Loop through a Combobox, Listbox in XUL/XPCOM

So, we have a XUL component, that looks like this:

<listbox id="listboxId">
<listitem label="1" />
<listitem label="2" />
<listitem label="3" />
</listbox>

We can loop through the elements of this componenet using XPCOM:

var lbox = document.getElementById('listboxId');

for (var i =0; i<lbox.children.length; i++)
{
var child = lbox.children[i];
//do someting with child, like
alert(child.label)
}

Javascript function to trim any character

Today I want to share a javascript function that will trim any character from the beginning and the end of the string.
The function will trim all occurrences of the character from the beginning and the end of the string.

function trim_chars(str, char)
{

while (str.substr(0, 1) == char)
str = str.substr(1);

var nrt = str.length;
while (str.substr(nrt-1, 1) == char)
{
str = str.substr(0, nrt-1);
}

return str;
}

The function will be used like this:

trim_chars('/public_html/images/', '/');

In this case it will trim the ‘/’ from the beginning and the end of the string leaving: public_html/images

If you would like to trim the characters only from the beginning of the string, the function would look like this:

function trim_chars_start(str, char)
{
while (str.substr(0, 1) == char)
str = str.substr(1);

return str;
}

If you would like to trim only the last characters:

function trim_chars(str, char)
{
var nrt = str.length;
while (str.substr(nrt-1, 1) == char)
{
str = str.substr(0, nrt-1);
}

return str;
}

PHP str_replace

PHP’s str_replace function will replace every occurrence of the selected string with another string.

echo str_replace("car", "bike", "That car is red!");

The code above displays the text: That bike is red!
Function parameters:

str_replace(searched_string, replacement_string, target_string, count)

searched_string – the string that will be replaced
replacement_string – the string that will be used to replace the searched string
target_string – the string in which the replacement will occur
count – the number or replacements that will be performed, if it is not specified all of the occurrences will be replaced

Notes:

  • The count parameter has been added in PHP5
  • The function is binary safe
  • The function is case-sensitive (use str_ireplace() function for case insensitive replace)
  • The function replaces from left to right

You can use arrays in replacements too:

Case 1: replace all values from an array with a single value

$arr = array('orange', 'lemon', 'pear');
str_replace($arr, 'apple', 'orange is big, lemon is small, pear is good');

It will return: apple is big, apple is small, apple is good

Case 2: replace all values from an array with another values from another array

$arr = array('orange', 'lemon', 'pear');
$arr2 = array('Hulk', 'Alvin', 'Pizza');
str_replace($arr, $arr2, 'orange is big, lemon is small, pear is good');

It will return: Hulk is big, Alvin is small, Pizza is good

LaunchTAE14

jQuery animate() is not working on element’s children in IE8

Today I encountered a problem I thought I should post about.

When you try to animate an element that has children (for example DIVs) positioned relative or absolute on Internet Explorer 8 these children will not animate, in fact they will not do anything the parent does. I tested this animating the opacity.

<div class="main">
<div class="first"></div>
<div class="second"></div>
<div class="third"></div>
</div>

If classes ’second’ and ‘third’ are positioned relatively or absolutely that will not be animated using this:

$(".main").animate({opacity : 0}, 500);

The best solution I found was to hide the elements after the animation has ended. So, after the animation ended I forced those DIVs to take their end values directly, no animation involved. This method will skip the animation only on IE8 and other browsers with the same problem.

First I needed to add another class to the problematic DIVs:

<div class="main">
<div class="first"></div>
<div class="second problem"></div>
<div class="third problem"></div>
</div>

And I modified the Javascript like this:

$(".main").animate({opacity : 0}, 500, function(){$(".main").find(".problem").css('opacity', 0);});

Xul Javascript: Difference between getService() and createInstance()

When calling an XPCom component from Javascript we can use to functions: getService() and createInstance().
* getService() will get a singleton class, so a single object will do all the work no matter how many times you call it.
* createInstance() will create a new instance of that class, this is useful in situations where you make asynchronous requests, or process things in parallel and you don’t want all of it to be processed by the same object.

Example:

var file = Components.classes["@mozilla.org/file/directory_service;1"]
.createInstance(Components.interfaces.nsIProperties)
.get("ProfD", Components.interfaces.nsIFile);
var file = Components.classes["@mozilla.org/file/directory_service;1"]
.getService(Components.interfaces.nsIProperties)
.get("ProfD", Components.interfaces.nsIFile);

Get and Set Preferences in XUL

Below are two funtions that will set and get boolean values in your firefox profile. These can be used in standalone XULRunner applications or in Firefox extensions.

Use them to save the settings of your application / extensions.

function setSettingValue(setting, value)
{
var prefs = Components.classes["@mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefService).getBranch("accessibility.");

prefs.setBoolPref(setting, value);
}

function getSettingValue(setting)
{
var prefs = Components.classes["@mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefService).getBranch("accessibility.");

return prefs.getBoolPref(setting);
}

For setting/getting int type preference use: getIntPref() and setIntPref().
For string preferences use: getCharPref() and setCharPref().

More details on MDN:
https://developer.mozilla.org/en/Code_snippets/Preferences