Facebook

Sunday, August 9, 2015

Tips and tricks of GIT

Removing Files you have added files to Git that you want it to track no longer.

Scenario: You added a file to Git accidentally or you may want to remove a file from current push
You cannot run git rm because you want to keep a copy of the file(git rm command will delete the file from file system)


 Solution: To tell Git to stop tracking a file, but still keep it on your local system, run the following command

git rm --cached [file_name]
GIT - Ignore changes in a file
--Assume file to be unchanged
git update-index --assume-unchanged path/to/file.txt
GIT - Add all files that are tracked and has change

Scenario: I have modified large set of files and added new files as well and I want to stage only the tracked files. In such situations, I can use this command
git add -u

Using Branches

1. git branch
Usage: List all of the branches in your repository.

2. git branch <new_branch>
Usage: Create a new branch called <new_branch>. This does not check out the new branch.

3. git branch -d <branch>
Usage: Delete the specified branch. This is a “safe” operation since Git prevents you from deleting the branch if it has unmerged changes.

4. git branch -D <branch>
Usage: Force delete the specified branch. Use this command only if you want to permanantly discard all unmerged changes

5. git branch -m <new_branch>
Usage: Rename the current branch to <new_branch>.

6. git clone git@yourrepositry.com:projectidentifier new-folder-name
Usage: Clone git repository to a folder with different name.

7. git reset --hard
Usage: Resets your index and reverts the tracked files back to state as they are in HEAD.

8. git clean -f -d
Usage: Cleans untracked files.

9. git clean -f -d -x
Usage: Remove your .gitignored files and get back to a pristine state

10. git log branch_name..origin/branch_name
Usage: Find difference between my local branch and remote branch
GIT - Stash

11. git stash
Usage: Stash files for future reference

12. git stash show
Usage: List stashed files

13. git stash show -p
Usage: Show changes in stashed files

14. git stash save -p "message"
Usage: Lets you choose changes to be stashed, you can stash part of changes in a file as well

Tuesday, December 23, 2014

Handle images uploaded using multi file select using PHP in serverside


Multi file upload via ajax can be implemented using jQuery. You can find the detailed documentation here.
OR copy & paste the following link to address bar of your browser

<?php
/**
 * Function to save images uploaded from content tab using bulk upload
 *
 * @return multitype:array
 */
public function save_uploaded_files()
{
    $response = array('status' => 0, 'message' => '');
    $posted_data = $_POST;
    $user_name = $posted_data['username'];
    $config['allowed_types'] = array('gif','jpg', 'jpeg', 'jpe', 'png');
    $config['upload_path'] = getcwd().'/uploadpath/';

    $values = array();
    $originalFileName = '';
    try {
        $fileDetails = $this->process_uploaded_file($originalFileName, $values, $user_id);
    } catch (Exception $e) {
        $response['message'] = 'Something went wrong. Please try again later';

        return $response;
    }
    $response['status'] = 1;
    $response['message'] = 'Files saved';
    foreach ($fileDetails as $details) {
        $response['file_info'][] = array(
            'original' => $details['uploaded_file_name'],
            'target' => $details['target_name'],
        );
    }

    return $response;
}

/**
 * Function to move uploaded file to target location
 *
 * @param string $fileName
 * @param array $values pass by reference
 *
 * @return string file name
 */
public function process_uploaded_file()

    $bulk_upload = $_POST['bulk_upload'];
    $config['upload_path'] = getcwd().'/uploaded/';
    $config['allowed_types'] = array('gif','jpg', 'jpeg', 'jpe', 'png');
    $uploaded_file_info = false;
    $number_of_images = get_number_of_images_uploaded($_FILES['image_uploader_multiple']);
    if ($number_of_images > 0) {
        foreach ($_FILES['image_uploader_multiple']['name'] as $key => $uploaded_file_name) {
            $uploaded_path_parts = pathinfo($uploaded_file_name);
            $temp_name = $_FILES['image_uploader_multiple']['tmp_name'][$key];
            $fileName = uniqid('', true).".".date("YmdHis").".".sprintf("%06d",rand());
            $fileFullName = $fileName.".".$uploaded_path_parts['extension'];
            $target_path_parts = pathinfo($fileName);
            $target_file_name = $target_path_parts['filename'].'.'.$uploaded_path_parts['extension'];

            $i = 1;
            while (file_exists($config['upload_path'].$target_file_name)) {
                $target_file_name = $target_path_parts['filename'].'-'.($i++).'.'.$uploaded_path_parts['extension'];
            }
          
            $config['file_name'] = $target_file_name;
            move_uploaded_file($temp_name, $config['upload_path'].$target_file_name);
            chmod_apply($config['upload_path'].$target_file_name);

            $uploaded_file_info[] = array(
                'target_name' => $target_file_name,
                'uploaded_file_name' => $uploaded_file_name
            );
         }
    }

    return $uploaded_file_info;
}

/**
 * Function to get number of images uploaded
 *
 * @param array $image_uploader_multiple
 *
 * @return number
 */
function get_number_of_images_uploaded($image_uploader_multiple)
{
    $count = 0;
    if (isset($image_uploader_multiple['error']) && is_array($image_uploader_multiple['error'])) {
        foreach($image_uploader_multiple['error'] as $error) {
            if ($error != 4) {
                $count++;
            }
        }
    }

    return $count;
}

/**
 * Function to apply proper permission to the upload file
 *
 * @param $filename
 * @return bool
 */
function chmod_apply($filename = '') {
    $stat = @ stat(dirname($filename));
    $perms = $stat['mode'] & 0007777;
    $perms = $perms & 0000666;
    if ( @chmod($filename, $perms) )
        return true;
    return false;
}

Multi file select preview without uploading and delayed upload

  • Ajax file upload
  • Multi file select
  • Selective upload of files in multi select


Requirement: Implement a file selector with multiple file select with following functions.
1. Allow user to select images only.
1. Preview of all selected images should be populated on the page without uploading the image to the server on selecting images.
2. User should be able to  filter images to be actually uploaded to the server from the previews, User should be able to remove selected files using a close button.
3. On clicking upload button, the images listed in the preview should be uploaded to server without page re-load(Ajax).

Implementation plan:
1. User can select images using multiple File Input.
2. Preview of images selected can be  populated by using a FileReader object and can be appended to html preview area.
3. Index of selected images can be used to generate class name of the respective image container, sothat we can match images selected and the one which is previewed.
4. Using a button populated near preview, we can close the preview(Remove the element from the html dom - make sure the container with matching class name is also removed)
5. On clicking the upload button, we can iterate through the images selected in the file selector and search for the corresponding image preview container having matching class name to find if the preview of the image is not removed by the user, if present, add them to formData object and submit them via ajax to the server.

Screen shots:






Code on github: https://github.com/imaimai86/multi-file-select-preview-without-uploading-and-delayed-upload

Demo on jsFiddle: http://jsfiddle.net/anas/6v8Kz/7/embedded/result/

http://jsfiddle.net/anas/6v8Kz/7/ 

Code Hint:

HTML:
<p>
<label for="image_uploader_multiple">Image:</label>
</p>
<form>
<table width="70%" id="multi_file_uploader">
    <tbody>
        <tr class="imageSelectorContainer">
            <td valign="top">
                <input type="file" name="image_uploader_multiple[]" 

                value="" class="multipleImageFileInput" 
                style="width:50%" 
                onchange="show_image_preview(this);"  
                accept="image/*" multiple="">
                <!-- Preview container table -->
                <table class="imagePreviewTable"></table>
            </td>
            <td valign="top" align="right">
                <input type="button" value="X" title="Remove" 

                class="removeButton"  style="display:none;" 
                onclick="remove_file_uploader(this)">
            </td>
            <td valign="top">

                <input type="button" value="+"  title="Add" 
                class="addButton"  style="" 
                onclick="add_new_file_uploader(this)"> 
            </td>
        </tr>
    </tbody>
    <tbody>
        <tr>
            <td colspan="3" class="buttonBox">
                <input type="submit" value="Save Images">
            </td>
        </tr>
    </tbody>
</table>
</form>
<div class="overlay">
    <div class="overlay_content">Saving....<br />

        <img src="spinner.gif" />
    </div>
</div>

CSS:
<style type="text/css">
.buttonBox{
    padding: 20px;
    text-align: center;
}
.imagePreviewTable{
    border: 1px solid #000;
    display: none;
}
.overlay {
    position:absolute; top:0; left:0; right:0; bottom:0; background-color:rgba(0, 0, 0, 0.85); background: url(data:;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAABl0RVh0U29mdHdhcmUAUGFpbnQuTkVUIHYzLjUuNUmK/OAAAAATSURBVBhXY2RgYNgHxGAAYuwDAA78AjwwRoQYAAAAAElFTkSuQmCC) repeat scroll transparent\9; /* ie fallback png background image */ z-index:9999; color:white; text-align:center; height:5000px; display:none;
}
.overlay_content{
    padding:300px;
}
</style>
 

JAVASCRIPT:
Include jquery 
<script type='text/javascript' src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>

Open "Script" tag
<script type="text/javascript">

Bind form submission with function to upload images using jQuery
$(document).ready(function(){
    $('form').submit(function(ev){
        $('.overlay').show();
        $(window).scrollTop(0);
        return upload_images_selected(ev, ev.target);
    })
})

Function to display preview of images selected using the input selector. 
Logic: For each images selected, add a preview row to the image preview table, with a class name corresponding to the index of the file in the file selector(imagePreviewRow_<index_of_image_in_file_selector>). Iterate through the files selected using the file selector input and check the mime type of the selected file, if it is an image, create a file reader object to read the content of the file and append file content to the preview row.
function show_image_preview(file_selector) {
    //files selected using current file selector
    var files = file_selector.files;
    //Container of image previews
    var imageContainer = $(file_selector).next('table.imagePreviewTable');
    //Number of images selected
    var number_of_images = files.length;
    //Build image preview row
    var imagePreviewRow = $( '<tr class="imagePreviewRow_0">'+

                                                 '<td valign=top style="width: 510px;"></td>' +                                                  '<td valign=top><input type="button" '+ 
                                                  ''value="X"  title="Remove Image"'+ 
                                                  ' class="removeImageButton" '+
                                                  'imageIndex="0" '+
                                                  ' onclick="remove_selected_image(this)" />'+
                                                  '</td></tr> ');
    //Add image preview row
    $(imageContainer).html(imagePreviewRow);
    if (number_of_images > 1) {
        for (var i =1; i<number_of_images; i++) {
            /**
             * Generate class name of the respective image container appending index 

             * of selected images, sothat we can match images selected and 
             * the one which is previewed
             */

            var newImagePreviewRow = $(imagePreviewRow)

                                                               .clone()
                                                               .removeClass('imagePreviewRow_0')
                                                               .addClass('imagePreviewRow_'+i);
            $(newImagePreviewRow).find('input[type="button"]').attr('imageIndex', i);
            $(imageContainer).append(newImagePreviewRow);
        }
    }
    for (var i = 0; i < files.length; i++) {
        var file = files[i];
        /**
         * Allow only images
         */

        var imageType = /image.*/;
        if (!file.type.match(imageType)) {
          continue;
        }
       
        /**
         * Create an image dom object dynamically
         */

        var img = document.createElement("img");
       
        /**
         * Get preview area of the image
         */

        var preview = $(imageContainer).find('tr.imagePreviewRow_'+i).find('td:first');

        /**
         * Append preview of selected image to the corresponding container
         */

        preview.append(img);
       
        /**
         * Set style of appended preview(Can be done via css also)
         */

        preview.find('img').addClass('previewImage')

                                     .css({'max-width': '500px', 'max-height': '500px'});
       
        /**
         * Initialize file reader
         */

        var reader = new FileReader();
        /**
         * Onload event of file reader assign target image to the preview
         */

        reader.onload = (function(aImg) { return function(e) { 

            aImg.src = e.target.result; }; 
        })(img);
        /**
         * Initiate read
         */

        reader.readAsDataURL(file);
    }
    /**
     * Show preview
     */

    $(imageContainer).show();
}

Function to remove selected image from preview. This function removes the image from DOM instead of hiding them.
function remove_selected_image(close_button)
{
    /**
     * Remove this image from preview
     */

    var imageIndex = $(close_button).attr('imageindex');
    $(close_button).parents('.imagePreviewRow_' + imageIndex).remove();
}

Function to upload remaining images available in the preview list.
Logic: Iterate through each file input and each files selected, and check if the image is in the preview. this checking can be done easily by checking the image preview row with name(imagePreviewRow_<index_of_image_in_file_selector>) corresponding to the index of the file in the file selector input exists. If the preview is available, create a formData object and append the image to the object. Now post the form data object using "XMLHttpRequest" to the server(Ajax).
This function sends an ajax request corresponding to each file selector to tackle the maximum file upload size limit that can be uploaded to the server. This method avoids uploading large number of files simultaneously to the server there by getting caught by the max file upload limit.
function upload_images_selected(event, formObj)
{
    event.preventDefault();
    //Get number of images
    var imageCount = $('.previewImage').length;
    //Get all multi select inputs
    var fileInputs = document.querySelectorAll('.multipleImageFileInput');
    //Url where the image is to be uploaded
    var url= "/admin/content/upload";
    //Get number of inputs
    var number_of_inputs = $(fileInputs).length;
    var inputCount = 0;

    //Iterate through each file selector input
    $(fileInputs).each(function(index, input){
       
        fileList = input.files;
        // Create a new FormData object.
        var formData = new FormData();
        //Extra parameters can be added to the form data object
        formData.append('bulk_upload', '1');
        formData.append('username', $('input[name="username"]').val());
        //Iterate throug each images selected by each file selector and 

        //find if the image is present in the preview
        for (var i = 0; i < fileList.length; i++) {
            if($(input).next('.imagePreviewTable').find('.imagePreviewRow_'+i).length!=0){
                var file = fileList[i];
                // Check the file type.
                if (!file.type.match('image.*')) {
                    continue;
                }
                // Add the file to the request.
                formData.append('image_uploader_multiple[' +(inputCount++)+ ']', 

                                              file, 
                                              file.name);
            }
        }
        // Set up the request.
        var xhr = new XMLHttpRequest();
        xhr.open('POST', url, true);
        xhr.onload = function () {
            if (xhr.status === 200) {
                var jsonResponse = JSON.parse(xhr.responseText);
                if (jsonResponse.status == 1) {
                    $(jsonResponse.file_info).each(function(){
                        //Iterate through response and find data corresponding 

                        //to each file uploaded
                        var uploaded_file_name = this.original;
                        var saved_file_name = this.target;
                        var file_name_input = '<input type="hidden" class="image_name"

                                                             name="image_names[]" 
                                                             value="' +saved_file_name+ '" />';
                        file_info_container.append(file_name_input);
                       
                        imageCount--;
                    })
                    //Decrement count of inputs to find all images 

                    //selected by all multi select are uploaded
                    number_of_inputs--;
                    if(number_of_inputs == 0) {
                        //All images selected by each file selector is uploaded
                        //Do necessary acteion post upload
                        $('.overlay').hide();
                    }
                } else {
                    if (typeof jsonResponse.error_field_name != 'undefined') {
                        //Do appropriate error action
                    } else {
                        alert(jsonResponse.message);
                    }
                    $('.overlay').hide();
                    event.preventDefault();
                    return false;
                }
            } else {
                alert('Something went wrong!');
                $('.overlay').hide();
                event.preventDefault();
            }
        };
        xhr.send(formData);
    })
   
    return false;
}


Function to populate new file uploader on clicking the "+" button near to existing file selectors. On clicking the "+" button, the row containing the "+" button is cloned, selected files and previews if any are removed and appended to the end of the container.
function add_new_file_uploader(addBtn) {
    var currentRow = $(addBtn).parent().parent();
    var newRow = $(currentRow).clone();
    $(newRow).find('.previewImage, .imagePreviewTable').hide();
    $(newRow).find('.removeButton').show();
    $(newRow).find('table.imagePreviewTable').find('tr').remove();
    $(newRow).find('input.multipleImageFileInput').val('');
    $(addBtn).parent().parent().parent().append(newRow);
}

File selector along with selected images are removed.
function remove_file_uploader(removeBtn) {
    $(removeBtn).parent().parent().remove();
}

Close "Script" tag
</script>

Serverside PHP code to handle uploads can be found here
OR copy & paste the following link to address bar of your browser

Customize file select input here
OR copy & paste the following link to address bar of your browser

Wednesday, November 6, 2013

Custom look for file selector

Custom look for file selector

Here is a way of adding custom styled buttons for file selctor inputs. Working: Overlay a transparent "<input type="file" />" over a styled button or other element

Code:
    <div id="" style="height: 30px; overflow: hidden; position: absolute; width: 300px; word-break: keep-all;">
        <input style="width: 100px;" type="button" value="select" />
            <span id="files">
                No files selected.      
            </span>
        </div>
        <input id="selector" style="height: 30px; opacity: 0; position: absolute; width: 100px;" type="file" />
    </div>

Try this on jsFiddle: http://jsfiddle.net/bMb59/
Multi file select with ajax upload: here
OR copy & paste the following link to address bar of your browser
http://customphpfunctions.blogspot.in/2014/12/handle-images-uploaded-using-multi-file.html

Friday, June 29, 2012

MySql Backup Class



MySql Backup Class  written by Vagharshak Tozalakyan <vagh@armdex.com>

This class is written in a file mysql_backup.class.php
This file is to be included in the file where we actually call this class to be executed.




HOW TO USE


HOW TO USE

1. Create the instance of MySQL_Backup class.
2. Define necessary properties.
3. Call Execute() method to create backup.

require_once 'mysql_backup.class.php';
$backup_obj = new MySQL_Backup();
$backup_obj->server = 'localhost';
$backup_obj->username = 'username';
$backup_obj->password = 'password';
$backup_obj->database = 'dbname';
$backup_obj->tables = array();
$backup_obj->drop_tables = true;
$backup_obj->struct_only = false;
$backup_obj->comments = true;
$backup_obj->fname_format = 'd_m_y__H_i_s';
if (!$backup_obj->Execute(MSB_DOWNLOAD, '', true))
{
  die($backup_obj->error);
}



PUBLIC PROPERTIES

var $server = 'localhost';
The name of MySQL server.

var $port = 3306;
The port of MySQl server.

var $username = 'root';
Database username.

var $password = '';
Database password.

var $database = '';
Name of the database.

var $link_id = -1;
MySQL link identifier of the current connection. You can set this if you
want to connect the MySQL server by your own.

var $connected = false;
Set true if the connection is already established before calling Execute().

var $tables = array();
Tables you want to backup. All tables in the database will be backed up if
this array is empty.

var $drop_tables = true;
Add DROP TABLE IF EXISTS queries before CREATE TABLE in backup file.

var $struct_only = false;
Only structure of the tables will be backed up if true.

var $comments = true;
Include comments in backup file if true.

var $backup_dir = '';
Directory on the server where the backup file will be placed. Used only if task
parameter equals to MSB_SAVE in Execute() method.

var $fname_format = 'd_m_y__H_i_s';
Default file name format.

var $error = '';
Error message.


PUBLIC METHODS

function Execute($task = MSB_STRING, $fname = '', $compress = false)
$task - operation to perform: MSB_STRING - return SQL commands as a string;
  MSB_SAVE - create the backup file on the server; MSB_DOWNLOAD - save backup
  file in the user's computer.
$fname - optional name of backup file.
$compress - use GZip compression?




mysql_backup.class.php
<?php

/*
  MySQL database backup class, version 1.0.0
  Written by Vagharshak Tozalakyan <vagh@armdex.com>
  Released under GNU Public license
*/


define('MSB_VERSION', '1.0.0');

define('MSB_NL', "\r\n");

define('MSB_STRING', 0);
define('MSB_DOWNLOAD', 1);
define('MSB_SAVE', 2);

class MySQL_Backup
{

  var $server = 'localhost';
  var $port = 3306;
  var $username = 'root';
  var $password = '';
  var $database = '';
  var $link_id = -1;
  var $connected = false;
  var $tables = array();
  var $drop_tables = true;
  var $struct_only = false;
  var $comments = true;
  var $backup_dir = '';
  var $fname_format = 'd_m_y__H_i_s';
  var $error = '';


  function Execute($task = MSB_STRING, $fname = '', $compress = false)
  {
    if (!($sql = $this->_Retrieve()))
    {
      return false;
    }
    if ($task == MSB_SAVE)
    {
      if (empty($fname))
      {
        $fname = $this->backup_dir;
        $fname .= date($this->fname_format);
        $fname .= ($compress ? '.sql.gz' : '.sql');
      }
      return $this->_SaveToFile($fname, $sql, $compress);
    }
    elseif ($task == MSB_DOWNLOAD)
    {
      if (empty($fname))
      {
        $fname = date($this->fname_format);
        $fname .= ($compress ? '.sql.gz' : '.sql');
      }
      return $this->_DownloadFile($fname, $sql, $compress);
    }
    else
    {
      return $sql;
    }
  }


  function _Connect()
  {
    $value = false;
    if (!$this->connected)
    {
      $host = $this->server . ':' . $this->port;
      $this->link_id = mysql_connect($host, $this->username, $this->password);
    }
    if ($this->link_id)
    {
      if (empty($this->database))
      {
        $value = true;
      }
      elseif ($this->link_id !== -1)
      {
        $value = mysql_select_db($this->database, $this->link_id);
      }
      else
      {
        $value = mysql_select_db($this->database);
      }
    }
    if (!$value)
    {
      $this->error = mysql_error();
    }
    return $value;
  }


  function _Query($sql)
  {
    if ($this->link_id !== -1)
    {
      $result = mysql_query($sql, $this->link_id);
    }
    else
    {
      $result = mysql_query($sql);
    }
    if (!$result)
    {
      $this->error = mysql_error();
    }
    return $result;
  }


  function _GetTables()
  {
    $value = array();
    if (!($result = $this->_Query('SHOW TABLES')))
    {
      return false;
    }
    while ($row = mysql_fetch_row($result))
    {
      if (empty($this->tables) || in_array($row[0], $this->tables))
      {
        $value[] = $row[0];
      }
    }
    if (!sizeof($value))
    {
      $this->error = 'No tables found in database.';
      return false;
    }
    return $value;
  }


  function _DumpTable($table)
  {
    $value = '';
    $this->_Query('LOCK TABLES ' . $table . ' WRITE');
    if ($this->comments)
    {
      $value .= '#' . MSB_NL;
      $value .= '# Table structure for table `' . $table . '`' . MSB_NL;
      $value .= '#' . MSB_NL . MSB_NL;
    }
    if ($this->drop_tables)
    {
      $value .= 'DROP TABLE IF EXISTS `' . $table . '`;' . MSB_NL;
    }
    if (!($result = $this->_Query('SHOW CREATE TABLE ' . $table)))
    {
      return false;
    }
    $row = mysql_fetch_assoc($result);
    $value .= str_replace("\n", MSB_NL, $row['Create Table']) . ';';
    $value .= MSB_NL . MSB_NL;
    if (!$this->struct_only)
    {
      if ($this->comments)
      {
        $value .= '#' . MSB_NL;
        $value .= '# Dumping data for table `' . $table . '`' . MSB_NL;
        $value .= '#' . MSB_NL . MSB_NL;
      }
      $value .= $this->_GetInserts($table);
    }
    $value .= MSB_NL . MSB_NL;
    $this->_Query('UNLOCK TABLES');
    return $value;
  }


  function _GetInserts($table)
  {
    $value = '';
    if (!($result = $this->_Query('SELECT * FROM ' . $table)))
    {
      return false;
    }
    while ($row = mysql_fetch_row($result))
    {
      $values = '';
      foreach ($row as $data)
      {
        $values .= '\'' . addslashes($data) . '\', ';
      }
      $values = substr($values, 0, -2);
      $value .= 'INSERT INTO ' . $table . ' VALUES (' . $values . ');' . MSB_NL;
    }
    return $value;
  }


  function _Retrieve()
  {
    $value = '';
    if (!$this->_Connect())
    {
      return false;
    }
    if ($this->comments)
    {
      $value .= '#' . MSB_NL;
      $value .= '# MySQL database dump' . MSB_NL;
      $value .= '# Created by MySQL_Backup class, ver. ' . MSB_VERSION . MSB_NL;
      $value .= '#' . MSB_NL;
      $value .= '# Host: ' . $this->server . MSB_NL;
      $value .= '# Generated: ' . date('M j, Y') . ' at ' . date('H:i') . MSB_NL;
      $value .= '# MySQL version: ' . mysql_get_server_info() . MSB_NL;
      $value .= '# PHP version: ' . phpversion() . MSB_NL;
      if (!empty($this->database))
      {
        $value .= '#' . MSB_NL;
        $value .= '# Database: `' . $this->database . '`' . MSB_NL;
      }
      $value .= '#' . MSB_NL . MSB_NL . MSB_NL;
    }
    if (!($tables = $this->_GetTables()))
    {
      return false;
    }
    foreach ($tables as $table)
    {
      if (!($table_dump = $this->_DumpTable($table)))
      {
        $this->error = mysql_error();
        return false;
      }
      $value .= $table_dump;
    }
    return $value;
  }


  function _SaveToFile($fname, $sql, $compress)
  {
    if ($compress)
    {
      if (!($zf = gzopen($fname, 'w9')))
      {
        $this->error = 'Can\'t create the output file.';
        return false;
      }
      gzwrite($zf, $sql);
      gzclose($zf);
    }
    else
    {
      if (!($f = fopen($fname, 'w')))
      {
        $this->error = 'Can\'t create the output file.';
        return false;
      }
      fwrite($f, $sql);
      fclose($f);
    }
    return true;
  }


  function _DownloadFile($fname, $sql, $compress)
  {
    header('Content-disposition: filename=' . $fname);
    header('Content-type: application/octetstream');
    header('Pragma: no-cache');
    header('Expires: 0');
    echo ($compress ? gzencode($sql) : $sql);
    return true;
  }

}

?>




execute_db_backup.php

<?
/*
|-----------------------
|Example MySQL Backup File  
|  
|Written by: Justin Keller <kobenews@cox.net>
|Released under GNU Public license.
|
|Only use with MySQL database backup class,
|version 1.0.0 written by Vagharshak Tozalakyan
|<vagh@armdex.com>.
|-----------------------
*/

require_once 'mysql_backup.class.php';
$backup_obj = new MySQL_Backup();

//--- EDIT - REQUIRED SETUP VARIABLES ------->>

$backup_obj->server = 'localhost';
$backup_obj->port = 3306;
$backup_obj->username = '';
$backup_obj->password = '';
$backup_obj->database = '';

//Tables you wish to backup. All tables in the database will be backed up if this array is null.
$backup_obj->tables = array();

//--- END - REQUIRED SETUP VARIABLES  ------->>

//---OPTIONAL PREFERENCE VARIABLES ------->>

//Add DROP TABLE IF EXISTS queries before CREATE TABLE in backup file.
$backup_obj->drop_tables = true;

//Only structure of the tables will be backed up if true.
$backup_obj->struct_only = false;

//Include comments in backup file if true.
$backup_obj->comments = true;

//Directory on the server where the backup file will be placed. Used only if task parameter equals MSB_SAVE.
$backup_obj->backup_dir = '/';

//Default file name format.
$backup_obj->fname_format = 'm_d_Y';

//---END - OPTIONAL PREFERENCE VARIABLES ------->>

//---EDIT - REQUIRED EXECUTE VARIABLES ------->>

/*
Task:
MSB_STRING - Return SQL commands as a single output string.
MSB_SAVE - Create the backup file on the server.
MSB_DOWNLOAD - Download backup file to the user's computer.

*/
$task = MSB_DOWNLOAD;

//Optional name of backup file if using 'MSB_SAVE' or 'MSB_DOWNLOAD'. If nothing is passed, the default file name format will be used.
$filename = '';

//Use GZip compression if using 'MSB_SAVE' or 'MSB_DOWNLOAD'?
$use_gzip = true;

//---END - REQUIRED EXECUTE VARIABLES ------->>

//---NO NEED TO ANYTHING BELOW THIS LINE ------->>

if (!$backup_obj->Execute($task, $filename, $use_gzip))
{
$output = $backup_obj->error;
}
else
{
$output = 'Operation Completed Successfully At: <b>' . date('g:i:s A') . '</b><i> ( Local Server Time )</i>';
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>MySQL Backup</title>
</head>
<body>
<?
echo $output;
?>
</body>
</html>

Saturday, February 4, 2012

Looping through XML with jQuery

Handling Xml on web pages is used to be a headache when i started coding ajax events. Most of the times we will be knowing the tag name of particular data we need and we can use
xml.find('result').find('userTypeDetails')

 But this is not always the case with xml.
I have a scenario in which i get an xml like the one follows as ajax response.

<result>
    <permissionDetails>
             <addBusiness>0</addBusiness>
             <viewBusiness>1</viewBusiness>
             <viewBusinessChargeDetails>1</viewBusinessChargeDetails>
             <editBusinessProfile>0</editBusinessProfile>
             <editBusinessAccount>1</editBusinessAccount>
             <editBusinessGatewayInfo>1</editBusinessGatewayInfo>
             <deleteBusiness>1</deleteBusiness>
             <addBillingUser>0</addBillingUser>
             <viewBillingUser>0</viewBillingUser>
             <viewBillingUserChargeDetails>0</viewBillingUserChargeDetails>
             <editBillingUserProfile>1</editBillingUserProfile>
             <editBillingUserAccount>1</editBillingUserAccount>
             <deleteBillingUser>1</deleteBillingUser>
             <viewCharge>0</viewCharge>
             <editCharge>1</editCharge>
             <viewRegularReport>0</viewRegularReport>
             <addRegularReport>0</addRegularReport>
             <editRegularReport>0</editRegularReport>
             <deleteRegularReport>0</deleteRegularReport>
             <viewAdvancedReport>1</viewAdvancedReport>
             <addAdvancedReport>0</addAdvancedReport>
             <editAdvancedReport>1</editAdvancedReport>
             <deleteAdvancedReport>1</deleteAdvancedReport>
             <viewUser>0</viewUser>
             <addUser>0</addUser>
             <editUser>1</editUser>
             <deleteUser>1</deleteUser>
             <viewTemplate>0</viewTemplate>
             <addTemplate>0</addTemplate>
             <editTemplate>0</editTemplate>
             <deleteTemplate>1</deleteTemplate>
             <viewMail>1</viewMail>
             <sendMail>1</sendMail>
             <deleteMail>0</deleteMail>
             <profileDetailsView>1</profileDetailsView>
             <profileDetailsEdit>1</profileDetailsEdit>
             <viewAccount>0</viewAccount>
             <editAccount>1</editAccount>
             <deleteAccount>1</deleteAccount>
             <viewGatewayInfo>1</viewGatewayInfo>
             <editGatewayInfo>1</editGatewayInfo>
             <deleteGatewayInfo>0</deleteGatewayInfo>
    </permissionDetails>
</result>

Now i have to update an html page as in figure

One of the solution is to create checkboxes with name same as tagname in xml and iterate through the xml to check or uncheck the check box with name same as the current tag name depending upon value.
dd

xml.find('result').find('permissionDetails').each(function(){
    $(this).children().each(function(){
        var tagName=this.tagName;
        var val=$(this).text();
        if(val==1){
            $('input:checkbox[name='+tagName+']').attr('checked',true);
        }
        else if(val==0){
            $('input:checkbox[name='+tagName+']').removeAttr('checked');
        }
    })
});

Friday, February 3, 2012

code ignitor: Getting the error “Disallowed Key Characters”


Code Ignitor: Getting the error “Disallowed Key Characters” ?

   In Codeignitor, its usual for the developer getting the Error: "Disallowed Key Characters"
 This error used to drove newbies nuts. I am not sure about the reason and the fix provided by codeignitor help page not works some times[Most of the times from my experience]. It is also difficult to find what caused the error.

Here is solution that help in diagnosis of the problem.

In the core CI code in system/libraries is a file called input.php This small modification would show the actual data that caused the Problem.

Around line number 199


function _clean_input_keys($str)
{
if ( ! preg_match(“/^[a-z0-9:_\/-]+$/i”, $str))
{
exit(‘Disallowed Key Characters: ‘.$str);
// The variable $str was added to display the data in question.
}
return $str;
}

jQuery: exclude $(this) from selector


I have a set of text boxes and i want to check for duplication of set values in any of the text box. ie, no text box should contain a value that is entered in any other.

HTML
<form method="post" action="" onsubmit="return validate()">
   <table>
       <tr>
               <td>
                         <input type="textkbox" name="priority[]" />
               </td>
       <tr>

       <tr>
               <td>
                         <input type="textkbox" name="priority[]" />
               </td>
       <tr>

       <tr>
               <td>
                         <input type="textkbox" name="priority[]" />
               </td>
       <tr>

       <tr>
               <td>
                         <input type="textkbox" name="priority[]" />
               </td>
       <tr>

       <tr>
               <td>
                         <input type="textkbox" name="priority[]" />
               </td>
       <tr>
   </table>
</form>
DEMO

JAVASCRIPT


var firstError='';
function validate(){
     $('input[type="text"]').each(function(){
var mastrPriority=$(this);
$('input[type="text"]').not(this).each(function(){
var priority=$(this);
if(mastrPriority.val()==priority.val()){
  seterrormessage(mastrPriority,'Duplicate Priority Values.');
seterrormessage(priority,'Duplicate Priority Values.');
if(firstError==''){
alert("Priority Field should contain unique values.");
firstError=mastrPriority;
}
}
});

})
if(firstError!=''){
  firstError.focus();
return false;
}
else{
  return true;
}
}


function seterrormessage(field,msg){
var errorBox=$(field).parent().find('div.validationError').first();
if(errorBox.length>0){
  errorBox.text(msg);
}
else{
  $(field).after('</br><div class="validationError">'+msg+'</a>');
}
}
The function validate() iterates through each text box and compare values of each box with all others except current one. The current text box is excluded from the set of text boxes using .not(this).