File size: 224,477 Bytes
07c3cdd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
<?php
/**
 * class.g.php
 * @package gulliver.system
 *
 * ProcessMaker Open Source Edition
 * Copyright (C) 2004 - 2011 Colosa Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * For more information, contact Colosa Inc, 2566 Le Jeune Rd.,
 * Coral Gables, FL, 33134, USA, or email info@colosa.com.
 *
 */

use ProcessMaker\Core\System;
use ProcessMaker\Plugins\PluginRegistry;

/**
 * @package gulliver.system
 */

class G
{
    const hashFx = 'md5';
    const hash = 'hash';
    const hashFile = 'md5_file';
    const hashCrc = 'crc32';
    public $sessionVar = array(); //SESSION temporary array store.
    public static $sysSys;
    public static $sysSkin;
    public static $pathDataSite;
    public static $pathDocument;
    public static $memcachedEnabled;
    public static $pathDataPublic;
    public static $httpHost;

    /**
     * Adapters used for different services inside Processmaker.
     *
     * @var string[] $adapters
     */
    private static $adapters = [
        'ldap'                          => LDAP::class,
        'ldapadvanced'                  => LdapAdvanced::class,
        'dashletopenvscompleted'        => DashletOpenVsCompleted::class,
        'dashletrssreader'              => DashletRssReader::class,
        'dashletprocessmakerenterprise' => DashletProcessMakerEnterprise::class,
        'dashletprocessmakercommunity'  => DashletProcessMakerCommunity::class,
    ];

    /**
     * This function verify if exist file name in the PATH_GULLIVER
     * @param string $strClass
     * @return boolean
     */
    public function LoadSystemExist($strClass)
    {
        if (file_exists( PATH_GULLIVER . 'class.' . $strClass . '.php' )) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * @deprecated 3.2.2, We keep this function only for backwards compatibility because is used in the plugin manager
     */
    public static function LoadSystem($strClass)
    {
        //For backward compatibilities
    }

    /**
     * @deprecated 3.2.2, We keep this function only for backwards compatibility because is used in the plugin manager
     */
    public function LoadInclude($strClass)
    {
        //For backward compatibilities
    }

    /**
     * @deprecated 3.2.2, We keep this function only for backwards compatibility because is used in the plugin manager
     */
    public function LoadClassRBAC($strClass)
    {
        //For backward compatibilities
    }

    /**
     * @deprecated 3.2.2, We keep this function only for backwards compatibility because is used in the plugin manager
     */
    public static function LoadClass($strClass)
    {
        //For backward compatibilities
    }

    /**
     * @deprecated 3.2.2, We keep this function only for backwards compatibility because is used in the plugin manager
     */
    public static function LoadThirdParty($sPath, $sFile)
    {
        //For backward compatibilities
    }

    /**
     * Include all model files
     * @access public
     * @return void
     */
    public function LoadAllModelClasses()
    {
        $baseDir = PATH_CORE . 'classes' . PATH_SEP . 'model';
        if ($handle = opendir( $baseDir )) {
            while (false !== ($file = readdir( $handle ))) {
                if (strpos( $file, '.php', 1 ) && ! strpos( $file, 'Peer.php', 1 )) {
                    require_once ($baseDir . PATH_SEP . $file);
                }
            }
        }
    }

    /**
     * is_https
     * @return bool
     */
    public static function is_https()
    {
        $is_http = false;
        if ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on') ||
            (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) {
            $is_http = true;
        }
        return $is_http;
    }

    /**
     * Fill array values (recursive)
     * @access public
     * @param Array $arr
     * @param Void $value
     * @param Boolean $recursive
     * @return Array
     */
    public function array_fill_value ($arr = Array(), $value = '', $recursive = false)
    {
        if (is_array( $arr )) {
            foreach ($arr as $key => $val) {
                if (is_array( $arr[$key] )) {
                    $arr[$key] = ($recursive === true) ? G::array_fill_value( $arr[$key], $value, true ) : $val;
                } else {
                    $arr[$key] = $value;
                }
            }
        } else {
            $arr = Array ();
        }
        return $arr;
    }

    /**
     * Generate Password Random
     * $availableSets set next options:
     * l: lowercase set a-z
     * u: uppercase set A-Z
     * n: numbers set 0-9
     * s: symbols set _-+=!@#$%*&,.;:?^()[]{}<>
     * 
     * $symbol is source symbol generate
     * 
     * @param int $length
     * @param string $availableSets
     * @param string $symbol
     * @return string
     */
    public function generate_password($length = 15, $availableSets = "luns", $symbol = "_-$!")
    {
        $chars = "";
        if (strpos($availableSets, "l") !== false) {
            $chars = $chars . "abcdefghjkmnpqrstuvwxyz";
        }
        if (strpos($availableSets, "u") !== false) {
            $chars = $chars . "ABCDEFGHJKMNPQRSTUVWXYZ";
        }
        if (strpos($availableSets, "n") !== false) {
            $chars = $chars . "0123456789";
        }
        if (strpos($availableSets, "s") !== false) {
            $chars = $chars . $symbol;
        }
        $n = strlen($chars);
        do {
        $password = "";
            $i = 0;
            while ($i < $length) {
                $chars = str_shuffle($chars);
                $char = substr($chars, mt_rand(0, $n - 1), 1);
            if (!strstr($password, $char)) {
                    $password = $password . $char;
                $i++;
            }
                $password = str_shuffle($password);
        }
            $info = G::check_password($password, $length, $length, $availableSets);
        } while (!$info->isValid);
        return $password;
    }

    /**
     * Check password strong
     * 
     * $availableSets set next options:
     * l: lowercase set a-z
     * u: uppercase set A-Z
     * n: numbers set 0-9
     * s: symbols set _-+=!@#$%*&,.;:?^()[]{}<>
     * 
     * @param string $password
     * @param int $min
     * @param int $max
     * @param string $availableSets
     * @return \stdClass
     */
    public function check_password($password, $min = 2, $max = 20, $availableSets = "luns")
    {
        $info = new stdClass();
        $info->isValid = true;
        $info->error = "";
        if (strlen($password) < $min) {
            $info->error .= G::LoadTranslation("ID_PASSWORD_TOO_SHORT") . " ";
            $info->isValid = false;
        }
        if (strlen($password) > $max) {
            $info->error .= G::LoadTranslation("ID_PASSWORD_TOO_LONG") . " ";
            $info->isValid = false;
        }
        if (strpos($availableSets, "l") !== false && !preg_match("#[a-z]+#", $password)) {
            $info->error .= G::LoadTranslation("ID_PASSWORD_MUST_INCLUDE_AT_LEAST_ONE_LETTER") . " ";
            $info->isValid = false;
        }
        if (strpos($availableSets, "u") !== false && !preg_match("#[A-Z]+#", $password)) {
            $info->error .= G::LoadTranslation("ID_PASSWORD_MUST_INCLUDE_AT_LEAST_ONE_CAPS") . " ";
            $info->isValid = false;
        }
        if (strpos($availableSets, "n") !== false && !preg_match("#[0-9]+#", $password)) {
            $info->error .= G::LoadTranslation("ID_PASSWORD_MUST_INCLUDE_AT_LEAST_ONE_NUMBER") . " ";
            $info->isValid = false;
        }
        if (strpos($availableSets, "s") !== false && !preg_match("#\W+#", $password)) {
            $info->error .= G::LoadTranslation("ID_PASSWORD_MUST_INCLUDE_AT_LEAST_ONE_SYMBOL") . " ";
            $info->isValid = false;
        }
        return $info;
    }

    /**
     * Array concat
     * array_concat(ArrayToConcat,ArrayOriginal);
     *
     * @access public
     * @param Array
     * @return Array
     */
    public function array_concat ()
    {
        $nums = func_num_args();
        $vars = func_get_args();
        $ret = Array ();
        for ($i = 0; $i < $nums; $i ++) {
            if (is_array( $vars[$i] )) {
                foreach ($vars[$i] as $key => $value) {
                    $ret[$key] = $value;
                }
            }
        }
        return $ret;
    }

    /**
     * Compare Variables
     * var_compare(value,[var1,var2,varN]);
     * @access public
     * @param  void $value
     * @param  void $var1-N
     * @return Boolean
     */
    public function var_compare ($value = true)
    {
        $nums = func_num_args();
        if ($nums < 2) {
              return true;
        }
        $vars = func_get_args();
        $ret = Array ();
        for ($i = 1; $i < $nums; $i ++) {
            if ($vars[$i] !== $value) {
                return false;
            }
        }
        return true;
    }

    /**
     * Emulate variable selector
     * @access public
     * @param  void
     * @return void
     */
    public function var_probe ()
    {
        //return (!$variable)?
        $nums = func_num_args();
        $vars = func_get_args();
        for ($i = 0; $i < $nums; $i ++) {
            if ($vars[$i]) {
                return $vars[$i];
            }
        }
        return 1;
    }

    /**
     * Get the current version of gulliver classes
     *
     * @author Fernando Ontiveros Lira <fernando@colosa.com>
     * @access public
     * @return string
     */
    public function &getVersion ()
    {
        //majorVersion.minorVersion-SvnRevision
        return '3.0-1';
    }

    /**
     * getIpAddress
     * @return string $ip
     */
    public static function getIpAddress ()
    {
        if (getenv( 'HTTP_CLIENT_IP' )) {
            $ip = getenv( 'HTTP_CLIENT_IP' );
        } elseif (getenv( 'HTTP_X_FORWARDED_FOR' )) {
            $ip = getenv( 'HTTP_X_FORWARDED_FOR' );
        } else {
            $ip = getenv( 'REMOTE_ADDR' );
        }
        return $ip;
    }

    /**
     * getMacAddress
     *
     * @return string $mac
    */
    public function getMacAddress ()
    {
        if (strstr( getenv( 'OS' ), 'Windows' )) {
            $ipconfig = `ipconfig /all`;
            preg_match( '/[\dA-Z]{2,2}[\:-][\dA-Z]{2,2}[\:-][\dA-Z]{2,2}[\:-][\dA-Z]{2,2}[\:-][\dA-Z]{2,2}[\:-][\dA-Z]{2,2}/i', $ipconfig, $mac );
        } else {
            $ifconfig = `/sbin/ifconfig`;
            preg_match( '/[\dA-Z]{2,2}[\:-][\dA-Z]{2,2}[\:-][\dA-Z]{2,2}[\:-][\dA-Z]{2,2}[\:-][\dA-Z]{2,2}[\:-][\dA-Z]{2,2}/i', $ifconfig, $mac );
        }
        return isset( $mac[0] ) ? $mac[0] : '00:00:00:00:00:00';
    }

    /**
     * microtime_float
     *
     * @return array_sum(explode(' ',microtime()))
     */
    /*public static*/
    public function microtime_float ()
    {
        return array_sum( explode( ' ', microtime() ) );
    }

    /**
     * * Encrypt and decrypt functions ***
     */

    /**
     * Encrypt string
     *
     * @access public
     * 
     * @param string $string
     * @param string $key
     * @param bool $urlSafe if it is used in url
     *
     * @return string
     */
    public static function encrypt ($string, $key, $urlSafe = false)
    {
        if (strpos($string, '|', 0) !== false) {
            return $string;
        }
        $result = '';
        for ($i = 0; $i < strlen($string); $i++) {
            $char = substr($string, $i, 1);
            $keychar = substr($key, ($i % strlen($key)) - 1, 1);
            $char = chr(ord($char) + ord($keychar));
            $result .= $char;
        }

        $result = base64_encode($result);
        $search = ['/' => '°', '=' => ''];

        if ($urlSafe) {
            $search['+'] = '-';
        }

        return strtr($result, $search);
    }

    /**
     * Decrypt string
     *
     * @access public
     * 
     * @param string $string
     * @param string $key
     * @param bool $urlSafe if it is used in url
     *
     * @return string
     */
    public static function decrypt($string, $key, $urlSafe = false)
    {
        $result = '';
        $search = ['°' => '/'];

        if ($urlSafe) {
            $search['-'] = '+';
        }

        $string = strtr($string, $search);
        $complement = explode('?', $string);
        $string = base64_decode($complement[0]);

        for ($i = 0; $i < strlen($string); $i++) {
            $char = substr($string, $i, 1);
            $keychar = substr($key, ($i % strlen($key)) - 1, 1);
            $char = chr(ord($char) - ord($keychar));
            $result .= $char;
        }
        if (!empty($complement[1])) {
            $result .= '?' . $complement[1];
        }
        return $result;
    }

    /**
     * Look up an IP address direction
     *
     * @author Fernando Ontiveros Lira <fernando@colosa.com>
     * @access public
     * @param string $target
     * @return void
     */
    public function lookup ($target)
    {
        //Made compatible to PHP 5.3
        if (preg_match( "[a-zA-Z]", $target )) {
            $ntarget = gethostbyname( $target );
        } else {
            $ntarget = gethostbyaddr( $target );
        }
        return ($ntarget);
    }

    /**
     * ************* path functions ****************
     */
    public static function mk_dir ($strPath, $rights = 0770)
    {
        $folder_path = array ($strPath);
        $oldumask = umask( 0 );
        while (! @is_dir( dirname( end( $folder_path ) ) ) && dirname( end( $folder_path ) ) != '/' && dirname( end( $folder_path ) ) != '.' && dirname( end( $folder_path ) ) != '') {
            array_push( $folder_path, dirname( end( $folder_path ) ) ); //var_dump($folder_path); die;
        }

        while ($parent_folder_path = array_pop( $folder_path )) {
            if (! @is_dir( $parent_folder_path )) {
                if (! @mkdir( $parent_folder_path, $rights)) {
                    error_log( "Can't create folder \"$parent_folder_path\"");
                    //umask( $oldumask );
                }
            }
        }
        umask($oldumask);
    }

    /**
     * rm_dir
     *
     * @param string $dirName
     *
     * @return void
     */
    public static function rm_dir ($dirName)
    {
        if (! is_writable( $dirName )) {
            return false;
        }

        if (is_dir( $dirName )) {
            foreach (glob( $dirName . '/{,.}*', GLOB_BRACE ) as $file) {
                if ($file == $dirName . '/.' || $file == $dirName . '/..') {
                    continue;
                }

                if (is_dir( $file )) {
                    G::rm_dir( $file );
                } else {
                    @unlink( $file );
                }
            }

            if (strtoupper(substr(PHP_OS, 0, 3)) === "WIN") {
                $dirName = str_replace("/", "\\", $dirName);

                exec("DEL /F /S /Q " . $dirName . "", $res);
                exec("RD /S /Q " . $dirName . "", $res);
            } else {
                @rmdir($dirName);
            }
        } else {
            @unlink( $dirName );
        }
    }

    /**
     * Delete all the directory tree cotents.
     * @param string $dir
     * @return void
     */
    public function delTree($dir)
    {
        $files = glob( $dir . '*', GLOB_MARK );
        foreach ($files as $file ) {
            if (substr( $file, -1 ) == '/' ) {
                self::delTree( $file );
            } else {
                unlink( $file );
            }
        }
        if (is_dir($dir)) {
            rmdir( $dir );
        }
    }

    /**
     * Recursive copy
     * @param string $source
     * @param string $destination
     * @return boolean
     */
    function recursive_copy ($source, $destination) {
        if ($source == $destination) {
            return false;
        }
        $dir = opendir($source);

        if (!file_exists($destination)) {
            G::mk_dir($destination, 0777);
        }

        while (false !== ( $file = readdir($dir))) {
            if (( $file != '.' ) && ( $file != '..' )) {
                if ( is_dir($source . '/' . $file) ) {
                    self::recursive_copy($source . '/' . $file, $destination . '/' . $file);
                } else {
                    copy($source . '/' . $file, $destination . '/' . $file);
                }
            }
        }
        closedir($dir);
        return true;
    }

    /**
     * verify path
     *
     * @author Fernando Ontiveros Lira <fernando@colosa.com>
     * @access public
     * @param string $strPath path
     * @param boolean $createPath if true this public function will create the path
     * @return boolean
     */
    public static function verifyPath ($strPath, $createPath = false)
    {
        $folder_path = strstr( $strPath, '.' ) ? dirname( $strPath ) : $strPath;

        if (file_exists( $strPath ) || @is_dir( $strPath )) {
            return true;
        } else {
            if ($createPath) {
                //TODO:: Define Environment constants: Devel (0777), Production (0770), ...
                G::mk_dir( $strPath, 0777 );
            } else {
                return false;
            }
        }
        return false;
    }

    /**
     * Expand the path using the path constants
     *
     * @author Fernando Ontiveros Lira <fernando@colosa.com>
     * @access public
     * @param string $strPath
     * @return string
     */
    public static function expandPath ($strPath = '')
    {
        $res = "";
        $res = PATH_CORE;
        if ($strPath != "") {
            $res .= $strPath . "/";
        }
        return $res;
    }


    /**
     * Render Page
     *
     * @author Fernando Ontiveros Lira <fernando@colosa.com>
     * @access public
     * @param object $objContent
     * @param string $strTemplate
     * @param string $strSkin
     * @return void
     */
    public static function RenderPage ($strTemplate = "default", $strSkin = SYS_SKIN, $objContent = null, $layout = '')
    {
        global $G_CONTENT;
        global $G_TEMPLATE;
        global $G_SKIN;
        global $G_PUBLISH;

        $G_CONTENT = $objContent;
        $G_TEMPLATE = $strTemplate;
        $G_SKIN = $strSkin;

        try {
            $file = G::ExpandPath( 'skinEngine' ) . 'skinEngine.php';
            include $file;
            $skinEngine = new SkinEngine( $G_TEMPLATE, $G_SKIN, $G_CONTENT );
            $skinEngine->setLayout( $layout );
            $skinEngine->dispatch();
        } catch (Exception $e) {
            global $G_PUBLISH;
            if (is_null( $G_PUBLISH )) {
                $G_PUBLISH = new Publisher();
            }
            if (count( $G_PUBLISH->Parts ) == 1) {
                array_shift( $G_PUBLISH->Parts );
            }
            global $oHeadPublisher;
            $leimnudInitString = $oHeadPublisher->leimnudInitString;
            $oHeadPublisher->clearScripts();
            $oHeadPublisher->leimnudInitString = $leimnudInitString;
            $oHeadPublisher->addScriptFile( '/js/maborak/core/maborak.js' );
            $G_PUBLISH->AddContent( 'xmlform', 'xmlform', 'login/showMessage', null, array ('MESSAGE' => self::getErrorMessage($e)
            ) );
            if (class_exists( 'SkinEngine' )) {
                $skinEngine = new SkinEngine( 'publish', 'blank', '' );
                $skinEngine->dispatch();
            } else {
                die( self::getErrorMessage($e) );
            }
        }
    }

    /**
     * Load a skin
     *
     * @author Fernando Ontiveros Lira <fernando@colosa.com>
     * @access public
     * @param string $strSkinName
     * @return void
     */
    public function LoadSkin ($strSkinName)
    {
        //print $strSkinName;
        //now, we are using the skin, a skin is a file in engine/skin directory
        $file = G::ExpandPath( "skins" ) . $strSkinName . ".php";
        //G::pr($file);
        if (file_exists( $file )) {
            require_once ($file);
            return;
        } else {
            if (file_exists( PATH_HTML . 'errors/error703.php' )) {
                header( 'location: /errors/error703.php' );
                die();
            } else {
                $text = "The Skin $file does not exist, please review the Skin Definition";
                throw (new Exception( $text ));
            }
        }

    }


    /**
     * Include all model plugin files
     *
     * LoadAllPluginModelClasses
     *
     * @author Hugo Loza <hugo@colosa.com>
     * @access public
     * @return void
     */
    public function LoadAllPluginModelClasses ()
    {
        //Get the current Include path, where the plugins directories should be
        if (! defined( 'PATH_SEPARATOR' )) {
            define( 'PATH_SEPARATOR', (substr( PHP_OS, 0, 3 ) == 'WIN') ? ';' : ':' );
        }
        $path = explode( PATH_SEPARATOR, get_include_path() );

        foreach ($path as $possiblePath) {
            if (strstr( $possiblePath, "plugins" )) {
                $baseDir = $possiblePath . 'classes' . PATH_SEP . 'model';
                if (file_exists( $baseDir )) {
                    if ($handle = opendir( $baseDir )) {
                        while (false !== ($file = readdir( $handle ))) {
                            if (strpos( $file, '.php', 1 ) && ! strpos( $file, 'Peer.php', 1 )) {
                                require_once ($baseDir . PATH_SEP . $file);
                            }
                        }
                    }
                    
                }
            }
        }
    }

    /**
     * Load a template
     *
     * @author Fernando Ontiveros Lira <fernando@colosa.com>
     * @access public
     * @param string $strTemplateName
     * @return void
     */
    public function LoadTemplate ($strTemplateName)
    {
        if ($strTemplateName == '') {
            return;
        }

        $temp = $strTemplateName . ".php";
        $file = G::ExpandPath( 'templates' ) . $temp;
        // Check if its a user template
        if (file_exists( $file )) {
            //require_once( $file );
            include ($file);
        } else {
            // Try to get the global system template
            $file = PATH_TEMPLATE . PATH_SEP . $temp;
            //require_once( $file );
            if (file_exists( $file )) {
                include ($file);
            }
        }
    }

    /**
     * Encrypt URL
     *
     * @author Fernando Ontiveros Lira <fernando@colosa.com>
     * @access public
     * @param string $urlLink
     * @return string
     */
    public function encryptlink ($url)
    {
        if (defined( 'ENABLE_ENCRYPT' ) && ENABLE_ENCRYPT == 'yes') {
            return urlencode( G::encrypt( $url, URL_KEY ) );
        } else {
            return $url;
        }
    }

    /**
     * Parsing the URI
     *
     * @author Fernando Ontiveros Lira <fernando@colosa.com>
     * @access public
     * @param string $urlLink
     * @return string
     */
    static public function parseURI ($uri, $isRestRequest = false)
    {
        //*** process the $_POST with magic_quotes enabled
        // The magic_quotes_gpc feature has been DEPRECATED as of PHP 5.3.0.
        if (get_magic_quotes_gpc() === 1) {
            $_POST = G::strip_slashes( $_POST );
        }

        $aRequestUri = explode( '/', $uri );
        if ($isRestRequest) {
            $args = self::parseRestUri( $aRequestUri );
        } else {
            $args = self::parseNormalUri( $aRequestUri );
        }

        define( "SYS_LANG", $args['SYS_LANG'] );
        define( "SYS_SKIN", $args['SYS_SKIN'] );
        define( 'SYS_COLLECTION', $args['SYS_COLLECTION'] );
        define( 'SYS_TARGET', $args['SYS_TARGET'] );

        if ($args['SYS_COLLECTION'] == 'js2') {
            print "ERROR";
            die();
        }
    }

    public function parseNormalUri ($aRequestUri)
    {
        if (substr( $aRequestUri[1], 0, 3 ) == 'sys') {
            define( 'SYS_TEMP', substr( $aRequestUri[1], 3 ) );
        } else {
            define( "ENABLE_ENCRYPT", 'yes' );
            define( 'SYS_TEMP', $aRequestUri[1] );
            $plain = '/sys' . SYS_TEMP;

            for ($i = 2; $i < count( $aRequestUri ); $i ++) {
                $decoded = G::decrypt( urldecode( $aRequestUri[$i] ), URL_KEY );
                if ($decoded == 'sWì›') {
                    $decoded = $VARS[$i]; //this is for the string  "../"
                }
                $plain .= '/' . $decoded;
            }
            $_SERVER["REQUEST_URI"] = $plain;
        }

        $work = explode( '?', $_SERVER["REQUEST_URI"] );

        if (count( $work ) > 1) {
            define( 'SYS_CURRENT_PARMS', $work[1] );
        } else {
            define( 'SYS_CURRENT_PARMS', '' );
        }

        define( 'SYS_CURRENT_URI', $work[0] );

        if (! defined( 'SYS_CURRENT_PARMS' )) {
            define( 'SYS_CURRENT_PARMS', $work[1] );
        }

        $preArray = explode( '&', SYS_CURRENT_PARMS );
        $buffer = explode( '.', $work[0] );

        if (count( $buffer ) == 1) {
            $buffer[1] = '';
        }

        //request type
        define( 'REQUEST_TYPE', ($buffer[1] != "" ? $buffer[1] : 'html') );

        $toparse = substr( $buffer[0], 1, strlen( $buffer[0] ) - 1 );
        $uriVars = explode( '/', $toparse );

        unset( $work );
        unset( $buffer );
        unset( $toparse );
        array_shift( $uriVars );

        $args = array ();
        $args['SYS_LANG'] = array_shift( $uriVars );
        $args['SYS_SKIN'] = array_shift( $uriVars );
        $args['SYS_COLLECTION'] = array_shift( $uriVars );
        $args['SYS_TARGET'] = array_shift( $uriVars );

        //to enable more than 2 directories...in the methods structure
        while (count( $uriVars ) > 0) {
            $args['SYS_TARGET'] .= '/' . array_shift( $uriVars );
        }

        /* Fix to prevent use uxs skin outside siplified interface,
        because that skin is not compatible with others interfaces*/
        if ($args['SYS_SKIN'] == 'uxs' && $args['SYS_COLLECTION'] != 'home' && $args['SYS_COLLECTION'] != 'cases') {
            $config = System::getSystemConfiguration();
            $args['SYS_SKIN'] = $config['default_skin'];
        }

        return $args;
    }

    public function parseRestUri ($requestUri)
    {
        $args = array ();
        //$args['SYS_TEMP'] = $requestUri[1];
        define( 'SYS_TEMP', $requestUri[2] );
        $restUri = '';

        for ($i = 3; $i < count( $requestUri ); $i ++) {
            $restUri .= '/' . $requestUri[$i];
        }

        $args['SYS_LANG'] = 'en'; // TODO, this can be set from http header
        $args['SYS_SKIN'] = '';
        $args['SYS_COLLECTION'] = '';
        $args['SYS_TARGET'] = $restUri;

        return $args;
    }

    public function strip_slashes ($vVar)
    {
        if (is_array( $vVar )) {
            foreach ($vVar as $sKey => $vValue) {
                if (is_array( $vValue )) {
                    G::strip_slashes( $vVar[$sKey] );
                } else {
                    $vVar[$sKey] = stripslashes( $vVar[$sKey] );
                }
            }
        } else {
            $vVar = stripslashes( $vVar );
        }

        return $vVar;
    }

    /**
     * function to calculate the time used to render a page
     */
    public function logTimeByPage ()
    {
        if (! defined( PATH_DATA )) {
            return false;
        }

        $serverAddr = $_SERVER['SERVER_ADDR'];
        global $startingTime;
        $endTime = microtime( true );
        $time = $endTime - $startingTime;
        $fpt = fopen( PATH_DATA . 'log/time.log', 'a' );
        fwrite( $fpt, sprintf( "%s.%03d %15s %s %5.3f %s\n", date( 'Y-m-d H:i:s' ), $time, getenv( 'REMOTE_ADDR' ), substr( $serverAddr, - 4 ), $time, $_SERVER['REQUEST_URI'] ) );
        fclose( $fpt );
    }

    /**
     * streaming a big JS file with small js files
     *
     * @author Fernando Ontiveros Lira <fernando@colosa.com>
     * @access public
     * @param string $file
     * @return string
     */
    public function streamCSSBigFile ($filename)
    {
        header( 'Content-Type: text/css' );

        //First get Skin info
        $filenameParts = explode( "-", $filename );
        $skinName = $filenameParts[0];
        $skinVariant = "skin";

        if (isset( $filenameParts[1] )) {
            $skinVariant = strtolower( $filenameParts[1] );
        }

        $configurationFile = '';
        if ($skinName == "jscolors") {
            $skinName = "classic";
        }
        if ($skinName == "xmlcolors") {
            $skinName = "classic";
        }
        if ($skinName == "classic") {
            $configurationFile = G::ExpandPath( "skinEngine" ) . 'base' . PATH_SEP . 'config.xml';
        } else {
            $configurationFile = PATH_CUSTOM_SKINS . $skinName . PATH_SEP . 'config.xml';

            if (! is_file( $configurationFile )) {
                $configurationFile = G::ExpandPath( "skinEngine" ) . $skinName . PATH_SEP . 'config.xml';
            }
        }

        //Read Configuration File
        $xmlConfiguration = file_get_contents( $configurationFile );
        $xmlConfigurationObj = G::xmlParser( $xmlConfiguration );
        $baseSkinDirectory = dirname( $configurationFile );
        $directorySize = G::getDirectorySize( $baseSkinDirectory );
        $mtime = $directorySize['maxmtime'];

        $outputHeader = "/* Autogenerated CSS file by gulliver framework \n";
        $outputHeader .= "   Skin: $filename\n";
        $mtimeNow = date( 'U' );
        $gmt_mtimeNow = gmdate( "D, d M Y H:i:s", $mtimeNow ) . " GMT";
        $outputHeader .= "   Date: $gmt_mtimeNow*/\n";
        $output = "";
        //Base files
        switch (strtolower( $skinVariant )) {
            case "extjs":
                //Base
                $baseCSSPath = PATH_SKIN_ENGINE . "base" . PATH_SEP . "baseCss" . PATH_SEP;
                $output .= file_get_contents( $baseCSSPath . 'ext-all-notheme.css' );

                //Classic Skin
                $extJsSkin = 'xtheme-gray';
                break;
            default:
                break;
        }

        //Get Browser Info
        $infoBrowser = G::browser_detection( 'full_assoc' );
        $browserName = $infoBrowser['browser_working'];
        if (isset( $infoBrowser[$browserName . '_data'] )) {
            if ($infoBrowser[$browserName . '_data'][0] != "") {
                $browserName = $infoBrowser[$browserName . '_data'][0];
            }
        }

        //Read Configuration File
        $xmlConfiguration = file_get_contents ( $configurationFile );
        $xmlConfigurationObj = G::xmlParser($xmlConfiguration);

        $skinFilesArray = $xmlConfigurationObj->result['skinConfiguration']['__CONTENT__']['cssFiles']['__CONTENT__'][$skinVariant]['__CONTENT__']['cssFile'] ;
        foreach ($skinFilesArray as $keyFile => $cssFileInfo) {
            $enabledBrowsers  = explode(",", $cssFileInfo['__ATTRIBUTES__']['enabledBrowsers']);
            $disabledBrowsers = explode(",", $cssFileInfo['__ATTRIBUTES__']['disabledBrowsers']);

            if (((in_array($browserName, $enabledBrowsers)) || (in_array('ALL', $enabledBrowsers)))&&(!(in_array($browserName, $disabledBrowsers)))) {
                if ($cssFileInfo['__ATTRIBUTES__']['file'] == 'rtl.css') {
                    $oServerConf =& ServerConf::getSingleton();
                    if (!(defined('SYS_LANG'))) {
                        if (isset($_SERVER['HTTP_REFERER'])) {
                            $syss = explode('://', $_SERVER['HTTP_REFERER']);
                            $sysObjets =  explode('/', $syss['1']);
                            $sysLang = $sysObjets['2'];
                        } else {
                            $sysLang = 'en';
                        }
                    } else {
                        $sysLang = SYS_LANG;
                    }
                    if ($oServerConf->isRtl($sysLang)) {
                        $output .= file_get_contents ( $baseSkinDirectory . PATH_SEP.'css'.PATH_SEP.$cssFileInfo['__ATTRIBUTES__']['file'] );
                    }
                } else {
                    $output .= file_get_contents ( $baseSkinDirectory . PATH_SEP.'css'.PATH_SEP.$cssFileInfo['__ATTRIBUTES__']['file'] );
                }
            }
        }

        //Remove comments..
        $regex = array ("`^([\t\s]+)`ism" => '',"`^\/\*(.+?)\*\/`ism" => "","`([\n\A;]+)\/\*(.+?)\*\/`ism" => "$1","`([\n\A;\s]+)//(.+?)[\n\r]`ism" => "$1\n","`(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+`ism" => "\n" );
        $output = preg_replace( array_keys( $regex ), $regex, $output );
        $output = $outputHeader . $output;

        return $output;
    }

    /**
     * streaming the translation.<lang>.js file
     * take the WEB-INF/translation.<lang> file and append it to file js/widgets/lang/<lang>.js file
     *
     * @author Fernando Ontiveros Lira <fernando@colosa.com>
     * @access public
     * @param string $file
     * @param boolean $download
     * @param string $downloadFileName
     * @return string
     */
    public function streamJSTranslationFile ($filename, $locale = 'en')
    {
        $defaultTranslations = Array ();
        $foreignTranslations = Array ();

        //if the default translations table doesn't exist we can't proceed
        if (! is_file( PATH_LANGUAGECONT . 'translation.en' )) {
            return ;
        }
        //load the translations table
        require_once (PATH_LANGUAGECONT . 'translation.en');
        $defaultTranslations = $translation;

        //if some foreign language was requested and its translation file exists
        if ($locale != 'en' && file_exists( PATH_LANGUAGECONT . 'translation.' . $locale )) {
            require_once (PATH_LANGUAGECONT . 'translation.' . $locale); //load the foreign translations table
            $foreignTranslations = $translation;
        }

        if (defined( "SHOW_UNTRANSLATED_AS_TAG" ) && SHOW_UNTRANSLATED_AS_TAG != 0) {
            $translation = $foreignTranslations;
        } else {
            $translation = array_merge( $defaultTranslations, $foreignTranslations );
        }

        $calendarJs = '';
        $calendarJsFile = PATH_GULLIVER_HOME . "js/widgets/js-calendar/lang/" . $locale .".js";
        if (! file_exists($calendarJsFile)) {
            $calendarJsFile = PATH_GULLIVER_HOME . "js/widgets/js-calendar/lang/en.js";
        }
        $calendarJs = file_get_contents($calendarJsFile) . "\n";

        return $calendarJs . 'var TRANSLATIONS = ' . G::json_encode( $translation ) . ';' ;
    }

    /**
     * streaming a file
     *
     * @author Fernando Ontiveros Lira <fernando@colosa.com>
     * @access public
     * @param string $file
     * @param boolean $download
     * @param string $downloadFileName
     * @return string
     */
    public static function streamFile ($file, $download = false, $downloadFileName = '')
    {

        $filter = new InputFilter();
        $file = $filter->xssFilterHard($file);
        if(isset($_SERVER['REQUEST_URI'])) {
            $_SERVER['REQUEST_URI'] = $filter->xssFilterHard($_SERVER['REQUEST_URI'],"url");
        }
        require_once (PATH_THIRDPARTY . 'jsmin/jsmin.php');
        $folderarray = explode( '/', $file );
        $typearray = explode( '.', basename( $file ) );
        $typefile = $typearray[count( $typearray ) - 1];
        $filename = $file;

        //trick to generate the translation.language.js file , merging two files
        if (strtolower( $typefile ) == 'js' && $typearray[0] == 'translation') {
            $download = $filter->xssFilterHard($download);
            $downloadFileName = $filter->xssFilterHard($downloadFileName);
            G::sendHeaders( $filename, 'text/javascript', $download, $downloadFileName );
            $output = G::streamJSTranslationFile( $filename, $typearray[1] );
            $output = $filter->xssFilterHard($output);
            print $output;
            return;
        }

        //trick to generate the big css file for ext style .
        if (strtolower( $typefile ) == 'css' && $folderarray[count( $folderarray ) - 2] == 'css') {
            G::sendHeaders( $filename, 'text/css', $download, $downloadFileName );
            $output = G::streamCSSBigFile( $typearray[0] );
            $output = $filter->xssFilterHard($output);
            print $output;
            return;
        }

        if (file_exists( $filename )) {
            switch (strtolower( $typefile )) {
                case 'swf':
                    G::sendHeaders( $filename, 'application/x-shockwave-flash', $download, $downloadFileName );
                    break;
                case 'js':
                    G::sendHeaders( $filename, 'text/javascript', $download, $downloadFileName );
                    break;
                case 'htm':
                case 'html':
                    G::sendHeaders( $filename, 'text/html', $download, $downloadFileName );
                    break;
                case 'htc':
                    G::sendHeaders( $filename, 'text/plain', $download, $downloadFileName );
                    break;
                case 'json':
                    G::sendHeaders( $filename, 'text/plain', $download, $downloadFileName );
                    break;
                case 'gif':
                    G::sendHeaders( $filename, 'image/gif', $download, $downloadFileName );
                    break;
                case 'png':
                    G::sendHeaders( $filename, 'image/png', $download, $downloadFileName );
                    break;
                case 'jpg':
                    G::sendHeaders( $filename, 'image/jpg', $download, $downloadFileName );
                    break;
                case 'css':
                    G::sendHeaders( $filename, 'text/css', $download, $downloadFileName );
                    break;
                case 'xml':
                    G::sendHeaders( $filename, 'text/xml', $download, $downloadFileName );
                    break;
                case 'txt':
                    G::sendHeaders( $filename, 'text/html', $download, $downloadFileName );
                    break;
                case 'pdf':
                    G::sendHeaders( $filename, 'application/pdf', $download, $downloadFileName );
                    break;
                case 'doc':
                case 'pm':
                case 'po':
                    G::sendHeaders( $filename, 'application/octet-stream', $download, $downloadFileName );
                    break;
                case 'php':
                    if ($download) {
                        G::sendHeaders( $filename, 'text/plain', $download, $downloadFileName );
                    } else {
                        if (\Bootstrap::getDisablePhpUploadExecution() === 0) {
                            \Bootstrap::registerMonologPhpUploadExecution('phpExecution', 200, 'Php Execution', $filename);
                            require_once ($filename);
                        } else {
                            $message = G::LoadTranslation('THE_PHP_FILES_EXECUTION_WAS_DISABLED');
                            \Bootstrap::registerMonologPhpUploadExecution('phpExecution', 550, $message, $filename);
                            echo $message;
                        }
                        return;
                    }
                    break;
                case 'tar':
                    G::sendHeaders( $filename, 'application/x-tar', $download, $downloadFileName );
                    break;
                default:
                    //throw new Exception ( "Unknown type of file '$file'. " );
                    G::sendHeaders( $filename, 'application/octet-stream', $download, $downloadFileName );
                    break;
            }
        } else {
            if (strpos( $file, 'gulliver' ) !== false) {
                list ($path, $filename) = explode( 'gulliver', $file );
            }

            $_SESSION['phpFileNotFound'] = $file;
            G::header( "location: /errors/error404.php?l=" . $_SERVER['REQUEST_URI'] );
        }

        if ( substr($filename,-10) == "ext-all.js" ) {
            $filename = PATH_GULLIVER_HOME . 'js/ext/min/ext-all.js';
        }
        @readfile( $filename );
    }

    /**
     * sendHeaders
     *
     * @param string $filename
     * @param string $contentType default value ''
     * @param boolean $download default value false
     * @param string $downloadFileName default value ''
     *
     * @return void
     */
    public function sendHeaders ($filename, $contentType = '', $download = false, $downloadFileName = '')
    {
        if ($download) {
            if ($downloadFileName == '') {
                $aAux = explode('/', $filename);
                $downloadFileName = $aAux[count($aAux) - 1];
            }
            header('Content-Disposition: attachment; filename="' . $downloadFileName . '"');
        } else {
            header('Content-Disposition: inline; filename="' . $downloadFileName . '"');
        }
        header('Content-Type: ' . $contentType);

        //if userAgent (BROWSER) is MSIE we need special headers to avoid MSIE behaivor.
        $userAgent = strtolower( $_SERVER['HTTP_USER_AGENT'] );
        if (preg_match( "/msie/i", $userAgent )) {
            //if ( ereg("msie", $userAgent)) {
            header( 'Pragma: cache' );

            if (file_exists( $filename )) {
                $mtime = filemtime( $filename );
            } else {
                $mtime = date( 'U' );
            }
            $gmt_mtime = gmdate( "D, d M Y H:i:s", $mtime ) . " GMT";
            header( 'ETag: "' . G::encryptOld( $mtime . $filename ) . '"' );
            header( "Last-Modified: " . $gmt_mtime );
            header( 'Cache-Control: public' );
            header( "Expires: " . gmdate( "D, d M Y H:i:s", time() + 60 * 10 ) . " GMT" ); //ten minutes
            return;
        }

        if (! $download) {

            header( 'Pragma: cache' );

            if (file_exists( $filename )) {
                $mtime = filemtime( $filename );
            } else {
                $mtime = date( 'U' );
            }
            $gmt_mtime = gmdate( "D, d M Y H:i:s", $mtime ) . " GMT";
            header( 'ETag: "' . G::encryptOld( $mtime . $filename ) . '"' );
            header( "Last-Modified: " . $gmt_mtime );
            header( 'Cache-Control: public' );
            header( "Expires: " . gmdate( "D, d M Y H:i:s", time() + 90 * 60 * 60 * 24 ) . " GMT" );
            if (isset( $_SERVER['HTTP_IF_MODIFIED_SINCE'] )) {
                if ($_SERVER['HTTP_IF_MODIFIED_SINCE'] == $gmt_mtime) {
                    header( 'HTTP/1.1 304 Not Modified' );
                    exit();
                }
            }

            if (isset( $_SERVER['HTTP_IF_NONE_MATCH'] )) {
                if (str_replace( '"', '', stripslashes( $_SERVER['HTTP_IF_NONE_MATCH'] ) ) == G::encryptOld( $mtime . $filename )) {
                    header( "HTTP/1.1 304 Not Modified" );
                    exit();
                }
            }
        }
    }

    /**
     * Transform a public URL into a local path.
     *
     * @author David S. Callizaya S. <davidsantos@colosa.com>
     * @access public
     * @param string $url
     * @param string $corvertionTable
     * @param string $realPath = local path
     * @return boolean
     */
    public function virtualURI ($url, $convertionTable, &$realPath)
    {
        foreach ($convertionTable as $urlPattern => $localPath) {
            //      $urlPattern = addcslashes( $urlPattern , '/');
            $urlPattern = addcslashes( $urlPattern, './' );
            $urlPattern = '/^' . str_replace( array ('*','?'
            ), array ('.*','.?'
            ), $urlPattern ) . '$/';
            if (preg_match( $urlPattern, $url, $match )) {
                if ($localPath === false) {
                    $realPath = $url;
                    return false;
                }
                if ($localPath != 'jsMethod') {
                    $realPath = $localPath . $match[1];
                } else {
                    $realPath = $localPath;
                }
                return true;
            }
        }
        $realPath = $url;
        return false;
    }

    /**
     * Create an encrypted unique identifier based on $id and the selected scope id.
     *
     * @author David S. Callizaya S. <davidsantos@colosa.com>
     * @access public
     * @param string $scope
     * @param string $id
     * @return string
     */
    public static function createUID ($scope, $id)
    {
        $e = $scope . $id;
        $e = G::encrypt( $e, URL_KEY );
        $e = str_replace( array ('+','/','='
        ), array ('__','_','___'
        ), base64_encode( $e ) );
        return $e;
    }

    /**
     * (Create an encrypted unique identificator based on $id and the selected scope id.) ^-1
     * getUIDName
     *
     * @author David S. Callizaya S. <davidsantos@colosa.com>
     * @access public
     * @param string $id
     * @param string $scope
     * @return string
     */
    public function getUIDName ($uid, $scope = '')
    {
        $e = str_replace( array ('=','+','/'
        ), array ('___','__','_'
        ), $uid );
        $e = base64_decode( $e );
        $e = G::decrypt( $e, URL_KEY );
        $e = substr( $e, strlen( $scope ) );
        return $e;
    }

    /* formatNumber
     *
     * @author David Callizaya <calidavidx21@yahoo.com.ar>
     * @param  int/string $num
     * @return string number
    */
    public function formatNumber ($num, $language = 'latin')
    {
        switch ($language) {
            default:
                $snum = $num;
        }
        return $snum;
    }

    /* Returns a date formatted according to the given format string
     * @author David Callizaya <calidavidx21@hotmail.com>
     * @param string $format     The format of the outputted date string
     * @param string $datetime   Date in the format YYYY-MM-DD HH:MM:SS
    */
    public function formatDate ($datetime, $format = 'Y-m-d', $lang = '')
    {
        if ($lang === '') {
            $lang = defined( SYS_LANG ) ? SYS_LANG : 'en';
        }
        $aux = explode( ' ', $datetime ); //para dividir la fecha del dia
        $date = explode( '-', isset( $aux[0] ) ? $aux[0] : '00-00-00' ); //para obtener los dias, el mes, y el año.
        $time = explode( ':', isset( $aux[1] ) ? $aux[1] : '00:00:00' ); //para obtener las horas, minutos, segundos.
        $date[0] = (int) ((isset( $date[0] )) ? $date[0] : '0');
        $date[1] = (int) ((isset( $date[1] )) ? $date[1] : '0');
        $date[2] = (int) ((isset( $date[2] )) ? $date[2] : '0');
        $time[0] = (int) ((isset( $time[0] )) ? $time[0] : '0');
        $time[1] = (int) ((isset( $time[1] )) ? $time[1] : '0');
        $time[2] = (int) ((isset( $time[2] )) ? $time[2] : '0');
        // Spanish months
        $ARR_MONTHS['es'] = array ("Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"
        );
        // English months
        $ARR_MONTHS['en'] = array ("January","February","March","April","May","June","July","August","September","October","November","December"
        );

        // Spanish days
        $ARR_WEEKDAYS['es'] = array ("Domingo","Lunes","Martes","Miércoles","Jueves","Viernes","Sábado"
        );
        // English days
        $ARR_WEEKDAYS['en'] = array ("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"
        );

        if ($lang == 'fa') {
            $number = 'persian';
        } else {
            $number = 'latin';
        }
        $d = '0' . $date[2];
        $d = G::formatNumber( substr( $d, strlen( $d ) - 2, 2 ), $number );
        $j = G::formatNumber( $date[2], $number );
        $F = isset( $ARR_MONTHS[$lang][$date[1] - 1] ) ? $ARR_MONTHS[$lang][$date[1] - 1] : '';
        $m = '0' . $date[1];
        $m = G::formatNumber( substr( $m, strlen( $m ) - 2, 2 ), $number );
        $n = G::formatNumber( $date[1], $number );
        $y = G::formatNumber( substr( $date[0], strlen( $date[0] ) - 2, 2 ), $number );
        $Y = '0000' . $date[0];
        $Y = G::formatNumber( substr( $Y, strlen( $Y ) - 4, 4 ), $number );
        $g = ($time[0] % 12);
        if ($g === 0) {
            $g = 12;
        }
        $G = $time[0];
        $h = '0' . $g;
        $h = G::formatNumber( substr( $h, strlen( $h ) - 2, 2 ), $number );
        $H = '0' . $G;
        $H = G::formatNumber( substr( $H, strlen( $H ) - 2, 2 ), $number );
        $i = '0' . $time[1];
        $i = G::formatNumber( substr( $i, strlen( $i ) - 2, 2 ), $number );
        $s = '0' . $time[2];
        $s = G::formatNumber( substr( $s, strlen( $s ) - 2, 2 ), $number );
        $names = array ('d','j','F','m','n','y','Y','g','G','h','H','i','s'
        );
        $values = array ($d,$j,$F,$m,$n,$y,$Y,$g,$G,$h,$H,$i,$s
        );
        $_formatedDate = str_replace( $names, $values, $format );
        return $_formatedDate;
    }

    /**
     * getformatedDate
     *
     * @param date $date
     * @param string $format default value 'yyyy-mm-dd',
     * @param string $lang default value ''
     *
     * @return string $ret
     */
    public static function getformatedDate ($date, $format = 'yyyy-mm-dd', $lang = '')
    {
        /**
         * ******************************************************************************************************
         * if the year is 2008 and the format is yy then -> 08
         * if the year is 2008 and the format is yyyy then -> 2008
         *
         * if the month is 05 and the format is mm then -> 05
         * if the month is 05 and the format is m and the month is less than 10 then -> 5 else digit normal
         * if the month is 05 and the format is MM or M then -> May
         *
         * if the day is 5 and the format is dd then -> 05
         * if the day is 5 and the format is d and the day is less than 10 then -> 5 else digit normal
         * if the day is 5 and the format is DD or D then -> five
         * *******************************************************************************************************
         */

        //scape the literal
        switch ($lang) {
            case 'es':
                $format = str_replace( ' del ', '[ofl]', $format );
                $format = str_replace( ' de ', '[of]', $format );
                break;
        }

        //first we must formatted the string
        $format = str_replace( 'h', '{h}', $format );
        $format = str_replace( 'i', '{i}', $format );
        $format = str_replace( 's', '{s}', $format );

        $format = str_replace( 'yyyy', '{YEAR}', $format );
        $format = str_replace( 'yy', '{year}', $format );

        $format = str_replace( 'mm', '{YONTH}', $format );
        $format = str_replace( 'm', '{month}', $format );
        $format = str_replace( 'M', '{XONTH}', $format );

        $format = str_replace( 'dd', '{DAY}', $format );
        $format = str_replace( 'd', '{day}', $format );

        if ($lang === '') {
            $lang = defined( SYS_LANG ) ? SYS_LANG : 'en';
        }

        $aux = explode( ' ', $date ); //para dividir la fecha del dia
        $date = explode( '-', isset( $aux[0] ) ? $aux[0] : '00-00-00' ); //para obtener los dias, el mes, y el año.
        $time = explode( ':', isset( $aux[1] ) ? $aux[1] : '00:00:00' ); //para obtener las horas, minutos, segundos.

        $year = (int) ((isset( $date[0] )) ? $date[0] : '0'); //year
        $month = (int) ((isset( $date[1] )) ? $date[1] : '0'); //month
        $day = (int) ((isset( $date[2] )) ? $date[2] : '0'); //day

        $h = isset( $time[0] ) ? $time[0] : '00'; //hour
        $i = isset( $time[1] ) ? $time[1] : '00'; //minute
        $s = isset( $time[2] ) ? $time[2] : '00'; //second

        $MONTHS = Array ();
        for ($j = 1; $j <= 12; $j ++) {
          $MONTHS[$j] = G::LoadTranslation( "ID_MONTH_$j", $lang );
        }

        $d = (int) $day;
        $dd = G::complete_field( $day, 2, 1 );

        //missing D

        $M = $MONTHS[$month];
        $m = (int) $month;
        $mm = G::complete_field( $month, 2, 1 );

        $yy = substr( $year, strlen( $year ) - 2, 2 );
        $yyyy = $year;

        $names = array ('{day}','{DAY}','{month}','{YONTH}','{XONTH}','{year}','{YEAR}','{h}','{i}','{s}'
        );
        $values = array ($d,$dd,$m,$mm,$M,$yy,$yyyy,$h,$i,$s
        );

        $ret = str_replace( $names, $values, $format );

        //recovering the original literal
        switch ($lang) {
            case 'es':
                $ret = str_replace( '[ofl]', ' del ', $ret );
                $ret = str_replace( '[of]', ' de ', $ret );
                break;
        }

        return $ret;
    }

    /**
     * By <erik@colosa.com>
     * Here's a little wrapper for array_diff - I found myself needing
     * to iterate through the edited array, and I didn't need to original keys for anything.
     */
    public function arrayDiff ($array1, $array2)
    {
        if (! is_array( $array1 )) {
            $array1 = (array) $array1;
        }

        if (! is_array( $array2 )) {
            $array2 = (array) $array2;
        }

        // This wrapper for array_diff rekeys the array returned
        $valid_array = array_diff( $array1, $array2 );

        // reinstantiate $array1 variable
        $array1 = array ();

        // loop through the validated array and move elements to $array1
        // this is necessary because the array_diff function returns arrays that retain their original keys
        foreach ($valid_array as $valid) {
            $array1[] = $valid;
        }
        return $array1;
    }

    /**
     *
     * @author Erik Amaru Ortiz <erik@colosa.com>
     * @name complete_field($string, $lenght, $type={1:number/2:string/3:float})
     */
    public static function complete_field ($campo, $long, $tipo)
    {
        $campo = trim( $campo );
        switch ($tipo) {
            case 1: //number
                $long = $long - strlen( $campo );
                for ($i = 1; $i <= $long; $i ++) {
                    $campo = "0" . $campo;
                }
                break;
            case 2: //string
                $long = $long - strlen( $campo );
                for ($i = 1; $i <= $long; $i ++) {
                    $campo = " " . $campo;
                }
                break;
            case 3: //float
                if ($campo != "0") {
                    $vals = explode( ".", $long );
                    $ints = $vals[0];

                    $decs = $vals[1];

                    $valscampo = explode( ".", $campo );

                    $intscampo = $valscampo[0];
                    $decscampo = $valscampo[1];

                    $ints = $ints - strlen( $intscampo );

                    for ($i = 1; $i <= $ints; $i ++) {
                        $intscampo = "0" . $intscampo;
                    }

                    //los decimales pueden ser 0 uno o dos
                    $decs = $decs - strlen( $decscampo );
                    for ($i = 1; $i <= $decs; $i ++) {
                        $decscampo = $decscampo . "0";
                    }

                    $campo = $intscampo . "." . $decscampo;
                } else {
                    $vals = explode( ".", $long );
                    $ints = $vals[0];
                    $decs = $vals[1];

                    $campo = "";
                    for ($i = 1; $i <= $ints; $i ++) {
                        $campo = "0" . $campo;
                    }
                    $campod = "";
                    for ($i = 1; $i <= $decs; $i ++) {
                        $campod = "0" . $campod;
                    }

                    $campo = $campo . "." . $campod;
                }
                break;
        }
        return $campo;
    }

    /* Escapes special characters in a string for use in a SQL statement
     * @author David Callizaya <calidavidx21@hotmail.com>
     * @param string $sqlString  The string to be escaped
     * @param string $DBEngine   Target DBMS
    */
    public function sqlEscape ($sqlString, $DBEngine = DB_ADAPTER)
    {
        $DBEngine = DB_ADAPTER;
        switch ($DBEngine) {
            case 'mysql':
                $con = Propel::getConnection( 'workflow' );
                return mysql_real_escape_string( stripslashes( $sqlString ), $con->getResource() );
                break;
            case 'myxml':
                $sqlString = str_replace( '"', '""', $sqlString );
                return str_replace( "'", "''", $sqlString );
                break;
            default:
                return addslashes( stripslashes( $sqlString ) );
                break;
        }
    }

    /**
     * Function MySQLSintaxis
     *
     * @access public
     * @return Boolean
     *
     */
    public function MySQLSintaxis ()
    {
        $DBEngine = DB_ADAPTER;
        switch ($DBEngine) {
            case 'mysql':
                return true;
                break;
            case 'mssql':
            default:
                return false;
                break;
        }
    }

    /* Returns a sql string with @@parameters replaced with its values defined
     * in array $result using the next notation:
     * NOTATION:
     *     @@  Quoted parameter acording to the SYSTEM's Database
     *     @Q  Double quoted parameter \\  \"
     *     @q  Single quoted parameter \\  \'
     *     @%  URL string
     *     @#  Non-quoted parameter
     *     @!  Evaluate string : Replace the parameters in value and then in the sql string
     *     @fn()  Evaluate string with the function "fn"
     * @author David Callizaya <calidavidx21@hotmail.com>
     */
    public static function replaceDataField ($sqlString, $result, $DBEngine = 'mysql')
    {
        if (! is_array( $result )) {
            $result = array ();
        }
        $result = $result + G::getSystemConstants();
        $__textoEval = "";
        $u = 0;
        $count = preg_match_all( '/\@(?:([\@\%\#\?\$\=\&Qq\!])([a-zA-Z\_]\w*)|([a-zA-Z\_][\w\-\>\:]*)\(((?:[^\\\\\)]*(?:[\\\\][\w\W])?)*)\))((?:\s*\[[\'"]?\w+[\'"]?\])+|\-\>([a-zA-Z\_]\w*))?/', $sqlString, $match, PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE );
        if ($count) {
            for ($r = 0; $r < $count; $r ++) {
                if (! isset( $result[$match[2][$r][0]] )) {
                    $result[$match[2][$r][0]] = '';
                }
                if (! is_array( $result[$match[2][$r][0]] )) {
                    $__textoEval .= substr( $sqlString, $u, $match[0][$r][1] - $u );
                    $u = $match[0][$r][1] + strlen( $match[0][$r][0] );
                    //Mysql quotes scape
                    if (($match[1][$r][0] == '@') && (isset( $result[$match[2][$r][0]] ))) {
                        $__textoEval .= "\"" . G::sqlEscape( $result[$match[2][$r][0]], $DBEngine ) . "\"";
                        continue;
                    }
                    //URL encode
                    if (($match[1][$r][0]=='%')&&(isset($result[$match[2][$r][0]]))) {
                        $__textoEval.=urlencode($result[$match[2][$r][0]]);
                        continue;
                    }
                    //Double quoted parameter
                    if (($match[1][$r][0]=='Q')&&(isset($result[$match[2][$r][0]]))) {
                        $__textoEval.='"'.addcslashes($result[$match[2][$r][0]],'\\"').'"';
                        continue;
                    }
                    //Single quoted parameter
                    if (($match[1][$r][0]=='q')&&(isset($result[$match[2][$r][0]]))) {
                        $__textoEval.="'".addcslashes($result[$match[2][$r][0]],'\\\'')."'";
                        continue;
                    }
                    //Substring (Sub replaceDataField)
                    if (($match[1][$r][0]=='!')&&(isset($result[$match[2][$r][0]]))) {
                        $__textoEval.=G::replaceDataField($result[$match[2][$r][0]],$result);
                        continue;
                    }
                    //Call function
                    if (($match[1][$r][0]==='')&&($match[2][$r][0]==='')&&($match[3][$r][0]!=='')) {
                        eval('$strAux = ' . $match[3][$r][0] . '(\'' . addcslashes(G::replaceDataField(stripslashes($match[4][$r][0]),$result),'\\\'') . '\');');

                        if ($match[3][$r][0] == "G::LoadTranslation") {
                            $arraySearch  = array("'");
                            $arrayReplace = array("\\'");
                            $strAux = str_replace($arraySearch, $arrayReplace, $strAux);
                        }

                        $__textoEval .= $strAux;
                        continue;
                    }
                    //Non-quoted
                    if (($match[1][$r][0]=='#')&&(isset($result[$match[2][$r][0]]))) {
                        $__textoEval.=G::replaceDataField($result[$match[2][$r][0]],$result);
                        continue;
                    }
                    //Non-quoted =
                    if (($match[1][$r][0]=='=')&&(isset($result[$match[2][$r][0]]))) {
                        $__textoEval.=G::replaceDataField($result[$match[2][$r][0]],$result);
                        continue;
                    }
                    //Objects attributes
                    if (($match[1][$r][0]=='&')&&(isset($result[$match[2][$r][0]]))) {
                        if (isset($result[$match[2][$r][0]]->{$match[6][$r][0]})) {
                            $__textoEval.=$result[$match[2][$r][0]]->{$match[6][$r][0]};
                        }
                        continue;
                    }
                }
            }
        }
        $__textoEval.=substr($sqlString,$u);
        return $__textoEval;
    }

    /**
    * Replace Grid Values
    * The tag @>GRID-NAME to open the grid and @<GRID-NAME to close the grid,
    *
    * @param type String $sContent
    * @param type Array $aFields
    * @return type String
    */
    public static function replaceDataGridField($sContent, $aFields, $nl2brRecursive = true)
    {
        $nrt     = array("\n",    "\r",    "\t");
        $nrthtml = array("(n /)", "(r /)", "(t /)");

        $sContent = G::unhtmlentities($sContent);
        $strContentAux = str_replace($nrt, $nrthtml, $sContent);

        $iOcurrences = preg_match_all('/\@(?:([\>])([a-zA-Z\_]\w*)|([a-zA-Z\_][\w\-\>\:]*)\(((?:[^\\\\\)]*(?:[\\\\][\w\W])?)*)\))((?:\s*\[[\'"]?\w+[\'"]?\])+)?/', $strContentAux, $arrayMatch1, PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE);

        if ($iOcurrences) {
            $arrayGrid = array();

            for ($i = 0; $i <= $iOcurrences - 1; $i++) {
                $arrayGrid[] = $arrayMatch1[2][$i][0];
            }

            $arrayGrid = array_unique($arrayGrid);

            //Given the set: 'valueOne', 'valueOneTwo', where the second string 
            //contains the first string, this causes the larger string to take 
            //the second, resulting in a delimitation error, to avoid this problem 
            //we first search the string larger size.
            usort($arrayGrid, function($a, $b) {
                return strlen($b) - strlen($a);
            });

            foreach ($arrayGrid as $index => $value) {
                if($value !== "") {
                    $grdName = $value;

                    $strContentAux1 = $strContentAux;
                    $strContentAux  = null;

                    $ereg = "/^(.*)@>" . $grdName . "(.*)@<" . $grdName . "(.*)$/";

                    while (preg_match($ereg, $strContentAux1, $arrayMatch2)) {
                        $strData = null;

                        if (isset($aFields[$grdName]) && is_array($aFields[$grdName])) {
                            foreach ($aFields[$grdName] as $aRow) {
                                if ($nl2brRecursive) {
                                    foreach ($aRow as $sKey => $vValue) {
                                        if (!is_array($vValue)) {
                                            $aRow[$sKey] = str_replace($nrt, $nrthtml, nl2br($aRow[$sKey]));
                                        }
                                    }
                                }
                                $strData = $strData . G::replaceDataField($arrayMatch2[2], $aRow);
                            }
                        }

                        $strContentAux1 = $arrayMatch2[1];
                        $strContentAux  = $strData . $arrayMatch2[3] . $strContentAux;
                    }

                    $strContentAux = $strContentAux1 . $strContentAux;

                }
            }
        }

        $strContentAux = str_replace($nrthtml, $nrt, $strContentAux);

        $sContent = $strContentAux;

        if ($nl2brRecursive) {
            foreach ($aFields as $sKey => $vValue) {
                if (!is_array($vValue) && !is_object($vValue)) {
                    $aFields[$sKey] = nl2br($aFields[$sKey]);
                }
            }
        }

        $sContent = G::replaceDataField($sContent, $aFields);

        return $sContent;
    }

    /* Load strings from a XMLFile.
     * @author David Callizaya <davidsantos@colosa.com>
     * @parameter $languageFile An xml language file.
     * @parameter $languageId   (es|en|...).
     * @parameter $forceParse   Force to read and parse the xml file.
     */
    public function loadLanguageFile ($filename, $languageId = '', $forceParse = false)
    {
        global $arrayXmlMessages;
        if ($languageId === '') {
            $languageId = defined( 'SYS_LANG' ) ? SYS_LANG : 'en';
        }
        $languageFile = basename( $filename, '.xml' );
        $cacheFile = substr( $filename, 0, - 3 ) . $languageId;
        if (($forceParse) || (! file_exists( $cacheFile )) || (filemtime( $filename ) > filemtime( $cacheFile ))) {
            $languageDocument = new Xml_document();
            $languageDocument->parseXmlFile( $filename );
            if (! is_array( $arrayXmlMessages )) {
                $arrayXmlMessages = array ();
            }
            $arrayXmlMessages[$languageFile] = array ();
            for ($r = 0; $r < sizeof( $languageDocument->children[0]->children ); $r ++) {
                $n = $languageDocument->children[0]->children[$r]->findNode( $languageId );
                if ($n) {
                    $k = $languageDocument->children[0]->children[$r]->name;
                    $arrayXmlMessages[$languageFile][$k] = $n->value;
                }
            }
            $f = fopen( $cacheFile, 'w' );
            fwrite( $f, "<?php\n" );
            fwrite( $f, '$arrayXmlMessages[\'' . $languageFile . '\']=' . 'unserialize(\'' . addcslashes( serialize( $arrayXmlMessages[$languageFile] ), '\\\'' ) . "');\n" );
            fwrite( $f, "?>" );
            fclose( $f );
        } else {
            require ($cacheFile);
        }
    }

    /* Funcion auxiliar Temporal:
     *   Registra en la base de datos los labels xml usados en el sistema
     * @author David Callizaya <calidavidx21@hotmail.com>
     */
    public function registerLabel ($id, $label)
    {
        return 1;
        $dbc = new DBConnection();
        $ses = new DBSession( $dbc );
        $ses->Execute( G::replaceDataField(
            'REPLACE INTO `TRANSLATION` (`TRN_CATEGORY`, `TRN_ID`, `TRN_LANG`, `TRN_VALUE`) VALUES
        ("LABEL", @@ID, "' . SYS_LANG . '", @@LABEL);', array ('ID' => $id,'LABEL' => ($label !== null ? $label : '')
        ) ) );
    }

    /**
     * Function LoadMenuXml
     *
     * @author David S. Callizaya S. <davidsantos@colosa.com>
     * @access public
     * @param eter string msgID
     * @return string
     */
    public function LoadMenuXml ($msgID)
    {
        global $arrayXmlMessages;
        if (! isset( $arrayXmlMessages['menus'] )) {
            G::loadLanguageFile( G::ExpandPath( 'content' ) . 'languages/menus.xml' );
        }
        G::registerLabel( $msgID, $arrayXmlMessages['menus'][$msgID] );
        return $arrayXmlMessages['menus'][$msgID];
    }

    /**
     * Function SendMessageXml
     *
     * @author David S. Callizaya S. <davidsantos@colosa.com>
     * @access public
     * @param eter string msgID
     * @param eter string strType
     * @param eter string file
     * @return string
     */
    public function SendMessageXml ($msgID, $strType, $file = "labels")
    {
        global $arrayXmlMessages;
        if (! isset( $arrayXmlMessages[$file] )) {
            G::loadLanguageFile( G::ExpandPath( 'content' ) . 'languages/' . $file . '.xml' );
        }
        $_SESSION['G_MESSAGE_TYPE'] = $strType;
        G::registerLabel( $msgID, $arrayXmlMessages[$file][$msgID] );
        $_SESSION['G_MESSAGE'] = nl2br( $arrayXmlMessages[$file][$msgID] );
    }

    /**
     * SendTemporalMessage
     *
     * @param string $msgID
     * @param string $strType
     * @param string $sType default value 'LABEL'
     * @param date $time default value null
     * @param integer $width default value null
     * @param string $customLabels default value null
     *
     * @return void
     */
    public static function SendTemporalMessage ($msgID, $strType, $sType = 'LABEL', $time = null, $width = null, $customLabels = null)
    {
        if (isset( $width )) {
            $_SESSION['G_MESSAGE_WIDTH'] = $width;
        }
        if (isset( $time )) {
            $_SESSION['G_MESSAGE_TIME'] = $time;
        }
        switch (strtolower( $sType )) {
            case 'label':
            case 'labels':
                $_SESSION['G_MESSAGE_TYPE'] = $strType;
                $_SESSION['G_MESSAGE'] = nl2br( G::LoadTranslation( $msgID ) );
                break;
            case 'string':
                $_SESSION['G_MESSAGE_TYPE'] = $strType;
                $_SESSION['G_MESSAGE'] = nl2br( $msgID );
                break;
        }
        if ($customLabels != null) {
            $message = $_SESSION['G_MESSAGE'];
            foreach ($customLabels as $key => $val) {
                $message = str_replace( '{' . nl2br( $key ) . '}', nl2br( $val ), $message );
            }
            $_SESSION['G_MESSAGE'] = $message;
        }
    }

    /**
     * SendMessage
     *
     * @param string $msgID
     * @param string $strType
     * @param string $file default value "labels"
     *
     * @return void
     */
    public function SendMessage ($msgID, $strType, $file = "labels")
    {
        global $arrayXmlMessages;
        $_SESSION['G_MESSAGE_TYPE'] = $strType;
        $_SESSION['G_MESSAGE'] = nl2br( G::LoadTranslation( $msgID ) );
    }

    /**
     * SendMessageText
     * Just put the $text in the message text
     *
     * @param string $text
     * @param string $strType
     *
     * @return void
     */
    public function SendMessageText ($text, $strType)
    {
        global $arrayXmlMessages;
        $_SESSION['G_MESSAGE_TYPE'] = $strType;
        $_SESSION['G_MESSAGE'] = nl2br( $text );
    }

    /**
     * Render message from XML file
     *
     * @author Fernando Ontiveros Lira <fernando@colosa.com>
     * @access public
     * @param string $msgID
     * @return void
     */
    public function LoadMessage ($msgID, $file = "messages")
    {
        global $_SESSION;
        global $arrayXmlMessages;

        if (! is_array( $arrayXmlMessages )) {
            $arrayXmlMessages = G::LoadArrayFile( G::ExpandPath( 'content' ) . $file . "." . SYS_LANG );
        }
        $aux = $arrayXmlMessages[$msgID];
        $msg = "";
        for ($i = 0; $i < strlen( $aux ); $i ++) {
            if ($aux[$i] == "$") {
                $token = "";
                $i ++;
                while ($i < strlen( $aux ) && $aux[$i] != " " && $aux[$i] != "." && $aux[$i] != "'" && $aux[$i] != '"') {
                    $token .= $aux[$i ++];
                }
                eval( "\$msg.= \$_SESSION['" . $token . "'] ; " );
                $msg .= $aux[$i];
            } else {
                $msg = $msg . $aux[$i];
            }
        }
        return $msg;
    }

    /**
     * Function LoadXmlLabel
     * deprecated
     */
    public function LoadXmlLabel ($msgID, $file = 'labels')
    {
        return 'xxxxxx';
    }

    /**
     * Function LoadMessageXml
     *
     * @author David S. Callizaya S. <davidsantos@colosa.com>
     * @access public
     * @param eter string msgID
     * @param eter string file
     * @return string
     */
    public function LoadMessageXml ($msgID, $file = 'labels')
    {
        global $arrayXmlMessages;
        if (! isset( $arrayXmlMessages[$file] )) {
            G::loadLanguageFile( G::ExpandPath( 'content' ) . 'languages/' . $file . '.xml' );
        }
        if (isset( $arrayXmlMessages[$file][$msgID] )) {
            G::registerLabel( $msgID, $arrayXmlMessages[$file][$msgID] );
            return $arrayXmlMessages[$file][$msgID];
        } else {
            G::registerLabel( $msgID, '' );
            return null;
        }
    }

    /**
     * Function LoadTranslationObject
     * It generates a global Translation variable that will be used in all the system.
     * this script check the file translation in folder shared/META-INF/
     *
     * deprecated
     *
     * @access public
     * @param string lang
     * @return void
     */
    public function LoadTranslationObject ($lang = SYS_LANG)
    {
        $defaultTranslations = Array ();
        $foreignTranslations = Array ();

        //if the default translations table doesn't exist we can't proceed
        if (! is_file( PATH_LANGUAGECONT . 'translation.en' )) {
            return null;
        }
        //load the translations table
        require_once (PATH_LANGUAGECONT . 'translation.en');
        $defaultTranslations = $translation;

        //if some foreign language was requested and its translation file exists
        if ($lang != 'en' && file_exists( PATH_LANGUAGECONT . 'translation.' . $lang )) {
            require_once (PATH_LANGUAGECONT . 'translation.' . $lang); //load the foreign translations table
            $foreignTranslations = $translation;
        }

        global $translation;
        if (defined( "SHOW_UNTRANSLATED_AS_TAG" ) && SHOW_UNTRANSLATED_AS_TAG != 0) {
            $translation = $foreignTranslations;
        } else {
            $translation = array_merge( $defaultTranslations, $foreignTranslations );
        }
        return true;
    }

    /**
     * Function LoadTranslation
     *
     * @author Aldo Mauricio Veliz Valenzuela. <mauricio@colosa.com>
     * @access public
     * @param eter string msgID
     * @param eter string file
     * @param eter array data // erik: associative array within data input to replace for formatted string i.e "any messsage {replaced_label} that contains a replace label"
     * @return string
     */
    public static function LoadTranslation ($msgID, $lang = SYS_LANG, $data = null)
    {
        global $translation;

        // if the second parameter ($lang) is an array, it was specified to use as data
        if (is_array( $lang )) {
            $data = $lang;
            $lang = SYS_LANG;
        }

        if (isset( $translation[$msgID] )) {
            $translationString = preg_replace( "[\n|\r|\n\r]", ' ', $translation[$msgID] );

            if (isset( $data ) && is_array( $data )) {
                foreach ($data as $label => $value) {
                    $translationString = str_replace( '{' . $label . '}', $value, $translationString );
                }
            }

            return $translationString;
        } else {
            if (defined( "UNTRANSLATED_MARK" )) {
                $untranslatedMark = strip_tags( UNTRANSLATED_MARK );
            } else {
                $untranslatedMark = "**";
            }
            return $untranslatedMark . $msgID . $untranslatedMark;
        }
    }

    /**
     * Function LoadTranslation
     *
     * @author Brayan Osmar Pereyra Suxo "Cochalo". <brayan@colosa.com>
     * @access public
     * @param eter string name plugin
     * @param eter string id msg
     * @param eter array data
     * @return string
     */
    public function LoadTranslationPlugin ($namePlugin, $msgID, $data = null)
    {
        eval('global $translation' . $namePlugin . ';');

        $existId = false;
        eval('if (isset( $translation' . $namePlugin . '[$msgID])) { $existId = true; }');
        if ($existId) {
            eval('$translationString = preg_replace( "[\n|\r|\n\r]", " ", $translation' . $namePlugin . '[$msgID] );');
            if (isset( $data ) && is_array( $data )) {
                foreach ($data as $label => $value) {
                    $translationString = str_replace( '{' . $label . '}', $value, $translationString );
                }
            }

            return $translationString;
        } else {
            if (defined( "UNTRANSLATED_MARK" )) {
                $untranslatedMark = strip_tags( UNTRANSLATED_MARK );
            } else {
                $untranslatedMark = "**";
            }
            return $untranslatedMark . $msgID . $untranslatedMark;
        }
    }

    /**
     * Function getTranslations
     *
     * @author Erik Amaru O. <erik@colosa.com>
     * @access public
     * @param eter array msgIDs
     * @param eter string file
     * @return string
     */
    public function getTranslations ($msgIDs, $lang = SYS_LANG)
    {
        if (! is_array( $msgIDs )) {
            return null;
        }
        $translations = Array ();
        foreach ($msgIDs as $mID) {
            $translations[$mID] = self::LoadTranslation( $mID, $lang );
        }

        return $translations;
    }

    /**
     * Load an array File Content
     *
     * @author Fernando Ontiveros Lira <fernando@colosa.com>
     * @access public
     * @param string $strFile
     * @return void
     */
    public function LoadArrayFile ($strFile = '')
    {
        $res = null;
        if ($strFile != '') {
            $src = file( $strFile );
            if (is_array( $src )) {
                foreach ($src as $key => $val) {
                    $res[$key] = trim( $val );
                }
            }
        }
        unset( $src );
        return $res;
    }

    /**
     * Expand an uri based in the current URI
     *
     * @author Fernando Ontiveros Lira <fernando@colosa.com>
     * @access public
     * @param string $methodPage the method directory and the page
     * @return the expanded uri, later, will encryt the uri...
     */
    public function expandUri ($methodPage)
    {
        $uri = explode( '/', getenv( 'REQUEST_URI' ) );
        $sw = 0;
        $newUri = '';
        if (! defined( 'SYS_SKIN' )) {
            for ($i = 0; $i < count( $uri ); $i ++) {
                if ($sw == 0) {
                    $newUri .= $uri[$i] . PATH_SEP;
                }
                if ($uri[$i] == SYS_SKIN) {
                    $sw = 1;
                }
            }
        } else {
            for ($i = 0; $i < 4; $i ++) {
                if ($sw == 0) {
                    $newUri .= $uri[$i] . PATH_SEP;
                }
                if ($uri[$i] == SYS_SKIN) {
                    $sw = 1;
                }
            }
        }
        $newUri .= $methodPage;
        return $newUri;
    }

    /**
     * Forces login for generic applications
     *
     * @author Fernando Ontiveros Lira <fernando@colosa.com>
     * @access public
     * @param string $userid
     * @param string $permission
     * @param string $urlNoAccess
     * @return void
     */
    public function genericForceLogin ($permission, $urlNoAccess, $urlLogin = 'login/login')
    {
        global $RBAC;

        //the session is expired, go to login page,
        //the login page is login/login.html
        if (! isset( $_SESSION )) {
            header( 'location: ' . G::expandUri( $urlLogin ) );
            die();
        }

        //$permission is an array, we'll verify all permission to allow access.
        if (is_array( $permission )) {
            $aux = $permission;
        } else {
            $aux[0] = $permission;
        }
        $sw = 0;
        for ($i = 0; $i < count( $aux ); $i ++) {
            $res = $RBAC->userCanAccess( $aux[$i] );
            if ($res == 1) {
                $sw = 1;
            }
        }

        //you don't have access to this page
        if ($sw == 0) {
            header( 'location: ' . G::expandUri( $urlNoAccess ) );
            die();
        }
    }

    /**
     * capitalize
     *
     * @param string $string
     *
     * @return string $string
     */
    public function capitalize ($string)
    {
        return ucfirst( $string );
    }

    /**
     * toUpper
     *
     * @param string $sText
     *
     * @return string strtoupper($sText)
     */
    public static function toUpper ($sText)
    {
        return strtoupper( $sText );
    }

    /**
     * toLower
     *
     * @param string $sText
     * @return string strtolower($sText)
     */
    public static function toLower ($sText)
    {
        return strtolower( $sText );
    }

    /**
     * http_build_query
     *
     * @param string $formdata,
     * @param string $numeric_prefix default value null,
     * @param string $key default value null
     *
     * @return array $res
     */
    public function http_build_query ($formdata, $numeric_prefix = null, $key = null)
    {
        $res = array ();
        foreach ((array) $formdata as $k => $v) {
            $tmp_key = rawurlencode( is_int( $k ) ? $numeric_prefix . $k : $k );
            if ($key) {
                $tmp_key = $key . '[' . $tmp_key . ']';
            }
            if (is_array( $v ) || is_object( $v )) {
                $res[] = G::http_build_query( $v, null /* or $numeric_prefix if you want to add numeric_prefix to all indexes in array*/, $tmp_key );
            } else {
                $res[] = $tmp_key . "=" . rawurlencode( $v );
            }
            /*
            If you want, you can write this as one string:
            $res[] = ( ( is_array($v) || is_object($v) ) ? G::http_build_query($v, null, $tmp_key) : $tmp_key."=".urlencode($v) );
            */
        }
        $separator = ini_get( 'arg_separator.output' );
        return implode( $separator, $res );
    }

    /**
     * Redirect URL
     *
     * @author Fernando Ontiveros Lira <fernando@colosa.com>
     * @access public
     * @param string $parameter
     * @return string
     */
    public static function header ($parameter)
    {
        if (defined( 'ENABLE_ENCRYPT' ) && (ENABLE_ENCRYPT == 'yes') && (substr( $parameter, 0, 9 ) == 'location:')) {
            $url = G::encryptUrl( substr( $parameter, 10 ), URL_KEY );
            header( 'location:' . $url );
        } else {
            header( $parameter );
        }
        return;
    }

    /**
     *
     * @author Fernando Ontiveros Lira <fernando@colosa.com>
     * @access public
     * @param string $permission
     * @param string $urlNoAccess
     * @return void
     */
    public function forceLogin ($permission = "", $urlNoAccess = "")
    {
        global $RBAC;

        if (isset( $_SESSION['USER_LOGGED'] ) && $_SESSION['USER_LOGGED'] == '') {
            $sys = (ENABLE_ENCRYPT == 'yes' ? config("system.workspace") : "sys" . config("system.workspace"));
            $lang = (ENABLE_ENCRYPT == 'yes' ? G::encrypt( urldecode( SYS_LANG ), URL_KEY ) : SYS_LANG);
            $skin = (ENABLE_ENCRYPT == 'yes' ? G::encrypt( urldecode( SYS_SKIN ), URL_KEY ) : SYS_SKIN);
            $login = (ENABLE_ENCRYPT == 'yes' ? G::encrypt( urldecode( 'login' ), URL_KEY ) : 'login');
            $loginhtml = (ENABLE_ENCRYPT == 'yes' ? G::encrypt( urldecode( 'login.html' ), URL_KEY ) : 'login.html');
            $direction = "/$sys/$lang/$skin/$login/$loginhtml";
            die();
        }

        $Connection = new DBConnection();
        $ses = new DBSession( $Connection );
        $stQry = "SELECT LOG_STATUS FROM LOGIN WHERE LOG_SID = '" . session_id() . "'";
        $dset = $ses->Execute( $stQry );
        $row = $dset->read();
        $sessionPc = defined( 'SESSION_PC' ) ? SESSION_PC : '';
        $sessionBrowser = defined( 'SESSION_BROWSER' ) ? SESSION_BROWSER : '';
        if (($sessionPc == "1") or ($sessionBrowser == "1")) {
            if ($row['LOG_STATUS'] == 'X') {
                $sys = (ENABLE_ENCRYPT == 'yes' ? config("system.workspace") : "sys" . config("system.workspace"));
                $lang = (ENABLE_ENCRYPT == 'yes' ? G::encrypt( urldecode( SYS_LANG ), URL_KEY ) : SYS_LANG);
                $skin = (ENABLE_ENCRYPT == 'yes' ? G::encrypt( urldecode( SYS_SKIN ), URL_KEY ) : SYS_SKIN);
                $login = (ENABLE_ENCRYPT == 'yes' ? G::encrypt( urldecode( 'login' ), URL_KEY ) : 'login');
                $loginhtml = (ENABLE_ENCRYPT == 'yes' ? G::encrypt( urldecode( 'login.html' ), URL_KEY ) : 'login.html');
                $direction = "/$sys/$lang/$skin/$login/$loginhtml";
                G::SendMessageXml( 'ID_CLOSE_SESSION', "warning" );
                header( "location: $direction" );
                die();
                return;
            }
        }
        if (defined( 'SIN_COMPATIBILIDAD_RBAC' ) and SIN_COMPATIBILIDAD_RBAC == 1) {
            return;
        }

        if ($permission == "") {
            return;
        }

        if (is_array( $permission )) {
            $aux = $permission;
        } else {
            $aux[0] = $permission;
        }

        $sw = 0;
        for ($i = 0; $i < count( $aux ); $i ++) {
            $res = $RBAC->userCanAccess( $aux[$i] );
            if ($res == 1) {
                $sw = 1;
            }
        }

        if ($sw == 0 && $urlNoAccess != "") {
            $aux = explode( '/', $urlNoAccess );
            $sys = (ENABLE_ENCRYPT == 'yes' ? config("system.workspace") : "/sys" . SYS_LANG);
            $lang = (ENABLE_ENCRYPT == 'yes' ? G::encrypt( urldecode( SYS_LANG ), URL_KEY ) : SYS_LANG);
            $skin = (ENABLE_ENCRYPT == 'yes' ? G::encrypt( urldecode( SYS_SKIN ), URL_KEY ) : SYS_SKIN);
            $login = (ENABLE_ENCRYPT == 'yes' ? G::encrypt( urldecode( $aux[0] ), URL_KEY ) : $aux[0]);
            $loginhtml = (ENABLE_ENCRYPT == 'yes' ? G::encrypt( urldecode( $aux[1] ), URL_KEY ) : $aux[1]);

            //header ("location: /$sys/$lang/$skin/$login/$loginhtml");
            header( "location: /fluid/mNE/o9A/mNGm1aLiop3V4qU/dtij4J°gmaLPwKDU3qNn2qXanw" );
            die();
        }

        if ($sw == 0) {
            header( "location: /fluid/mNE/o9A/mNGm1aLiop3V4qU/dtij4J°gmaLPwKDU3qNn2qXanw" );
            die();
        }
    }

    /**
     * Add slashes to a string
     *
     * @author Fernando Ontiveros Lira <fernando@colosa.com>
     * @access public
     * @param string $val_old
     * @return string
     */
    public function add_slashes ($val_old)
    {

        if (! is_string( $val_old )) {
            $val_old = "$val_old";
        }

        $tamano_cadena = strlen( $val_old );
        $contador_cadena = 0;
        $new_val = "";

        for ($contador_cadena = 0; $contador_cadena < $tamano_cadena; $contador_cadena ++) {
            $car = $val_old[$contador_cadena];

            if ($car != chr( 34 ) && $car != chr( 39 ) && $car != chr( 92 )) {
                $new_val .= $car;
            } else {
                if ($car2 != chr( 92 )) {
                    //print " xmlvar: $new_val -- $car -- $car2 <br>";
                    $new_val .= chr( 92 ) . $car;
                } else {
                    $new_val .= $car;
                }
            }
        }
        return $new_val;
    }

    /**
     * Extract the structure version value from serializated table field and check it.
     * @return true if the version is bigger than 1
     */
    public function gotDirectoryStructureVer2()
    {

        $configuration = new Configurations();
        if (!empty(config("system.workspace")) && $configuration->exists("ENVIRONMENT_SETTINGS")) {
            return ($configuration->getDirectoryStructureVer() > 1);
        }
        return false;
    }

    /**
     * Get the default blank directory 0 for external files
     */
    public function getBlackHoleDir()
    {
        //len32:12345678901234567890123456789012
        return "00000000000000000000000000000000";
    }

    /**
     * Function used to fix 32K issue related to ext3 max subdirectory storage, but checking Version first.
     *
     * @param string $uid
     * @param int $splitSize
     * @param int $pieces
     *
     * @return string xxx/xxx/xxx/xxxxxxxxxxxxxxxxxxxxx
     */
    public static function getPathFromUID($uid, $splitSize = 3, $pieces = 3)
    {
        if (! G::gotDirectoryStructureVer2()) {
            return $uid;
        }
        return G::getPathFromUIDPlain($uid, $splitSize, $pieces);
    }

    /**
     * Funtion used to fix 32K issue related to ext3 max subdirectory storage.
     * @param string $uid
     * @param int $splitSize
     * @param int $pieces
     * @return string xxx/xxx/xxx/xxxxxxxxxxxxxxxxxxxxx
     */
    public static function getPathFromUIDPlain($uid, $splitSize = 3, $pieces = 3)
    {
        $dirArray = array();
        if (is_string($uid) && strlen($uid) >= 32 && $uid != G::getBlackHoleDir()) {
            for ($i = 0; $i < $pieces; $i++) {
                $dirArray[] = substr($uid, 0, $splitSize);
                $len = strlen($uid);
                $uid = substr($uid, $splitSize, $len);
            }
        }
        $dirArray[] = $uid;
        $newfileStructure = implode($dirArray, '/');
        return $newfileStructure;
    }

    /**
     * Get the uid from the splitted directory + filename.
     * @param string $path
     * @return string
     */
    public static function getUIDfromPath($path)
    {
        $uid = '';
        $item = explode($path, '/');
        $len = sizeof($item);
        for ($i = 0; $i < $len; $i++) {
            $uid .= $item[$i];
        }
        if (strlen($uid) != 32){
            return "invalid";
        }
        return $uid;
    }

    /**
     * Get the file stored in '0' dir as splitted, but checking version first.
     * @param string $appUid
     * @param string $fileUid
     * @param int $splitSize
     * @param int $pieces
     * @return array index:0 got the path, index:1 got the filename
     */
    public static function getPathFromFileUID($appUid, $fileUid, $splitSize = 3, $pieces = 3)
    {
        if (! G::gotDirectoryStructureVer2()) {
            $response = array();
            $response[] = '';
            $response[] = $fileUid;
            return $response;
        }
        return G::getPathFromFileUIDPlain($appUid, $fileUid, $splitSize, $pieces);
    }

    /**
     * Get the file stored in '0' dir as splitted.
     * @param string $appUid
     * @param string $fileUid
     * @param int $splitSize
     * @param int $pieces
     * @return array index:0 got the path, index:1 got the filename
     */
    public function getPathFromFileUIDPlain($appUid, $fileUid, $splitSize = 3, $pieces = 3)
    {
        $response = array();
        if ($appUid == G::getBlackHoleDir()) {
            $dirArray = array();
            if (is_string($fileUid) && strlen($fileUid) >= 32) {
                for ($i = 0; $i < $pieces; $i++) {
                    $dirArray[] = substr($fileUid, 0, $splitSize);
                    $len = strlen($fileUid);
                    $fileUid = substr($fileUid, $splitSize, $len);
                }
            }
            $response[] = implode($dirArray, '/') . '/';
            $response[] = $fileUid;
        } else {
            $response[] = '';
            $response[] = $fileUid;
        }
        return $response;
    }

    /**
     * Upload a file and then copy to path+ nameToSave
     *
     * @author Mauricio Veliz <mauricio@colosa.com>
     * @access public
     * @param string $file
     * @param string $path
     * @param string $nameToSave
     * @param integer $permission
     * @return void
     */
    public static function uploadFile ($file, $path, $nameToSave, $permission = 0755)
    {
        try {
            if ($file == '') {
                throw new Exception( 'The filename is empty!' );
            }
            if (filesize( $file ) > ((((ini_get( 'upload_max_filesize' ) + 0)) * 1024) * 1024)) {
                throw new Exception( 'The size of upload file exceeds the allowed by the server!' );
            }
            $oldumask = umask( 0 );
            if (! is_dir( $path )) {
                G::verifyPath( $path, true );
            }

            if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
                $file = str_replace("\\\\","\\",$file,$count);
                if(!$count) {
                    $winPath = explode("\\",$file);
                    $file = "";
                    foreach($winPath as $k => $v){
                        if($v != "") {
                            $file.= $v."\\";
                        }
                    }
                    $file = substr($file,0,-1);
                }
            }


            $filter = new InputFilter();
            $file = $filter->validateInput($file, "path");
            $path = $filter->validateInput($path, "path");

            move_uploaded_file( $file, $path . "/" . $nameToSave );
            $nameToSave = $filter->validateInput($nameToSave, "path");
            @chmod( $path . "/" . $nameToSave, $permission );
            umask( $oldumask );

        } catch (Exception $oException) {
            throw $oException;
        }
    }

    /**
     * resizeImage
     *
     * @param string $path,
     * @param string $resWidth
     * @param string $resHeight
     * @param string $saveTo default value null
     *
     * @return void
     */
    public function resizeImage ($path, $resWidth, $resHeight, $saveTo = null)
    {
        $imageInfo = @getimagesize( $path );

        if (! $imageInfo) {
            throw new Exception( "Could not get image information" );
        }
        list ($width, $height) = $imageInfo;
        $percentHeight = $resHeight / $height;
        $percentWidth = $resWidth / $width;
        $percent = ($percentWidth < $percentHeight) ? $percentWidth : $percentHeight;
        $resWidth = $width * $percent;
        $resHeight = $height * $percent;

        // Resample
        $image_p = imagecreatetruecolor( $resWidth, $resHeight );
        imagealphablending( $image_p, false );
        imagesavealpha( $image_p, true );

        $background = imagecolorallocate( $image_p, 0, 0, 0 );
        ImageColorTransparent( $image_p, $background ); // make the new temp image all transparent


        //Assume 3 channels if we can't find that information
        if (! array_key_exists( "channels", $imageInfo )) {
            $imageInfo["channels"] = 3;
        }
        $memoryNeeded = Round( ($imageInfo[0] * $imageInfo[1] * $imageInfo['bits'] * $imageInfo['channels'] + Pow( 2, 16 )) * 1.95 ) / (1024 * 1024);
        if ($memoryNeeded < 80) {
            $memoryNeeded = 80;
        }
        ini_set( 'memory_limit', intval( $memoryNeeded ) . 'M' );

        $functions = array (IMAGETYPE_GIF => array ('imagecreatefromgif','imagegif'
        ),IMAGETYPE_JPEG => array ('imagecreatefromjpeg','imagejpeg'),IMAGETYPE_PNG => array ('imagecreatefrompng','imagepng'));

        if (! array_key_exists( $imageInfo[2], $functions )) {
            throw new Exception( "Image format not supported" );
        }
        list ($inputFn, $outputFn) = $functions[$imageInfo[2]];

        $image = $inputFn( $path );
        imagecopyresampled( $image_p, $image, 0, 0, 0, 0, $resWidth, $resHeight, $width, $height );
        $outputFn( $image_p, $saveTo );
        
        if(!is_null($saveTo)) {

            $filter = new InputFilter();
            $saveTo = $filter->validateInput($saveTo, "path");
        }

        @chmod( $saveTo, 0666 );
    }

    /**
     * Merge 2 arrays
     *
     * @author Fernando Ontiveros Lira <fernando@colosa.com>
     * @access public
     * @return array
     */
    public static function array_merges()
    {
        $array = array ();
        $arrays = & func_get_args();
        foreach ($arrays as $array_i) {
            if (is_array( $array_i )) {
                G::array_merge_2( $array, $array_i );
            }
        }
        return $array;
    }

    /**
     * Merge 2 arrays
     *
     * @author Fernando Ontiveros Lira <fernando@colosa.com>
     * @access public
     * @param string $array
     * @param string $array_i
     * @return array
     */
    public function array_merge_2 (&$array, &$array_i)
    {
        foreach ($array_i as $k => $v) {
            if (is_array( $v )) {
                if (! isset( $array[$k] )) {
                    $array[$k] = array ();
                }
                G::array_merge_2( $array[$k], $v );
            } else {
                if (isset( $array[$k] ) && is_array( $array[$k] )) {
                    $array[$k][0] = $v;
                } else {
                    if (isset( $array ) && ! is_array( $array )) {
                        $temp = $array;
                        $array = array();
                        $array[0] = $temp;
                    }
                    $array[$k] = $v;
                }
            }
        }
    }

    /**
     * Generate random number
     *
     * @author Fernando Ontiveros Lira <fernando@colosa.com>
     * @access public
     * @return int
     */
    public static function generateUniqueID ()
    {
        do {
            $sUID = str_replace( '.', '0', uniqid( rand( 0, 999999999 ), true ) );
        } while (strlen( $sUID ) != 32);
        return $sUID;
        //return strtoupper(substr(uniqid(rand(0, 9), false),0,14));
    }

    /**
     * Generate a numeric or alphanumeric code
     *
     * @author Julio Cesar Laura Avendaힼjuliocesar@colosa.com>
     * @access public
     * @return string
     */
    public static function generateCode ($iDigits = 4, $sType = 'NUMERIC')
    {
        if (($iDigits < 4) || ($iDigits > 50)) {
            $iDigits = 4;
        }
        if (($sType != 'NUMERIC') && ($sType != 'ALPHA') && ($sType != 'ALPHANUMERIC')) {
            $sType = 'NUMERIC';
        }
        $aValidCharacters = array ('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
        );
        switch ($sType) {
            case 'NUMERIC':
                $iMin = 0;
                $iMax = 9;
                break;
            case 'ALPHA':
                $iMin = 10;
                $iMax = 35;
                break;
            case 'ALPHANUMERIC':
                $iMin = 0;
                $iMax = 35;
                break;
        }
        $sCode = '';
        for ($i = 0; $i < $iDigits; $i ++) {
            $sCode .= $aValidCharacters[rand( $iMin, $iMax )];
        }
        return $sCode;
    }

    /**
     * Verify if the input string is a valid UID
     *
     * @author David Callizaya <davidsantos@colosa.com>
     * @access public
     * @return int
     */
    public function verifyUniqueID ($uid)
    {
        return (bool) preg_match( '/^[0-9A-Za-z]{14,}/', $uid );
    }

    /**
     * Verify if the input string is a valid UID of size 32
     * @param string $uid
     * @return boolean
     */
    public static function verifyUniqueID32($uid)
    {
        return (bool) preg_match('/^[0-9A-Za-z]{32,32}$/', $uid);
    }

    /**
     * is_utf8
     *
     * @param string $string
     *
     * @return string utf8_encode()
     */
    public function is_utf8 ($string)
    {
        if (preg_match('//u', $string)) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * Return date in Y-m-d format
     *
     * @author Fernando Ontiveros Lira <fernando@colosa.com>
     * @access public
     * @return void
     */
    public function CurDate($sFormat = '')
    {
        $sFormat = ($sFormat != '')? $sFormat : 'Y-m-d H:i:s';

        return date($sFormat);
    }

    /**
     * Return the System defined constants and Application variables
     *   Constants: SYS_*
     *   Sessions : USER_* , URS_*
     */
    public static function getSystemConstants($params = null)
    {
        $t1 = G::microtime_float();
        $sysCon = array();

        if (defined("SYS_LANG")) {
            $sysCon["SYS_LANG"] = SYS_LANG;
        }

        if (defined("SYS_SKIN")) {
            $sysCon["SYS_SKIN"] = SYS_SKIN;
        }

        if (!empty(config("system.workspace"))) {
            $sysCon["SYS_SYS"] = config("system.workspace");
        }

        $sysCon["APPLICATION"]  = (isset($_SESSION["APPLICATION"]))?  $_SESSION["APPLICATION"]  : "";
        $sysCon["PROCESS"]      = (isset($_SESSION["PROCESS"]))?      $_SESSION["PROCESS"]      : "";
        $sysCon["TASK"]         = (isset($_SESSION["TASK"]))?         $_SESSION["TASK"]         : "";
        $sysCon["INDEX"]        = (isset($_SESSION["INDEX"]))?        $_SESSION["INDEX"]        : "";
        $sysCon["USER_LOGGED"]  = (isset($_SESSION["USER_LOGGED"]))?  $_SESSION["USER_LOGGED"]  : "";
        $sysCon["USR_USERNAME"] = (isset($_SESSION["USR_USERNAME"]))? $_SESSION["USR_USERNAME"] : "";

        //###############################################################################################
        // Added for compatibility betweek aplication called from web Entry that uses just WS functions
        //###############################################################################################

        if ($params != null) {
            if (isset($params->option)) {
                switch ($params->option) {
                    case "STORED SESSION":
                        if (isset($params->SID)) {
                            $oSessions = new Sessions($params->SID);
                            $sysCon = array_merge($sysCon, $oSessions->getGlobals());
                        }
                        break;
                }
            }

            if (isset($params->appData) && is_array($params->appData)) {
                $sysCon["APPLICATION"] = $params->appData["APPLICATION"];
                $sysCon["PROCESS"]     = $params->appData["PROCESS"];
                $sysCon["TASK"]        = $params->appData["TASK"];
                $sysCon["INDEX"]       = $params->appData["INDEX"];

                if (empty($sysCon["USER_LOGGED"])) {
                    $sysCon["USER_LOGGED"]  = $params->appData["USER_LOGGED"];
                    $sysCon["USR_USERNAME"] = $params->appData["USR_USERNAME"];
                }
            }
        }

        return $sysCon;
    }

    /*
     * Return the Friendly Title for a string, capitalize every word and remove spaces
     *   param : text string
     */
    public function capitalizeWords($text)
    {
        return mb_convert_case($text, MB_CASE_TITLE, 'UTF-8');
    }

    /**
     * unhtmlentities
     *
     * @param string $string
     *
     * @return string substring
     */
    public function unhtmlentities ($string)
    {
        if (version_compare(PHP_VERSION, '5.4.0', '<')) {
            $trans_tbl = get_html_translation_table( HTML_ENTITIES );
        } else {
            $trans_tbl = get_html_translation_table( HTML_ENTITIES, ENT_COMPAT, 'ISO-8859-1' );
        }
        foreach ($trans_tbl as $k => $v) {
            $ttr[$v] = utf8_encode( $k );
        }
        return strtr( $string, $ttr );
    }

    /**
     * ************************************* init **********************************************
     * Xml parse collection functions
     * Returns a associative array within the xml structure and data
     *
     * @author Erik Amaru Ortiz <erik@colosa.com>
     */
    public function xmlParser (&$string)
    {
        $parser = xml_parser_create();
        xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, 0 );
        xml_parse_into_struct( $parser, $string, $vals, $index );

        $mnary = array ();
        $ary = &$mnary;
        foreach ($vals as $r) {
            $t = $r['tag'];
            if ($r['type'] == 'open') {
                if (isset( $ary[$t] )) {
                    if (isset( $ary[$t][0] )) {
                        $ary[$t][] = array ();
                    } else {
                        $ary[$t] = array ($ary[$t],array () );
                    }
                    $cv = &$ary[$t][count( $ary[$t] ) - 1];
                } else {
                    $cv = &$ary[$t];
                }
                if (isset( $r['attributes'] )) {
                    foreach ($r['attributes'] as $k => $v) {
                        $cv['__ATTRIBUTES__'][$k] = $v;
                    }
                }
                // note by gustavo cruz gustavo[at]colosa[dot]com
                // minor adjustments to validate if an open node have a value attribute.
                // for example a dropdown has many childs, but also can have a value attribute.
                if (isset( $r['value'] ) && trim( $r['value'] ) != '') {
                    $cv['__VALUE__'] = $r['value'];
                }
                // end added code
                $cv['__CONTENT__'] = array ();
                $cv['__CONTENT__']['_p'] = &$ary;
                $ary = &$cv['__CONTENT__'];

            } elseif ($r['type'] == 'complete') {
                if (isset( $ary[$t] )) {
                    if (isset( $ary[$t][0] )) {
                        $ary[$t][] = array ();
                    } else {
                        $ary[$t] = array ($ary[$t],array ());
                    }
                    $cv = &$ary[$t][count( $ary[$t] ) - 1];
                } else {
                    $cv = &$ary[$t];
                }
                if (isset( $r['attributes'] )) {
                    foreach ($r['attributes'] as $k => $v) {
                        $cv['__ATTRIBUTES__'][$k] = $v;
                    }
                }
                $cv['__VALUE__'] = (isset( $r['value'] ) ? $r['value'] : '');

            } elseif ($r['type'] == 'close') {
                $ary = &$ary['_p'];
            }
        }

        self::_del_p( $mnary );

        $obj_resp = new stdclass();
        $obj_resp->code = xml_get_error_code( $parser );
        $obj_resp->message = xml_error_string( $obj_resp->code );
        $obj_resp->result = $mnary;
        xml_parser_free( $parser );

        return $obj_resp;
    }

    /**
     * _del_p
     *
     * @param string &$ary
     *
     * @return void
     */
    // _Internal: Remove recursion in result array
    public function _del_p (&$ary)
    {
        foreach ($ary as $k => $v) {
            if ($k === '_p') {
                unset( $ary[$k] );
            } elseif (is_array( $ary[$k] )) {
                self::_del_p( $ary[$k] );
            }
        }
    }

    /**
     * ary2xml
     *
     * Array to XML
     *
     * @param string $cary
     * @param string $d=0
     * @param string $forcetag default value ''
     *
     * @return void
     */
    // Array to XML
    public function ary2xml ($cary, $d = 0, $forcetag = '')
    {
        $res = array ();
        foreach ($cary as $tag => $r) {
            if (isset( $r[0] )) {
                $res[] = self::ary2xml( $r, $d, $tag );
            } else {
                if ($forcetag) {
                    $tag = $forcetag;
                }
                $sp = str_repeat( "\t", $d );
                $res[] = "$sp<$tag";
                if (isset( $r['_a'] )) {
                    foreach ($r['_a'] as $at => $av) {
                        $res[] = " $at=\"$av\"";
                    }
                }
                $res[] = ">" . ((isset( $r['_c'] )) ? "\n" : '');
                if (isset( $r['_c'] )) {
                    $res[] = ary2xml( $r['_c'], $d + 1 );
                } elseif (isset( $r['_v'] )) {
                    $res[] = $r['_v'];
                }
                $res[] = (isset( $r['_c'] ) ? $sp : '') . "</$tag>\n";
            }

        }
        return implode( '', $res );
    }

    /**
     * ins2ary
     *
     * Insert element into array
     *
     * @param string &$ary
     * @param string $element
     * @param string $pos
     *
     * @return void
     */
    // Insert element into array
    public function ins2ary (&$ary, $element, $pos)
    {
        $ar1 = array_slice( $ary, 0, $pos );
        $ar1[] = $element;
        $ary = array_merge( $ar1, array_slice( $ary, $pos ) );
    }

    /*
    * Xml parse collection functions
    **/

    /**
     * evalJScript
     *
     * @param string $c
     *
     * @return void
     */
    public function evalJScript ($c)
    {
        /*

        $filter = new InputFilter();
        $c = $filter->xssFilterHard($c);*/
        print ('<script language="javascript">'.$c.'</script>') ;
    }

    /**
     * Inflects a string with accented characters and other characteres not suitable for file names, by defaul replace with undescore
     *
     * @author Erik Amaru Ortiz <erik@colosa.com, aortiz.erik@gamil.com>
     * @param (string) string to convert
     * @param (string) character for replace
     * @param (array) additional characteres map
     *
     */
    public function inflect($string, $replacement = '_', $map = array())
    {
        if (is_array($replacement)) {
            $map = $replacement;
            $replacement = '_';
        }

        $quotedReplacement = preg_quote($replacement, '/');

        $default = array('/à|á|å|â/' => 'a',
            '/è|é|ê|ẽ|ë/' => 'e',
            '/ì|í|î/' => 'i',
            '/ò|ó|ô|ø/' => 'o',
            '/ù|ú|ů|û/' => 'u',
            '/ç/' => 'c',
            '/ñ/' => 'n',
            '/ä|æ/' => 'ae',
            '/ö/' => 'oe',
            '/ü/' => 'ue',
            '/Ä/' => 'Ae',
            '/Ü/' => 'Ue',
            '/Ö/' => 'Oe',
            '/ß/' => 'ss',
            '/[\.|\,|\+|\"|\:|\;|\-|\\|\/]/' => " ",
            '/\\s+/' => $replacement);

        $map = array_merge($default, $map);
        return preg_replace(array_keys($map), array_values($map), $string);
    }

    /**
     * pr
     *
     * @param string $var
     *
     * @return void
     */
    public function pr ($var)
    {
        print ("<pre>") ;
        print_r( $var );
        print ("</pre>") ;
    }

    /**
     * dump
     *
     * @param string $var
     *
     * @return void
     */
    public function dump ($var)
    {
        print ("<pre>") ;
        var_dump( $var );
        print ("</pre>") ;
    }

    /**
     * stripCDATA
     *
     * @param string $string
     *
     * @return string str_replace
     */
    public function stripCDATA ($string)
    {
        preg_match_all( '/<!\[cdata\[(.*?)\]\]>/is', $string, $matches );
        return str_replace( $matches[0], $matches[1], $string );
    }

    /**
     * Get the temporal directory path on differents O.S.
     * i.e. /temp -> linux, C:/Temp -> win
     *
     * @author <erik@colosa.com>
     */
    public function sys_get_temp_dir ()
    {
        if (! function_exists( 'sys_get_temp_dir' )) {
            // Based on http://www.phpit.net/
            // article/creating-zip-tar-archives-dynamically-php/2/
            // Try to get from environment variable
            if (! empty( $_ENV['TMP'] )) {
                return realpath( $_ENV['TMP'] );
            } elseif (! empty( $_ENV['TMPDIR'] )) {
                return realpath( $_ENV['TMPDIR'] );
            } elseif (! empty( $_ENV['TEMP'] )) {
                return realpath( $_ENV['TEMP'] );
            } else {
                // Detect by creating a temporary file
                // Try to use system's temporary directory as random name shouldn't exist
                $temp_file = tempnam( G::encryptOld( uniqid( rand(), true ) ), '' );
                if ($temp_file) {
                    $temp_dir = realpath( dirname( $temp_file ) );
                    unlink( $temp_file );
                    return $temp_dir;
                } else {
                    return false;
                }
            }
        } else {
            return sys_get_temp_dir();
        }
    }

    /**
     * Get the content of a compose pmos web service response
     * Returns an array when has a valid reponse, if the response is invalid returns an object containing a status_code and message properties.
     *
     * @author <erik@colosa.com>
     */
    public function PMWSCompositeResponse ($oResp, $prop)
    {
        $Resp = new stdClass();

        if (is_object( $oResp ) && isset( $oResp->{$prop} )) {
            $list = $oResp->{$prop};

            if (is_object( $list )) {
                $aList[0] = $list;
            } else {
                $aList = $list;
            }

            $result = true;
            if (is_array( $aList )) {
                foreach ($aList as $item) {
                    if (! isset( $item->guid )) {
                        $result = false;
                        break;
                    }
                }
            } else {
                $Resp->status_code = - 1;
                $Resp->message = "Bad respose type for ({$prop})";
            }

            if ($result) {
                //verifing if the response has a composite response into a guid value of the first row.
                $tmp = explode( ' ', trim( $aList[0]->guid ) );
                if (sizeof( $tmp ) >= 2) {
                    //the guid can't has a space, so this should be a ws response
                    $Resp->status_code = $tmp[0];
                    $Resp->message = substr( $aList[0]->guid, strpos( $aList[0]->guid, ' ' ) + 1 );
                } else {
                    return $aList;
                }

            } else {
                $Resp->status_code = - 2;
                $Resp->message = "Bad respose, the response has not a uniform struct.";
            }
        } elseif (is_object( $oResp )) {
            return Array ();
        } else {
            $Resp->status_code = - 1;
            $Resp->message = "1 Bad respose type for ({$prop})";
        }
        return $Resp;
    }

    /**
     * Validate and emai address in complete forms,
     *
     * @author Erik A.O. <erik@colosa.com>
     * i.e. if the param. is 'erik a.o. <erik@colosa.com>'
     *      -> returns a object within $o->email => erik@colosa.com and $o->name => erik A.O. in other case returns false
     *
     */
    public function emailAddress($sEmail)
    {
        $o = new stdClass();

        if ( strpos($sEmail, '<') !== false ) {
            preg_match('/([\"\w@\.-_\s]*\s*)?(<(\w+[\.-]?\w+]*@\w+([\.-]?\w+)*\.\w{2,3})+>)/', $sEmail, $matches);

            if ( isset($matches[1]) && $matches[3]) {
                $o->email = $matches[3];
                $o->name = $matches[1];
                return $o;
            }
            return false;
        } else {
            preg_match('/\w+[\.-]?\w+]*@\w+([\.-]?\w+)*\.\w{2,3}+/', $sEmail, $matches);
            if ( isset($matches[0]) ) {
                $o->email = $matches[0];
                $o->name = '';
                return $o;
            }

            return false;
        }
    }

    /**
     * JSON encode
     *
     * @author Erik A.O. <erik@colosa.com>
     */
    public static function json_encode($Json)
    {
        if ( function_exists('json_encode') ) {
            return json_encode($Json);
        } else {

            $oJSON = new Services_JSON();
            return $oJSON->encode($Json);
        }
    }

    /**
      * JSON decode
      *
      * @author Erik A.O. <erik@colosa.com>
     */
    public static function json_decode($Json, $assoc = false)
    {
        if (function_exists('json_decode')) {
            return json_decode($Json, $assoc);
        } else {

            $oJSON = new Services_JSON();
            return $oJSON->decode($Json);
        }
    }

    /**
     * isHttpRequest
     *
     * @return boolean true or false
     */
    public static function isHttpRequest()
    {
        if (isset($_SERVER['SERVER_SOFTWARE']) && strpos(strtolower($_SERVER['SERVER_SOFTWARE']), 'apache') !== false) {
            return true;
        }
        return false;
    }

    /**
     * Send a mail using phpmailer
     * this method use the global smtp server connection stored on Configuration table
     * this information is retrieved by the PMFunction getEmailConfiguration()
     *
     * @author Erik Amaru Ortiz <erik@colosa.com>
     * @param string $from address that is sending the email
     * @param string $fromName name of sender
     * @param mixed $address the possibles values are:
     *        string
     *        array('email1', 'some name <email2>')
     *        array('to'=>array('email1', 'some name <email2>'), 'cc'=>array(...), 'bcc'=>array(...))
     * @param string $subject contains the email subject
     * @param string $body contains the email body (text plain or html)
     * @return mixed boolean or string : if the email was sent successfully returns true, otherwise returns a string within error message
     */
    public function sendMail ($from, $fromName, $address, $subject, $body)
    {
        // require_once "classes/class.pmFunctions.php";

        $setup = getEmailConfiguration();
        if ($setup['MESS_RAUTH'] == false || (is_string($setup['MESS_RAUTH']) && $setup['MESS_RAUTH'] == 'false')) {
            $setup['MESS_RAUTH'] = 0;
        } else {
            $setup['MESS_RAUTH'] = 1;
        }

        if (count($setup) == 0 || !isset($setup['MESS_ENGINE']) || !isset($setup['MESS_SERVER'])
            || !isset($setup['MESS_ENABLED']) || !isset($setup['MESS_RAUTH']) || $setup['MESS_SERVER'] == '') {
            return G::LoadTranslation('ID_EMAIL_ENGINE_IS_NOT_CONFIGURED');
        }

        if (!$setup['MESS_ENABLED']) {
            return G::LoadTranslation('ID_EMAIL_ENGINE_IS_NOT_ENABLED');
        }

        $passwd    = $setup['MESS_PASSWORD'];
        $passwdDec = G::decrypt($passwd,'EMAILENCRYPT');
        $auxPass = explode('hash:', $passwdDec);
        if (count($auxPass) > 1) {
            if (count($auxPass) == 2) {
                $passwd = $auxPass[1];
            } else {
                array_shift($auxPass);
                $passwd = implode('', $auxPass);
            }
        }
        $setup['MESS_PASSWORD'] = $passwd;
        $mail = new PHPMailer(true);
        $mail->From = $from != '' && $from ? $from : $setup['MESS_ACCOUNT'];
        $mail->FromName = $fromName;
        $mail->Subject = $subject;
        $mail->Body = $body;
        $mail->IsHTML (true);
        $mail->IsSMTP();
        $mail->Host = $setup['MESS_SERVER'];
        $mail->Port = $setup['MESS_PORT'];
        $mail->SMTPAuth = isset($setup['MESS_RAUTH']) && $setup['MESS_RAUTH'] ? true : false;
        $mail->Username = $setup['MESS_ACCOUNT'];
        $mail->Password = $setup['MESS_PASSWORD'];
        $mail->SMTPSecure = $setup['SMTPSecure'];

        $emailAddressList = G::envelopEmailAddresses($address);

        foreach ($emailAddressList['to'] as $emails) {
            $mail->AddAddress($emails[0], $emails[1]);
        }
        foreach ($emailAddressList['cc'] as $emails) {
            $mail->AddCC($emails[0], $emails[1]);
        }
        foreach ($emailAddressList['bcc'] as $emails) {
             $mail->AddBCC($emails[0], $emails[1]);
        }

        return $mail->Send() ? true : $mail->ErrorInfo;
    }

    /**
     * Envelope a emails collection from a string or array
     * @author Erik Amaru Ortiz <erik@colosa.com>
     * @param mixed $address the possibles values are:
     *        string
     *        array('email1', 'some name <email2>')
     *        array('to'=>array('email1', 'some name <email2>'), 'cc'=>array(...), 'bcc'=>array(...))
     * @return array contains:
     *                 array(
     *                    'to' => array('email@host.com', 'some name or empty string', array('email@host.com', '..'), ...),
     *                    'cc' => array('email@host.com', 'some name or empty string', ...),
     *                    'bcc' => array('email@host.com', 'some name or empty string', ...)
     *                 )
     */
    public function envelopEmailAddresses($address)
    {
        $emailAddressList = array();
        $emailAddressList['to'] = array();
        $emailAddressList['cc'] = array();
        $emailAddressList['bcc'] = array();
        $ereg = '/([\"\w\W\s]*\s*)?(<([\w\-\.]+@[\.-\w]+\.\w{2,3})+>)/';

        if (!is_array($address)) {
            if (preg_match($ereg, $address, $match)) {
                $emailAddressList['to'][] = array($match[3], $match[1]);
            } else {
                $emailAddressList['to'][] = array($address, '');
            }
        } else {
            foreach ($address as $type => $emails) {
                if (!is_array($emails)) {
                    if (preg_match($ereg, $emails, $match)) {
                        $emailAddressList['to'][] = array($match[3], $match[1]);
                    } else {
                        $emailAddressList['to'][] = array($emails, '');
                    }
                } else {
                    switch ($type) {
                        case 'cc':
                            foreach ($emails as $email) {
                                if (preg_match($ereg, $email, $match)) {
                                    $emailAddressList['cc'][] = array($match[3], $match[1]);
                                } else {
                                    $emailAddressList['cc'][] = array($email, '');
                                }
                            }
                            break;
                        case 'bcc':
                            foreach ($emails as $email) {
                                if (preg_match($ereg, $email, $match)) {
                                    $emailAddressList['bcc'][] = array($match[3], $match[1]);
                                } else {
                                    $emailAddressList['bcc'][] = array($email, '');
                                }
                            }
                            break;
                        case 'to':
                        default:
                            foreach ($emails as $email) {
                                if (preg_match($ereg, $email, $match)) {
                                    $emailAddressList['to'][] = array($match[3], $match[1]);
                                } else {
                                    $emailAddressList['to'][] = array($email, '');
                                }
                            }
                            break;
                    }
                }
            }
        }
        return $emailAddressList;
    }

    /**
     * Get the type of a variable
     * Returns the type of the PHP variable var.
     *
     * @author Erik A. Ortiz. <erik@colosa.com>
     * @return (string) type of variable
     */
    public function gettype($var)
    {
        switch ($var) {
            case is_null($var):
                $type='NULL';
                break;
            case is_bool($var):
                $type='boolean';
                break;
            case is_float($var):
                $type='double';
                break;
            case is_int($var):
                $type='integer';
                break;
            case is_string($var):
                $type='string';
                break;
            case is_array($var):
                $type='array';
                break;
            case is_object($var):
                $type='object';
                break;
            case is_resource($var):
                $type='resource';
                break;
            default:
                $type='unknown type';
                break;
        }
        return $type;
    }

    public function removeComments($buffer)
    {
        /* remove comments */
        $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
        /* remove tabs, spaces, newlines, etc. */
        $buffer = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $buffer);
        return $buffer;
    }

    public function getMemoryUsage()
    {
        $size = memory_get_usage(true);
        $unit=array('B','Kb','Mb','Gb','Tb','Pb');
        return @round($size/pow(1024,($i=floor(log($size,1024)))),2).' '.$unit[$i];
    }

    public function getFormatUserList($format, $aUserInfo)
    {
        switch ($format) {
            case '@firstName @lastName':
                $infoUser = str_replace('@firstName', $aUserInfo['USR_FIRSTNAME'], $format);
                $infoUser = str_replace('@lastName', $aUserInfo['USR_LASTNAME'], $infoUser);
                break;
            case '@firstName @lastName (@userName)':
                $infoUser = str_replace('@firstName', $aUserInfo['USR_FIRSTNAME'], $format);
                $infoUser = str_replace('@lastName', $aUserInfo['USR_LASTNAME'], $infoUser);
                $infoUser = str_replace('@userName', $aUserInfo['USR_USERNAME'], $infoUser);
                break;
            case '@userName':
                $infoUser = str_replace('@userName', $aUserInfo['USR_USERNAME'], $format);
                break;
            case '@userName (@firstName @lastName)':
                $infoUser = str_replace('@userName', $aUserInfo['USR_USERNAME'], $format);
                $infoUser = str_replace('@firstName', $aUserInfo['USR_FIRSTNAME'], $infoUser);
                $infoUser = str_replace('@lastName', $aUserInfo['USR_LASTNAME'], $infoUser);
                break;
            case '@lastName @firstName':
                $infoUser = str_replace('@lastName', $aUserInfo['USR_LASTNAME'], $format);
                $infoUser = str_replace('@firstName', $aUserInfo['USR_FIRSTNAME'], $infoUser);
                break;
            case '@lastName, @firstName':
                $infoUser = str_replace('@lastName', $aUserInfo['USR_LASTNAME'], $format);
                $infoUser = str_replace('@firstName', $aUserInfo['USR_FIRSTNAME'], $infoUser);
                break;
            case '@lastName, @firstName (@userName)':
                $infoUser = str_replace('@lastName', $aUserInfo['USR_LASTNAME'], $format);
                $infoUser = str_replace('@firstName', $aUserInfo['USR_FIRSTNAME'], $infoUser);
                $infoUser = str_replace('@userName', $aUserInfo['USR_USERNAME'], $infoUser);
                break;
            default:
                $infoUser = str_replace('@userName', $aUserInfo['USR_USERNAME'], '@userName');
                break;
        }
        return $infoUser;
    }

    //public function getModel($model)
    //{

    //    return new $model();
    //}

    /**
     * Recursive Is writeable function
     *
     * @author Erik Amaru Ortiz <erik@colosa.com>
     *
     * @param $path path to scan recursively the write permission
     * @param $pattern pattern to filter some specified files
     * @return <boolean> if the $path, assuming that is a directory -> all files in it are writeables or not
     */
    public function is_rwritable($path, $pattern = '*')
    {
        $files = G::rglob($pattern, 0, $path);
        foreach ($files as $file) {
            if (! is_writable($file)) {
                return false;
            }
        }
        return true;
    }

    /**
     * Recursive version of glob php standard function
     *
     * @author Erik Amaru Ortiz <erik@colosa.com>
     *
     * @param $path path to scan recursively the write permission
     * @param $flags to notive glob function
     * @param $pattern pattern to filter some specified files
     * @return <array> array containing the recursive glob results
     */
    public static function rglob($pattern = '*', $flags = 0, $path = '')
    {
        $paths = glob($path.'*', GLOB_MARK|GLOB_ONLYDIR|GLOB_NOSORT);
        $files = glob($path.$pattern, $flags);
        foreach ($paths as $path) {
            $files = array_merge($files, G::rglob($pattern, $flags, $path));
        }
        return $files;
    }

    public function browser_detection($which_test, $test_excludes = '', $external_ua_string = '')
    {
        G::script_time(); // set script timer to start timing

        static $a_full_assoc_data, $a_mobile_data, $a_moz_data, $a_webkit_data, $b_dom_browser, $b_repeat, $b_safe_browser, $browser_name, $browser_number, $browser_math_number, $browser_user_agent, $browser_working, $ie_version, $mobile_test, $moz_number, $moz_rv, $moz_rv_full, $moz_release_date, $moz_type, $os_number, $os_type, $true_ie_number, $ua_type, $webkit_type, $webkit_type_number;

        // switch off the optimization for external ua string testing.
        if ( $external_ua_string ) {
            $b_repeat = false;
        }

        /*
        this makes the test only run once no matter how many times you call it since
        all the variables are filled on the first run through, it's only a matter of
        returning the the right ones
        */
        if ( !$b_repeat ) {
            //initialize all variables with default values to prevent error
            $a_browser_math_number = '';
            $a_full_assoc_data = '';
            $a_full_data = '';
            $a_mobile_data = '';
            $a_moz_data = '';
            $a_os_data = '';
            $a_unhandled_browser = '';
            $a_webkit_data = '';
            $b_dom_browser = false;
            $b_os_test = true;
            $b_mobile_test = true;
            $b_safe_browser = false;
            $b_success = false;// boolean for if browser found in main test
            $browser_math_number = '';
            $browser_temp = '';
            $browser_working = '';
            $browser_number = '';
            $ie_version = '';
            $mobile_test = '';
            $moz_release_date = '';
            $moz_rv = '';
            $moz_rv_full = '';
            $moz_type = '';
            $moz_number = '';
            $os_number = '';
            $os_type = '';
            $run_time = '';
            $true_ie_number = '';
            $ua_type = 'bot';// default to bot since you never know with bots
            $webkit_type = '';
            $webkit_type_number = '';

            // set the excludes if required
            if ( $test_excludes ) {
                switch ( $test_excludes ){
                    case '1':
                        $b_os_test = false;
                        break;
                    case '2':
                        $b_mobile_test = false;
                        break;
                    case '3':
                        $b_os_test = false;
                        $b_mobile_test = false;
                        break;
                    default:
                        die( 'Error: bad $test_excludes parameter 2 used: ' . $test_excludes );
                        break;
                }
            }

            /*
            make navigator user agent string lower case to make sure all versions get caught
            isset protects against blank user agent failure. tolower also lets the script use
            strstr instead of stristr, which drops overhead slightly.
            */
            if ( $external_ua_string ) {
                $browser_user_agent = strtolower( $external_ua_string );
            } elseif ( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
                $browser_user_agent = strtolower( $_SERVER['HTTP_USER_AGENT'] );
            } else {
                $browser_user_agent = '';
            }

            // known browsers, list will be updated routinely, check back now and then
            $a_browser_types = array(
                array( 'opera', true, 'op', 'bro' ),
                array( 'msie', true, 'ie', 'bro' ),
                // webkit before gecko because some webkit ua strings say: like gecko
                array( 'webkit', true, 'webkit', 'bro' ),
                // konq will be using webkit soon
                array( 'konqueror', true, 'konq', 'bro' ),
                // covers Netscape 6-7, K-Meleon, Most linux versions, uses moz array below
                array( 'gecko', true, 'moz', 'bro' ),
                array( 'netpositive', false, 'netp', 'bbro' ),// beos browser
                array( 'lynx', false, 'lynx', 'bbro' ), // command line browser
                array( 'elinks ', false, 'elinks', 'bbro' ), // new version of links
                array( 'elinks', false, 'elinks', 'bbro' ), // alternate id for it
                array( 'links2', false, 'links2', 'bbro' ), // alternate links version
                array( 'links ', false, 'links', 'bbro' ), // old name for links
                array( 'links', false, 'links', 'bbro' ), // alternate id for it
                array( 'w3m', false, 'w3m', 'bbro' ), // open source browser, more features than lynx/links
                array( 'webtv', false, 'webtv', 'bbro' ),// junk ms webtv
                array( 'amaya', false, 'amaya', 'bbro' ),// w3c browser
                array( 'dillo', false, 'dillo', 'bbro' ),// linux browser, basic table support
                array( 'ibrowse', false, 'ibrowse', 'bbro' ),// amiga browser
                array( 'icab', false, 'icab', 'bro' ),// mac browser
                array( 'crazy browser', true, 'ie', 'bro' ),// uses ie rendering engine

                // search engine spider bots:
                array( 'bingbot', false, 'bing', 'bot' ),// bing
                array( 'exabot', false, 'exabot', 'bot' ),// exabot
                array( 'googlebot', false, 'google', 'bot' ),// google
                array( 'google web preview', false, 'googlewp', 'bot' ),// google preview
                array( 'mediapartners-google', false, 'adsense', 'bot' ),// google adsense
                array( 'yahoo-verticalcrawler', false, 'yahoo', 'bot' ),// old yahoo bot
                array( 'yahoo! slurp', false, 'yahoo', 'bot' ), // new yahoo bot
                array( 'yahoo-mm', false, 'yahoomm', 'bot' ), // gets Yahoo-MMCrawler and Yahoo-MMAudVid bots
                array( 'inktomi', false, 'inktomi', 'bot' ), // inktomi bot
                array( 'slurp', false, 'inktomi', 'bot' ), // inktomi bot
                array( 'fast-webcrawler', false, 'fast', 'bot' ),// Fast AllTheWeb
                array( 'msnbot', false, 'msn', 'bot' ),// msn search
                array( 'ask jeeves', false, 'ask', 'bot' ), //jeeves/teoma
                array( 'teoma', false, 'ask', 'bot' ),//jeeves teoma
                array( 'scooter', false, 'scooter', 'bot' ),// altavista
                array( 'openbot', false, 'openbot', 'bot' ),// openbot, from taiwan
                array( 'ia_archiver', false, 'ia_archiver', 'bot' ),// ia archiver
                array( 'zyborg', false, 'looksmart', 'bot' ),// looksmart
                array( 'almaden', false, 'ibm', 'bot' ),// ibm almaden web crawler
                array( 'baiduspider', false, 'baidu', 'bot' ),// Baiduspider asian search spider
                array( 'psbot', false, 'psbot', 'bot' ),// psbot image crawler
                array( 'gigabot', false, 'gigabot', 'bot' ),// gigabot crawler
                array( 'naverbot', false, 'naverbot', 'bot' ),// naverbot crawler, bad bot, block
                array( 'surveybot', false, 'surveybot', 'bot' ),//
                array( 'boitho.com-dc', false, 'boitho', 'bot' ),//norwegian search engine
                array( 'objectssearch', false, 'objectsearch', 'bot' ),// open source search engine
                array( 'answerbus', false, 'answerbus', 'bot' ),// http://www.answerbus.com/, web questions
                array( 'sohu-search', false, 'sohu', 'bot' ),// chinese media company, search component
                array( 'iltrovatore-setaccio', false, 'il-set', 'bot' ),

                // various http utility libaries
                array( 'w3c_validator', false, 'w3c', 'lib' ), // uses libperl, make first
                array( 'wdg_validator', false, 'wdg', 'lib' ), //
                array( 'libwww-perl', false, 'libwww-perl', 'lib' ),
                array( 'jakarta commons-httpclient', false, 'jakarta', 'lib' ),
                array( 'python-urllib', false, 'python-urllib', 'lib' ),
                // download apps
                array( 'getright', false, 'getright', 'dow' ),
                array( 'wget', false, 'wget', 'dow' ),// open source downloader, obeys robots.txt
                // netscape 4 and earlier tests, put last so spiders don't get caught
                array( 'mozilla/4.', false, 'ns', 'bbro' ),
                array( 'mozilla/3.', false, 'ns', 'bbro' ),
                array( 'mozilla/2.', false, 'ns', 'bbro' )
            );

            //array( '', false ); // browser array template

            /*
            moz types array
            note the order, netscape6 must come before netscape, which  is how netscape 7 id's itself.
            rv comes last in case it is plain old mozilla. firefox/netscape/seamonkey need to be later
            Thanks to: http://www.zytrax.com/tech/web/firefox-history.html
            */
            $a_moz_types = array( 'bonecho', 'camino', 'epiphany', 'firebird', 'flock', 'galeon', 'iceape', 'icecat', 'k-meleon', 'minimo', 'multizilla', 'phoenix', 'songbird', 'swiftfox', 'seamonkey', 'shiretoko', 'iceweasel', 'firefox', 'minefield', 'netscape6', 'netscape', 'rv' );

            /*
            webkit types, this is going to expand over time as webkit browsers spread
            konqueror is probably going to move to webkit, so this is preparing for that
            It will now default to khtml. gtklauncher is the temp id for epiphany, might
            change. Defaults to applewebkit, and will all show the webkit number.
            */
            $a_webkit_types = array( 'arora', 'chrome', 'epiphany', 'gtklauncher', 'konqueror', 'midori', 'omniweb', 'safari', 'uzbl', 'applewebkit', 'webkit' );

            /*
            run through the browser_types array, break if you hit a match, if no match, assume old browser
            or non dom browser, assigns false value to $b_success.
            */
            $i_count = count( $a_browser_types );
            for ($i = 0; $i < $i_count; $i++) {
                //unpacks browser array, assigns to variables, need to not assign til found in string
                $browser_temp = $a_browser_types[$i][0];// text string to id browser from array

                if ( strstr( $browser_user_agent, $browser_temp ) ) {
                    /*
                    it defaults to true, will become false below if needed
                    this keeps it easier to keep track of what is safe, only
                    explicit false assignment will make it false.
                    */
                    $b_safe_browser = true;
                    $browser_name = $browser_temp;// text string to id browser from array

                    // assign values based on match of user agent string
                    $b_dom_browser = $a_browser_types[$i][1];// hardcoded dom support from array
                    $browser_working = $a_browser_types[$i][2];// working name for browser
                    $ua_type = $a_browser_types[$i][3];// sets whether bot or browser

                    switch ( $browser_working ) {
                        // this is modified quite a bit, now will return proper netscape version number
                        // check your implementation to make sure it works
                        case 'ns':
                            $b_safe_browser = false;
                            $browser_number = G::get_item_version( $browser_user_agent, 'mozilla' );
                            break;
                        case 'moz':
                            /*
                            note: The 'rv' test is not absolute since the rv number is very different on
                            different versions, for example Galean doesn't use the same rv version as Mozilla,
                            neither do later Netscapes, like 7.x. For more on this, read the full mozilla
                            numbering conventions here: http://www.mozilla.org/releases/cvstags.html
                            */
                            // this will return alpha and beta version numbers, if present
                            $moz_rv_full = G::get_item_version( $browser_user_agent, 'rv' );
                            // this slices them back off for math comparisons
                            $moz_rv = substr( $moz_rv_full, 0, 3 );

                            // this is to pull out specific mozilla versions, firebird, netscape etc..
                            $j_count = count( $a_moz_types );
                            for ($j = 0; $j < $j_count; $j++) {
                                if ( strstr( $browser_user_agent, $a_moz_types[$j] ) ) {
                                    $moz_type = $a_moz_types[$j];
                                    $moz_number = G::get_item_version( $browser_user_agent, $moz_type );
                                    break;
                                }
                            }
                            /*
                            this is necesary to protect against false id'ed moz'es and new moz'es.
                            this corrects for galeon, or any other moz browser without an rv number
                            */
                            if ( !$moz_rv ) {
                                // you can use this if you are running php >= 4.2
                                if ( function_exists( 'floatval' ) ) {
                                    $moz_rv = floatval( $moz_number );
                                } else {
                                    $moz_rv = substr( $moz_number, 0, 3 );
                                }
                                $moz_rv_full = $moz_number;
                            }
                            // this corrects the version name in case it went to the default 'rv' for the test
                            if ( $moz_type == 'rv' ) {
                                $moz_type = 'mozilla';
                            }

                            //the moz version will be taken from the rv number, see notes above for rv problems
                            $browser_number = $moz_rv;
                            // gets the actual release date, necessary if you need to do functionality tests
                            G::get_set_count( 'set', 0 );
                            $moz_release_date = G::get_item_version( $browser_user_agent, 'gecko/' );
                            /*
                            Test for mozilla 0.9.x / netscape 6.x
                            test your javascript/CSS to see if it works in these mozilla releases, if it
                            does, just default it to: $b_safe_browser = true;
                            */
                            if ( ( $moz_release_date < 20020400 ) || ( $moz_rv < 1 ) ) {
                                $b_safe_browser = false;
                            }
                            break;
                        case 'ie':
                            /*
                            note we're adding in the trident/ search to return only first instance in case
                            of msie 8, and we're triggering the  break last condition in the test, as well
                            as the test for a second search string, trident/
                            */
                            $browser_number = G::get_item_version( $browser_user_agent, $browser_name, true, 'trident/' );
                            // construct the proper real number if it's in compat mode and msie 8.0/9.0
                            if ( strstr( $browser_number, '7.' ) && strstr( $browser_user_agent, 'trident/5' ) ) {
                                // note that 7.0 becomes 9 when adding 1, but if it's 7.1 it will be 9.1
                                $true_ie_number = $browser_number + 2;
                            } elseif ( strstr( $browser_number, '7.' ) && strstr( $browser_user_agent, 'trident/4' ) ) {
                                // note that 7.0 becomes 8 when adding 1, but if it's 7.1 it will be 8.1
                                $true_ie_number = $browser_number + 1;
                            }
                            // the 9 series is finally standards compatible, html 5 etc, so worth a new id
                            if ( $browser_number >= 9 ) {
                                $ie_version = 'ie9x';
                            } elseif ( $browser_number >= 7 ) {
                                $ie_version = 'ie7x';
                            } elseif ( strstr( $browser_user_agent, 'mac') ) {
                                $ie_version = 'ieMac';
                            } elseif ( $browser_number >= 5 ) {
                                $ie_version = 'ie5x';
                            } elseif ( ( $browser_number > 3 ) && ( $browser_number < 5 ) ) {
                                $b_dom_browser = false;
                                $ie_version = 'ie4';
                                // this depends on what you're using the script for, make sure this fits your needs
                                $b_safe_browser = true;
                            } else {
                                $ie_version = 'old';
                                $b_dom_browser = false;
                                $b_safe_browser = false;
                            }
                            break;
                        case 'op':
                            $browser_number = G::get_item_version( $browser_user_agent, $browser_name );
                            // opera is leaving version at 9.80 (or xx) for 10.x - see this for explanation
                            // http://dev.opera.com/articles/view/opera-ua-string-changes/
                            if ( strstr( $browser_number, '9.' ) && strstr( $browser_user_agent, 'version/' ) ) {
                                G::get_set_count( 'set', 0 );
                                $browser_number = G::get_item_version( $browser_user_agent, 'version/' );
                            }

                            if ( $browser_number < 5 ) {
                                $b_safe_browser = false;
                            }
                            break;
                        case 'webkit':
                            // note that this is the Webkit version number
                            $browser_number = G::get_item_version( $browser_user_agent, $browser_name );
                            // this is to pull out specific webkit versions, safari, google-chrome etc..
                            $j_count = count( $a_webkit_types );
                            for ($j = 0; $j < $j_count; $j++) {
                                if (strstr( $browser_user_agent, $a_webkit_types[$j])) {
                                    $webkit_type = $a_webkit_types[$j];
                                    if ( $webkit_type == 'omniweb' ) {
                                        G::get_set_count( 'set', 2 );
                                    }
                                    $webkit_type_number = G::get_item_version( $browser_user_agent, $webkit_type );
                                    // epiphany hack
                                    if ( $a_webkit_types[$j] == 'gtklauncher' ) {
                                        $browser_name = 'epiphany';
                                    } else {
                                        $browser_name = $a_webkit_types[$j];
                                    }
                                    break;
                                }
                            }
                            break;
                        default:
                            $browser_number = G::get_item_version( $browser_user_agent, $browser_name );
                            break;
                    }
                    // the browser was id'ed
                    $b_success = true;
                    break;
                }
            }

            //assigns defaults if the browser was not found in the loop test
            if ( !$b_success ) {
                /*
                this will return the first part of the browser string if the above id's failed
                usually the first part of the browser string has the navigator useragent name/version in it.
                This will usually correctly id the browser and the browser number if it didn't get
                caught by the above routine.
                If you want a '' to do a if browser == '' type test, just comment out all lines below
                except for the last line, and uncomment the last line. If you want undefined values,
                the browser_name is '', you can always test for that
                */
                // delete this part if you want an unknown browser returned
                $browser_name = substr( $browser_user_agent, 0, strcspn( $browser_user_agent , '();') );
                // this extracts just the browser name from the string, if something usable was found
                if ( $browser_name && preg_match( '/[^0-9][a-z]*-*\ *[a-z]*\ *[a-z]*/', $browser_name, $a_unhandled_browser ) ) {
                    $browser_name = $a_unhandled_browser[0];
                    if ( $browser_name == 'blackberry' ) {
                        G::get_set_count( 'set', 0 );
                    }
                    $browser_number = G::get_item_version( $browser_user_agent, $browser_name );
                } else {
                    $browser_name = 'NA';
                    $browser_number = 'NA';
                }
            }
            // get os data, mac os x test requires browser/version information, this is a change from older scripts
            if ($b_os_test) {
                $a_os_data = G::get_os_data( $browser_user_agent, $browser_working, $browser_number );
                $os_type = $a_os_data[0];// os name, abbreviated
                $os_number = $a_os_data[1];// os number or version if available
            }
            /*
            this ends the run through once if clause, set the boolean
            to true so the function won't retest everything
            */
            $b_repeat = true;
            if ($browser_number && preg_match( '/[0-9]*\.*[0-9]*/', $browser_number, $a_browser_math_number ) ) {
                $browser_math_number = $a_browser_math_number[0];
            }
            if ( $b_mobile_test ) {
                $mobile_test = G::check_is_mobile( $browser_user_agent );
                if ( $mobile_test ) {
                    $a_mobile_data = G::get_mobile_data( $browser_user_agent );
                    $ua_type = 'mobile';
                }
            }
        }

        switch ($which_test) {
            case 'math_number':
                $which_test = 'browser_math_number';
                break;
            case 'number':
                $which_test = 'browser_number';
                break;
            case 'browser':
                $which_test = 'browser_working';
                break;
            case 'moz_version':
                $which_test = 'moz_data';
                break;
            case 'true_msie_version':
                $which_test = 'true_ie_number';
                break;
            case 'type':
                $which_test = 'ua_type';
                break;
            case 'webkit_version':
                $which_test = 'webkit_data';
                break;
        }
        /*
        assemble these first so they can be included in full return data, using static variables
        Note that there's no need to keep repacking these every time the script is called
        */
        if (!$a_moz_data) {
            $a_moz_data = array( $moz_type, $moz_number, $moz_rv, $moz_rv_full, $moz_release_date );
        }
        if (!$a_webkit_data) {
            $a_webkit_data = array( $webkit_type, $webkit_type_number, $browser_number );
        }
        $run_time = G::script_time();

        if ( !$a_full_assoc_data ) {
            $a_full_assoc_data = array(
                'browser_working' => $browser_working,
                'browser_number' => $browser_number,
                'ie_version' => $ie_version,
                'dom' => $b_dom_browser,
                'safe' => $b_safe_browser,
                'os' => $os_type,
                'os_number' => $os_number,
                'browser_name' => $browser_name,
                'ua_type' => $ua_type,
                'browser_math_number' => $browser_math_number,
                'moz_data' => $a_moz_data,
                'webkit_data' => $a_webkit_data,
                'mobile_test' => $mobile_test,
                'mobile_data' => $a_mobile_data,
                'true_ie_number' => $true_ie_number,
                'run_time' => $run_time
            );
        }

        // return parameters, either full data arrays, or by associative array index key
        switch ($which_test) {
            // returns all relevant browser information in an array with standard numberic indexes
            case 'full':
                $a_full_data = array(
                    $browser_working,
                    $browser_number,
                    $ie_version,
                    $b_dom_browser,
                    $b_safe_browser,
                    $os_type,
                    $os_number,
                    $browser_name,
                    $ua_type,
                    $browser_math_number,
                    $a_moz_data,
                    $a_webkit_data,
                    $mobile_test,
                    $a_mobile_data,
                    $true_ie_number,
                    $run_time
                );
                return $a_full_data;
                break;
            case 'full_assoc':
                return $a_full_assoc_data;
                break;
            default:
                # check to see if the data is available, otherwise it's user typo of unsupported option
                if (isset( $a_full_assoc_data[$which_test])) {
                    return $a_full_assoc_data[$which_test];
                } else {
                    die( "You passed the browser detector an unsupported option for parameter 1: " . $which_test );
                }
                break;
        }
    }

    // gets which os from the browser string
    public function get_os_data ($pv_browser_string, $pv_browser_name, $pv_version_number)
    {
        // initialize variables
        $os_working_type = '';
        $os_working_number = '';
        /*
        packs the os array. Use this order since some navigator user agents will put 'macintosh'
        in the navigator user agent string which would make the nt test register true
        */
        $a_mac = array( 'intel mac', 'ppc mac', 'mac68k' );// this is not used currently
        // same logic, check in order to catch the os's in order, last is always default item
        $a_unix_types = array( 'dragonfly', 'freebsd', 'openbsd', 'netbsd', 'bsd', 'unixware', 'solaris', 'sunos', 'sun4', 'sun5', 'suni86', 'sun', 'irix5', 'irix6', 'irix', 'hpux9', 'hpux10', 'hpux11', 'hpux', 'hp-ux', 'aix1', 'aix2', 'aix3', 'aix4', 'aix5', 'aix', 'sco', 'unixware', 'mpras', 'reliant', 'dec', 'sinix', 'unix' );
        // only sometimes will you get a linux distro to id itself...
        $a_linux_distros = array( 'ubuntu', 'kubuntu', 'xubuntu', 'mepis', 'xandros', 'linspire', 'winspire', 'jolicloud', 'sidux', 'kanotix', 'debian', 'opensuse', 'suse', 'fedora', 'redhat', 'slackware', 'slax', 'mandrake', 'mandriva', 'gentoo', 'sabayon', 'linux' );
        $a_linux_process = array ( 'i386', 'i586', 'i686' );// not use currently
        // note, order of os very important in os array, you will get failed ids if changed
        $a_os_types = array( 'android', 'blackberry', 'iphone', 'palmos', 'palmsource', 'symbian', 'beos', 'os2', 'amiga', 'webtv', 'mac', 'nt', 'win', $a_unix_types, $a_linux_distros );

        //os tester
        $i_count = count( $a_os_types );
        for ($i = 0; $i < $i_count; $i++) {
            // unpacks os array, assigns to variable $a_os_working
            $os_working_data = $a_os_types[$i];
            /*
            assign os to global os variable, os flag true on success
            !strstr($pv_browser_string, "linux" ) corrects a linux detection bug
            */
            if (!is_array($os_working_data) && strstr($pv_browser_string, $os_working_data ) && !strstr( $pv_browser_string, "linux")) {
                $os_working_type = $os_working_data;

                switch ($os_working_type) {
                    // most windows now uses: NT X.Y syntax
                    case 'nt':
                        if (strstr( $pv_browser_string, 'nt 6.1' )) {
                            $os_working_number = 6.1;
                        } elseif (strstr( $pv_browser_string, 'nt 6.0')) {
                            $os_working_number = 6.0;
                        } elseif (strstr( $pv_browser_string, 'nt 5.2')) {
                            $os_working_number = 5.2;
                        } elseif (strstr( $pv_browser_string, 'nt 5.1') || strstr( $pv_browser_string, 'xp')) {
                            $os_working_number = 5.1;//
                        } elseif (strstr( $pv_browser_string, 'nt 5') || strstr( $pv_browser_string, '2000')) {
                            $os_working_number = 5.0;
                        } elseif (strstr( $pv_browser_string, 'nt 4')) {
                            $os_working_number = 4;
                        } elseif (strstr( $pv_browser_string, 'nt 3')) {
                            $os_working_number = 3;
                        }
                        break;
                    case 'win':
                        if (strstr( $pv_browser_string, 'vista')) {
                            $os_working_number = 6.0;
                            $os_working_type = 'nt';
                        } elseif ( strstr( $pv_browser_string, 'xp')) {
                            $os_working_number = 5.1;
                            $os_working_type = 'nt';
                        } elseif ( strstr( $pv_browser_string, '2003')) {
                            $os_working_number = 5.2;
                            $os_working_type = 'nt';
                        }
                        elseif ( strstr( $pv_browser_string, 'windows ce' ) )// windows CE
                        {
                            $os_working_number = 'ce';
                            $os_working_type = 'nt';
                        }
                        elseif ( strstr( $pv_browser_string, '95' ) )
                        {
                            $os_working_number = '95';
                        }
                        elseif ( ( strstr( $pv_browser_string, '9x 4.9' ) ) || ( strstr( $pv_browser_string, ' me' ) ) )
                        {
                            $os_working_number = 'me';
                        }
                        elseif ( strstr( $pv_browser_string, '98' ) )
                        {
                            $os_working_number = '98';
                        }
                        elseif ( strstr( $pv_browser_string, '2000' ) )// windows 2000, for opera ID
                        {
                            $os_working_number = 5.0;
                            $os_working_type = 'nt';
                        }
                        break;
                    case 'mac':
                        if (strstr($pv_browser_string, 'os x')) {
                            if (strstr($pv_browser_string, 'os x ')) {
                                $os_working_number = str_replace( '_', '.', G::get_item_version( $pv_browser_string, 'os x' ) );
                            } else {
                                $os_working_number = 10;
                            }
                        } elseif ( ( $pv_browser_name == 'saf' ) || ( $pv_browser_name == 'cam' ) ||
                            ( ( $pv_browser_name == 'moz' ) && ( $pv_version_number >= 1.3 ) ) ||
                            ( ( $pv_browser_name == 'ie' ) && ( $pv_version_number >= 5.2 ) ) ) {
                            $os_working_number = 10;
                        }
                        break;
                    case 'iphone':
                        $os_working_number = 10;
                        break;
                    default:
                        break;
                }
                break;
            } elseif ( is_array( $os_working_data ) && ( $i == ( $i_count - 2 ) ) ) {
                $j_count = count($os_working_data);
                for ($j = 0; $j < $j_count; $j++) {
                    if (strstr( $pv_browser_string, $os_working_data[$j])) {
                        $os_working_type = 'unix'; //if the os is in the unix array, it's unix, obviously...
                        $os_working_number = ( $os_working_data[$j] != 'unix' ) ? $os_working_data[$j] : '';// assign sub unix version from the unix array
                        break;
                    }
                }
            } elseif (is_array( $os_working_data ) && ( $i == ( $i_count - 1 ))) {
                $j_count = count($os_working_data);
                for ($j = 0; $j < $j_count; $j++) {
                    if ( strstr( $pv_browser_string, $os_working_data[$j] )) {
                        $os_working_type = 'lin';
                        // assign linux distro from the linux array, there's a default
                        //search for 'lin', if it's that, set version to ''
                        $os_working_number = ( $os_working_data[$j] != 'linux' ) ? $os_working_data[$j] : '';
                        break;
                    }
                }
            }
        }

        // pack the os data array for return to main function
        $a_os_data = array( $os_working_type, $os_working_number );

        return $a_os_data;
    }

    public function get_item_version($pv_browser_user_agent, $pv_search_string, $pv_b_break_last = '', $pv_extra_search = '')
    {
        $substring_length = 15;
        $start_pos = 0; // set $start_pos to 0 for first iteration
        $string_working_number = '';
        for ($i = 0; $i < 4; $i++) {
            //start the search after the first string occurrence
            if (strpos( $pv_browser_user_agent, $pv_search_string, $start_pos ) !== false) {
                $start_pos = strpos( $pv_browser_user_agent, $pv_search_string, $start_pos ) + strlen( $pv_search_string );
                if (!$pv_b_break_last || ( $pv_extra_search && strstr( $pv_browser_user_agent, $pv_extra_search ) )) {
                    break;
                }
            } else {
                break;
            }
        }

        $start_pos += G::get_set_count( 'get' );
        $string_working_number = substr( $pv_browser_user_agent, $start_pos, $substring_length );
        $string_working_number = substr( $string_working_number, 0, strcspn($string_working_number, ' );/') );
        if (!is_numeric( substr( $string_working_number, 0, 1 ))) {
            $string_working_number = '';
        }
        return $string_working_number;
    }

    public function get_set_count($pv_type, $pv_value = '')
    {
        static $slice_increment;
        $return_value = '';
        switch ( $pv_type ) {
            case 'get':
                if ( is_null( $slice_increment ) ) {
                    $slice_increment = 1;
                }
                $return_value = $slice_increment;
                $slice_increment = 1; // reset to default
                return $return_value;
                break;
            case 'set':
                $slice_increment = $pv_value;
                break;
        }
    }

    public function check_is_mobile($pv_browser_user_agent)
    {
        $mobile_working_test = '';
        $a_mobile_search = array(
            'android', 'epoc', 'linux armv', 'palmos', 'palmsource', 'windows ce', 'windows phone os', 'symbianos', 'symbian os', 'symbian', 'webos',
            // devices - ipod before iphone or fails
            'benq', 'blackberry', 'danger hiptop', 'ddipocket', ' droid', 'ipad', 'ipod', 'iphone', 'kindle', 'lge-cx', 'lge-lx', 'lge-mx', 'lge vx', 'lge ', 'lge-', 'lg;lx', 'nintendo wii', 'nokia', 'palm', 'pdxgw', 'playstation', 'sagem', 'samsung', 'sec-sgh', 'sharp', 'sonyericsson', 'sprint', 'zune', 'j-phone', 'n410', 'mot 24', 'mot-', 'htc-', 'htc_', 'htc ', 'sec-', 'sie-m', 'sie-s', 'spv ', 'vodaphone', 'smartphone', 'armv', 'midp', 'mobilephone',
            // browsers
            'avantgo', 'blazer', 'elaine', 'eudoraweb', 'iemobile',  'minimo', 'mobile safari', 'mobileexplorer', 'opera mobi', 'opera mini', 'netfront', 'opwv', 'polaris', 'semc-browser', 'up.browser', 'webpro', 'wms pie', 'xiino',
            // services - astel out of business
            'astel',  'docomo',  'novarra-vision', 'portalmmm', 'reqwirelessweb', 'vodafone'
        );

        // then do basic mobile type search, this uses data from: get_mobile_data()
        $j_count = count( $a_mobile_search );
        for ($j = 0; $j < $j_count; $j++) {
            if (strstr( $pv_browser_user_agent, $a_mobile_search[$j] )) {
                $mobile_working_test = $a_mobile_search[$j];
                break;
            }
        }
        return $mobile_working_test;
    }

    public function get_mobile_data ($pv_browser_user_agent)
    {
        $mobile_browser = '';
        $mobile_browser_number = '';
        $mobile_device = '';
        $mobile_device_number = '';
        $mobile_os = ''; // will usually be null, sorry
        $mobile_os_number = '';
        $mobile_server = '';
        $mobile_server_number = '';

        $a_mobile_browser = array( 'avantgo', 'blazer', 'elaine', 'eudoraweb', 'iemobile',  'minimo', 'mobile safari', 'mobileexplorer', 'opera mobi', 'opera mini', 'netfront', 'opwv', 'polaris', 'semc-browser', 'up.browser', 'webpro', 'wms pie', 'xiino' );
        $a_mobile_device = array( 'benq', 'blackberry', 'danger hiptop', 'ddipocket', ' droid', 'htc_dream', 'htc espresso', 'htc hero', 'htc halo', 'htc huangshan', 'htc legend', 'htc liberty', 'htc paradise', 'htc supersonic', 'htc tattoo', 'ipad', 'ipod', 'iphone', 'kindle', 'lge-cx', 'lge-lx', 'lge-mx', 'lge vx', 'lg;lx', 'nintendo wii', 'nokia', 'palm', 'pdxgw', 'playstation', 'sagem', 'samsung', 'sec-sgh', 'sharp', 'sonyericsson', 'sprint', 'zunehd', 'zune', 'j-phone', 'milestone', 'n410', 'mot 24', 'mot-', 'htc-', 'htc_',  'htc ', 'lge ', 'lge-', 'sec-', 'sie-m', 'sie-s', 'spv ', 'smartphone', 'armv', 'midp', 'mobilephone' );
        $a_mobile_os = array( 'android', 'epoc', 'cpu os', 'iphone os', 'palmos', 'palmsource', 'windows phone os', 'windows ce', 'symbianos', 'symbian os', 'symbian', 'webos', 'linux armv'  );
        $a_mobile_server = array( 'astel', 'docomo', 'novarra-vision', 'portalmmm', 'reqwirelessweb', 'vodafone' );

        $k_count = count( $a_mobile_browser );
        for ($k = 0; $k < $k_count; $k++) {
            if (strstr( $pv_browser_user_agent, $a_mobile_browser[$k] )) {
                $mobile_browser = $a_mobile_browser[$k];
                $mobile_browser_number = G::get_item_version( $pv_browser_user_agent, $mobile_browser );
                break;
            }
        }
        $k_count = count( $a_mobile_device );
        for ($k = 0; $k < $k_count; $k++) {
            if (strstr( $pv_browser_user_agent, $a_mobile_device[$k] )) {
                $mobile_device = trim ( $a_mobile_device[$k], '-_' ); // but not space trims yet
                if ($mobile_device == 'blackberry') {
                    G::get_set_count( 'set', 0 );
                }
                $mobile_device_number = G::get_item_version( $pv_browser_user_agent, $mobile_device );
                $mobile_device = trim( $mobile_device ); // some of the id search strings have white space
                break;
            }
        }
        $k_count = count( $a_mobile_os );
        for ($k = 0; $k < $k_count; $k++) {
            if (strstr( $pv_browser_user_agent, $a_mobile_os[$k] )) {
                $mobile_os = $a_mobile_os[$k];
                $mobile_os_number = str_replace( '_', '.', G::get_item_version( $pv_browser_user_agent, $mobile_os ) );
                break;
            }
        }
        $k_count = count( $a_mobile_server );
        for ($k = 0; $k < $k_count; $k++) {
            if (strstr( $pv_browser_user_agent, $a_mobile_server[$k] )) {
                $mobile_server = $a_mobile_server[$k];
                $mobile_server_number = G::get_item_version( $pv_browser_user_agent, $mobile_server );
                break;
            }
        }
        // just for cases where we know it's a mobile device already
        if (!$mobile_os && ( $mobile_browser || $mobile_device || $mobile_server ) && strstr( $pv_browser_user_agent, 'linux' ) ) {
            $mobile_os = 'linux';
            $mobile_os_number = G::get_item_version( $pv_browser_user_agent, 'linux' );
        }

        $a_mobile_data = array( $mobile_device, $mobile_browser, $mobile_browser_number, $mobile_os, $mobile_os_number, $mobile_server, $mobile_server_number, $mobile_device_number );
        return $a_mobile_data;
    }

    public function getBrowser ()
    {
        $u_agent = $_SERVER['HTTP_USER_AGENT'];
        $bname = 'Unknown';
        $platform = 'Unknown';
        $version = "";
        $ub = "other";

        //First get the platform?
        if (preg_match( '/linux/i', $u_agent )) {
            $platform = 'linux';
        } elseif (preg_match( '/macintosh|mac os x/i', $u_agent )) {
            $platform = 'mac';
        } elseif (preg_match( '/windows|win32/i', $u_agent )) {
            $platform = 'windows';
        }

        // Next get the name of the useragent yes seperately and for good reason
        if ((preg_match('~Trident/7.0; rv:11.0~', $u_agent) || preg_match( '/MSIE/i', $u_agent )) && ! preg_match( '/Opera/i', $u_agent )) {
            $bname = 'Internet Explorer';
            $ub = "MSIE";
        } elseif (preg_match( '/Firefox/i', $u_agent )) {
            $bname = 'Mozilla Firefox';
            $ub = "Firefox";
        } elseif ((preg_match( '/Opera/i', $u_agent )) || (preg_match( '/OPR/i', $u_agent ))) {
            $bname = 'Opera';
            $ub = "Opera";
        } elseif (preg_match( '/Chrome/i', $u_agent )) {
            $bname = 'Google Chrome';
            $ub = "Chrome";
        } elseif (preg_match( '/Safari/i', $u_agent )) {
            $bname = 'Apple Safari';
            $ub = "Safari";
        } elseif (preg_match( '/Netscape/i', $u_agent )) {
            $bname = 'Netscape';
            $ub = "Netscape";
        } elseif (preg_match( '/bingbot/i', $u_agent )) {
            $bname = 'Bing Bot';
            $ub = "bingbot";
        }

        // finally get the correct version number
        $known = array ('Version',$ub,'other');
        $pattern = '#(?P<browser>' . join( '|', $known ) . ')[/ ]+(?P<version>[0-9.|a-zA-Z.]*)#';
        @preg_match_all( $pattern, $u_agent, $matches );

        // see how many we have
        $i = count( $matches['browser'] );
        if ($i != 1) {
            //we will have two since we are not using 'other' argument yet
            //see if version is before or after the name
            if (strripos( $u_agent, "Version" ) < strripos( $u_agent, $ub )) {
                $version = $matches['version'][0];
            } else {
                $version = isset($matches['version'][1]) ? $matches['version'][1] : '';
            }
        } else {
            $version = $matches['version'][0];
        }

        // check if we have a number
        if ($version == null || $version == "") {
        	if($ub == 'MSIE'){
        		$parent = 'RV';
        	} elseif ($ub == 'Opera'){
        		$parent = 'OPR';
        	}
        	if (isset($parent) && $parent != ""){
        		$s = strpos(strtoupper($u_agent), $parent);
        		$f = $s + strlen($parent);
        		$version = substr($u_agent, $f, 15);
        		$version = preg_replace('/[^0-9,.]/','',$version);
            }else {
                $version = "?";
        	}
        }

        return array ('userAgent' => $u_agent,'name' => strtolower( $ub ),'longName' => $bname,'version' => $version,'platform' => $platform,'pattern' => $pattern
        );
    }

    // track total script execution time
    public function script_time ()
    {
        static $script_time;
        $elapsed_time = '';
        /*
        note that microtime(true) requires php 5 or greater for microtime(true)
        */
        if (sprintf( "%01.1f", phpversion() ) >= 5) {
            if (is_null( $script_time )) {
                $script_time = microtime( true );
            } else {
                // note: (string)$var is same as strval($var)
                // $elapsed_time = (string)( microtime(true) - $script_time );
                $elapsed_time = (microtime( true ) - $script_time);
                $elapsed_time = sprintf( "%01.8f", $elapsed_time );
                $script_time = null; // can't unset a static variable
                return $elapsed_time;
            }
        }
    }

    public function getDirectorySize ($path, $maxmtime = 0)
    {
        $totalsize = 0;
        $totalcount = 0;
        $dircount = 0;
        if ($handle = opendir( $path )) {
            while (false !== ($file = readdir( $handle ))) {
                $nextpath = $path . '/' . $file;
                if ($file != '.' && $file != '..' && ! is_link( $nextpath ) && $file != '.svn') {
                    if (is_dir( $nextpath )) {
                        $dircount ++;
                        $result = G::getDirectorySize( $nextpath, $maxmtime );
                        $totalsize += $result['size'];
                        $totalcount += $result['count'];
                        $dircount += $result['dircount'];
                        $maxmtime = $result['maxmtime'] > $maxmtime ? $result['maxmtime'] : $maxmtime;
                    } elseif (is_file( $nextpath )) {
                        $totalsize += filesize( $nextpath );
                        $totalcount ++;

                        $mtime = filemtime( $nextpath );
                        if ($mtime > $maxmtime) {
                            $maxmtime = $mtime;
                        }
                    }
                }
            }
        }
        closedir( $handle );
        $total['size'] = $totalsize;
        $total['count'] = $totalcount;
        $total['dircount'] = $dircount;
        $total['maxmtime'] = $maxmtime;

        return $total;
    }

    /**
     * Get checksum from multiple files
     *
     * @author erik amaru ortiz <erik@colosa.com>
     */
    public function getCacheFileNameByPattern ($path, $pattern)
    {
        if ($file = glob( $path . $pattern )) {
            preg_match( '/[a-f0-9]{32}/', $file[0], $match );
        } else {
            $file[0] = '';
        }
        return array ('filename' => $file[0],'checksum' => (isset( $match[0] ) ? $match[0] : ''));
    }

    /**
     * Get checksum from multiple files
     *
     * @author erik amaru ortiz <erik@colosa.com>
     */
    public function getCheckSum ($files)
    {
        $key = System::getVersion();

        if (! is_array( $files )) {
            $tmp = $files;
            $files = array ();
            $files[0] = $tmp;
        }

        $checkSum = '';
        foreach ($files as $file) {
            if (is_file( $file )) {
                $checkSum .= G::encryptFileOld( $file );
            }
        }
        return G::encryptOld( $checkSum . $key );
    }

    /**
     * parse_ini_string
     * Define parse_ini_string if it doesn't exist.
     * Does accept lines starting with ; as comments
     * Does not accept comments after values
     */
    public function parse_ini_string ($string)
    {
        if (function_exists( 'parse_ini_string' )) {
            return parse_ini_string( $string );
        } else {
            $array = Array ();
            $lines = explode( "\n", $string );

            foreach ($lines as $line) {
                $statement = preg_match( "/^(?!;)(?P<key>[\w+\.\-]+?)\s*=\s*(?P<value>.+?)\s*$/", $line, $match );
                if ($statement) {
                    $key = $match['key'];
                    $value = $match['value'];

                    //Remove quote
                    if (preg_match( "/^\".*\"$/", $value ) || preg_match( "/^'.*'$/", $value )) {
                        $value = mb_substr( $value, 1, mb_strlen( $value ) - 2 );
                    }
                    $array[$key] = $value;
                }
            }
            return $array;
        }
    }

    /**
     * disableEnableINIvariable
     * disable or enable a variable in ini file, this is useful for editing the env.ini file
     * automatically get the value, and change to inverse value, I mean from true to false and viceversa
     */
    public function disableEnableINIvariable ($inifile, $variable)
    {
        $enabled = 'false';
        if (file_exists( $inifile )) {
            $fp = fopen( $inifile, 'r' );
            $line = fgets( $fp );
            $found = false;
            $buffer = null;

            while (! feof( $fp )) {
                $config = G::parse_ini_string( $line );
                if (isset( $config[$variable] )) {
                    $enabled = $config[$variable];
                    $buffer .= sprintf( "%s = %d \n", $variable, 1 - $enabled );
                    $found = true;
                } else {
                    $buffer .= trim( $line ) . "\n";
                }
                $line = fgets( $fp );
            }
            fclose( $fp );
            if (! $found) {
                $buffer .= sprintf( "\n%s = 1 \n", $variable );
            }
            @file_put_contents( $inifile, $buffer );
        } else {
            $contents = file_put_contents( $inifile, sprintf( "\n%s = 1\n", $variable ) );
        }
    }

    /**
     * set a variable in ini file
     */
    public function setINIvariable ($inifile, $variable, $value)
    {
        if (file_exists( $inifile )) {
            $fp = fopen( $inifile, 'r' );
            $line = fgets( $fp );
            $found = false;
            $buffer = null;

            while (! feof( $fp )) {
                $config = G::parse_ini_string( $line );
                if (isset( $config[$variable] )) {
                    $enabled = $config[$variable];
                    $buffer .= sprintf( "%s = %s \n", $variable, $value );
                    $found = true;
                } else {
                    $buffer .= trim( $line ) . "\n";
                }
                $line = fgets( $fp );
            }
            fclose( $fp );
            if (! $found) {
                $buffer .= sprintf( "\n%s = %s \n", $variable, $value );
            }
            file_put_contents( $inifile, $buffer );
        } else {
            $contents = file_put_contents( $inifile, sprintf( "\n%s = $s\n", $variable, $value ) );
        }
    }

    public function write_php_ini ($file, $array)
    {
        $res = array ();
        foreach ($array as $key => $val) {
            if (is_array( $val )) {
                $res[] = "[$key]";
                foreach ($val as $skey => $sval) {
                    $res[] = "$skey = " . (is_numeric( $sval ) ? $sval : '"' . $sval . '"');
                }
            } else {
                $res[] = "$key = " . (is_numeric( $val ) ? $val : '"' . $val . '"');
            }
        }
        file_put_contents( $file, implode( "\r\n", $res ) );
    }

    /**
     * verify if all files & directories passed by param.
     * are writable
     *
     * @author Erik Amaru Ortiz <erik@colosa.com>
     * @param $resources array a list of files to verify write access
     */
    public function verifyWriteAccess ($resources)
    {
        $noWritable = array ();
        foreach ($resources as $i => $resource) {
            if (! is_writable( $resource )) {
                $noWritable[] = $resource;
            }
        }

        if (count( $noWritable ) > 0) {
            $e = new Exception( "Write access not allowed for ProcessMaker resources" );
            $e->files = $noWritable;
            throw $e;
        }
    }

    /**
     * render a smarty template
     *
     * @author Erik Amaru Ortiz <erik@colosa.com>
     * @param $template string containing the template filename on /gulliver/templates/ directory
     * @param $data associative array containig the template data
     */
    public function renderTemplate ($template, $data = array())
    {
        if (! defined( 'PATH_THIRDPARTY' )) {
            throw new Exception( 'System constant (PATH_THIRDPARTY) is not defined!' );
        }

        $fInfo = pathinfo( $template );

        $tplExists = true;

        // file has absolute path
        if (strpos($template, PATH_TRUNK) === false) {
            $template = PATH_TPL . $template;
        }

        // fix for template that have dot in its name but is not a valid extension
        if (isset( $fInfo['extension'] ) && ($fInfo['extension'] != 'tpl' || $fInfo['extension'] != 'html')) {
            unset( $fInfo['extension'] );
        }

        if (! isset( $fInfo['extension'] )) {
            if (file_exists( $template . '.tpl' )) {
                $template .= '.tpl';
            } elseif (file_exists( $template . '.html' )) {
                $template .= '.html';
            } else {
                $tplExists = false;
            }
        } else {
            if (! file_exists( $template )) {
                $tplExists = false;
            }
        }

        if (! $tplExists) {
            throw new Exception( "Template: $template, doesn't exist!" );
        }

        $smarty = new Smarty();
        $smarty->compile_dir = G::sys_get_temp_dir();
        $smarty->cache_dir = G::sys_get_temp_dir();
        $smarty->config_dir = PATH_THIRDPARTY . 'smarty/configs';

        $smarty->template_dir = PATH_TEMPLATE;
        $smarty->force_compile = true;

        foreach ($data as $key => $value) {
            $smarty->assign( $key, $value );
        }

        $smarty->display( $template );
    }

    /**
     * parse a smarty template and return teh result as string
     *
     * @author Erik Amaru Ortiz <erik@colosa.com>
     * @param $template string containing the template filename on /gulliver/templates/ directory
     * @param $data associative array containig the template data
     * @return $content string containing the parsed template content
     */
    public function parseTemplate ($template, $data = array())
    {
        $content = '';

        ob_start();
        G::renderTemplate( $template, $data );
        $content = ob_get_contents();
        ob_get_clean();

        return $content;
    }

    /**
     * Update a ini file passing a array values, this function don't remove the original comments
     *
     * @author Erik Amaru Ortiz <erik@colosa.com>
     * @licence GPL v2 (http://www.gnu.org/licenses/gpl-2.0.html)
     *
     * @param $file string containing the ini file to update
     * @param $array associative array containing the config data
     */
    public function update_php_ini ($file, $array)
    {
        $iniLines = array ();
        $iniContent = array ();

        if (file_exists( $file ) && ! is_writable( $file )) {
            throw new Exception( "File $file, is not writable." );
        }

        if (file_exists( $file )) {
            $iniContent = file( $file );
        }

        foreach ($iniContent as $line) {
            $line = trim( $line );
            $lineParts = explode( ';', $line );
            $setting = G::parse_ini_string( $lineParts[0] );

            if (is_array( $setting ) && count( $setting ) > 0) {
                list ($key, ) = array_keys( $setting );

                if (isset( $array[$key] )) {
                    $value = $array[$key];
                    $line = "$key = " . (is_numeric( $value ) ? $value : '"' . $value . '"');
                    $line .= isset( $lineParts[1] ) ? ' ;' . $lineParts[1] : '';
                    unset( $array[$key] );

                    $lastComment = array_pop( $iniLines );
                    if (strpos( $lastComment, "Setting $key" ) === false) {
                        $iniLines[] = $lastComment;
                    }

                    $iniLines[] = ";Setting $key - Updated by System on " . date( 'D d M, Y H:i:s' );
                }
            }
            $iniLines[] = $line;
        }

        // inserting new values
        foreach ($array as $key => $value) {
            $line = "$key = " . (is_numeric( $value ) ? $value : '"' . $value . '"');
            $iniLines[] = '';
            $iniLines[] = ";Setting $key - Created by System on " . date( 'D d M, Y H:i:s' );
            $iniLines[] = $line;
        }

        $content = implode( "\r\n", $iniLines );

        if (@file_put_contents( $file, $content ) === false) {
            throw new Exception( "G::update_php_ini() -> can't update file: $file" );
         } else {
            //first a raw permission check
            if(fileperms($file) != 33200) {
                @chmod ($file, 0660);
            }
        }
    }

    /**
     * recursive file & directories write permission detect
     *
     * @author Erik Amaru Ortiz <erik@colosa.com>
     * @licence GPL v2 (http://www.gnu.org/licenses/gpl-2.0.html)
     *
     * @param $path string of directory or file to verify recursively
     * @param $noWritableFiles (alternative) array passed by reference to store all no-writable files
     * @return bool true if all files inside a directory path are writable, false in another case
     */
    public function is_writable_r ($path, &$noWritableFiles = array())
    {
        if (is_writable( $path )) {
            if (! is_dir( $path )) {
                return true;
            }
            $list = glob( rtrim( $path, DIRECTORY_SEPARATOR ) . DIRECTORY_SEPARATOR . '*' );

            $sw = true;
            if(is_array($list)){
                foreach ($list as $f) {
                    if (! G::is_writable_r( $f, $noWritableFiles )) {
                        $sw = false;
                    }
                }
            } else {
                $sw = false;
            }

            return $sw;
        } else {
            if (! in_array( $path, $noWritableFiles )) {
                $noWritableFiles[] = $path;
            }
            return false;
        }
    }

    /**
     * This method allow dispatch rest services using 'Restler' thirdparty library
     *
     * @author Erik Amaru Ortiz <aortiz.erik@gmail.com>
     */
    public function dispatchRestService ($uri, $config, $apiClassesPath = '')
    {
        require_once 'restler/restler.php';

        $rest = new Restler();
        $rest->setSupportedFormats( 'JsonFormat', 'XmlFormat' );
        // getting all services class
        $restClasses = array ();
        $restClassesList = G::rglob( '*', 0, PATH_CORE . 'services/' );
        foreach ($restClassesList as $classFile) {
            if (substr( $classFile, - 4 ) === '.php') {
                $restClasses[str_replace( '.php', '', basename( $classFile ) )] = $classFile;
            }
        }
        if (! empty( $apiClassesPath )) {
            $pluginRestClasses = array ();
            $restClassesList = G::rglob( '*', 0, $apiClassesPath . 'services/' );
            foreach ($restClassesList as $classFile) {
                if (substr( $classFile, - 4 ) === '.php') {
                    $pluginRestClasses[str_replace( '.php', '', basename( $classFile ) )] = $classFile;
                }
            }
            $restClasses = array_merge( $restClasses, $pluginRestClasses );
        }
        // hook to get rest api classes from plugins
        if (class_exists( 'ProcessMaker\Plugins\PluginRegistry' )) {
            $pluginRegistry = PluginRegistry::loadSingleton();
            $pluginClasses = $pluginRegistry->getRegisteredRestServices();
            $restClasses = array_merge( $restClasses, $pluginClasses );
        }
        foreach ($restClasses as $key => $classFile) {
            if (! file_exists( $classFile )) {
                unset( $restClasses[$key] );
                continue;
            }
            //load the file, and check if exist the class inside it.
            require_once $classFile;
            $namespace = 'Services_Rest_';
            $className = str_replace( '.php', '', basename( $classFile ) );

            // if the core class does not exists try resolve the for a plugin
            if (! class_exists( $namespace . $className )) {
                $namespace = 'Plugin_Services_Rest_';
                // Couldn't resolve the class name, just skipp it
                if (! class_exists( $namespace . $className )) {
                    unset( $restClasses[$key] );
                    continue;
                }
            }
            // verify if there is an auth class implementing 'iAuthenticate'
            $classNameAuth = $namespace . $className;
            $reflClass = new ReflectionClass( $classNameAuth );
            // that wasn't from plugin
            if ($reflClass->implementsInterface( 'iAuthenticate' ) && $namespace != 'Plugin_Services_Rest_') {
                // auth class found, set as restler authentication class handler
                $rest->addAuthenticationClass( $classNameAuth );
            } else {
                // add api class
                $rest->addAPIClass( $classNameAuth );
            }
        }
        //end foreach rest class
        // resolving the class for current request
        $uriPart = explode( '/', $uri );
        $requestedClass = '';
        if (isset( $uriPart[1] )) {
            $requestedClass = ucfirst( $uriPart[1] );
        }
        if (class_exists( 'Services_Rest_' . $requestedClass )) {
            $namespace = 'Services_Rest_';
        } elseif (class_exists( 'Plugin_Services_Rest_' . $requestedClass )) {
            $namespace = 'Plugin_Services_Rest_';
        } else {
            $namespace = '';
        }
        // end resolv.
        // Send additional headers (if exists) configured on rest-config.ini
        if (array_key_exists( 'HEADERS', $config )) {
            foreach ($config['HEADERS'] as $name => $value) {
                header( "$name: $value" );
            }
        }
        // to handle a request with "OPTIONS" method
        if (! empty( $namespace ) && $_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
            $reflClass = new ReflectionClass( $namespace . $requestedClass );
            // if the rest class has not a "options" method
            if (! $reflClass->hasMethod( 'options' )) {
                header( 'Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS, HEADERS' );
                header( 'Access-Control-Allow-Headers: authorization, content-type' );
                header( "Access-Control-Allow-Credentials", "false" );
                header( 'Access-Control-Max-Age: 60' );
                exit();
            }
        }
        // override global REQUEST_URI to pass to Restler library
        $_SERVER['REQUEST_URI'] = '/' . strtolower( $namespace ) . ltrim( $uri, '/' );
        // handle the rest request
        $rest->handle();
    }

    public static function reservedWordsSql ()
    {
        //Reserved words SQL
        $reservedWordsSql = array ("ACCESSIBLE","ACTION","ADD","ALL","ALTER","ANALYZE","AND","ANY","AS","ASC","ASENSITIVE","AUTHORIZATION","BACKUP","BEFORE","BEGIN","BETWEEN","BIGINT","BINARY","BIT","BLOB","BOTH","BREAK","BROWSE","BULK","BY","CALL","CASCADE","CASE","CHANGE","CHAR","CHARACTER","CHECK","CHECKPOINT","CLOSE","CLUSTERED","COALESCE","COLLATE","COLUMN","COMMIT","COMPUTE","CONDITION","CONSTRAINT","CONTAINS","CONTAINSTABLE","CONTINUE","CONVERT","CREATE","CROSS","CURRENT","CURRENT_DATE","CURRENT_TIME","CURRENT_TIMESTAMP","CURRENT_USER","CURSOR","DATABASE","DATABASES","DATE","DAY_HOUR","DAY_MICROSECOND","DAY_MINUTE","DAY_SECOND","DBCC","DEALLOCATE","DEC","DECIMAL","DECLARE","DEFAULT","DELAYED","DELETE","DENY","DESC","DESCRIBE","DETERMINISTIC","DISK","DISTINCT","DISTINCTROW",
                        "DISTRIBUTED","DIV","DOUBLE","DROP","DUAL","DUMMY","DUMP","EACH","ELSE","ELSEIF","ENCLOSED","END","ENUM","ERRLVL","ESCAPE","ESCAPED","EXCEPT","EXEC","EXECUTE","EXISTS","EXIT","EXPLAIN","FALSE","FETCH","FILE","FILLFACTOR","FLOAT","FLOAT4","FLOAT8","FOR","FORCE","FOREIGN","FREETEXT","FREETEXTTABLE","FROM","FULL","FULLTEXT","FUNCTION","GENERAL","GOTO","GRANT","GROUP","HAVING","HIGH_PRIORITY","HOLDLOCK","HOUR_MICROSECOND","HOUR_MINUTE","HOUR_SECOND","IDENTITY","IDENTITYCOL","IDENTITY_INSERT","IF","IGNORE","IGNORE_SERVER_IDS","IN","INDEX","INFILE","INNER","INOUT","INSENSITIVE","INSERT","INT","INT1","INT2","INT3","INT4","INT8","INTEGER","INTERSECT","INTERVAL","INTO","IS","ITERATE","JOIN","KEY","KEYS","KILL","LEADING","LEAVE","LEFT","LIKE","LIMIT","LINEAR","LINENO","LINES",
                        "LOAD","LOCALTIME","LOCALTIMESTAMP","LOCK","LONG","LONGBLOB","LONGTEXT","LOOP","LOW_PRIORITY","MASTER_HEARTBEAT_PERIOD","MASTER_SSL_VERIFY_SERVER_CERT","MATCH","MAXVALUE","MEDIUMBLOB","MEDIUMINT","MEDIUMTEXT","MIDDLEINT","MINUTE_MICROSECOND","MINUTE_SECOND","MOD","MODIFIES","NATIONAL","NATURAL","NO","NOCHECK","NONCLUSTERED","NOT","NO_WRITE_TO_BINLOG","NULL","NULLIF","NUMERIC","OF","OFF","OFFSETS","ON","OPEN","OPENDATASOURCE","OPENQUERY","OPENROWSET","OPENXML","OPTIMIZE","OPTION","OPTIONALLY","OR","ORDER","OUT","OUTER","OUTFILE","OVER","PERCENT","PLAN","PRECISION","PRIMARY","PRINT","PROC","PROCEDURE","PUBLIC","PURGE","RAISERROR","RANGE","READ","READS","READTEXT","READ_WRITE","REAL","RECONFIGURE","REFERENCES","REGEXP","RELEASE","RENAME","REPEAT","REPLACE",
                        "REPLICATION","REQUIRE","RESIGNAL","RESTORE","RESTRICT","RETURN","REVOKE","RIGHT","RLIKE","ROLLBACK","ROWCOUNT","ROWGUIDCOL","RULE","SAVE","SCHEMA","SCHEMAS","SECOND_MICROSECOND","SELECT","SENSITIVE","SEPARATOR","SESSION_USER","SET","SETUSER","SHOW","SHUTDOWN","SIGNAL","SLOW","SMALLINT","SOME","SPATIAL","SPECIFIC","SQL","SQLEXCEPTION","SQLSTATE","SQLWARNING","SQL_BIG_RESULT","SQL_CALC_FOUND_ROWS","SQL_SMALL_RESULT","SSL","STARTING","STATISTICS","STRAIGHT_JOIN","SYSTEM_USER","TABLE","TERMINATED","TEXT","TEXTSIZE","THEN","TIME","TIMESTAMP","TINYBLOB","TINYINT","TINYTEXT","TO","TOP","TRAILING","TRAN","TRANSACTION","TRIGGER","TRUE","TRUNCATE","TSEQUAL","UNDO","UNION","UNIQUE","UNLOCK","UNSIGNED","UPDATE","UPDATETEXT","USAGE","USE","USER","USING","UTC_DATE","UTC_TIME",
                        "UTC_TIMESTAMP","VALUES","VARBINARY","VARCHAR","VARCHARACTER","VARYING","VIEW","WAITFOR","WHEN","WHERE","WHILE","WITH","WRITE","WRITETEXT","XOR","YEAR_MONTH","ZEROFILL");
        return $reservedWordsSql;
    }

    /**
    * isPMUnderUpdating, Used to set a file flag to check if PM is upgrading.
    *
    * @setFlag          Contains the flag to set or unset the temporary file:
    *                   0 to delete the temporary file flag
    *                   1 to set the temporary file flag.
    *                   2 or bigger to check if the temporary file exists.
    * @content          Contains the content of the temporary file
    *                   true to all workspace
    *                   nameWorkspace to specific workspace
    * return            true if the file exists, otherwise false.
    */
    public function isPMUnderUpdating($setFlag = 2, $content="true")
    {
        if (!defined('PATH_DATA')) {
            return false;
        }
        $fileCheck = PATH_DATA."UPDATE.dat";
        if ($setFlag == 0) {
            if (file_exists($fileCheck)) {
                unlink ($fileCheck);
            }
        } elseif ($setFlag == 1) {
            $fp = fopen($fileCheck,'w');
            $line = fputs($fp,$content);
        }
        //checking temporary file
        if ($setFlag >= 1) {
            if (file_exists($fileCheck)) {
                $res['action'] = true;
                $fp = fopen($fileCheck, "r");
                $res['workspace'] = fread($fp, filesize($fileCheck));
                fclose($fp);
                return $res;
            }
        }
        return false;
    }

    /**
     * Save the $_SESSION variables into $sessionVar array, to unset them temporary.
     *
     */
    public function sessionVarSave()
    {
        //Unset any variable
        $this->sessionVar = array();

        if (isset($_SESSION["APPLICATION"])) {
            $this->sessionVar["APPLICATION"] = $_SESSION["APPLICATION"];
        }

        if (isset($_SESSION["INDEX"])) {
            $this->sessionVar["INDEX"] = $_SESSION["INDEX"];
        }

        if (isset($_SESSION["PROCESS"])) {
            $this->sessionVar["PROCESS"] = $_SESSION["PROCESS"];
        }

        if (isset($_SESSION["TASK"])) {
            $this->sessionVar["TASK"] = $_SESSION["TASK"];
        }

        if (isset($_SESSION["USER_LOGGED"])) {
            $this->sessionVar["USER_LOGGED"] = $_SESSION["USER_LOGGED"];
        }

        if (isset($_SESSION["USR_USERNAME"])) {
            $this->sessionVar["USR_USERNAME"] = $_SESSION["USR_USERNAME"];
        }

        if (isset($_SESSION["STEP_POSITION"])) {
            $this->sessionVar["STEP_POSITION"] = $_SESSION["STEP_POSITION"];
        }
    }

    /**
     * Restore the session variables with values of $sessionVar array, if this is set.
     *
     */
    public function sessionVarRestore()
    {
        if (count($this->sessionVar) > 0) {
            //Restore original values
            unset($_SESSION["APPLICATION"]);
            unset($_SESSION["INDEX"]);
            unset($_SESSION["PROCESS"]);
            unset($_SESSION["TASK"]);
            unset($_SESSION["USER_LOGGED"]);
            unset($_SESSION["USR_USERNAME"]);
            unset($_SESSION["STEP_POSITION"]);

            if (isset($this->sessionVar["APPLICATION"])) {
                $_SESSION["APPLICATION"] = $this->sessionVar["APPLICATION"];
            }

            if (isset($this->sessionVar["INDEX"])) {
                $_SESSION["INDEX"] = $this->sessionVar["INDEX"];
            }

            if (isset($this->sessionVar["PROCESS"])) {
                $_SESSION["PROCESS"] = $this->sessionVar["PROCESS"];
            }

            if (isset($this->sessionVar["TASK"])) {
                $_SESSION["TASK"] = $this->sessionVar["TASK"];
            }

            if (isset($this->sessionVar["USER_LOGGED"])) {
                $_SESSION["USER_LOGGED"] = $this->sessionVar["USER_LOGGED"];
            }

            if (isset($this->sessionVar["USR_USERNAME"])) {
                $_SESSION["USR_USERNAME"] = $this->sessionVar["USR_USERNAME"];
            }

            if (isset($this->sessionVar["STEP_POSITION"])) {
                $_SESSION["STEP_POSITION"] = $this->sessionVar["STEP_POSITION"];
            }
        }
    }

    public static function browserCacheFilesGetLibraryJs()
    {
        $arrayLibrary = array();

        //Translations /js/ext/translation.en.js
        //Translations /js/ext/translation.xxx.en.js //xxx is an plugin
        $arrayLibrary["translation"] = 1; //Not use null

        //Translation environment /jscore/labels/en.js
        if (file_exists(PATH_DATA . "META-INF" . PATH_SEP . "translations.env")) {
            $arrayData = unserialize(file_get_contents(PATH_DATA . "META-INF" . PATH_SEP . "translations.env"));

            foreach ($arrayData as $index1 => $value1) {
                foreach ($value1 as $index2 => $value2) {
                    $record = $value2;

                    if (file_exists(PATH_CORE . "js" . PATH_SEP . "labels" . PATH_SEP . $record["LOCALE"] . ".js")) {
                        $arrayLibrary[$record["LOCALE"]] = 1;
                    }
                }
            }
        }

        //Libraries
        $library = G::json_decode(file_get_contents(PATH_HOME . "engine" . PATH_SEP . "bin" . PATH_SEP . "tasks" . PATH_SEP . "libraries.json"));

        foreach ($library as $index => $value) {
            $lib = $value;

            if ($lib->build) {
                if (substr($lib->build_js_to, -1) != "/") {
                    $lib->build_js_to = $lib->build_js_to . "/";
                }

                $arrayLibrary[$lib->name] = 1;
            }
        }

        return $arrayLibrary;
    }

    public static function browserCacheFilesSetUid()
    {
        $uid = G::generateUniqueID();

        $arrayData = array();
        $arrayData["browser_cache_files_uid"] = $uid;

        G::update_php_ini(PATH_CONFIG . "env.ini", $arrayData);
    }

    public static function browserCacheFilesGetUid()
    {
        $sysConf = System::getSystemConfiguration(PATH_CONFIG . "env.ini");

        return (isset($sysConf["browser_cache_files_uid"]))? $sysConf["browser_cache_files_uid"] : null;
    }

    public static function browserCacheFilesUrl($url)
    {
        $browserCacheFilesUid = self::browserCacheFilesGetUid();

        if ($browserCacheFilesUid != null) {
            $arrayAux = explode("/", $url);
            $n = count($arrayAux);

            if ($n > 0 && !empty($arrayAux[$n - 1])) {
                $arrayAux = explode("?", $arrayAux[$n - 1]);
                $name = $arrayAux[0];

                if (preg_match("/^(.*)\.js$/i", $name, $arrayMatch)) {
                    $index = $arrayMatch[1];
                    $index = (preg_match("/^translation\..*$/", $index))? "translation" : $index;

                    $arrayLibrary = G::browserCacheFilesGetLibraryJs();

                    if (isset($arrayLibrary[$index])) {
                        $url = str_replace($name, $arrayMatch[1] . "." . $browserCacheFilesUid . ".js", $url);
                    }
                }
            }
        }

        return $url;
    }

    public static function skinGetPathToSrcByVirtualUri($option, $sysConf)
    {
        $path = "";
        $ereg = "";
        $strSearch = "";

        switch ($option) {
            case "errors":
                $ereg = "/^\/errors\/.*$/";
                $strSearch = "/errors/";
                break;
            case "update":
                $ereg = "/^\/update\/.*$/";
                $strSearch = "/update/";
                break;
        }

        if (preg_match($ereg, $_SERVER["REQUEST_URI"])) {
            $strAux = str_replace($strSearch, null, $_SERVER["REQUEST_URI"]);

            if ($strAux != "") {
                $skin = "base"; //classic

                if (isset($_SESSION["currentSkin"])) {
                    $skin = $_SESSION["currentSkin"];
                } else {

                    if (isset($sysConf["default_skin"])) {
                        $skin = $sysConf["default_skin"];
                    }
                }

                $arrayAux = explode("?", $strAux);
                $fileTemplate = $arrayAux[0];

                if (file_exists(PATH_SKIN_ENGINE . "base" . PATH_SEP . $fileTemplate)) {
                    $path = PATH_SKIN_ENGINE . "base" . PATH_SEP;
                }

                if (file_exists(PATH_SKIN_ENGINE . $skin . PATH_SEP . $fileTemplate)) {
                    $path = PATH_SKIN_ENGINE . $skin . PATH_SEP;
                }

                if (file_exists(PATH_SKINS . $skin . PATH_SEP . $fileTemplate)) {
                    $path = PATH_SKINS . $skin . PATH_SEP;
                }

                if (file_exists(PATH_CUSTOM_SKINS . $skin . PATH_SEP . $fileTemplate)) {
                    $path = PATH_CUSTOM_SKINS . $skin . PATH_SEP;
                }
            }
        }

        return $path;
    }

    public function isUserFunction($functionName) {
        $allFunctions = get_defined_functions();
        if (!isset($allFunctions['user'])) {
            $allFunctions['user'] = array();
        }
        $allFunctions['user'][] = 'sort';
        return in_array(strtolower($functionName), $allFunctions['user']);
    }

    /**
      * Constructor for inputFilter class. Only first parameter is required.
      * @access constructor
      * @data Mixed - input string/array-of-string to be 'cleaned'
      * @param Array $tagsArray - list of user-defined tags
      * @param Array $attrArray - list of user-defined attributes
      * @param int $tagsMethod - 0= allow just user-defined, 1= allow all but user-defined
      * @param int $attrMethod - 0= allow just user-defined, 1= allow all but user-defined
      * @param int $xssAuto - 0= only auto clean essentials, 1= allow clean blacklisted tags/attr
      */
    public function sanitizeInput($data, $tagsArray = array(), $attrArray = array(), $tagsMethod = 0, $attrMethod = 0, $xssAuto = 1)
    {

        $filtro = new InputFilter($tagsArray , $attrArray, $tagsMethod, $attrMethod, $xssAuto);
        return $filtro->process($data);
    }

    /**
     * Stores a message in the log file, if the file size exceeds
     * specified log file is renamed and a new one is created.
     *
     * @param type $message
     * @param type $pathData
     * @param type $file
     */
    public static function log($message, $pathData = PATH_DATA, $file = 'cron.log')
    {
        $config = System::getSystemConfiguration();


        $oLogger = Logger::getSingleton($pathData, PATH_SEP, $file);
        $oLogger->limitFile = $config['number_log_file'];
        $oLogger->limitSize = $config['size_log_file'];
        $oLogger->write($message);
    }

    /**
     * This function save history about some actions in the file audit.log
     * The data is used in the Audit Log functionality
     *
     * @param string $actionToLog
     * @param string $valueToLog
     * @return void
    */
    public static function auditLog($actionToLog, $valueToLog = "")
    {
	    $workspace = !empty(config("system.workspace")) ? config("system.workspace") : 'Undefined Workspace';
        $conf = new Configurations();
        $sflag = $conf->getConfiguration('AUDIT_LOG', 'log');
        $sflagAudit = $sflag == 'true' ? true : false;
        $ipClient = G::getIpAddress();
        $userUid = 'Unknow User';
        $fullName = '-';

        /*----------------------------------********---------------------------------*/
    }

    /**
     * Changes all keys in an array and sub-arrays
     *
     * @param array $arrayData The array to work on
     * @param int   $case      Either CASE_UPPER or CASE_LOWER (default)
     *
     * return array Returns an array with its keys lower or uppercased, or false if $arrayData is not an array
     */
    public static function array_change_key_case2($arrayData, $case = CASE_LOWER)
    {
        $arrayData = array_change_key_case($arrayData, $case);

        foreach ($arrayData as $key => $value) {
            if (is_array($value)) {
                $arrayData[$key] = self::array_change_key_case2($value, $case);
            }
        }

        return $arrayData;
    }

    public static function buildFrom($configuration, $from = '') {
        if (!isset($configuration['MESS_FROM_NAME'])) {
            $configuration['MESS_FROM_NAME'] = '';
        }
        if (!isset($configuration['MESS_FROM_MAIL'])) {
            $configuration['MESS_FROM_MAIL'] = '';
        }
        if ($from != '') {
            if (!preg_match('/(.+)@(.+)\.(.+)/', $from, $match)) {
                if ($configuration['MESS_FROM_MAIL'] != '') {
                    $from .= ' <' . $configuration['MESS_FROM_MAIL'] . '>';
                } else if ($configuration['MESS_ENGINE'] == 'PHPMAILER' && preg_match('/(.+)@(.+)\.(.+)/', $configuration['MESS_ACCOUNT'], $match)) {
                    $from .= ' <' . $configuration['MESS_ACCOUNT'] . '>';
                } else {
                    $from .= ' <info@' . ((isset($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] != '')? $_SERVER['HTTP_HOST'] : 'processmaker.com') . '>';
                }
            }
        } else {
            if ($configuration['MESS_FROM_NAME'] != '' && $configuration['MESS_FROM_MAIL'] != '') {
                $from = $configuration['MESS_FROM_NAME'] . ' <' . $configuration['MESS_FROM_MAIL'] . '>';
            } else if ($configuration['MESS_FROM_NAME'] != '' && $configuration['MESS_ENGINE'] == 'PHPMAILER' && preg_match('/(.+)@(.+)\.(.+)/', $configuration['MESS_ACCOUNT'], $match)) {
                $from = $configuration['MESS_FROM_NAME'] . ' <' . $configuration['MESS_ACCOUNT'] . '>';
            } else if ($configuration['MESS_FROM_NAME'] != '') {
                $from = $configuration['MESS_FROM_NAME'] . ' <info@' . ((isset($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] != '')? $_SERVER['HTTP_HOST'] : 'processmaker.com') . '>';
            } else if ($configuration['MESS_FROM_MAIL'] != '') {
                $from = $configuration['MESS_FROM_MAIL'];
            } else if ($configuration['MESS_ENGINE'] == 'PHPMAILER' && preg_match('/(.+)@(.+)\.(.+)/', $configuration['MESS_ACCOUNT'], $match)) {
                $from = $configuration['MESS_ACCOUNT'];
            } else if ($configuration['MESS_ENGINE'] == 'PHPMAILER' && $configuration['MESS_ACCOUNT'] != '' && !preg_match('/(.+)@(.+)\.(.+)/', $configuration['MESS_ACCOUNT'], $match)) {
                $from = $configuration['MESS_ACCOUNT'] . ' <info@' . ((isset($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] != '')? $_SERVER['HTTP_HOST'] : 'processmaker.com') . '>';
            } else {
                $from = 'info@' . ((isset($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] != '')? $_SERVER['HTTP_HOST'] : 'processmaker.com');
            }
        }
        return $from;
    }

    public function getRealExtension($extensionInpDoc) {
        $aux = explode('.', strtolower($extensionInpDoc));
        return isset($aux[1]) ? $aux[1] : '';
    }

   /**
    * Verify the InputDoc extension, cheking the file name extension (.pdf, .ppt) and the file content.
    *
    *
    *
    */
    public function verifyInputDocExtension($InpDocAllowedFiles, $fileName, $filesTmpName)
    {
        // Initialize variables
        $res = new stdclass();
        $res->status = false;
        $allowedTypes = array_map('G::getRealExtension', explode(',', $InpDocAllowedFiles));

        // Get the file extension
        $aux = pathinfo($fileName);
        $fileExtension = isset($aux['extension']) ? strtolower($aux['extension']) : '';

        if (\Bootstrap::getDisablePhpUploadExecution() === 1 && $fileExtension === 'php') {
            $message = \G::LoadTranslation('THE_UPLOAD_OF_PHP_FILES_WAS_DISABLED');
            \Bootstrap::registerMonologPhpUploadExecution('phpUpload', 550, $message, $fileName);
            $res->status = false;
            $res->message = $message;
            return $res;
        }

        // If required extension is *.* don't validate
        if (in_array('*', $allowedTypes)) {
            $res->status = true;
            return $res;
        }

        // If no valid extension finish (unnecesary check file content)
        $validExtension = in_array($fileExtension, $allowedTypes);
        if (!$validExtension) {
            $res->status = false;
            $res->message = G::LoadTranslation('ID_UPLOAD_ERR_NOT_ALLOWED_EXTENSION' ) . ' ' . $fileName;
            return $res;
        }

        // If not enabled fileinfo extension finish validation
        if (!extension_loaded('fileinfo')) {
            $res->status = true;
            return $res;
        }

        // If enabled fileinfo extension check the content
        $finfo = new finfo(FILEINFO_MIME_TYPE);
        $mimeType = $finfo->file($filesTmpName);    
        $docType = explode('/', $mimeType);

        // If is a empty file finish validation
        if ($docType[1] == 'x-empty') {
            $res->status = true;
            return $res;
        }

        // Check file content
        foreach ($allowedTypes as $allowedType) {
            switch ($allowedType) {
                case 'xls':
                    if ($docType[1] == 'vnd.ms-excel' || ($fileExtension == 'xls' && $docType[1] == 'plain')) {
                        $res->status = true;
                        break 2;
                    }
                    break;
                case 'doc':
                    if ($docType[1] == 'msword' || ($fileExtension == 'doc' && $docType[1] == 'html')) {
                        $res->status = true;
                        break 2;
                    }
                    break;
                case 'ppt':
                    if ($docType[1] == 'vnd.ms-office') {
                        $res->status = true;
                        break 2;
                    }
                    break;
                case 'docx':
                    if ($docType[1] == 'vnd.openxmlformats-officedocument.wordprocessingml.document') {
                        $res->status = true;
                        break 2;
                    }
                    break;
                case 'pptx':
                    if ($docType[1] == 'vnd.openxmlformats-officedocument.presentationml.presentation') {
                        $res->status = true;
                        break 2;
                    }
                    break;
                case 'xlsx':
                    if ($docType[1] == 'vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
                        $res->status = true;
                        break 2;
                    }
                    break;
                case 'exe':
                    if ($docType[1] == 'x-msdownload' || $docType[1] == 'x-dosexec') {
                        $res->status = true;
                        break 2;
                    }
                    break;
                case 'wmv':
                    if ($docType[1] == 'x-ms-asf' || $docType[1] == 'x-ms-wmv') {
                        $res->status = true;
                        break 2;
                    }
                    break;
                case 'jpg':
                    if ($docType[1] == 'jpeg') {
                        $res->status = true;
                        break 2;
                    }
                    break;
                case 'mp3':
                    if ($docType[1] == 'mpeg') {
                        $res->status = true;
                        break 2;
                    }
                    break;
                case 'rar':
                    if ($docType[1] == 'x-rar') {
                        $res->status = true;
                        break 2;
                    }
                    break;
                case 'txt':
                case 'pm':
                    if ($docType[1] == 'plain') {
                        $res->status = true;
                        break 2;
                    }
                    break;
                case 'htm':
                case 'html':
                    if ($docType[1] == 'html') {
                        $res->status = true;
                        break 2;
                    }
                    break;
                case 'po':
                    if ($docType[1] == 'x-po') {
                        $res->status = true;
                        break 2;
                    }
                    break;
                case 'pdf':
                case 'png':
                case 'jpeg':
                case 'gif':
                case 'zip':
                case 'mp4':
                    if ($docType[1] == $allowedType) {
                        $res->status = true;
                        break 2;
                    }
                    break;
                default:
                    $res->status = $validExtension;
                    break;
            }
        }

        // If content don't match return error
        if (!$res->status) {
            $res->message = G::LoadTranslation('ID_UPLOAD_ERR_NOT_ALLOWED_EXTENSION' ) . ' ' . $fileName;
        }
        return $res;

    }

    /**
     * Check the browser compatibility
     *
     * @param string $browser
     * @param integer $version
     *
     * @return boolean
     */
    public function checkBrowserCompatibility($browser = null, $version = null)
    {
        if ($browser == null || $version == null) {
            $info = G::getBrowser();
            $browser = $info['name'];
            $version = $info['version'];
        }

        if (
            (($browser == 'msie') && (($version >= 8) && ($version <= 11))) ||
            (($browser == 'chrome') && ($version >= 26)) ||
            (($browser == 'firefox') && ($version >= 20)) ||
            (($browser == 'safari') && ($version >= 10))
        ) {
            return true;
        }

        return false;
    }

    /**
     * This function sanitizes the string
     *
     * @param string $string, The string to sanitize.
     * @param boolean $lowercase, Force the string to lowercase
     * @param boolean $alpha, If set to *true*, will remove all non-alphanumeric characters.
     *
     * @return string
     */
    public function sanitizeString ($string, $lowercase = true, $alpha = false)
    {
       $strip = array("~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "=", "+", "[", "{", "]",
                      "}", "\\", "|", ";", ":", "\"", "'", "&#8216;", "&#8217;", "&#8220;", "&#8221;", "&#8211;", "&#8212;",
                      "—", "–", ",", "<", ".", ">", "/", "?");
       $clean = trim(str_replace($strip, "", strip_tags($string)));
       $clean = preg_replace('/\s+/', "-", $clean);
       $clean = ($alpha) ? preg_replace("/[^a-zA-Z0-9]/", "", $clean) : $clean ;
       $clean = ($lowercase) ? (function_exists('mb_strtolower')) ? mb_strtolower($clean, 'UTF-8') : strtolower($clean) : $clean;
       return $clean;
   }
   /**
    * Out the result
    *
    * @param string $sVar
    *
    * @return showRes($string)
    */
    public static function outRes ($sInfVar)
    {
        echo $sInfVar;
    }
   /**
    * encryptOld
    *
    * @param string $string
    *
    * @return md5($string)
    */
    public static function encryptOld($string)
    {
        $consthashFx = self::hashFx;
        return $consthashFx($string);
    }
    /**
     * encryptSha
     *
     * @param string $string
     *
     * @return sha256($string)
     */
    public static function encryptHash($string)
    {
        $consthash = self::hash;
        return $consthash('sha256', $string);
    }
    /**
    * encryptFileOld
    *
    * @param string $string
    *
    * @return md5_file($string)
    */
    public function encryptFileOld ($string)
    {
        $consthashFx = self::hashFile;
        return $consthashFx($string);
    }
    /**
    * crc32
    *
    * @param string $string
    *
    * @return crc32($string)
    */
    public static function encryptCrc32 ($string)
    {
        $consthashFx = self::hashCrc;
        return $consthashFx($string);
    }

    /**
     * this function get the Message
     * @access public
     * @param string $e
     * @return string
     *
     */
    public static function getErrorMessage($e)
    {
        return $e->getMessage();
    }

    /**
     * Add log of execution of triggers
     * @param $data
     * @param string $error
     * @param string $typeError
     * @param int $executionTime
     */
    public static function logTriggerExecution($data, $error = 'NO-ERROR', $typeError = '', $executionTime = 0)
    {
        if ((!empty($data['_CODE_']) || $typeError == 'FATAL_ERROR') && isset($data['_DATA_TRIGGER_']) &&
            !isset($data['_DATA_TRIGGER_']['_TRI_LOG_'])
        ) {
            $lg = Bootstrap::getDefaultContextLog();
            $lg['TRI_TITLE'] = isset($data['_DATA_TRIGGER_']['TRI_TITLE']) ? $data['_DATA_TRIGGER_']['TRI_TITLE'] : '';
            $lg['TRI_UID'] = isset($data['_DATA_TRIGGER_']['TRI_UID']) ? $data['_DATA_TRIGGER_']['TRI_UID'] : '';
            $lg['TRI_CODE'] = isset($data['_DATA_TRIGGER_']['TRI_WEBBOT']) ? $data['_DATA_TRIGGER_']['TRI_WEBBOT'] : '';
            $lg['TRI_EXECUTION_TIME'] = $executionTime;
            $lg['TRI_MSG_ERROR'] = $error;
            $lg['APP_UID'] = isset($data['APPLICATION']) ? $data['APPLICATION'] : '';
            $lg['PRO_UID'] = isset($data['PROCESS']) ? $data['PROCESS'] : '';
            $lg['TAS_UID'] = isset($data['TASK']) ? $data['TASK'] : '';
            $lg['USR_UID'] = isset($data['USER_LOGGED']) ? $data['USER_LOGGED'] : '';

            Bootstrap::registerMonolog(
                (empty($sError)) ? 'TriggerExecution' : 'TriggerExecutionError',
                (empty($sError)) ? 200 : 400,
                (empty($sError)) ? 'Trigger Execution' : 'Trigger Execution Error',
                $lg, $lg['workspace'], 'processmaker.log');

            $_SESSION['_DATA_TRIGGER_']['_TRI_LOG_'] = true;
        }
    }

    /**
     * Define the Processmaker constants.
     *
     */
    public static function defineConstants()
    {
        //Moved from Enterprise class.
        if (file_exists(PATH_METHODS . "login/version-pmos.php")) {
            include (PATH_METHODS . "login/version-pmos.php");
        }
        //Removed default version from code.
        
        /**
         * The constants defined comes from the file:
         * processmaker/workflow/engine/classes/class.plugin.php, the loading of this
         * file is not done by 'require' in this version of ProcessMaker. Therefore,
         * these definitions have been moved to this class.
         */
        define('G_PLUGIN_CLASS', 1);
        define('PM_CREATE_CASE', 1001);
        define('PM_UPLOAD_DOCUMENT', 1002);
        define('PM_CASE_DOCUMENT_LIST', 1003);
        define('PM_BROWSE_CASE', 1004);
        define('PM_NEW_PROCESS_LIST', 1005);
        define('PM_NEW_PROCESS_SAVE', 1006);
        define('PM_NEW_DYNAFORM_LIST', 1007);
        define('PM_NEW_DYNAFORM_SAVE', 1008);
        define('PM_EXTERNAL_STEP', 1009);
        define('PM_CASE_DOCUMENT_LIST_ARR', 1010);
        define('PM_LOGIN', 1011);
        define('PM_UPLOAD_DOCUMENT_BEFORE', 1012);
        define('PM_CREATE_NEW_DELEGATION', 1013);
        define('PM_SINGLE_SIGN_ON', 1014);
        define('PM_GET_CASES_AJAX_LISTENER', 1015);
        define('PM_BEFORE_CREATE_USER', 1016);
        define('PM_AFTER_LOGIN', 1017);
        define('PM_HASH_PASSWORD', 1018);
        define('PM_SCHEDULER_CREATE_CASE_BEFORE', 1019);
        define('PM_SCHEDULER_CREATE_CASE_AFTER', 1020);
    }

    /**
     * Instanciate an adapter by name.
     *
     * @param string $name Adapter name or class name                                                                                                     :P
     * 
     * @param string[] $parameters Constructor parameters
     */
    public static function factory($name, ...$parameters)
    {
        $key = strtolower($name);
        $class = isset(self::$adapters[$key]) ? self::$adapters[$key] : $name;
        $rc = new ReflectionClass($class);
        return $rc->newInstanceArgs($parameters);
    }

    /**
     * Return current class
     *
     * @param $name string name class
     * @return string name of class
     */
    public static function nameClass($name)
    {
        $key = strtolower($name);
        return isset(self::$adapters[$key]) ? self::$adapters[$key] : $name;
    }

    /**
     * Verify class exists
     *
     * @param $name
     * @return bool true or false
     */
    public static function classExists($name)
    {
        $key = strtolower($name);
        $class = isset(self::$adapters[$key]) ? self::$adapters[$key] : $name;
        return class_exists($class);
    }
}