Friday, January 26, 2007

Who's running to get Vista ?

Yesterday HTML.it posted a nice question about Vista: "If You have Vista or You'll install them quickly put your hand in the air".

This is just a mini report about users opinions (totally: 47) and I think these informations should be interesting:

  • I'll install Vista as soon as I can or I just have Vista
    12.8 %

  • I don't believe in Vista and I'll be on XP for many other months/years
    38.3 %

  • I'm thinking to spend money for a Mac (with OSX) instead of Vista license
    8.5 %

  • I'm thinking to install Ubuntu or I'll never instal Vista (I'm just on Ubuntu or other Linux distributions)
    40.4 %


So what are You waiting for to change your OS ? Get Linux !

Wednesday, January 24, 2007

bored with something to array convertion ? map them !

I'm rewriting my JSL to include by default inside my next project.
This project will include automatically a lot of standard JS 1.5 methods or functions, and Array.map is one of those.

While I'm testing some proto performances, I've thought about a really simple way to switch from an array or from a node list (getElementsByTagName) with a simple, fast and single line of function.

// old example version
// function _A(a){return [].map.call(a,function(a){return a})};

// new version, Daniel suggest, faster and doesn't require any prototype !
function _A(a){return [].slice.call(a)};

and that's all, do You like it ?

As first point, You need FireFox 1 or greater (or Mozilla if You prefere) or this short piece of code:

if(!Array.prototype.map) Array.prototype.map = function(callback){
for(var i = 0, j = this.length, result = new Array(j), self = arguments[1], u; i < j; i++) {
if(this[i] !== u)
result[i] = callback.call(self, this[i], i, this);
};
return result;
};


Then You have "everything You need" to get quickly every iterable element.

These are just two examples

function sort(){
return _A(arguments).sort().join("<br />");
};
document.writeln(sort("Luke", "Jabba", "Fenner"));
document.writeln(sort("c", "a", "b"));



var firstScript = _A(document.getElementsByTagName("script")).shift();
alert(firstScript);

var allUnorderedList = _A(document.getElementsByTagName("ul"));

alert(_A(null).constructor === Array); // true ;-)


These nice trick should be used with forEach method too.
Stop for and while loops, each them !

function changeLinks(onclick){
[].forEach.apply(document.getElementsByTagName("a"),
function(link){
link.onclick = onclick;
});
};

changeLinks(function(){
window.open(this.href, "");
return false;
});


... and sure, You need forEach prototype too ...

I suppose every other JS 1.5 Array method should be cool enought to work with DOM nodes too ... do You agree ?

Are thinking about performances ? Well guys, quite the same of generic loops, even faster (works in core) with every FireFox !!!

Thursday, January 18, 2007

JavaScript Unobtrusive Security Form

In some cases JavaScript should be used to add more security during a client/servr interaction.

Paul Johnston knows this and tha's why He created md5 and sha1 hashing JavaScript implemntations.

You can choose to send just hashed form variables, to be sure, for example, that recieved stirngs are valid hash and they are present on db (removing sql injections problems).

You could even create special hashed strings too, to forget "man in the middle" problems, using a salt that will be generated and verified from server side code.

This hashed value could make your password more secure, requiring a kind of brute force that will be quite hard to do.

// man in the middle found the salt and the logging string
$try = 12345;
if(hash($salt.hash($try)))
echo 'Passwrod or collision found: '.$try;
else {
$try = 12346;
if(hash($salt.hash($try)))
// ... and again, again ..
// every time with a double hashed string ( slower than a single :D )
}


At the same time, this salt creates a collisions free hashed string, then a brute force operation should not be used to login in a form like this one because new salt , hashed with collision, will not produce a compatible authorizzation hashed string (or better, it's really difficult that a collision, hashed with a different string, will produce another collision).

This form is absolutely WAI-AAA WatchFire approved, valid W3C XHTML 1.1 and valid W3 CSS.
It's unobtrusive, works without JavaScript too (in a less secure way) and SecurityForm JavaScript function should be used in every kind of form, just modifing form and inputs id as You want.

This is a basic php example page, compatible with PHP 4.3 or 5 or 5.2, that shows how You should "drive correctly" login operation.

I hope code description is enought to understand this kind of form and I suggest to use sha1 instead of md5 (better security).

This is a short description:

  1. Client verify user and pass, if these are not empty call form.action page to recieve a new salt ($salt = uniqid(rand(), true)) sending just userName

  2. Server generates a new salt then it saves them on a simple table adding userName and time() so it sends them as SecurityForm onload callback

  3. Client recieves this new uniq string and generates a logging variable

    logging = choosedHash(salt + choosedHash(userPassword))

    and redirects client to authentication page sending uniqid recieved from server, userName and loging

  4. Server verify that salt table contains recieved salt and verify if found userName is the same of GET value, then verify that logging is a valid authorizzation string:

    // example query
    $query = 'SELECT * FROM user_list WHERE user = $user AND MD5(CONCAT($salt, pass)) = $logging';

    where pass is just hashed during registration

  5. server removes recieved salt from table and other salts with expire less than time() - 30 seconds



... and that's all.
Are You sure, now, that your user with JS enabled are a bit more protected ? :-)
(of course, SSL is absolutely the best way to "ensure privacy" ... but You could implement this kind of form with SSL too)


What about compatibility list ?
Well, every JavaScript compatible browser, starting from IE 5 and every JavaScript disabled or uncompatible browser too.

Monday, January 15, 2007

a little error choosing byte family plugin namespace :D

Well ... not much things to tell You .. just sorry for my last plugin namespace choice.

Now that I know What does it mean (thanks to Dean and Mario) I've changed namespace, Welcome overbyte plugin library :D

(probably the uniq plugin I need is one for my English, not for my libraries ... :E)

Friday, January 12, 2007

prototype, singleton, what else ?

A lot or JS developers use prototype style to write (extends) classes (functions) or singleton to have a private scope.

I often use different ways to create my classes (function) and I use prototype only to extend and not to create.

These are some examples:

/** prototype style */
// class Blog
function Blog(){};

// prototype to extend Blog
Blog.prototype = {
getName:function(){
return this.name;
},
setName:function(name){
this.name = name;
},
name:""
};


// how to use Blog class
var myblog = new Blog;
// new Blog() with parenthesis is not useful.
// full prototype style "doesn't accept"
// parameters on constructor
// (or better, it accepts but doesn't use them)

myblog.setName("WebReflection");
// setName is absolutely necessary to set public
// name parameter

/** prototype style */



/** singleton style */
function Blog(name){
return {
getName:function(){
return name;
// name has a global scope
// in this object, private
// for every other external scripts
}
};
};

// how to use this Blog function
var myblog = Blog("WebReflection");

// Singleton style should accept one or more
// arguments on fake constractor.
// myblog is an instanceof Object and
// is not a Blog class (I've not used new to set this var)

The first important difference is that with Singleton you don't need to create setName because a blog name shouldn't be modified from other scripts (in this example).
Then why You should declare public parameter (classVar.name) or public methods (classVar.setName) when a property shouldn't be changable ?

This is a common full prototype style problem, everything is public and everything should be modified from other scripts.

In the other hand, with above Singleton example You don't create an instance of Blog, just recieve everytime a new Object.

With prototype = {something} Your varible will be an instance of className but constructor will be an Object while if You declare every method "manually" variable constructor will be exactly the original function.

function Person1(){};
Person1.prototype = {
getClassName:function(){return "Person1"},
isPerson1:function(){return this instanceof Person1}
};
var p1 = new Person1;
document.write([
p1.getClassName(),
p1.isPerson1(),
p1.constructor,
p1.constructor === Person1
] + "
");
// Person1,true,function Object() { [native code] },false


function Person2(){};
Person2.prototype.getClassName = function(){return "Person1"};
Person2.prototype.isPerson2 = function(){return this instanceof Person2};
var p2 = new Person2;
document.write([
p2.getClassName(),
p2.isPerson2(),
p2.constructor,
p2.constructor === Person2
]);
// Person1,true,function Person2() { },true

For many developers it is a feature, because they think that native code is faster than function eveluation (that should be performed every time) ... however, I've never seen performance differences from prototype style and other styles.
Think that func by func prototype doesn't work as single object too, then I suppose there are a lot of scripts that clones prototype (or extends them) using a for in loop and that these scripts doesn't perform better (if it's true) than others.

This is another way, not native, to have both instanceof class and private scope on object You should do something like that:

function Blog(name){
this.getName = function(){
return name;
// as Singleton, name has
// a global scope inside this
// instance, private for
// every other script
};
};

// You could set private methods too ...
function Blog(name){

// private method, global scope
// inside this instance
function setName(){
selfname = arguments[0] || name;
};

// private variable
var selfname;

this.getName = function(){
setName(name);
return selfname;
};
};

var myblog = new Blog("WebReflection");
// You have an instanceof class Blog with
// a private internal scope and an external one


These kind of class instances are not possible to create with full prototype style and in this case evey instance will not be modified if other scripts changes Blog.prototype.getName with a new function.

function Blog(name){
function setName(){selfname = arguments[0] || name};
var selfname;
this.getName = function(){
setName(name);
return selfname;
};
};
Blog.prototype.getName = function(){
return "prototype doesn't change anything";
};

var myblog = new Blog("WebReflection");
document.write(myblog.getName()); // WebReflection

So this way should be thought as "more secure" than others because created instance will not be affected by prototype changes on constructor or on global Object, however, Singleton should be secure too.


function Blog(){
return {getName:function(){return "WebReflection"}}
};
Blog.prototype.getName = function(){
return "override";
};
Object.prototype.getName = function(){
return "override";
};

var myblog = new Blog;
document.write(myblog.getName()); // WebReflection

// if You don't use new ..
var myblog2 = Blog;
document.write(myblog2.getName()); // override

As I've said, the bad thing of singleton is that resulting variable will not be an instance of used className with or without new before declaration.


Last way, if You need a single object instance in your script, You should use this way too.

Blog = new function(){

// private method
function setName(){
selfname = arguments[0] || name;
};

// private variable
var selfname;

// public method
this.getName = function(){
return selfname;
};
this.setName = function(name){
setName(name);
};
};

Blog.setName("WebReflection");
document.write(Blog.getName());

// what kind of instance ? ... it's an "anonymous secret"
document.write(Blog instanceof Function); // false
document.write(Blog instanceof Blog.constructor);// true

This example is something like Singleton without the possibility to send arguments on constructor (and this one will not be a native Object code).
So this method has a "secret" constructor but You could extend them using Blog.constructor.prototype or extend another class using new Blog.constructor.
This example should be useful when You need a single instance of an anonymous function (a bit harder to be modified from other scripts) but remember that
to create a new instance You need GlobalObj.constructor and that other scripts should change a GlobalObj.construtor with prototype.

Now, this post is just to show different ways to create an "instance of something" ... but at this point I think that:

  1. if native code constructr is really faster to execute, Singleton should be the better choice (private scope too)
  2. if speed is important (and native code is really faster) but We don't need a private scope and We need to change every method/property of every className instance, prototype style is the better choice because We can know if a var is instance of a class and not only a generic instanceof Object.
  3. if extreme speed is not a problem (or native code doesn't perform faster), the best solution should be the simple function, to know both constructor and instanceof ... but We can't change every var in a single line.
  4. if we need a single anonymous instance, we could use the last example.

The third point limit, the possibility to change every instance of a class, should be solved with a simple Object proto

Object.prototype.syncronize = function(){
for(var key in this.constructor.prototype)
this[key] = this.constructor.prototype[key];
};

function Blog(name){
function setName(){
selfname = arguments[0] || name;
};
var selfname;
this.getName = function(){
setName(name);
return selfname;
};
};

var myblog = new Blog("WebReflection");
document.write([
myblog.constructor === Blog,
myblog instanceof Blog,
myblog.getName()
]);
// true,true,WebReflection


Blog.prototype.getName = function(){
return "override";
};

document.write([
myblog.constructor === Blog,
myblog instanceof Blog,
myblog.getName()
]);
// true,true,WebReflection


myblog.syncronize();

document.write([
myblog.constructor === Blog,
myblog instanceof Blog,
myblog.getName()
]);
// true,true,override


So, wich way do You like and Why ?

Thursday, January 11, 2007

Dojo source ? 39,09 Kb generated in 0.0006 seconds

It's true, less than 40Kb for dojo.js packed file without any packer, just using my overbyte Editor

How ?
Just open dojo.js file (146Kb) with one text editor (sure, Notepad too), select all, copy and past them inside overbyte Editor working area.

Now click on download, and choose the first option as showed on image:


Save the file as dojo.php and test on your host ... so view page informations, it's less than 40Kb with all gz compatible browsers ;-)

What a news ?
The beautyful thing is that my auto-generated php file (about 300Kb) decodes this js source in less than 1 millisecond, exactly 0.0006 seconds on my "old" centrino 1.6 Ghz with Apache 2.2 and PHP 5.2 running on PAMPA !

If You consider that generated file doesn't require zlib or gzencode function, as bootstrap js or php solution, and is compatible with every php hosting solution, You can think that JS size is not a big problem because You should decrease about 5X the final size.

I don't know how many Kbytes should be a packed packer version without comments of the same file, using my Editor to generate the php page ... but don't worry, result page will be generated in less than 0.0006 seconds :-)


I don't believe You and I don't want to view your damn Editor
Well, You could view dojo.php file using this link ...

P.S. Hey Ajaxians, Why didn't You find interesting my Editor expreiment ?

Wednesday, January 10, 2007

overbyte Editor, from Alpha to Beta

Update !!!
overbyte Editor now has a Suggest Panel inside textarea !
It doesn't contain every function or method but it has a kind of intelligent code interaction, do You like it ? :D

---------------------------------------

Just a little update about my last experiment, overbyte Editor.

I've fixed a lot of bugs and now it should work correctly on IE5.5, IE6, IE7, FireFox 2 (probably 1.5 too) and Opera 9 (probably 8 too).

I don't know why Safari has some problem with menu and I'm working to solve Safari incompatibility, however, now this Editor is version beta, so You could test them or use without problems ( I mean without every Alpha release problems :D ).

Please report me bugs or features You think should be cool and good JavaScripting ! :-)

[edit]
I forget a detail ... using my GzOutput.class.php with bootstrap.php solution, this component size is less than 14Kb without jsmin :-)

jhp is about 12 Kb without jsmin too ... but I'm working on, this project will not be available so soon.

Tuesday, January 9, 2007

JavaScript get_class and is_a functions

Update a new version of get_class, works with prototype classes too.

We often need to know the type of a variable with JavaScript but every dedicated function, such typeof or instanceof, are not always perfect.

For example, the typeof a string, that should be declared as both primitive and object value, should be "string" or should be "object".

var $1 = "test",
$2 = new String($1);

alert([
typeof($2), // object
typeof($1), // string
$2 == $1, // true
$2 === $1, // false
$2 instanceof String, // true
$1 instanceof String, // false

$2.constructor === $1.constructor
// true !!!
].join("\n"));

It's quite caotic ... but perfect, but every time We need to know if a variable is exactly that kind of variable We should
verify the typeof or the constructor and the instanceof ... little boring ?

With PHP We have two nice functions (... more than two, that's why I'm developing jhp) that are perfectly to know the class name of a variable or to know if that var "is a" class type.

These are my two proposal, one to know the generic class name of a variable and one to know if a variable is a class.

function get_class(obj){ // webreflection.blogspot.com
function get_class(obj){
return "".concat(obj).replace(/^.*function\s+([^\s]*|[^\(]*)\([^\x00]+$/, "$1") || "anonymous";
};
var result = "";
if(obj === null)
result = "null";
else if(obj === undefined)
result = "undefined";
else {
result = get_class(obj.constructor);
if(result === "Object" && obj.constructor.prototype) {
for(result in this) {
if(typeof(this[result]) === "function" && obj instanceof this[result]) {
result = get_class(this[result]);
break;
}
}
}
};
return result;
};
function is_a(obj, className){ // webreflection.blogspot.com
className = className.replace(/[^\w\$_]+/, ""); // paranoia
return get_class(obj) === className && {function:1}[eval("typeof(".concat(className,")"))] && obj instanceof eval(className)
};


With get_class function You could know the name of the constructor of a variable.
This means that if You need a string, both primitive and object, You could simply do a check like this

if(get_class(somevar) === "String")
// ... do stuff, the var is exactly a string


You could even use a switch

switch(get_class(somevar)) {
case "String":
alert(somevar);
break;
case "Number":
somevar += 1;
break;
case "Boolean":
somevar = !somevar;
break;
};

... or if You prefere, a portable object ...

var operations = {
String:function(v){document.write(v); return v},
Number:function(v){return v + 1}
};
somevar = operations[get_class(somevar)](somevar);


Finally, if You want to know if a variable is exaclty a type of class You could use is_a, that's a deeper check than instanceof because doesn't verify only the instance name.

document.write([
is_a(null, "Date"), // false
is_a(undefined, "Date"), // false
is_a(Date, "Date"), // false
is_a(new Date, "Date"), // true
is_a({}, "Object"), // true
is_a([], "Array"), // true
is_a("", "String"), // false
is_a(new String(""), "String"), // true
is_a(1, "Number"), // false
is_a(new Number(1), "Number"), // true
is_a(false, "Boolean"), // false
is_a(new Boolean(0), "Boolean"),// true
is_a(/re/, "RegExp"), // true
is_a(Math, "Math"), // false
is_a(Math, "Object") // true
].join("
"));

Monday, January 8, 2007

Simple JavaScript bootstrap solution

As WebSiteOptimization suggests external JavaScript files should be included "one time for all".
There are a lot of procedures to do that, using a server-side script to include and compress required files.
This simple anonymous function should do something like dynamic JavaScript inclusion, based on unobrtusive cross-browser function and really simple to use.

The concept is this one:
when You add a script on Your page this will be exactly the last script present on document so You could do some operation using its source.

bootstrap.js does it, and works as "includer" from first file name to last.


<script type="text/javascript" src="jsfolder/bootstrap.js?jsfile"></script>

In this example bootstrap will include jsfile.js that's inside jsfolder so You just need to include bootstrap.js file inside your dedicated JavaScript files folder.

You could load multiple JS too, using char "|" as separator

<script type="text/javascript" src="jsfolder/bootstrap.js?jsfile|otherfile|init"></script>

In this case bootstrap will load jsfile.js, then otherfile.js and finally init.js, everyone automatically from folder jsfolder.

// bootstrap resulting string for inclusion
jsfolder/jsfile.js
jsfolder/otherfile.js
jsfolder/init.js


If You need to include files with a different extension, You could simply add a suffix after last file name.

<script type="text/javascript" src="jsfolder/bootstrap.js?jsfile|otherfile|init#php"></script>

// bootstrap resulting string for inclusion
jsfolder/jsfile.php
jsfolder/otherfile.php
jsfolder/init.php


Then, for example, You could pack your js code using my overbyte Editor and call saved php files quickly.

You can use any kind of extension, then PHP is not required.

You can use more than one bootstrap too, copying bootstrap.js file inside every dedicated javascript folders.

Could be this an unobtrusive and alternative way to include dynamically your libraries and functions ? ... and it's less than 500 bytes :-)

Update
Now GzOutput php class supports something like bootstrap for JS, CSS and other kind of files.

You can test PHP 4 version or PHP 5, successful tested on E_ALL | E_STRICT error_reporting enviroment.

Thursday, January 4, 2007

overbyte Editor and jhp

Happy New Year :-)

I would like to present my last idea, jhp, that's absolutely alpha and that requires "a special" component to be tested quickly ... and that's the reason of this post, a work in progress plugin for my byte family library, called overbyte Editor.

It's alpha version too and for some strange reason it doesn't work on Safari browser (but it doesn't show any error too ... ) but it's a simple online runtime JavaScript editor / debugger with some funny features that I've never seen on the net.

It's not a FireBug alternative, it's just a "quick and dirty" enviroment to test rapidly your scripts, functions, html pages and probably other.

overbyte Editor has some Extra special function, based on syncronous php interatcions or using jsmin to parse and test your code in one step.

It could open your files, save them or inject into a dedicated php file that should solve definitely bandwidth problems using both jsmin and gz features even on hosts that haven't zlib enabled (adapted version of GzOutput class without gzencode or gz_hendler).

You can read more about overbyte and jhp directly on Editor page, using About menu to read these and other Editor informations.

I'm waiting for your suggests, bug reports or comments,
bye bye :-)