Friday, November 15, 2013

php codeigniter config for email library send using gmail

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

//webmaster email
$config['noreply_email_setting'] = Array(
    'protocol' => 'smtp',
    'mailpath' => '/usr/sbin/sendmail',
    'smtp_crypto' => 'tls',//tls or ssl
    'smtp_host' => 'smtp.gmail.com',//'ssl://smtp.googlemail.com'//ssl://smtp.gmail.com
    'smtp_port' => 587,//465//25
    'smtp_timeout' => 5,
    'smtp_user' => 'boroog@gmail.com',
    'smtp_pass' => '******',
    'mailtype' => 'html',
    'charset' => 'utf-8',
    'newline' => "\r\n",
    'wordwrap' => TRUE,
    'validation' => TRUE // bool whether to validate email or not
);



Tuesday, November 5, 2013

jquery file upload plugin with php method with custom progress bar

var url = window.location.hostname === 'blueimp.github.io' ? '//jquery-file-upload.appspot.com/' : '<?php echo admin_url('media/upload'); ?>';
кодыг сайн анхаар "window.location.hostname" ;

server side php

private function initialize() {
        if ($this->_server_var('REQUEST_METHOD') == 'GET') {
            $seleted_dir_id = $this->session->userdata(self::$SELECTED_DIR_ID);
            if (empty($seleted_dir_id)) {
                $seleted_dir_id = 0;
            }
            if ($seleted_dir_id === TRUE) {
                $seleted_dir_id = 0;
            }
            try {
                $files = $this->media_model->get_list(array('folder_id' => $seleted_dir_id));
                echo json_encode($files);
            } catch (Exception $ex) {
                log_message('error', $ex->getMessage());
            }
        }
    }

    public function upload() {
        $this->initialize();

        $upload = isset($_FILES['files']) ? $_FILES['files'] : null;
        // Parse the Content-Disposition header, if available:
        $file_name = $this->_server_var('HTTP_CONTENT_DISPOSITION') ? rawurldecode(preg_replace('/(^[^"]+")|("$)/', '', $this->_server_var('HTTP_CONTENT_DISPOSITION'))) : null;
        // Parse the Content-Range header, which has the following form:
        // Content-Range: bytes 0-524287/2000000
        $content_range = $this->_server_var('HTTP_CONTENT_RANGE') ? preg_split('/[^0-9]+/', $this->_server_var('HTTP_CONTENT_RANGE')) : null;
        $size = $content_range ? $content_range[3] : null;

        $files = array();
        if ($upload && is_array($upload['tmp_name'])) {
            // param_name is an array identifier like "files[]",
            // $_FILES is a multi-dimensional array:
            foreach ($upload['tmp_name'] as $index => $value) {
                $files[] = $this->_handle_file_upload(
                        $upload['tmp_name'][$index], $file_name ? $file_name : $upload['name'][$index], $size ? $size : $upload['size'][$index], $upload['type'][$index], $upload['error'][$index], $index, $content_range
                );
            }
        } else {

            // param_name is a single object identifier like "file",
            // $_FILES is a one-dimensional array:
            $files[] = $this->_handle_file_upload(
                    isset($upload['tmp_name']) ? $upload['tmp_name'] : null, $file_name ? $file_name : (isset($upload['name']) ? $upload['name'] : null), $size ? $size : (isset($upload['size']) ? $upload['size'] : $this->_server_var('CONTENT_LENGTH')), isset($upload['type']) ? $upload['type'] : $this->_server_var('CONTENT_TYPE'), isset($upload['error']) ? $upload['error'] : null, null, $content_range
            );
        }

        echo json_encode($files);
    }

    // -----------------------------------------------------------------------

    private function _handle_file_upload($uploaded_file, $name, $size, $type, $error, $index = null, $content_range = null) {       
        $file = new stdClass();
        $file->name = $this->_file_name($name, $type, $index, $content_range);
        $file->size = $this->_fix_integer_overflow(intval($size));
        $file->type = $type;

        $seleted_dir_id = $this->session->userdata(self::$SELECTED_DIR_ID);
        $seleted_dir_path = $this->session->userdata(self::$SELECTED_DIR_PATH);
        if (!empty($seleted_dir_path)) {
            $seleted_dir_path = $seleted_dir_path . '/';
        }

        $validate = $this->_validate_file($uploaded_file, $file, $error, $index);
       
        if ($seleted_dir_id && $validate) {
            if ($seleted_dir_id === TRUE) {
                $seleted_dir_id = 0;
            }
            //path generate
            $upload_dir = UPLOADPATH . $seleted_dir_path;
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, $this->config->item('mkdir_mode'), true);
            }
            $file_path = $upload_dir . $file->name;
            //check is uploaded file
            $append_file = $content_range && is_file($file_path) && $file->size > $this->_file_size($file_path);
            if ($uploaded_file && is_uploaded_file($uploaded_file)) {
                // multipart/formdata uploads (POST method uploads)
                if ($append_file) {
                    file_put_contents(
                            $file_path, fopen($uploaded_file, 'r'), FILE_APPEND
                    );
                } else {
                    move_uploaded_file($uploaded_file, $file_path);
                }
            } else {
                // Non-multipart uploads (PUT method support)
                file_put_contents(
                        $file_path, fopen('php://input', 'r'), $append_file ? FILE_APPEND : 0
                );
            }
            //check is upload success
            $file_size = $this->_file_size($file_path, $append_file);
            if ($file_size === $file->size) {

                $fext = strtolower(strrchr($file->name, '.'));
                $fname = empty($fext) ? $file->name : stristr($file->name, $fext, true);
                $fret = $this->thumbmanager->get_mimetype_groupname($fext);

                if ($fret === FALSE) {
                    $file->error = 'Зөвшөөрөгдсөн файлын төрөл биш байна!';
                } else {
                    $mimetype = (is_array($fret[1]) ? $fret[1][0] : $fret[1]);

                    $media = array();
                    $media['typecode'] = $fret[0];
                    $media['folder_id'] = $seleted_dir_id;
                    $media['filename'] = $fname;
                    $media['extension'] = substr($fext, 1);
                    $media['mimetype'] = $mimetype;
                    $media['size'] = $file_size;
                    $media['createddate'] = utc_datetime();
                    $media['user_id'] = User()->get_user_id();

                    if ($this->media_model->insert($media) > 0) {
                        $file->url = $this->thumbmanager->thumb_url($media);
                    }
                }
            } else {
                $file->size = $file_size;
                if (!$content_range && $this->config->item('discard_aborted_uploads')) {
                    unlink($file_path);
                    $file->error = 'abort';
                }
            }
        }
        return $file;
    }
 
CSS
 
/*
    Document   : file
    Created on : Nov 5, 2013, 10:12:17 PM
    Author     : boroo
    Description:
        Purpose of the stylesheet follows.
*/
.process {
    display: block;
    position: relative;
    height: 20px;
    width: 100%;
}
.progress-bar {
    background: url(images/progressbar.gif) repeat-x scroll left top #333;
}
.progress-bar-success {
    float: left;
    height: 20px;
    position: relative;
}


.fileinput-button {
  position: relative;
  overflow: hidden;
}

.fileinput-button input {
  position: absolute;
  top: 0;
  right: 0;
  margin: 0;
  opacity: 0;
  -ms-filter: 'alpha(opacity=0)';
  font-size: 200px;
  direction: ltr;
  cursor: pointer;
}

/* Fixes for IE < 8 */
@media screen\9 {
  .fileinput-button input {
    filter: alpha(opacity=0);
    font-size: 100%;
    height: 100%;
  }
}


HTML



<!-- The jQuery UI widget factory, can be omitted if jQuery UI is already included -->
<script src="<?php echo theme_url('jQuery-File-Upload-9.0.1/js/vendor/jquery.ui.widget.js', 'shared'); ?>"></script>
<!-- The Iframe Transport is required for browsers without support for XHR file uploads -->
<script src="<?php echo theme_url('jQuery-File-Upload-9.0.1/js/jquery.iframe-transport.js', 'shared'); ?>"></script>
<!-- The basic File Upload plugin -->
<script src="<?php echo theme_url('jQuery-File-Upload-9.0.1/js/jquery.fileupload.js', 'shared'); ?>"></script>
<script>
    /*jslint unparam: true */
    /*global window, $ */
    $(function() {
        'use strict';
        // Change this to the location of your server-side upload handler:
        var url = window.location.hostname === 'blueimp.github.io' ? '//jquery-file-upload.appspot.com/' : '<?php echo admin_url('media/upload'); ?>';
        $('#fileupload').fileupload({
            url: url,
            dataType: 'json',
            acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
            process: [
                {
                    action: 'load',
                    fileTypes: /^image\/(gif|jpeg|png)$/,
                    maxFileSize: 5000000 // 5MB
                },
                {
                    action: 'resize',
                    maxWidth: 1440,
                    maxHeight: 900
                },
                {
                    action: 'save'
                }
            ],
            done: function(e, data) {
                if (data && typeof data.result !== 'undefined') {
                    try {
                        for (var key in data.result) {
                            var item = data.result[key];
                            $('<img/>').attr('src', '<?php echo site_url(); ?>' + item.url)
                                    .appendTo('#files');
                        }
                    } catch (ex) {
                        alert(ex);
                    }
                }
            },
            error: function(e, data) {
                var a = 1;
            },
            progressall: function(e, data) {
                var progress = parseInt(data.loaded / data.total * 100, 10);
                $('#progress .progress-bar').css('width', progress + '%');
            }
        }).prop('disabled', !$.support.fileInput).parent().addClass($.support.fileInput ? undefined : 'disabled');
    });
</script>

Sunday, November 3, 2013

codeigniter media file manager example , php , json

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class media extends HO_Admin {

    public function __construct() {
        parent::__construct();

        $this->load->config('uploader');
        $this->load->model(array('media_model', 'mediafolder_model'));
        $this->load->library('NetAdvDirectoryService', NULL, '_directoryService');
        $this->load->library('NetAdvImageService', NULL, '_imageService');

        $this->AllowedFileTypes = $this->config->item('AllowedFileTypes');
        $this->load->helper('file');
    }

    public function index() {
        $this->view();
    }

    public function browser($dir = 0) {
        if (empty($dir)) {
            $dir = 0;
        }
       
        $selected_dir = $this->mediafolder_model->get($dir);       
        if(!empty($selected_dir)) {
            $selected_dir['selected_dir_breadcrumbs'] = $this->mediafolder_model->collect_parent_folders($selected_dir, NULL, TRUE);
        }
        $child_folders = $this->mediafolder_model->get_list(array('parent_id' => $dir));
        $child_medias = $this->media_model->get_list(array('folder_id' => $dir));

        $data = array();
        $data['selected_dir'] = $selected_dir;
        $data['dir_list'] = $child_folders;
        $data['file_list'] = $child_medias;

//        $files = scandir($dir);
//        foreach ($files as $file) {
//            if ($file != '.' && $file != '..') {
//                if (is_file($dir . $file)) {
//                    $info = pathinfo($dir . $file);
//                    $file_ext = strtolower($info['extension']);
//                    if (in_array($file_ext, $this->AllowedFileTypes)) {
//                        $data['file_list'][] = array(
//                            'basename' => $info['basename'],
//                            'extension' => $file_ext,
//                            'filename' => $info['filename']);
//                    }
//                } elseif (is_dir($dir . $file)) {
//                    $data['dir_list'][] = $file;
//                }
//            }
//        }
        $this->view('media/partial/filemanager-browser', $data);
    }

    public function delete() {
        $command = $this->input->get('file');
        if (!empty($command)) {
            try {
                if (is_dir($command)) {
                    if (is_dir_empty($command)) {
                        $this->success($command . ' санг устгачихлаа!');
                    } else {
                        $this->error($command . ' санд файл байгаа тул устгах боломжгүй');
                    }
                } elseif (is_file($command)) {
//                $this->load->model('article_media_model');
//                if ($this->article_media_model->media_in_article($command)) {
//                    $this->error($command . ' файл ашиглагдаж байгаа тул устгах боломжгүй');
//                }
                    unlink($command);
                    $this->success($command . ' файлыг устгачихлаа!');
                }
            } catch (Exception $ex) {
                $this->error($ex->getMessage());
            }
        }
    }

    public function rename() {
        $command = $this->input->get('filename');
        if (!empty($command)) {
            try {
                if (is_dir($command)) {
                    if (is_dir_empty($command)) {
                        $this->success($command . ' санг устгачихлаа!');
                    } else {
                        $this->error($command . ' санд файл байгаа тул устгах боломжгүй');
                    }
                } elseif (is_file($command)) {
//                $this->load->model('article_media_model');
//                if ($this->article_media_model->media_in_article($command)) {
//                    $this->error($command . ' файл ашиглагдаж байгаа тул устгах боломжгүй');
//                }
                    unlink($command);
                    $this->success($command . ' файлыг устгачихлаа!');
                }
            } catch (Exception $ex) {
                $this->error($ex->getMessage());
            }
        }
    }

    public function fileNameDialog() {
        $data = array();
        $data['command'] = $this->input->get('command');
        $data['filename'] = $this->input->get('filename');
        $this->view('media/partial/filename-dialog', $data);
    }

    public function qqupload($path = '') {
        if (empty($path)) {
            $this->view();
        } else {
            $path = trim($path) . '/';
            try {
                $inputHandler = false;

                $qqfile = $this->input->post('qqfile');
                if (empty($qqfile)) {
                    foreach ($_FILES as $file) {
                        $qqfile = $file["name"];
                        $ftype = $file["type"];
                        $fsize = $file["size"] / 1024;
                        $ftmp = $file["tmp_name"];

                        $inputHandler = fopen($ftmp, "rb");
                    }
                } else {
                    $inputHandler = fopen('php://input', "r");
                }

                // create a temp file where to save data from the input stream
                $fileHandler = fopen($path . $qqfile, "w+");

                // save data from the input stream
                while (true) {
                    $buffer = fgets($inputHandler, 4096);
                    if (strlen($buffer) == 0) {
                        fclose($inputHandler);
                        fclose($fileHandler);
                        return true;
                    }

                    fwrite($fileHandler, $buffer);
                }
                // done
            } catch (Exception $ex) {
                echo json_encode(array('success' => false, 'message' => $ex->getMessage()));
            }

            echo json_encode(array('success' => true));
        }
    }

    public function upload() {
        $this->load->library('UploadHandler');
    }

}

Friday, November 1, 2013

javascript html 5 FileReader example for php input stream

html

<input name="upload_files" id="upload_files" multiple="multiple" type="file">

javascript

function upload(fileInputId, fileIndex)
        {
            // take the file from the input
            var file = document.getElementById(fileInputId).files[fileIndex];
            var reader = new FileReader();
            reader.readAsBinaryString(file); // alternatively you can use readAsDataURL
            reader.onloadend  = function(evt)
            {
                    // create XHR instance
                    xhr = new XMLHttpRequest();
                    
                    // send the file through POST
                    xhr.open("POST", 'upload.php', true);

                    // make sure we have the sendAsBinary method on all browsers
                    XMLHttpRequest.prototype.mySendAsBinary = function(text){
                        var data = new ArrayBuffer(text.length);
                        var ui8a = new Uint8Array(data, 0);
                        for (var i = 0; i < text.length; i++) ui8a[i] = (text.charCodeAt(i) & 0xff);
            
                        if(typeof window.Blob == "function")
                        {
                             var blob = new Blob([data]);
                        }else{
                             var bb = new (window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder)();
                             bb.append(data);
                             var blob = bb.getBlob();
                        }

                        this.send(blob);
                    }
                    
                    // let's track upload progress
                    var eventSource = xhr.upload || xhr;
                    eventSource.addEventListener("progress", function(e) {
                        // get percentage of how much of the current file has been sent
                        var position = e.position || e.loaded;
                        var total = e.totalSize || e.total;
                        var percentage = Math.round((position/total)*100);
                        
                        // here you should write your own code how you wish to proces this
                    });
                    
                    // state change observer - we need to know when and if the file was successfully uploaded
                    xhr.onreadystatechange = function()
                    {
                        if(xhr.readyState == 4)
                        {
                            if(xhr.status == 200)
                            {
                                // process success
                            }else{
                                // process error
                            }
                        }
                    };
                    
                    // start sending
                    xhr.mySendAsBinary(evt.target.result);
            };
        }

server side(php)


// read contents from the input stream
$inputHandler = fopen('php://input', "r");
// create a temp file where to save data from the input stream
$fileHandler = fopen('/tmp/myfile.tmp', "w+");

// save data from the input stream
while(true) {
    $buffer = fgets($inputHandler, 4096);
    if (strlen($buffer) == 0) {
        fclose($inputHandler);
        fclose($fileHandler);
        return true;
    }

    fwrite($fileHandler, $buffer);
}

// read contents from the input stream
$inputHandler = fopen('php://input', "r");
// create a temp file where to save data from the input stream
$fileHandler = fopen('/tmp/myfile.tmp', "w+");
 
// save data from the input stream
while(true) {
    $buffer = fgets($inputHandler, 4096);
    if (strlen($buffer) == 0) {
        fclose($inputHandler);
        fclose($fileHandler);
        return true;
    }
 
    fwrite($fileHandler, $buffer);
}
- See more at: http://www.webiny.com/blog/2012/05/07/webiny-file-upload-with-html5-and-ajax-using-php-streams/#sthash.aIgHd8zw.dpuf
// read contents from the input stream
$inputHandler = fopen('php://input', "r");
// create a temp file where to save data from the input stream
$fileHandler = fopen('/tmp/myfile.tmp', "w+");
 
// save data from the input stream
while(true) {
    $buffer = fgets($inputHandler, 4096);
    if (strlen($buffer) == 0) {
        fclose($inputHandler);
        fclose($fileHandler);
        return true;
    }
 
    fwrite($fileHandler, $buffer);
}
- See more at: http://www.webiny.com/blog/2012/05/07/webiny-file-upload-with-html5-and-ajax-using-php-streams/#sthash.aIgHd8zw.dpuf

- See more at: http://www.webiny.com/blog/2012/05/07/webiny-file-upload-with-html5-and-ajax-using-php-streams/#sthash.aIgHd8zw.dpuf