Tuesday, December 23, 2014

Moodle - get country list and add additional country



Moodle countries list not stored in database. Its maintained in moodle language files.

Following path to find the countries list : \lang\en\countries.php

To get the countries list like this :

$countries = get_string_manager()->get_list_of_countries(false);

Output:

Array
(
    [AX] => Ă…land Islands
    [AF] => Afghanistan
    [AL] => Albania
    [DZ] => Algeria
    [AS] => American Samoa
    [AD] => Andorra
    .
    .
    .
    .
   [YE] => Yemen
   [ZM] => Zambia
   [ZW] => Zimbabwe
)

Friday, October 03, 2014

php mysql Group By to get latest record


If you select attributes that are not used in the group clause, and are not aggregates, the result is unspecified. I.e you don't know which rows the other attributes are selected from. (The sql standard does not allow such queries, but MySQL is more relaxed).

try something like

change the order by and limit as needed.

SELECT post_id, forum_id, topic_id 
FROM   (SELECT post_id, forum_id, topic_id
        FROM posts
        ORDER BY post_time DESC) 
GROUP BY topic_id 
ORDER BY topic_id desc
LIMIT 0,5
Special thanks to stackoverslow .

Thursday, September 25, 2014

PHP search word in string

preg_match — Perform a regular expression match.

Syntax :
int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )

preg_match() returns 1 if the pattern matches given subject, 0 if it does not, or FALSE if an error occurred.

 <?php

/* The \b in the pattern indicates a word boundary, so only the distinct
* word "web" is matched, and not a word partial like "webbing" or "cobweb" */

if (preg_match("/\bweb\b/i", "PHP is the web scripting language of choice.")) {
echo "A match was found.";
} else {
echo "A match was not found.";
}

//OUTPUT : A match was found.

if (preg_match("/\bweb\b/i", "PHP is the website scripting language of choice.")) {
echo "A match was found.";
} else {
echo "A match was not found.";
}

//OUTPUT : A match was not  found.
?>

Special  thanks to buriedunderground .

Thursday, September 18, 2014

jquery ajax file upload php

This is HTML part:

<input id="sortpicture" type="file" name="sortpic" />

<button id="upload">Upload</button>

A PHP script is necessary to put the file uploaded to the server in the uploads directory. The jQuery ajax function directs the form data to the particular file that handles the upload.

$('#upload').on('click', function() {
    var file_data = $('#sortpicture').prop('files')[0];   
    var form_data = new FormData();                  
    form_data.append('file', file_data)
    alert(form_data);                             
    $.ajax({
                url: 'upload.php',
                dataType: 'text',
                cache: false,
                contentType: false,
                processData: false,
                data: form_data,                         
                type: 'post',
                success: function(data){
                    alert(data); 
                }
     });

});

upload.php:

<?php

    if ( 0 < $_FILES['file']['error'] ) {
        echo 'Error: ' . $_FILES['file']['error'] . '<br>';
    }
    else {
        move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
    }


?>

A couple things about the destination directory: 1) make sure you have the correct server path, and 2) make sure it's writeable.

Tuesday, September 02, 2014

Differences between require and include, include_once and require_once

The include() statement includes and evaluates the specified file.The documentation below also applies to require(). The two constructs are identical in every way except how they handle failure. include() produces a Warning while require() results in a Fatal Error. In other words, use require() if you want a missing file to halt processing of the page.
include() does not behave this way, the script will continue regardless.
The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again. As the name suggests, it will be included just once.include_once() should be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, and you want to be sure that it is included exactly once
to avoid problems with function redefinition's, variable value reassignments, etc.
require_once() should be used in cases where the same file might be included and evaluated
more than once during a particular execution of a script, and you want to be sure that it is included exactly once to avoid problems with function redefinitions, variable value
reassignments, etc.

Tuesday, August 26, 2014

mysql case sensitive query

MySQL queries are not case-sensitive by default. Following is a simple query that is looking for 'value'. However it will return 'VALUE', 'value', 'VaLuE', etc…

SELECT * FROM `table` WHERE `column` = 'value'

The good news is that if you need to make a case-sensitive query, it is very easy to do:

SELECT * FROM `table` WHERE BINARY `column` = 'value'



Monday, August 11, 2014

Move WordPress From Local Server to Live Site

Changing the Site URL:

Need to change the site URL, so you can setup your live WordPress site. In your phpMyAdmin, look for the wp_options table in your database.

Click on the browse button next to wp_options or the link that you see in the sidebar to open the page with a list of fields within the wp_options table. See screenshot below:




Under the field options_name, you need to look for siteurl. Click the Edit Field icon which can be found at the far left at the beginning of the row.
                           


Setting Up your Live Site:
Connect to your website using an FTP client and edit wp-config.php file. Provide the database name, user and password you created 
                        
                         /** The name of the database for WordPress */
                         define('DB_NAME', 'database_name_here');

                       /** MySQL database username */
                        define('DB_USER', 'username_here');

                      /** MySQL database password */
                        define('DB_PASSWORD', 'password_here');


Login to your WordPress admin panel, and go to Settings » General. Click save Options. This will ensure that the site url is corrected anywhere else that needs to be.
Then go to Settings » Permalink and click Save to ensure that all post links are working fine.

Fixing Images and Broken Links by updating Paths:

Whenever you are moving a WordPress site from one domain to another, or from local server to a live site, you would face broken links and missing images issue.
Here is a simple SQL query that should solve this problem:
UPDATE wp_posts SET post_content = REPLACE(post_content, 'localhost/test/', 'www.yourlivesite.com/');


That’s all, hopefully your live site will be up and running by now. Checkout your site to make sure that every thing is working fine as expected.

Special thanks to wordpress .



Monday, June 23, 2014

Connect to Amazon EC2 file directory using FileZilla

Following steps to connect to Amazon EC2 file directory using FileZilla.

1.Edit (Preferences) > Settings > Connection > SFTP, Click "Add key file”

2.Browse to the location of your .pem file and select it.

3.A message box will appear asking your permission to convert the file into ppk format. Click Yes, then give the file a name and store it somewhere.

4.If the new file is shown in the list of Keyfiles, then continue to the next step. If not, then click "Add keyfile..." and select the converted file.

5.File > Site Manager Add a new site with the following parameters:

Host: Your public dns name of ec2 instance, or the public ip address of the server

Protocol: SFTP

Logon Type: Normal

User: From the docs: "For Amazon Linux, the default user name is ec2-user. For RHEL5, the user name is often root but might be ec2-user. For Ubuntu, the user name is ubuntu. For SUSE Linux, the user name is root. Otherwise, check with your AMI provider."

Press Connect Button - If saving of passwords has been disabled, you will be prompted that the logon type will be changed to 'Ask for password'. Say 'OK' and when connecting, at the password prompt push 'OK' without entering a password to proceed past the dialog.

Note: FileZilla automatically figures out which key to use. You do not need to specify the key after importing it as described above.

Friday, June 06, 2014

simple counter timer in javascript

Here the following code for simple timer in javascript.



Thursday, May 29, 2014

GROUP_CONCAT - concatenate strings in mysql command

In this tutorial, you will learn how to use the MySQL GROUP_CONCAT function to concatenate strings from a group of values with various options.

The following illustrates the GROUP_CONCAT function:

SYNTAX:

GROUP_CONCAT(DISTINCT expression
ORDER BY {column_name | usinged_integer | expression}
SEPARATOR sep);


  • You specify the DISTINCT clause to eliminate duplicate values in a group before combining values.
  • The ORDER BY clause allows you to sort the values in ascending or descending order before concatenating values. 
  • The ORDER BY clause sort the values in ascending ( ASC) order by default. If you want to sort the values in the descending order, you need to specify the DESC explicitly.
  • The SEPARATOR specifies a literal value inserted between values in the group. If you do not specify a separator, the GROUP_CONCAT function use a comma (,) as the default separator.
  • The GROUP_CONCAT function ignores NULL values. It returns NULL if there was no matching row found or there were no non-NULL values. The GROUP_CONCAT function returns a binary or non-binary string, which depends on the arguments. The maximum length of the return string is 1024 by default. You can extend the returned value’s length by setting the group_concat_max_len system variable at SESSION or GLOBAL level.

Example
To get all countries where customers locate as a comma-separated string, you use the GROUP_CONCAT function as follows:

SELECT GROUP_CONCAT(DISTINCT country ORDER BY country)FROM customers;

Result :
                             

However, some customers locate in the same country. To remove the duplicate country’s names, you add the DISTINCT clause as the following query:

SELECT GROUP_CONCAT(DISTINCT country) FROM customers;

Result
                         

It is more readable if the country’s names are in ascending order. To sort the country’s name before concatenating, you use the ORDER BY clause as follows:

SELECT GROUP_CONCAT(DISTINCT country ORDER BY country) FROM customers;

Result :
                         

To change the default separator of the returned string from a comma (,) to a semi-colon (;), you use the SEPARATOR clause as the following query:

SELECT GROUP_CONCAT(DISTINCT country ORDER BY country SEPARATOR ';') FROM customers;

Result :
                           




Tuesday, May 06, 2014

jquery show hide by using jquery toggle method

The toggle() method is used to toggle between show and hide selected HTML elements. If elements are hidden then toggle method will show hidden selected elements and vice versa.

 Syntax:
$(selector).toggle(speed,callback)
Where

Selector = can be an element like div, p, etc.
Speed = Optional parameter that specifies the hide speed with possible values of
  1. “slow”
  2. “fast”
  3. Or value in milliseconds
Callback = after togle () method is completed, an optional callback function to perform certain action can be given.

Example:
 
 
jQuery Testing 
    
    

  
    
    
 

Wednesday, April 30, 2014

Preg Match Between two words

Extract words between two words Using Preg Match



we need the word  between "modules"  and  "widgets".

Please use this code.

Code :


$str = "addons/modules/featured/widgets/single/";

//$str = str_replace("/","-",$str);

preg_match('/modules\/(.*?)\/widgets/', $str, $match);

echo "<pre>";

print_r($match);

echo "</pre>";


Output :


Array
(
    [0] => modules/featured/widgets
    [1] => featured
)

Monday, April 21, 2014

PYROCMS Module View Call from Helper

 Pyrocms:
We used pyrocms , in this each module contain plugin.php.
This file used for display the module views.
This plugin.php used $this->module_view function.

But we need to load  the other modules view files only option in plugin.php.
Not other option.


so i wrote this code for simply call the module view from any location.



Code : [put this code to helper file or create new helper file  in (system/cms/helpers/)]
require_once APPPATH.'libraries/Plugins.php';

class Display_mview extends Plugin
{

 public    function disp_module($module, $view, $vars = array(), $parse_output = true) {
       
        $ci =& get_instance();
        $mview = $this->module_view($module,$view, $vars , $parse_output);
        return $mview ;
    }

}


 function module_view($module, $view, $vars = array(), $parse_output = true)
{
    $dview = new Display_mview();
    $module_view = $dview->disp_module($module,$view, $vars , $parse_output);   
    return $module_view;
}





Ex : [call any view or any controller or any where]

 call from anywhere and any module.

<?php echo module_view('module_name','view name',array('data'=>'value')); ?>


Thursday, April 17, 2014

OpenCart Global Functions – Developer Cheatsheet

In this blog post, you see complete list of all the useful OpenCart functions which can be called in all Controllers, Models and View Templates.

AFFILIATE

$this->affiliate->login($email, $password);
This function logs the user into their Affiliate account, not their customer account. Incorporate this to build custom login pages for affiliates.

$this->affiliate->logout();
This function logs the user out of their Affiliate account.

$this->affiliate->isLogged();
This function checks to see if the Affiliate is logged in. Returns true or false. Can be used to put a login restriction on important Affiliate pages such as payment details which require them to be logged in.

$this->affiliate->getId();
Returns the Affiliate ID number.

$this->affiliate->getFirstName();
Returns the first name of the Affiliate.

$this->affiliate->getLastName();
Returns the last name of the Affiliate.

$this->affiliate->getEmail();
Returns the email address of the Affiliate.

$this->affiliate->getTelephone();
Returns the phone number of the Affiliate.

$this->affiliate->getFax();
Returns the fax number of the Affiliate.

$this->affiliate->getCode();

Returns the registered tracking code of the Affiliate.


CACHE

$this->cache->get($key);
Grabs the requested cache file for faster local loading.

$this->cache->set($key, $value);
Use this to create a cache file for search results, images or other site data for faster loading.

$this->cache->delete($key);
Delete a local cache file from it’s key.

CAPTCHA

$this->captcha->getCode();
Returns the correct code to match against user input to approve or fail a Captcha challenge.

$this->captcha->showImage();
Displays the Captcha image to the user.


CART

$this->cart->getProducts();
Returns an array of all the contents in user’s basket along with other info like quantity, name, weights etc.

$this->cart->add($product_id, $quantity = 1, $option = array());
Add an item to the user’s cart with the code. First argument is the product ID, then the quantity, then the third option is an array for adding product options like colours, size, shape etc.

$this->cart->update($key, $quantity);
Updates the quantity of the products in a customer’s basket.

$this->cart->remove($key);
Remove a product from the user’s basket based on it’s key value in the getProducts() array.

$this->cart->clear();
Delete everything in the user’s basket

$this->cart->getWeight();
Get the total combined weight of everything in the user’s basket.

$this->cart->getSubTotal();
Get the subtotal of all the products in the user’s basket. This does not take into account extra order totals like handling fees, low order fees, shipping costs etc

$this->cart->getTaxes();
Get the total Tax payable on the products in the basket.

$this->cart->getTotal();
Get’s the final total for everything in the user’s basket. Including handling fees, low order fees and shipping costs (if set) etc.

$this->cart->countProducts();
Counts the number of products in the customer’s basket. This takes into account the quantity of the product so if a basket as 1 of Product A and 2 of Product B then the countProducts() will return 3.

$this->cart->hasProducts();
Checks to see if the user’s basket has anything in it. Returns true or false.

$this->cart->hasStock();
Checks to see if there is stock available for products in the user’s basket.

$this->cart->hasShipping();
Checks to see if there is a product in the user’s basket which requires shipping.

$this->cart->hasDownload();

Checks to see if there is a product in the user’s basket which is a downloadable product.

CONFIG

$this->config->get($key);
Get a config setting from the database based on it’s key.

$this->config->set($key, $value);
Create a new config setting with a new key and value, used mainly for installing modules.

$this->config->has($key);
Checks to see if the config table has a setting with a particular key.

$this->config->load($filename);
Load a file within OpenCart.

CURRENCY

$this->currency->set($currency);
Quickly set the user’s currency by the currency code with this.

$this->currency->format($number, $currency = ”, $value = ”, $format = true);
Used for formatting prices to match the layout of the selected currency.

$this->currency->convert($value, $from, $to);
Used for working out the value of something in one currency to another.

$this->currency->getId($currency = ”);
Gets the ID of the currency, leave blank to gett he ID of the selected currency or enter a currency code to choose.

$this->currency->getSymbolLeft($currency = ”);
Gets the left symbol, if any, for displaying next to the price.

$this->currency->getSymbolRight($currency = ”);
Gets the right symbol, if any, for displaying next to the price.

$this->currency->getDecimalPlace($currency = ”);
Gets the symbol which represents a decimal place in the selected currency.

$this->currency->getCode();
Returns the ISO code of the currently selected currency.

$this->currency->getValue($currency = ”);
Returns the value of the selected currency. This is the value used to work out currency rates.

$this->currency->has($currency);
Checks to see that there are active currencies and one has been set.

CUSTOMER

$this->customer->login($email, $password, $override = false);
Log the customer into their account quickly with their email and password. Can be used for quick logins and custom login pages.

$this->customer->logout();
Log the customer out of their account.

$this->customer->isLogged();
Checks to see if the customer is logged in or a guest browser. Returns true or false.

$this->customer->getId();
Gets the customer ID number, if logged in.

$this->customer->getFirstName();
Returns the first name of the customer.

$this->customer->getLastName();
Returns the last name of the customer.

$this->customer->getEmail();
Returns the email address of the customer.

$this->customer->getTelephone();
Returns the phone number of the customer.

$this->customer->getFax();
Returns the fax number of the customer.

$this->customer->getNewsletter();
Checks whether the customer has subscribed to the newsletter or not.

$this->customer->getCustomerGroupId();
Returns the ID of the customer group to which the user belongs.

$this->customer->getAddressId();
Returns the Address ID number of the default address of the customer.

$this->customer->getBalance();
Returns the store credit balance of the customer, if any.

$this->customer->getRewardPoints();
Returns the number of reward points which the customer has available.

DATABASE

$this->db->query($sql);
Fires a database query, the SQL code can be input between the brackets as normal.

$this->db->escape($value);
Escapes potentially harmful characters from posted data before entering them into the database. Useful for avoiding SQL injection attacks.

$this->db->countAffected();
Returns the number of affected rows after a query string.

$this->db->getLastId();
Get the last inserted ID number for a database.

DOCUMENT

$this->document->setTitle($title);
Set the title of a page. Visible in the tab on a browser and the blue link in a search result set.

$this->document->getTitle();
Get the title of a page. Visible in the tab on a browser and the blue link in a search result set.

$this->document->setDescription($description);
Set the meta description for a page.

$this->document->getDescription();
Get the meta description for a page.

$this->document->setKeywords($keywords);
Set the meta keywords for a page.

$this->document->getKeywords();
Get the meta keywords for a page.

$this->document->addLink($link, $rel);
Add a new rel link into the header for a particular page. Useful for setting custom headers for a page but not for others.

$this->document->getLinks();
Returns rel links set for page.

$this->document->addStyle($href, $rel = ‘stylesheet’, $media = ‘screen’);
Set a new stylesheet for the page.

$this->document->getStyles();
Returns extra stylesheets set for a page.

$this->document->addScript($script);
Add a new script file, such as JavaScript, for a page.

$this->document->getScripts();
Returns the extra script files for a page.

ENCRYPTION

$this->encryption->encrypt($value);
Secure a string with OpenCart’s encryption settings.

$this->encryption->decrypt($value);
Decrypt a secured sting with OpenCart’s encryption settings.

IMAGE

$this->image->create($image);
Used for image formatting, create the new image.

$this->image->save($file, $quality = 90);
Save an image file with the default quality setting.

$this->image->resize($width = 0, $height = 0, $default = ”);
Resize an image to certain dimensions.

$this->image->watermark($file, $position = ‘bottomright’);
Add a watermark to an image.

$this->image->crop($top_x, $top_y, $bottom_x, $bottom_y);
Crop an image to certain parameters.

$this->image->rotate($degree, $color = ‘FFFFFF’);
Rotate an image a certain amount of degrees and set a background colour (default white).

$this->image->filter($filter);
Add a filter to an image.

$this->image->text($text, $x = 0, $y = 0, $size = 5, $color = ’000000′);
Add text to an image and position it. Last argument for is font colour.

$this->image->merge($file, $x = 0, $y = 0, $opacity = 100);
Merge an image.

$this->image->html2rgb($color);
Convert the colour type to RGB output with this function.

LANGUAGE

$this->language->get($key);
Get the key of the currently selected language.

$this->language->load($filename);
Load the language file for the currently selected language.

 LENGTH

$this->length->convert($value, $from, $to);
Convert one length value into another for conversions.

$this->length->format($value, $length_class_id, $decimal_point = ‘.’, $thousand_point = ‘,’);
Format the length to display properly with symbols.

$this->length->getUnit($length_class_id);
Get the base unit for a measurement i.e. cm.

LOG

$this->log->write($message);
Write a custom message to OpenCart’s log file. Useful for debugging new features.

MAIL

$this->mail->setTo($to);
Set the recipient’s email address.

$this->mail->setFrom($from);
Set the sender email address.

$this->mail->setSender($sender);
Set the name of the sender.

$this->mail->setSubject($subject);
Set the subject line for the email.

$this->mail->setText($text);
Set the text format version of the email content.

$this->mail->setHtml($html);
Set the HTML version of the email content.

$this->mail->addAttachment($filename);
Add an attachment to the email.

$this->mail->send();
Send the email.

PAGINATION

$this->pagination->render();
Display number tabs for multiple pages.

REQUEST

$this->request->get[$key];
Request a variable from the URL.

$this->request->post[$key];
Request POST data.

$this->request->cookie[$key];
Request COOKIE value.

$this->request->files[$key];
Request FILE data.

$this->request->server[$key];
Request SERVER data.

RESPONSE

$this->response->addHeader($header);
Add a new PHP header to be sent to the user’s browser.

$this->response->redirect($url);
Redirect user to a certain URL, can be internal and external.

$this->response->setCompression($compression);
Set the compression level.

$this->response->setOutput($output);
Add data to the content to be sent to the user’s browser for display.

$this->response->compress($data, $level = 0);
Compress files with the compression level set in the OpenCart admin area.

$this->response->output();
Actually output the data.

SESSION

$this->session->getId();
Get the PHP session ID.

TAX

$this->tax->setShippingAddress($country_id, $zone_id);
Set the shipping address for working out Tax on destination.

$this->tax->setPaymentAddress($country_id, $zone_id);
Set the payment address for working out Tax on Payment country and zone.

$this->tax->setStoreAddress($country_id, $zone_id);
Set the location of the store for working out Tax on the physical location of the shop itself.

$this->tax->calculate($value, $tax_class_id, $calculate = true);
Calculate the amount of Tax payable.

$this->tax->getTax($value, $tax_class_id);
Return the amount of Tax to pay.

$this->tax->getRateName($tax_rate_id);
Return the name of the tax rate which is payable for displaying to the customer.

$this->tax->getRates($value, $tax_class_id);
Return the names of all the tax rates which are relevant to the customer.

$this->tax->has($tax_class_id);
Checks to see if there are Tax classes set up in the admin section of the store.

TEMPLATE

$this->template->fetch($filename);
Load up the requested template filename.

URL

$this->url->addRewrite($rewrite);
ReWrite the URL for SEO.

$this->url->link($route, $args = ”, $connection = ‘NONSSL’);
Create a URL based on route and arguments. OpenCart auto-checks for an SEO-URL equivalent and returns that if possible.

USER

$this->user->login($username, $password);
Login an admin user to their admin account.

$this->user->logout();
Log an admin user out of their account.

$this->user->hasPermission($key, $value);
Checks to see if the logged in user has permission to view or edit a particular admin page.

$this->user->isLogged();
Checks to see if the admin user is logged into their account.

$this->user->getId();
Gets the ID number of the administrator account.

$this->user->getUserName();
Returns the username of the logged in administrator.


WEIGHT

$this->weight->convert($value, $from, $to);
Convert one weight value into another measurement.

$this->weight->format($value, $weight_class_id, $decimal_point = ‘.’, $thousand_point = ‘,’);
Display a formatted weight with symbols for the customer.

$this->weight->getUnit($weight_class_id);

Get the base unit of weight for the class i.e. kg.