Pages

Sunday, March 30, 2014

Wordpress-allow login with email address

Wordpress allow login with email address

    function login_with_email_address($username)  
    {  
      $user = get_user_by_email($username);  
      if(!empty($user->user_login))  
          $username = $user->user_login;  
      return $username;  
    }  
    add_action('wp_authenticate','login_with_email_address');  



Tuesday, March 18, 2014

Zend-Setup on Ubuntu 13.10

To setup zend on ubuntu 13.10(my version)

We need to download its latest framework from
http://www.zend.com/en/company/community/downloads

Zend 1.12.5 is latest as of writing this post

Next unzip and place the same in your home directory and delete all folders except bin and library

Next we need to tell our php to include Zend library so in our php.ini

(found in /etc/php5/apache2/php.ini)

perform following actions

Add
include_path=".:/home/gaurav/ZendFramework-1.12.5/library"
if you find include_path  not used or

Append "/home/gaurav/ZendFramework-1.12.5/library" to current path if include_path is defined (check it's commented by default)

Save and Close

Next move to root and using root privileges(sudo)
 
create a file 
cd /
nano .bashrc
 
and add code 
 
"alias zf=/home/gaurav/ZendFramework-1.12.5/bin/zf.sh"

Save and exit

Next Source .bashrc by following command
 
"source .bashrc"
 
now run zf command
 
If you get an output as follows
 
 An Error Has Occurred                         
 An action and provider is required.                                    

Zend Framework Command Line Console Tool v1.12.4
Usage:
    zf [--global-opts] action-name [--action-opts] provider-name [--provider-opts] [provider parameters ...]
    Note: You may use "?" in any place of the above usage string to ask for more specific help information.
    Example: "zf ? version" will list all available actions for the version provider.

Providers and their actions:
  Version
    zf show version mode[=mini] name-included[=1]
    Note: There are specialties, use zf show version.? to get specific help on them.

  Config
    zf create config
    zf show config
    zf enable config
    Note: There are specialties, use zf enable config.? to get specific help on them.
    zf disable config
    Note: There are specialties, use zf disable config.? to get specific help on them.

  Phpinfo
    zf show phpinfo

  Manifest
    zf show manifest

  Profile
    zf show profile

  Project
    zf create project path name-of-profile file-of-profile
    zf show project
    Note: There are specialties, use zf show project.? to get specific help on them.

  Application
    zf change application.class-name-prefix class-name-prefix

  Model
    zf create model name module

  View
    zf create view controller-name action-name-or-simple-name module

  Controller
    zf create controller name index-action-included[=1] module

  Action
    zf create action name controller-name[=Index] view-included[=1] module

  Module
    zf create module name

  Form
    zf enable form module
    zf create form name module

  Layout
    zf enable layout
    zf disable layout

  DbAdapter
    zf configure db-adapter dsn section-name[=production]

  DbTable
    zf create db-table name actual-table-name module force-overwrite
    Note: There are specialties, use zf create db-table.? to get specific help on them.

  ProjectProvider
    zf create project-provider name actions

Thursday, January 2, 2014

Authorize .Net-Reading Response of Authorize.net api

Reading Error Response
 
AuthorizeNetCIM_Response Object  
 (  
   [xml] => SimpleXMLElement Object  
     (  
       [messages] => SimpleXMLElement Object  
         (  
           [resultCode] => Error  
           [message] => SimpleXMLElement Object  
             (  
               [code] => E00003  
               [text] => The 'AnetApi/xml/v1/schema/AnetApiSchema.xsd:cardNumber' element is invalid - The value '668988888888177645' is invalid according to its datatype 'String' - The actual length is greater than the MaxLength value.  
             )  
         )  
     )  
   [response] => ErrorE00003The 'AnetApi/xml/v1/schema/AnetApiSchema.xsd:cardNumber' element is invalid - The value '668988888888177645' is invalid according to its datatype 'String' - The actual length is greater than the MaxLength value.  
   [xpath_xml] => SimpleXMLElement Object  
     (  
       [messages] => SimpleXMLElement Object  
         (  
           [resultCode] => Error  
           [message] => SimpleXMLElement Object  
             (  
               [code] => E00003  
               [text] => The 'AnetApi/xml/v1/schema/AnetApiSchema.xsd:cardNumber' element is invalid - The value '668988888888177645' is invalid according to its datatype 'String' - The actual length is greater than the MaxLength value.  
             )  
         )  
     )  
 ) 
 Reading Error Response
 $error = (string)array_pop($response->xpath('messages/message/text'));  

Reading Success Response
 AuthorizeNetCIM_Response Object  
 (  
   [xml] => SimpleXMLElement Object  
     (  
       [messages] => SimpleXMLElement Object  
         (  
           [resultCode] => Ok  
           [message] => SimpleXMLElement Object  
             (  
               [code] => I00001  
               [text] => Successful.  
             )  
         )  
       [customerPaymentProfileId] => 21000823
     )  
   [response] => OkI00001Successful.21000823 
   [xpath_xml] => SimpleXMLElement Object  
     (  
       [messages] => SimpleXMLElement Object  
         (  
           [resultCode] => Ok  
           [message] => SimpleXMLElement Object  
             (  
               [code] => I00001  
               [text] => Successful.  
             )  
         )  
       [customerPaymentProfileId] => 21000844  
     )  
 )
 Reading Authorize .Net Success Object
 if($response->isOk())  

Wordpress-Get Post ID in functions.php

  $url = explode('?', 'http://'.$_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);  
   $ID = url_to_postid($url[0]);  
   echo $ID;  

Friday, November 29, 2013

Javascript-Fire event on resolution change

In the era of responsive websites sometimes it is needed to fire an event on change of resolution.

My designer was stuck in one such scenario and we sorted the same out as follows


 <script>  
 $(document).ready(function () {  
 var width = screen.width,  
 height = screen.height;  
 setInterval(function () {  
 if (screen.width !== width || screen.height !== height) {  
 width = screen.width;  
 height = screen.height;  
 $(window).trigger('resolutionchange');  
 }  
 }, 50);  
 }());  
 $(window).bind('resolutionchange', heightchanges)  
 function heightchanges(){  
 /*Your code on resolution change event here*/
 }  
 });  
 </script>  

HTML-Input Field that accepts only number

If you are looking for a Html Input field that accepts only number on basis of regular expression here is the code


 <input name="number"  
 onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')">  

Thursday, October 17, 2013

Cakephp-Query and Cache Optimization

Recently while working for a technical client I learnt a lot of things regarding optimization of a cakephp site
which I am discussing as follows

1. Cache regularly used queries in cache.Queries regarding listing Menu's which are listed on every page footer item's,header item's should be cached.

For example if you are showing a list of categories in Menu from database.You must cache those so same query is not run again and again on same page

I cached as follows

 $mainCategories = Cache::read('Categories','long_db');  
         if (!$mainCategories)   
         {  
           $mainCategories = $this->Category->find('all', array('conditions' => array(''),'fields'=>array(''),'order'=>array('')));  
           Cache::write('Categories',$mainCategories,'long_db');  
         }  

2. In AppModel add

 public $recursive = -1;  
    function find($conditions = null, $fields = array(), $order = null, $recursive = null) {  
     $doQuery = true;  
     // check if we want the cache  
     if (!empty($fields['cache'])) {  
       $cacheConfig = null;  
       // check if we have specified a custom config  
       if (!empty($fields['cacheConfig'])) {  
         $cacheConfig = $fields['cacheConfig'];  
       }  
       $cacheName = $this->name . '-' . $fields['cache'];  
       // if so, check if the cache exists  
       $data = Cache::read($cacheName, $cacheConfig);  
       if ($data == false) {  
         $data = parent::find($conditions, $fields,  
           $order, $recursive);  
         Cache::write($cacheName, $data, $cacheConfig);  
       }  
       $doQuery = false;  
     }  
     if ($doQuery) {  
       $data = parent::find($conditions, $fields, $order,  
         $recursive);  
     }  
     return $data; 
    } 

Now what we have done here is
a. In first line we have added recursive=-1 so cake will no longer fetch 1st level relationships by default and they can be acquired by manually setting when required thus reducing over load.
b. In the second line we have added a function which will allow you to cache your queries even without writing the code in step one it automates the process as follows


 $this->User->find('list',  
   array('cache' => 'userList', 'cacheConfig' => 'short')  
 );  

This will automatically cache your query's when it finds cache and cacheConfig parameter's in find condition

Make sure following is enabled and added in "/app/Config/core.php"

 Configure::write('Cache.check', true);  
 Cache::config('short', array(  
   'engine' => 'File',  
   'duration'=> '+5 minutes',  
   'probability'=> 100,  
   'path' => CACHE,  
   'prefix' => 'cache_short_'  
 ));  


The second statement is a cache configuration defined in core.You can also set another configuration and pass the same to "cacheConfig" parameter's above like we have passed "short"

3. Bind/Unbind Model's on Fly

This requires proper requirement analysis and analyzing ERD the way it reflects on project.
One way out is that if you feel if the binding between 2 model's is required at every step

For example Menu categories and subcategories are required so it is very much feasible to join them together at the beginning only.So if at any point you require only categories you should unbind the subcategories relation.

It's very hard to judge which way to follows to Bind all model's first and then unbind on fly to taste or vice versa.I prefer a mix approach i.e. when in doubt I prefer to bind on fly rather than to load an unnecessary association on fly

Friday, October 4, 2013

HTACCESS-Add MIME Type

Sometimes some MIME types are not present in default Apache Server configurations.But we may need to add them to our server so that we can perform operation's such as gzip compression,add them to browser caching etc

Recently I came across one such issue where I had to add a font type called "woff" to the same i added the same as follows

 <IfModule mod_mime.c>  
   AddType application/x-font-woff woff  
 </Ifmodule>  

Page Speed-Enable gzip compression

Add the following code to .htaccess(preferably in root)


 # compress text, HTML, JavaScript, CSS, and XML  
 AddOutputFilterByType DEFLATE text/plain  
 AddOutputFilterByType DEFLATE text/html  
 AddOutputFilterByType DEFLATE text/xml  
 AddOutputFilterByType DEFLATE text/css  
 AddOutputFilterByType DEFLATE text/javascript  
 AddOutputFilterByType DEFLATE application/xml  
 AddOutputFilterByType DEFLATE application/xhtml+xml  
 AddOutputFilterByType DEFLATE application/rss+xml  
 AddOutputFilterByType DEFLATE application/javascript  
 AddOutputFilterByType DEFLATE application/x-javascript  
 # remove browser bugs  
 BrowserMatch ^Mozilla/4 gzip-only-text/html  
 BrowserMatch ^Mozilla/4\.0[678] no-gzip  
 BrowserMatch \bMSIE !no-gzip !gzip-only-text/html  
 Header append Vary User-Agent  

Thursday, October 3, 2013

Page Speed-Leverage browser caching

Make sure that Browser cache expire time should be at least 
1 week for consistent things. This can be reduced files that change constantly.
 
To add this add following like structure in .htaccess
(preferably root can be changed to taste in some cases)
 
 
 ## EXPIRES CACHING ##  
 ExpiresActive On  
 ExpiresByType image/jpg "access plus 1 year"  
 ExpiresByType image/jpeg "access plus 1 year"  
 ExpiresByType image/gif "access plus 1 year"  
 ExpiresByType image/png "access plus 1 year"
 ExpiresByType text/javascript "access plus 1 month"
 ExpiresByType text/css "access plus 1 month"
 ExpiresByType application/pdf "access plus 1 month"  
 ExpiresByType text/x-javascript "access plus 1 month"  
 ExpiresByType application/x-shockwave-flash "access plus 1 month"  
 ExpiresByType image/x-icon "access plus 1 year"  
 ExpiresDefault "access plus 2 days"  
 ## EXPIRES CACHING ##