Pages

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 ##  

Page Speed-Specify a Vary: Accept-Encoding header


 <IfModule mod_headers.c>  
  <FilesMatch "\.(js|css|xml|gz)$">  
   Header append Vary Accept-Encoding  
  </FilesMatch>  
 </IfModule>  
If you would like to add more file type to this rule, add the its extension to the statement

Wednesday, October 2, 2013

PHP-Version Check code

 if (version_compare(phpversion(), '5.0.0', '>=') !== true) {  
   exit('This website runs with PHP5... You version is <b>' . phpversion() . '</b>.Please upgrade');  
 }  

Sunday, September 29, 2013

CodeIgniter-Seo Urls

1. I am using ubuntu 13.04. To setup mod_rewrite on debian based machines ubuntu is in concern here go through my this post

http://itfeast.blogspot.in/2013/09/cakephpubuntu-setting-up-cakephp-on.html

If you are assured that mod_rewrite is working perfectly on your Apache Server Proceed Further.

Now We will proceed with configuring CodeIgniter for seo urls

2. Remove Index.php

Your root .htaccess should look like this

 <IfModule mod_rewrite.c>  
 # Turn on URL rewriting  
 RewriteEngine On  
 # If your website begins from a folder e.g localhost/my_project then   
 # you have to change it to: RewriteBase /my_project/  
 # If your site begins from the root e.g. example.local/ then  
 # let it as it is  
 RewriteBase /ci/  
 # Protect application and system files from being viewed when the index.php is missing  
 RewriteCond $1 ^(application|system|private|logs)  
 # Rewrite to index.php/access_denied/URL  
 RewriteRule ^(.*)$ index.php/access_denied/$1 [PT,L]  
 # Allow these directories and files to be displayed directly:  
 RewriteCond $1 ^(index\.php|robots\.txt|favicon\.ico|public|assets|css|js|images)  
 # No rewriting  
 RewriteRule ^(.*)$ - [PT,L]  
 # Rewrite to index.php/URL  
 RewriteRule ^(.*)$ index.php/$1 [PT,L]  
 </IfModule>  

3. Now in application/config/config.php

change
$config['index_page'] = 'index.php';
to
$config['index_page'] = '';

In some cases you may also need to configure

$config['uri_protocol'] = 'AUTO';

To

$config['uri_protocol'] = 'PATH_INFO';

Or To

$config['uri_protocol'] = 'REQUEST_URI';

4. Now your folder structure should look like this

website_folder/ 
–––– application/ 
–––– system/ 
–––– user_guide/ 
====>.htaccess
–––– index.php 
–––– license.txt
 
You might also go for custom routing further as
 
$route['default_controller'] = 'webpages'; //Our default Controller

//Get rid of the first segment (in our case we get rid of webpages)
$route["about"] = 'webpages/about'; 
$route["blog/(.*)"] = 'webpages/blog/$1';
$route["view/(.*)"] = 'webpages/view/$1';
 
Source: http://www.web-and-development.com/codeigniter-remove-index-php-minimize-url/ 

Sunday, September 22, 2013

PHP-Find current quarter for genarating quarterly payments etc.

    $firstday1=date("Y-1-1 00:00:00");
        $lastday1=date("Y-3-31 23:59:59");
        $firstday2=date("Y-4-1 00:00:00");
        $lastday2=date("Y-6-30 23:59:59");
        $firstday3=date("Y-7-1 00:00:00");
        $lastday3=date("Y-9-30 23:59:59");
        $firstday4=date("Y-10-1 00:00:00");
        $lastday4=date("Y-12-31 23:59:59");
        $today = time();
        if( (strtotime($firstday1) <= $today) && ($today<= strtotime($lastday1)))
        {
            $qtr=1;
        }
        elseif( (strtotime($firstday2) <= $today) && ($today <= strtotime($lastday2)))
        {
            $qtr=2;
        }
        elseif( (strtotime($firstday3) <= $today) && ($today <= strtotime($lastday3)))
        {
            $qtr=3;
        }
        elseif( (strtotime($firstday4) <= $today) && ($today <= strtotime($lastday4)))
        {
            $qtr=4;
        }
        echo $qtr;

Wednesday, September 18, 2013

Design-Issue for site in IE8 and IE9

Recently I face a design issue error in IE8 and IE9 the design was a bit misaligned it was coming perfectly on all other browser's

My team fixed the same by adding following tag above HTML

 <!DocType html>  



Thanks to Manendra Verma for his efforts

FFMPEG-[libmp3lame @ 0x1c0d8d0]flv does not support that sample rate, choose from (44100, 22050, 11025)

Recently while converting video's for my site I came across this error

The solution was simple simple place all the parameters after -i parameter i.e input parameter

for ex I was using -ar 44100 -y -qscale 4 before -i anf ter i shifted all of them after -i my issue was resolved

Sunday, September 15, 2013

Cakephp-Data Validation Not Working-Resolution workflow

Recently while working on a Linux Machine I faced an issue where cake's default validation was not working.Here is the walkthrough of steps which you must ensure to make it work if it still doesn't let me know

1. First things first-If you are working on linux server File Name Casing is an issue.Make sure your model File name,Class name matches the name of your first parameter in form.


 //File name  
 Task.php  
 //Model Class  
 class Task extends AppModel  
 {  
 }  
 //Form Start  
 <?php echo $this->Form->create('Task');?>  

2. Check Validation rule's format they should match cake convention's

     public $validate = array(
        'title'=>array(
            'alphaNumeric' => array(
                'rule'     => 'alphaNumeric',
                'required' => true,
                'message'  => 'Alphanumeric only'
            ))); 

I was doing everything right but my file name was incorrect I was using a lowercase filename which caused the error

Cakephp,Ubuntu-Setting Up Cakephp on Ubuntu Server/Enabling Mode_Rewrite

Recently while installing Cakephp on Ubuntu Server I face some initial setup errors.

1. Firstly rewrite_module was not enabled I enabled it using the following commands

sudo a2enmod rewrite

2.  Needed to Enable AllowOverride All For this I modified following file

/etc/apache2/sites-available/default



 <VirtualHost *:80>  
      ServerAdmin webmaster@localhost  
      DocumentRoot /var/www  
      <Directory />  
           Options FollowSymLinks  
           AllowOverride All  
      </Directory>  
      <Directory /var/www/>  
           Options Indexes FollowSymLinks MultiViews  
           AllowOverride All  
           Order allow,deny  
           allow from all  
      </Directory>  
      ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/  
      <Directory "/usr/lib/cgi-bin">  
           AllowOverride All  
           Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch  
           Order allow,deny  
           Allow from all  
      </Directory>  
      ErrorLog ${APACHE_LOG_DIR}/error.log  
      # Possible values include: debug, info, notice, warn, error, crit,  
      # alert, emerg.  
      LogLevel warn  
      CustomLog ${APACHE_LOG_DIR}/access.log combined  
   Alias /doc/ "/usr/share/doc/"  
   <Directory "/usr/share/doc/">  
     Options Indexes MultiViews FollowSymLinks  
     AllowOverride All  
     Order deny,allow  
     Deny from all  
     Allow from 127.0.0.0/255.0.0.0 ::1/128  
   </Directory>  
 </VirtualHost>  


3. Finally restart Apache

 sudo /etc/init.d/apache2 restart

Sunday, August 18, 2013

PHP-Convert a timestamp into facebook post time representation i.e years ago,months ago,weeks ago,days ago,hours ago,minutes ago,seconds ago format

This code is helpful for converting a timestamp field to a time stated as

years ago if it is more than an year ago
months ago if it is more than a month ago
week ago
days ago
hours ago
seconds ago

For example a post made yesterday will be shown as " 1 day ago"

Here goes the code
 <?php  
 $today = time();    
                 $createdday= strtotime($post['created']); //mysql timestamp of when post was created  
                 $datediff = abs($today - $createdday);  
                 $difftext="";  
                 $years = floor($datediff / (365*60*60*24));  
                 $months = floor(($datediff - $years * 365*60*60*24) / (30*60*60*24));  
                 $days = floor(($datediff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));  
                 $hours= floor($datediff/3600);  
                 $minutes= floor($datediff/60);  
                 $seconds= floor($datediff);  
                 //year checker  
                 if($difftext=="")  
                 {  
                   if($years>1)  
                    $difftext=$years." years ago";  
                   elseif($years==1)  
                    $difftext=$years." year ago";  
                 }  
                 //month checker  
                 if($difftext=="")  
                 {  
                    if($months>1)  
                    $difftext=$months." months ago";  
                    elseif($months==1)  
                    $difftext=$months." month ago";  
                 }  
                 //month checker  
                 if($difftext=="")  
                 {  
                    if($days>1)  
                    $difftext=$days." days ago";  
                    elseif($days==1)  
                    $difftext=$days." day ago";  
                 }  
                 //hour checker  
                 if($difftext=="")  
                 {  
                    if($hours>1)  
                    $difftext=$hours." hours ago";  
                    elseif($hours==1)  
                    $difftext=$hours." hour ago";  
                 }  
                 //minutes checker  
                 if($difftext=="")  
                 {  
                    if($minutes>1)  
                    $difftext=$minutes." minutes ago";  
                    elseif($minutes==1)  
                    $difftext=$minutes." minute ago";  
                 }  
                 //seconds checker  
                 if($difftext=="")  
                 {  
                    if($seconds>1)  
                    $difftext=$seconds." seconds ago";  
                    elseif($seconds==1)  
                    $difftext=$seconds." second ago";  
                 }  
                 echo " | ".$difftext;  
 ?>  

MYSQL-Find a word from comma separated list(in string)

I have a table as follows

id name status
1  test1  option1,option2
2  test2  option,option1
3  test3  option2,option3
4  test4  option3,option4
5  test5  option1,option3

"SELECT * FROM TABLE WHERE FIND_IN_SET('option',status-name of column/attribute)">0

simple query to check whether a string is present in comma separated values entered as string under a column or attribute

Cakephp-Refresh Auth Session information after a database change of current user

In order to update current user logged in Auth Session after a database change in his information in Users Table use the following command

$userid=$this->Auth->user('id');

$this->Session->write('Auth',$this->User->read(null,$userid));

That's it and your auth session is updated..

This is usually done once a user updates his information....

Authroize .Net-Error:E00044 [text]=>Customer Information Manager is not Enabled

This error I faced using Authorize .Net CIM.My only mistake was I signed up with an account with credit card present in Authorize .net developers

Sign up with an account with "Card Not Present option" and it will give you a different admin panel where you can enable disable CIM.


cakephp-Ascending Order in Pagination

Recently I faced an issue while implementing an "Order By" command in cakephp pagination it was not taking the regular cakephp syntax

So I performed the same as follows

$this->Paginate=array('limit'=>10,'order'=>array('Model.field1'=>'asc'));

remember I used regular order i.e.

$this->Paginate=array('limit'=>10,'order'=>array('Model.field1 ASC'));

but this did not work

Amazon Cloud-AMI Machines-Setup PHP and mysql on Amazon Cloud

In my case I needed to install -mcrypt library to decrypt passwords

I used

yum install php libmcrypt libmcrypt-devel php-mcrypt php-mbstring

The best complete tutorial I got was here

http://calebogden.com/wordpress-on-linux-in-the-amazon-cloud-with-mac/

Best FLV conversion parameters from ffmpeg

Recently while developing one of my projects We were using Hit and Try to get best output from ffmpeg to convert to a flv.

when one of my co-developers finally came out with following command

exec ("/usr/bin/ffmpeg -qscale 4 -i" old_video_loc new_video_loc);

Thanks Hitesh for efforts

Install FFmpeg and ffmpeg-php on CentOS

1. Create and open a new file called /etc/yum.repos.d/dag.repo.

vi /etc/yum.repos.d/dag.repo“.

2. Add the following text to the file:
[dag]
name=DAG RPM Repository
baseurl=http://apt.sw.be/redhat/el$releasever/en/$basearch/dag
gpgcheck=1
enabled=1 
Finally, save and close the file.

3. In order to successfully use the DAG repository with tools such as yum, you need to add DAG’s GPG key.

Failure to do so will result in an error like the following: warning: rpmts_HdrFromFdno: Header V3 DSA signature: NOKEY, key ID 6b8d79e6 Public key for faac.x86_64.1.26-1.el5.rf.rpm is not installed 

4. In order to add the GPG key for DAG, run the following:
rpm --import http://apt.sw.be/RPM-GPG-KEY.dag.txt

5. Now that DAG is setup, it’s a good idea to update all your packages.

yum update

6. Search for ffmpeg package

yum search ffmpeg

7. Install package with depencdecy packages

yum install ffmpeg ffmpeg-devel ffmpeg-libpostproc

8. There are four things that are required to successfully install and run ffmpeg-php; they are:
  • ffmpeg-0.4.9_pre1 or higher
  • php-4.3.0 or higher
  • gd-2.0 or higher
  • php-devel
PHP and FFmpeg should be good to go since at the time of this writing, DAG has PHP version 5.1.6 and FFmpeg version 0.4.9. GD and php-devel can be easily installed by running the following yum command:
yum install php-gd php-devel
 
Installing ffmpeg-php

Now we are ready to install ffmpeg-php.
This can be done in six easy steps:

1. Download the latest ffmpeg-php release
2. Extract the archive: tar -xjf ffmpeg-php-X.x.x.tbz2
3. cd ffmpeg-php-X.x.x/
4. phpize
5 ./configure & & make
6 sudo make install

Wednesday, July 17, 2013

Web Development/Jquery/Javascript-Set a menu Link "selected" class if its href matches page url

Here is a simple js code with HTML to set a "seected" class to menu item when its corresponding page is open.

 <dl class="sidebarBox">  
   <dt>Mailboxes</dt>  
   <dd>  
     <ul class="mailbar">  
       <li><a href="inbox"><b>Inbox</b></a></li>  
       <li><a href="sent">Sent</a></li>  
       <li><a href="trash">Trash</a></li>  
     </ul>  
   </dd>  
 </dl>  
 <script type="text/javascript">  
   var winpath=window.location.pathname;  
   $(".mailbar li a").each(function(index)  
   {  
     var menupath=$(this).attr('href');  
     if(menupath==winpath)  
       $(this).parent().addClass("current");  
     else  
       $(this).parent().removeClass("current");  
   });  
 </script>  

Paypal-Authorization Error 1002

While integrating Paypal I was receiving an authorization error 1002

My NVP header string all the things except paymentaction which can be selected based needs from following url

https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_ECSettlements

Other things needed for header string are

API_USERNAME
API_SIGNATURE
API_ENDPOINT
SUBJECT
PAYPAL_URL
Paymentaction

I used it as "Sale" as mine was a case of st right forward sale

If you are receiving a  result as follows

Array
(
    [TIMESTAMP] => 2013-06-22T10:06:14Z
    [CORRELATIONID] => 5xc75ssx3d7e2
    [ACK] => Success
    [VERSION] => 65.1
    [BUILD] => 6454311
    [AMT] => 23.00
    [CURRENCYCODE] => USD
    [AVSCODE] => X
    [CVV2MATCH] => M
    [TRANSACTIONID] => 9T29872102086351Q
)

then payment is processed successfully

Amazon S3-RequestTimeTooSkewed The difference between the request time and the current time is too large

Recently while working on a Project which had a hosting on Amazon Cloudfront, Storage on S3 and Streaming from Amazon EC2.I came across an issue which went ok initially but became a 2 day R&D Topic for my team after a server shutdown and Reset...

While requesting bucket I got a strange error from Amazon

"RequestTimeTooSkewed The difference between the request time and the current time is too large"

I checked everything from security credentials to bucket name finally going to Amazon Support where I came to knew that i was the fault of my system clock.

Our Systems must sync to NTP-Network Time Protocol in order to sync with Amazon Cloud Services..

My server

Centos which is redhat/suse based

Here is how i resolved the same

First and foremost I installed ntp again to be on safer side and make sure every stone in path was carved to needs

Install NTP
Yum install ntp

Check from config NTP is On
Chkconfig ntpd on

If everything is going well without any warnings till now its time to finalize

Sync Server time with amazon ntp

You have to check by trying to access your bucket and adding file to it after each and every sync with following servers..its like hit and try depending on your region.

ntpdate -u 0.amazon.pool.ntp.org
ntpdate -d 0.amazon.pool.ntp.org

ntpdate -u 1.amazon.pool.ntp.org
ntpdate -d 1.amazon.pool.ntp.org

ntpdate -u 2.amazon.pool.ntp.org
ntpdate -d 2.amazon.pool.ntp.org

ntpdate -u 3.amazon.pool.ntp.org
ntpdate -d 3.amazon.pool.ntp.org

That's it that solved my issue out

GIT Repository-Export only modified and added files with folder structure in Git

Recently I was working on a git repository setup on  my local and had a task of getting all the modified and changed files in a tar.(Remember I had not committed my changed files).Even if you have you can use the corresponding commit id to get list of changed files in that commit

Here is the command I used to extract modified and added files in a GIT repository


 git diff-tree -r --no-commit-id --name-only --diff-filter=ACMRT $commit_id | xargs tar -rf mytarfile.tar  

Sunday, June 9, 2013

Cakephp/PHP-Maintaing Pagination id's in sequance for each page

 Cakephp/PHP-Logic,Setting Pagination id's in sequance

 $paginationdata=$this->Paginator->params();  
 $currentpage=$this->Paginator->current();  
 foreach($data as ($key=>$value))  
 {  
   echo ($paginationdata['limit']*($currentPage-1))+$key+1;  
 }  
Now for any page id's will start according to selected page for example for first page on a limit 5...1,2,3,4,5 on second page limit 5.....6,7,8,9.10

PHP-How to generate Youtube like video url's



 <?php  
 $encoded=base64_encode(Uniqid().$myVideosValue['Uservideo']['id']);  
 ?>  


and then send this along with URL and at receiving end decode it as follows

 <?php  
 $decoded= substr(base64_decode($paramstr),13);  
 ?>  




Cakephp-Convert time from ffmpeg extension to required format

Recently I used ffmeg to encode videos to flv format in one of my projects.

You need to include its php extension to perform the same or you can use the software too..I will discuss the same in some lator post..

Meanwhile after encoding videos it was returning me its time in following format

"00:04:43.77"

where as client asked me to change the same to

"00:04:43" i.e, to eliminate the millisecond part..


I used

 <?php  
 $vidlen=new DateTime($myvideolength);  
 echo "converted time=";  
 $vidlen->format("H:i:s");  
 ?>  

PHP-get User Browser

 <?php  
 function get_user_browser()  
 {  
   $u_agent = $_SERVER['HTTP_USER_AGENT'];  
   $ub = '';  
   if(preg_match('/MSIE/i',$u_agent))  
   {  
     $ub = "ie";  
   }  
   elseif(preg_match('/Firefox/i',$u_agent))  
   {  
     $ub = "firefox";  
   }  
   elseif(preg_match('/Safari/i',$u_agent))  
   {  
     $ub = "safari";  
   }  
   elseif(preg_match('/Chrome/i',$u_agent))  
   {  
     $ub = "chrome";  
   }  
   elseif(preg_match('/Flock/i',$u_agent))  
   {  
     $ub = "flock";  
   }  
   elseif(preg_match('/Opera/i',$u_agent))  
   {  
     $ub = "opera";  
   }  
   return $ub;  
 }  
 ?>  

Cakephp-using Timthumb in cakephp

Using TimThumb in cakephp

Timthumb library is used to generated required sized images on the fly..it produces images of required size which are stored in its cache as such page is loaded much faster...

Timthumb can be easily downloaded from

http://timthumb.googlecode.com/svn/trunk/timthumb.php

Download the file and place it in

/webroot/files/timthumb.php

create a folder called cache with permissions "777" under the same folder.

now use the following code to echo images via timthumb

 echo $this->Html->image('/files/timthumb.php?src='.WWW_ROOT.'/img/imgname.jpg&w=63&h=63');  


this will convert any size image to 63X63 on the fly...you see more options of this library to make a better use of the same.

Cakephp-Send Multiple elements in ajax request frpm ajaxhelper/jshelper

From the following post

http://itfeast.blogspot.in/2013/06/cakephp-20-create-0bserve-field.html

To send multiple elements in ajax request from ajaxhelper/jshelper

 'data'=>$(\'#category,#sort\');  

For example this is how I passed the same in cakephp
  <script type="text/javascript">  
            <?php   
              echo $this->Js->get('#category')->event('change',$this->Js->request(  
                  array('controller' => 'contributors', 'action' => 'changevideos'),  
                  array('update'=>'#vediocontainer','async' => true,'dataExpression' => true,'method' => 'post','data'=>'$(\'#category,#sort,#fileid\').serializeArray()')  
                  ),false);  
             ?>  

Cakephp 2.0-Create 0bserve field equivalent with new jshelper

Many things have changed in v2.0 of cakephp removal of ajaxhelper is one of them in its plce we have a new helper called jshelper() to perform similar tasks here is how to use observe field with jshelper in cakephp 2.x


 <?php  
 echo $this->Js->get('#category')->event->('change',$this->JS->request(array(  
 'controller'=>'contributers',  
 'action'=>'changevideos'),  
 array(  
 'update'=>'#videocontainer',  
 'async'=>true,  
 'dataExpression'=>true,  
 'method'=>Post,  
 'data'=>$(this).serialize()'),  
 false))  
 ?>   

Where #category is the id of element which fires event and #videocontainer is the id of div which is updated of data from controller "contributors" and its action "changevideos"

Cakephp-Sort by custom made field in MYSQL not working in pagination

Recently in one of my cakephp projects.I came across a issue in pagination and sorting of data on basis of a custom made field..

Case:
I had a MYSQL field "video_length" in STRING which should have been in TIME(DB was not created by me)...

My requirement was sort on basis of this field so in my find function of Model I used

"TIME_TO_SEC(UserVideo.video_length)" AS vid_len and sorted by the same

It was working fine in normal scenario but was not showing sorted results under pagination may be because it was not permanent column of table

Solution:

I did some tricky thing here..I needed the column in format TIME_TO_SEC so in my fields property in my find function I customized fields and added concerned field in name of old field sth like

$this->UserVideo->find('all',array('fields'=>array("TIME_TO_SEC(UserVideo.video_length)" AS video_length)))

See words marked in bold

And finally all was coming well under pagination as well

Cakephp->check if there was a referrer page/last page

Cakephp check for a last page/redirect to last page


 if($this->reffrrer()!='/')  
 {  
 $this->redirect($this->reffrrer());
 }  
 This works in controller 

Sunday, May 12, 2013

Zend-Error-Zend_Loader::registerAutoload is deprecated as of 1.8.0 and will be removed with 2.0.0

This warning appear's because you have the lines:

require_once 'Zend/Loader.php';
Zend_Loader::registerAutoload();


Replace them with
 
require_once 'Zend/Loader/Autoloader.php';
$loader = Zend_Loader_Autoloader::getInstance();
$loader->registerNamespace('App_');



Where 'App_' is the name of a directory on your include path that has classes within it that follow the Zend Framework naming convention, so change it as appropriate and add more if you need them. 

Zend-Adding/Appending an element in a control in block

$form->submit->setDecorators(

 array(
             'ViewHelper',
              array(
                   array('data'=>'Html Tag' ),
                   array('placement'=>Zend_Form_Decorator_Abstract::PREPEND),
                    'tag'=>'span',
                    'class'=>'wp_submit'
                      ),
               array(
                    array(array('data'=>'Html Tag')),
                    array('tag'=>'span','class'=>'newspan')
                      )
        )

)

Zend-Escaping a Label of Element in a Form/Block

Zend-For Escaping a label in a block use

$form->submit->setAttributes("escape",false);

$form->submit->setLabel('Login');

Social Engine-Get User level,id

Social Engine 4

Get User level

//Get User Level

$userEngine_Api::_()->user()->getViewer()->level_id.

//Get User Id

$UserEngine_Api::_()->user()->getViewer()->getIdentity

Friday, May 10, 2013

Upload Files to Amazon S3(Simple Storage) using PHP

Recently I was working on a project which required to upload files on Amazon Simple storage service which is S3

The 2 tutorials which worked perfectly for me are mentioned in links as follows

http://www.9lessons.info/2012/08/upload-files-to-amazon-s3-php.html

http://net.tutsplus.com/tutorials/php/how-to-use-amazon-s3-php-to-dynamically-store-and-manage-files-with-ease/


The latest SDK has somefor PHP 2 has some limitations I will point further...

Monday, May 6, 2013

Social Engine 4-Get values from a table

//gets a table called engine4_authorization_permissions

$permissionTable=Engine_Api_()->getDbTable('permissions','authorization');

$permissionSelect=$permissionTable->select()->where('level_id'=?,$userlevel)->where('type'=>'usercommit');

$fetchdata=$permissionTable->fetchrow($permissionSelect);

$fetchdatas=$permissionTable->fetchrows($permissionSelect);
//To get attribute from row

echo $fetchdata->attribute_name

foreach($fetchdatas as $fetchdata)
{
     echo $fetchdata->attribute_name;
}

Social Engine 4-Finding name of widget and Calling/Running a widget by custom code via name

First things first

1. In the backend select layout=>layout editor

Select the page on which your widget is currently placed

Or

If you know the name of your widget find it in concerned module on right hand side

You can use my technique for the same

For example we are looking for the widget "Statistics" Find the plugin text in admin using "find text tool(Ctrl+F)" of your browser and search for the same under "Available Blocks"

2. Once yo know the widget and its module for example for above mentioned  widget we find it under "Core Module"

Moving Back to code

under

/application/modules/core/settings (considering our example for Core Module and Statistics Widget)

open file content.php

find the array of widget Statistics there like


 array(  
 'title'=>'statistics',  
 'description'=>'',  
 'category'=>'core',  
 'type'=>'widget',  
 'name'=>'core.statistics',  
 'defaultParams'=>array(  
 'title'=>'Statistics'  
 ),  
 'requirements'=>array(  
 'no-subject',  
 ),  
 );  

Now we need the name attribute to call our widget in code as


 <?php  
 echo $this->content()->renderWidget('core.statistics';)  
 ?>  

other examples can be

content()->renderWidget('core.ad-campaign') ?>

content()->renderWidget('user.home-photo') ?>

Social Engine 4-Fetching and displaying a menu from backend

1. Create a menu from admin backend by going to Layout->Menu Editor from menu

2. Now go to database and in table "engine4_core_menus" find the entry for your menu and give the same name under "name" field(if already not there)

3. Now in controller to assign the menu to a view variable use

 $this->view->navigation=Engine_Api::_()->getApi('menus','core')->getNavigation('credit_main');  

where 'credit_main' is the 'name' of your menu from table "engine4_core_menus"

To render menu in view use


 echo $this->navigation()->menu()->setContainer($this->navigation)->render();  



Sunday, May 5, 2013

Social Engine 4-Managing a page from Admin Panel or only by widgets

In Social Engine 4 many a times we feel the need to manage our page only from backend i.e. from the widgets we have created only

Here are the steps to perform the same

1. Disable layout from controller's action function you have to create an action for the newly added page see second step on how to add actions for concerned pages in respective controllers

$this->helper->content->setNoRender()->setEnabled();

2. In "Engine4_core_pages" find the corresponding entry to your newly created page(generally this will be the last entery of table if ordered by id).

and set its name as

"credit_index_manage" or "credit_index_network"

Here
"credit" is your module name
"index" is the controller(IndexController) of module
and
"manage/network" are the action names under the controller

that's it now you can manage your page from widgets in backend no need to create a view.....


Social Engine 4 - Adding a Menu Item to a Menu Specified under Module(create a menu plugin)

First things first

1. Create/Add a menu item to respective menu from admin

Layout=>Menu Editor

2. Now in table "engine4_core_menuitems" set the following attributes

name="credit_main_network" //we will use this later in code avoid spaces
module=Credit(your module name)
label=Network(label of your menu item)
plugin=Credit_Plugin_Menus
{"route" : "credit_general","action":network}


3. Next route will be defined in your "modulename/settings/manifest.php"

for example

'credit_general'=>array(
'route'=>'credits/:action/*',
'defaults'=>array(
      'module'=>'credit',
      'controller'=>'index',
      'action'=>'index'
      ),
'menu'=>'credit_main' //(from table engine4_core_menus)
'submenu'=> if any
'enabled'=>1,
'order'=>3
)

4. Now in plugin under your module create a file "Menus.php"(if not there)

and template it as follows

for example for me file was /module/credit/Plugin/menus.php

class Credit_Plugin_Menus
{
     // see name of menu from table we have used after underscore

    public function onMenuInitialize_CreditMainNetwork($row)
   {
           If(!Engine_Api::_()->user()->getViewers()->getIdentity())
           {
               return false;
           }
           return true;
   }
}

That's it you have successfully configured menu for your Module in Social Engine 4

Social Engine 4-Create a module

In Admin Panel

Manage=>Packages & Plugins=>Developer SDK=>Create a Package


This will give you a complete zip package and required directory sturcture for module

Friday, May 3, 2013

Magento-Get information of Items in Cart

Magento-Get Information of Items in Cart

$items=Mage::getSingleton('Checkout/Session')->getQuote()->getAllItems();

foreach($items as $item)
{
    echo $item->getName();
                      ->getQty();
                      ->getPrice();
                      ->getSku();
                      ->getProductid()
}


Magento-get Cart Count

Mage::('checkout/cart')->getItemsCount();

Social Engine 4-Get avtar of user

$user_id=Engine_Api::()_->user->getviewer->getIdentity();

$userinfo=Engine_Api::_()->user()->getUser($user_id);

$photo_id=$user_info['photo_id'];


//Fetches table Engine4_storage_files

$filesTable=Engine_APi::_()->getDbtable('files','storage');

$adapter=Engine_Db_Table::getDefaultAdapter();

$filesTableName=$filesTable->info('name');

$query=Engine_Db_Table::getDefaultAdapter()->select("storage_path")->from($statsTableName)->where("field_id=?",$photo_id)->limit(1);

$result=$query->query()->fetch();

$result['storage_path'] //has the path to your photo


Social Engine 4-Get User Info

$user_id=Engine_Api::()_->user()->getviewer()->getIdentity();

$user_info=Engine_Api::_()->user()->getUser($user_id);

Then you get an array $user_info

Now to get let us suppose email of user we use

$user_info['email'];

print_r($user_info) to get data array and check other key's

The other keys are


  1. user_id
  2. email
  3. username
  4. displayname
  5. photo_id
  6. status
  7. status_date
  8. password
  9. salt
  10. locale
  11. language
  12. timezone
  13. search
  14. show_profileviews
  15. level_id
  16. invites_used
  17. extra_invites
  18. enabled
  19. verified
  20. approved
  21. creation_date
  22. creation_ip
  23. modified_date
  24. lastlogin_date
  25. lastlogin_ip
  26. update_date
  27. member_count
  28. view_count

Sunday, April 21, 2013

Social Engine 4-Render and manage a page/view from backend

Here I will show you how to create and run a page from backend and get the control of the same from backend in Social Engine 4

Generally when we create pages we need to define a controller and action for them and control them via code.Some themes have fixed pages in them which are controlled directly from backend.

But if we want to add a custom page to be manageable from backend here is how to do the same

  1. First things First Take a backup of your database and also the files that you modify along I prefer to use a versioning system for lator case
  2. Create a new blank page from "Layout Manager"  in the backend/backadmin of Social Engine 4
  3.  Now go to your database and in the table Engine4_core_pages you will find NULL in "name" change this to "yourmodulename_yourcontrollername_yourviewname" for example if your
    1. Module is "Credits"
    2. Controller is "index"
    3. View is also "index"
Then name will be "credit_index_index"

Give it a title and description which you can also set from backend by modifying this page

4. Navigate to your Module directory "credits" in this case and then navigate to controllers and under controller create a file "IndexController"

1:  <?php   
2:  class Credit_IndexController extends Core_Controller_Action_Standard  
3:  {  
4:    public function indexAction()  
5:    {  
6:        $this->_helper->content->setNoRender()->setEnabled();  
7:    }  
8:  }  
9:  ?>  

This lets you add page from backend but will not render its content i.e "/module/views/scripts/index.tpl"

Now your view will be rendered and managed from backadmin only

Social Engine 4-Creating a widget in a module

Before creating a widget in a module we need to register the same

1. Go to your module folder and then in your module go to file

settings/content.php

This file contains all widgets which this module will provide.

As an example we will create a widget to show graph and also called it graph

This file returns an array of array's where the former contains various widgets information

 return array(  
  array(  
   'title' => 'Navigation Tabs',  
   'description' => 'Displays the Navigation tabs(menu) for Credits: Credits Home, My Credits, FAQ. Put this widget on the top of Credits Home and My Credits pages.',  
   'category' => 'Credits',  
   'active' => true,  
   'type' => 'widget',  
   'name' => 'credit.navigation-tabs',  
  ),  
  array(  
   'title' => 'Top Members',  
   'description' => 'Displays top members list with highest number of credits. Put this widget on Credits Home or on any other page.',  
   'category' => 'Credits',  
   'active' => true,  
   'type' => 'widget',  
   'name' => 'credit.browse-users',  
   'defaultParams' => array(  
    'title' => 'Top Members'  
   )  
  ),  
  array(  
   'title' => 'Graph',  
   'description' => 'Displays a widgets which displays a list of quick links to create a graph.',  
   'category' => 'Credits',  
   'type' => 'widget',  
   'name' => 'credit.graph',  
    'active' => true,  
   'defaultParams' => array(  
    'title' => 'Graph'  
   )  
  ));  

Look in the last array we have added our custom widget array in the end

Now lets move into the widget's folder of our module

Let's suppose our Module name is "Credit"

so in /widgets/graph/controller.php

We need to create these directories as per requirement

1:  Class Credit_Widget_GraphController extends Engine_Content_Widget_Abstract  
2:  {  
3:     public function indexAction()  
4:     {  
5:        $this->view->myvar="myvarvalue";  
6:       //You can also include forms (defined in forms of your module)  
7:         $this->view->form=new Filter_Form()  
8:     }  
9:  }  

Look at the name of the class see in settings file we have defined property "name" in widget array as credit.graph like wise here "Credit" is our module and "Graph" is widget...This should match with property.

Next we define template in
in /widgets/graph/index.tpl

and Access variables as

1:  <?php echo $this->filterForm ?>  


That's It Add widget from backend to the respective page

Social Engine 4-Flash,External Interface Available Text

Text in Social Engine

SM2 SWF V2.97a. 20110918(AS3/Flash)
External Interface Available
Adding External Interface Callbacks
Testing Flash->JS,
JS->Flash OK
Flash->JS OK

This is Social Engine Debug Info and comes only in Production Mode

Stop a link from reloading page

Place Javascript:void(0) for the href property.

or Javascript:return 0 and your page will not reload it self on click of the link.

Wednesday, April 3, 2013

Magento install error - Exception printing is disabled

Here is the walk through to recover from this error

  1. Navigate to the "errors" folder.
  2. Change local.xml.sample to local.xml
Worked for me till here while I was in installation phase

However fellow experts have added few more steps

3. You will see a bunch of errors now
4. Open magento/lib/Zend/Cache/Backend/File.php and look for:

protected $_options = array(
'cache_dir' => 'null', 


5. Change the same to

protected $_options = array(
'cache_dir' => 'tmp/', 


and save the file

6. Now the final step is to go create a tmp folder in the root Magento folder.


That's It

Tuesday, April 2, 2013

Magento-Home Page-Store or Store View is not showing up-404 error: Page not found

Checklist :

1. Make sure the default store view of your defaut store of your default website is not disabled.
2. Flush your cache's
3. Reindex Data
4. Set Main website as default and and then set back your website as default.

The last option worked me with once I changed the Default store for my default website and did every thing till 7th point untill I hit and tried 8th one and it worked for me.

If this is not helping you need to debug the issue since it may either be your .htaccess issue or issue from index.php
Open the index.php in root directory of the Magento installation and comment the line
Mage::run($mageRunCode, $mageRunType);
 (you will find this line near the end)
 Run your website if you still find a 404 page not found error its an .htaccess issue try renaming the same

Else try this hardcode in index.php

Just above the code mentioned above type in the following code

/* Store or website code */
$mageRunCode = 'code of store view to load';

/* you will find the code field when you edit your store view type the same code exactly here */

/* Run store or run website */
$mageRunType ='store';


(make sure you type this just before the code line "Mage::run($mageRunCode, $mageRunType);" ) inorder to override default value of these variables

If you are able to open your store view here you need to go back and check store Management.

Post here if you further have any issues

Magento-Home Page-Language drop down not showing up

Checklist:

1. To show a language bar in the header of your website you should have multiple stores(or store views).

If I peek into languages.phtml we get the following code

"getStores())>1): ?>"

which clearly states that the number of stores should be greater than 1

2. Make sure in case you are using 2 websites the "Main Website" default one and the other one(your's) then your's should be default one.

3. Make sure System>>Configuration>>General>>Locale is set to local languages for your respective store views.

4. Make sure language files are installed perfectly and correctly.If not download them from

http://www.magentocommerce.com/translations

and added them in accordance to the folder sequence as in zip file

5. Make sure it is called correctly in page.xml in respective block

6. Flush your cache's

7. Reindex Data

Saturday, March 30, 2013

Recover Lost WAMP Databases

Sometimes we are messed up tinkering with WAMP vanilla package.And all we end up is fatal errors that either restrict us to use PHP MyAdmin or let us forget the fact of importance of an Database Backup.

We take the backup of WWW/our Important Projects but are hopeless when we find no database for the same.

Here is a way to resolve the problem.First and Important step Backup of whatever you are left with

If you have the the following folder intact with you

"D:\wamp\bin\mysql\mysql5.5.24\data".(You may find a change in version of your Mysql Folder.)

You can bring back the Data out from ashes.

This folder remains even if you uninstall wamp.Its ur Mysql Data Dump.Unless and untill you have tempered with this area you can get your databases back.

Now That's the ingredients we need

1. The folder in bold above
2. A Wamp setup(we will be going for a fresh installation)

 If you have them in hand let's startoff with recovery process then

1. Rename this folder to something other than "wamp".Let's say "wamp_bak"
2. Reinstall wamp to your favorite location.
3. Under your wamp installation you will find a file with path and name as follows

"D:\wamp\bin\mysql\mysql5.5.24\my.ini"

You may see only "my" as file name in case your extension types are hidden.Again your mysql version may differ.

Open this file in your favorite text editor.I prefer using "notepad","notepad++" in order to preserve their encodings.

Search for a line like as follows

"datadir=d:/wamp/bin/mysql/mysql5.5.24/data"

It was 39th line I am using notepad++. 

copy this line and place a hash before the same.

"#datadir=d:/wamp/bin/mysql/mysql5.5.24/data"

We have commented this line here....

paste the uncommented  exactly same line just below this commented line.

"datadir=d:/wamp/bin/mysql/mysql5.5.24/data"

We will be playing with Path's now

In windows explorer navigate to your old wamp backup till the data folder and copy its path. Considering you are following the same directory and naming conventions as me you would get a path like this one

"D:\wamp_bak\bin\mysql\mysql5.5.24\data"

(I suppose you have copied it from window's explorer's address bar like any smart freak does )


paste the path in my.ini and replace it with the path in our copied uncommented text.We will get sth like this


"#datadir=d:/wamp/bin/mysql/mysql5.5.24/data" (commented line)
"datadir=D:\wamp_bak\bin\mysql\mysql5.5.24\data" (uncommented line)

In the uncommented line change the copied path as follows

"d:/wamp_bak/bin/mysql/mysql5.5.24/data"

Restart Wamp if you get a green signal everything went well if not check path again.

Open phpmyadmin in browser

http://localhost/phpmyadmin

You will find a list of databases from your previous installations.

Next Step: Exporting Databases

Select Export

Under "Export Method" select "Custom"

Select All Databases Except/Excluding

1. mysql
2. performace_schema
3. information_schema
4. test

Scroll Down Select Go soon you will be told to save an sql file containg sql dump of all your previous databases.

Save it....That's your Magic Wand in Hand to bring up Databases from Ashes.

Change the Path in "my.ini" back to

"datadir=d:/wamp/bin/mysql/mysql5.5.24/data"

(remove the copied line and uncomment the orignal one to get a line sth as above)

Restart Wamp and open 

http://localhost/phpmyadmin in browser 

You should be back with your original setup by now

Now all you need to do is Import SQL File

You may need to modify the sql file again open the same in your favorite editor

remove following lines from top

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
 


remove following lines from bottom

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;


Also you might need to modify some Referential Integrity Constraints if you are facing importing error's.

If it imports successfully you are back with original databases.If not let me know the error's.I would with glad to assist you in recovery.

PS:In case you fail even after this do follow our important comments too

Wednesday, January 23, 2013

Shine.com Hack(select all jobs at once)

Paste the following code in firebug(mozilla firefox) or run via js debugger in any browser and apply to all your selected jobs at once at shine.com

jQuery(".cls_chk_apply_cnd_job").each(function(){$(this).attr("checked","checked");});