Showing posts with label CodeIgniter. Show all posts
Showing posts with label CodeIgniter. Show all posts

Friday, July 19, 2019

How to Install CodeIgniter PHP Framework on Ubuntu 18.04 LTS

<VirtualHost *:80>
 #ServerAdmin admin@yourdomain.com
 #ServerName yourdomain.com
 DocumentRoot /home/boroo/ftp/projects/codeigniter
 <Directory /home/boroo/ftp/projects/codeigniter/>
   Options +FollowSymLinks
   AllowOverride All
   Order allow,deny
   allow from all
 </Directory>
 ErrorLog /var/log/apache2/codeigniter-error_log
 CustomLog /var/log/apache2/codeigniter-access_log common
</VirtualHost>
linux server deer apache garaar tohiruulj baihad rewrite mod ajillahgui tohioldol baival htacces doorhi tohirgood hiigeerei, support ssl+rewrite mod. result: https://domain/subdir/api
#on apache2
#Options Indexes FollowSymLinks Includes ExecCGI
#AllowOverride All
<IfModule mod_rewrite.c>
RewriteEngine on
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
</IfModule>

Thursday, April 28, 2016

codeigniter my custom captcha controller, view

$config['compress_output'] = TRUE;
****************************************************************

<?php

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

class captcha extends HO_Admin {

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

        //image captcha library
        $this->load->library('HO/HiimelCaptcha', array($this), 'captcha');
    }

    public function image() {
        $this->xhr_protect();

        header("Content-type: image/jpeg");

        $arr = $this->captcha->createImage(6);
        $im = reset(array_values($arr));
        ob_start();
        imagejpeg($im);
        $this->output->cache(0);
        $this->output->set_output('data:image/jpeg;base64,' . base64_encode(ob_get_clean()));
    }

}

******************************************

if ($this->web_cache_minute > 0) {
                $this->output->cache($this->web_cache_minute);
            }
            $this->output->set_output($this->web->page());

********************************************

<div class="captcha">
                <div class="detail">
                    <div class="img">
                        <img src="" alt="" title="captcha">
                    </div>
                    <div class="inp">
                        <input type="text" maxlength="10" id="captcha_code" name="captcha_code">
                        <label>Дуурайж бичээрэй!</label>
                    </div>
                </div>
            </div>
            <script>
                (function reloadCaptchaImg(capimg) {
                    var link = '<?php echo admin_url('captcha/image?'); ?>' + getTimeAsLong();
                    $.ajax({
                        url: link,
                        success: function (result) {
                            var par = capimg.parent();
                            capimg.remove();
                            capimg = $('<img src="' + result + '"/>');
                            capimg.appendTo(par);
                            capimg.animate({'opacity': '1'}, {
                                duration: 300
                            });
                        }
                    });
                })($('.captcha img'));
            </script>

Saturday, December 26, 2015

codeigniter login controller with facebook login methods

<?php

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

// Skip these two lines if you're using Composer
define('FACEBOOK_SDK_V4_SRC_DIR', APPPATH . 'libraries/facebook-php-sdk-v4/src/Facebook/');
require APPPATH . 'libraries/facebook-php-sdk-v4/autoload.php';

use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\FacebookRequestException;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\GraphUser;

class login extends HO_Site {

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

        $this->load->config('facebook');
        $this->load->library('session');

        $this->lang->load('user');
        $this->load->library('validation/UserValidation', array($this), 'validation');

        FacebookSession::setDefaultApplication(
                $this->config->item('api_id', 'facebook'), $this->config->item('app_secret', 'facebook'));
    }

    public function fbs() {
        $helper = new FacebookRedirectLoginHelper($this->config->item('redirect_url', 'facebook'));
        $loginUrl = $helper->getLoginUrl($this->config->item('permissions', 'facebook'));
        redirect($loginUrl);
    }

    public function fbe() {
        $helper = new FacebookRedirectLoginHelper($this->config->item('redirect_url', 'facebook'));
        $session = FALSE;
        try {
            if ($session === FALSE) {
                $session = $helper->getSessionFromRedirect();
            }
        } catch (FacebookRequestException $ex) {
            log_message('error', $ex->getMessage());
        } catch (\Exception $ex) {
            log_message('error', $ex->getMessage());
        }
        if ($session) {
            try {
                $me = (new FacebookRequest(
                        $session, 'GET', '/me'
                        ))->execute()->getGraphObject(GraphUser::className());

                $firstname = $me->getFirstName();
                $lastname = $me->getLastName();
                $email = $me->getEmail();

                if (!User()->logged_in()) {
                    $user = $this->user_model->find_user($email);

                    if (empty($user) || !isset($user['id'])) {

                        $new_password = User()->get_random_password();

                        $posted['firstname'] = $firstname;
                        $posted['lastname'] = $lastname;
                        $posted['username'] = $email;
                        $posted['email'] = $email;
                        $posted['salt'] = User()->get_salt();
                        $posted['password'] = User()->get_hashed_password($posted, $new_password);
                        $posted['createddate'] = utc_datetime();

                        $role = $this->role_model->get(array('code' => 'user'));
                        $posted['role_id'] = $role['id'];
                        $posted['id'] = $this->user_model->save($posted);
                       
                    } else {
                        if (User()->login($email, $user['password'], true, true)) {
                            redirect(site_url());
                        } else {
                            redirect(site_url('login'));
                        }
                    }
                } else {
                    redirect(site_url());
                }
            } catch (FacebookRequestException $e) {
                // The Graph API returned an error
                $this->error($ex->getMessage());
            } catch (\Exception $e) {
                // Some other error occurred
                $this->error($ex->getMessage());
            }
        } else {
            redirect(site_url('login'));
        }
    }

    public function index($error = '') {
        if (User()->logged_in()) {
            redirect(site_url());
        } else {
            $loginUrl = site_url('login/fbs');
            $this->view('index', array('loginUrl' => $loginUrl, 'error' => $error));
        }
    }

    public function auth() {
        if ($this->validation->validate_login()) {
            $posted = $this->input->post();
            $email = $posted['username'];
            $password = $posted['password'];

            try {
                if (!User()->logged_in()) {
                    $user = $this->user_model->find_user($email);

                    if (empty($user) || !isset($user['id'])) {
                        $posted['username'] = $email;
                        $posted['email'] = $email;
                        $posted['salt'] = User()->get_salt();
                        $posted['password'] = User()->get_hashed_password($posted, $password);
                        $posted['createddate'] = utc_datetime();

                        $role = $this->role_model->get(array('code' => 'user'));
                        $posted['role_id'] = $role['id'];
                        $posted['id'] = $this->user_model->save($posted);
                    } else {
                        if (User()->login($email, $password, true)) {
                            redirect(site_url());
                        } else {
                            $this->index('Нэр эсвэл нууц үг буруу байна!');
                        }
                    }
                } else {
                    redirect(site_url());
                }
            } catch (Exception $ex) {
                //500 Internal Server Error
                log_message('error', $ex->getMessage());
                $this->index('Нэвтрэх үед алдаа гарлаа!');
            }
        } else {
            //400 Bad Request
            $this->index('Нэр эсвэл нууц үг буруу байна!');
        }
    }

    public function reset() {
        if ($this->validation->validate_reset()) {
            try {
                $posted = $this->input->post('email');
                if (User()->reset($posted)) {
                    $this->success('Нууц үгийг сэргээлээ!');
                } else {
                    $this->error('Нууц үгийг сэргээлээ!');
                }
            } catch (Exception $ex) {
                log_message('error', $ex->getMessage());
                $this->error($ex->getMessage());
            }
        } else {
            $this->error('Хүсэлт буруу байна!');
        }
    }

}

Monday, August 10, 2015

write comment by ajax post using codeigniter with recaptcha

PHP

public function write_comment($article_id) {
        $this->xhr_protect();

        $this->load->config('recaptcha');
        $secret_key = $this->config->item('secret_key', 'recaptcha');
        require_once (APPPATH . 'libraries/recaptcha/recaptchalib.php');

        $cf = $this->input->post('recaptcha_challenge_field');
        $rf = $this->input->post('recaptcha_response_field');
        $title = $this->input->post('title');
        $message = $this->input->post('message');
       
        if (empty($title) || empty($message)) {
            $this->error('Нэр эсвэл сэтгэгдэл хоосон байна!');
        }

        $resp = recaptcha_check_answer($secret_key
                , $this->input->ip_address()
                , $cf
                , $rf);

        if (!$resp->is_valid) {
            $this->error("Шалгах хэсэг буруу байна! (reCAPTCHA said: " . $resp->error . ")");
        }

        $article = $this->article_model->get($article_id);
        if (empty($article)) {
            show_404();
        } else {
            $this->load->model('comment_model');

            $comment = array();
            $comment['title'] = html_escape($title);
            $comment['message'] = html_escape($message);
            $comment['approved'] = 1;
            $comment['ipaddress'] = $this->input->ip_address();
            $comment['createddate'] = utc_datetime();

            $comment['id'] = $this->comment_model->save($comment);

            $article_comment = array('article_id' => $article['id'], 'comment_id' => $comment['id']);
            $this->article_comment_model->save($article_comment);

            $comment['date'] = date_descr($comment['createddate']);
            $this->success('Амжилттай!', array('data' => $comment));
        }
    }


JS



<script type="text/javascript">

        function CreateCaptcha() {
            Recaptcha.create('<?php echo $site_key; ?>', 'recaptcha', {theme: "red"});
        }
        $.getScript('http://www.google.com/recaptcha/api/js/recaptcha_ajax.js', CreateCaptcha);
        $('.post-reply-entry button').click(function (event) {
            event.preventDefault();
            var arr = $('#write_comment').postItems();
            var params = {};
            for (var i = 0; i < arr.length; i++) {
                params[arr[i].name] = arr[i].value;
            }
            $.ajax({
                url: '<?php echo site_url('forum/write_comment/' . $article['id']); ?>',
                type: 'post',
                dataType: 'json',
                data: params,
                cache: false,
                success: function (result) {
                    CreateCaptcha();
                    if (result.success) {
                        $('#write_comment').find('[name="message"]').val();
                        var comment = (result.data);
                        var s = '<div class="reply-post-one"><div class="reply-user"><span class="username">' + comment.title;
                        s += '</span><span class="date">' + comment.date + '</span></div><p>' + comment.message + '</p></div>';
                        $(s).prependTo($('#forum_comment_list'));
                    } else {
                        alert(result.message);
                    }
                },
                error: function (jqXhr, textStatus, errorThrown) {
                    alert("Error '" + jqXhr.status + "' (textStatus: '" + textStatus + "', errorThrown: '" + errorThrown + "')");
                }
            });
        });
        $('a[href="#write_comment"]').click(function (event) {
            event.preventDefault();
            $('.site-container').animate({
                scrollTop: $($(this).attr('href')).offset().top - 100
            }, 1000, 'swing');
            return false;
        });

    </script>

Monday, June 22, 2015

Facebook libraries using example for Codeigniter

<?php

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

// Skip these two lines if you're using Composer
define('FACEBOOK_SDK_V4_SRC_DIR', APPPATH . 'libraries/facebook-php-sdk-v4/src/Facebook/');
require APPPATH . 'libraries/facebook-php-sdk-v4/autoload.php';

use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\FacebookRequestException;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\GraphUser;

class login extends HO_Site {

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

        $this->load->config('facebook');
        $this->load->library('session');

        $this->lang->load('user');
        $this->load->library('validation/UserValidation', array($this), 'validation');

        FacebookSession::setDefaultApplication(config_item('facebook_app_id'), config_item('facebook_app_secret'));
    }

    public function fbs() {
        $helper = new FacebookRedirectLoginHelper($this->config->item('redirect_url', 'facebook'));
        $loginUrl = $helper->getLoginUrl(); //($this->config->item('permissions', 'facebook'));
        redirect($loginUrl);
    }

    public function fbe() {
        $helper = new FacebookRedirectLoginHelper($this->config->item('redirect_url', 'facebook'));
        $session = FALSE;
        try {
            if ($session === FALSE) {
                $session = $helper->getSessionFromRedirect();
            }
        } catch (FacebookRequestException $ex) {
            log_message('error', $ex->getMessage());
        } catch (\Exception $ex) {
            log_message('error', $ex->getMessage());
        }
        if ($session) {
            try {
                $me = (new FacebookRequest(
                        $session, 'GET', '/me'
                        ))->execute()->getGraphObject(GraphUser::className());

                $firstname = $me->getFirstName();
                $lastname = $me->getLastName();
                $email = $me->getEmail();

                if (!User()->logged_in()) {
                    $user = $this->user_model->find_user($email);

                    if (empty($user) || !isset($user['id'])) {

                        $new_password = User()->get_random_password();

                        $posted['firstname'] = $firstname;
                        $posted['lastname'] = $lastname;
                        $posted['username'] = $email;
                        $posted['email'] = $email;
                        $posted['salt'] = User()->get_salt();
                        $posted['password'] = User()->get_hashed_password($posted, $new_password);
                        $posted['createddate'] = utc_datetime();

                        $role = $this->role_model->get(array('code' => 'user'));
                        $posted['role_id'] = $role['id'];
                        $posted['id'] = $this->user_model->save($posted);
                       
                    } else {
                        if (User()->login($email, $user['password'], true, true)) {
                            redirect(site_url());
                        } else {
                            redirect(site_url('login'));
                        }
                    }
                } else {
                    redirect(site_url());
                }
            } catch (FacebookRequestException $e) {
                // The Graph API returned an error
                $this->error($ex->getMessage());
            } catch (\Exception $e) {
                // Some other error occurred
                $this->error($ex->getMessage());
            }
        } else {
            redirect(site_url('login'));
        }
    }

    public function index($error = '') {
        if (User()->logged_in()) {
            redirect(site_url());
        } else {
            $loginUrl = site_url('login/fbs');
            $this->view('index', array('loginUrl' => $loginUrl, 'error' => $error));
        }
    }

    public function auth() {
        if ($this->validation->validate_login()) {
            $posted = $this->input->post();
            $email = $posted['username'];
            $password = $posted['password'];

            try {
                if (!User()->logged_in()) {
                    $user = $this->user_model->find_user($email);

                    if (empty($user) || !isset($user['id'])) {
                        $posted['username'] = $email;
                        $posted['email'] = $email;
                        $posted['salt'] = User()->get_salt();
                        $posted['password'] = User()->get_hashed_password($posted, $password);
                        $posted['createddate'] = utc_datetime();

                        $role = $this->role_model->get(array('code' => 'user'));
                        $posted['role_id'] = $role['id'];
                        $posted['id'] = $this->user_model->save($posted);
                    } else {
                        if (User()->login($email, $password, true)) {
                            redirect(site_url());
                        } else {
                            $this->index('Нэр эсвэл нууц үг буруу байна!');
                        }
                    }
                } else {
                    redirect(site_url());
                }
            } catch (Exception $ex) {
                //500 Internal Server Error
                log_message('error', $ex->getMessage());
                $this->index('Нэвтрэх үед алдаа гарлаа!');
            }
        } else {
            //400 Bad Request
            $this->index('Нэр эсвэл нууц үг буруу байна!');
        }
    }

    public function reset() {
        if ($this->validation->validate_reset()) {
            try {
                $posted = $this->input->post('email');
                if (User()->reset($posted)) {
                    $this->success('Нууц үгийг сэргээлээ!');
                } else {
                    $this->error('Нууц үгийг сэргээлээ!');
                }
            } catch (Exception $ex) {
                log_message('error', $ex->getMessage());
                $this->error($ex->getMessage());
            }
        } else {
            $this->error('Хүсэлт буруу байна!');
        }
    }

}

PHPExcel libraries using example for Codeigniter

public function export() {
        $this->load->library('PHPExcel');

        $where = array(
            'role.code' => 'user',
            'user_meta.key' => 'winner',
            'user_meta.value' => 'OK');
        $joins = array('user.role_id=role.id', 'user.id=user_meta.user_id');
        $fields = 'user.id,user.email,user.username,user.firstname,user.lastname';

        $winner_users = $this->user_model->get_list($where, null, $fields, $joins);

        $winner_list = array();
        foreach ($winner_users as $winner_user) {
            $user_meta = $this->user_model->get(
                    array('user_id' => $winner_user['id'], 'key' => 'article_name'), 'user_meta');
            $winner_user['article_name'] = $user_meta['value'];
            $winner_list[] = $winner_user;
        }

        $heading = array('ID', 'И-Мэйл', 'Хэрэглэгч', 'Нэр', 'Овог', 'Урамшуулал');

        //Create a new PHPExcel Object
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->getActiveSheet()->setTitle("Ялагч болсон хэрэглэгчид");

        //Loop Heading
        $rowNumberH = 1;
        $colH = 'A';
        foreach ($heading as $h) {
            $cell_name = $colH . $rowNumberH;
            $objPHPExcel->getActiveSheet()->setCellValue($cell_name, $h);
            // Make bold cells
            $objPHPExcel->getActiveSheet()->getStyle($cell_name)->getFont()->setBold(true);
            $colH++;
        }

        //Loop Result
        $no = 2;
        foreach ($winner_list as $winner) {
            $objPHPExcel->getActiveSheet()->setCellValue('A' . $no, $winner['id']);
            $objPHPExcel->getActiveSheet()->setCellValue('B' . $no, $winner['email']);
            $objPHPExcel->getActiveSheet()->setCellValue('C' . $no, $winner['username']);
            $objPHPExcel->getActiveSheet()->setCellValue('D' . $no, $winner['firstname']);
            $objPHPExcel->getActiveSheet()->setCellValue('E' . $no, $winner['lastname']);
            $objPHPExcel->getActiveSheet()->setCellValue('F' . $no, $winner['article_name']);
            $no++;
        }

        //Columns size by auto
        foreach (array('B', 'C', 'D', 'E', 'F') as $colname) {
            $col = $objPHPExcel->getActiveSheet()->getColumnDimension($colname);
            $col->setAutoSize(true);
        }
        $objPHPExcel->getActiveSheet()->calculateColumnWidths();

        //Freeze pane
        $objPHPExcel->getActiveSheet()->freezePane('A1');

        //Save as an Excel BIFF (xls) file
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');

        $filename = "winners_" . date('Ymd') . ".xls";
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$filename\"");
        header('Cache-Control: max-age=0');

        $objWriter->save('php://output');
        exit;
    }

Wednesday, June 17, 2015

php codeigniter facebook javascript sdk example

<script>

        window.fbAsyncInit = function () {
            FB.init({
                appId: '<?php echo config_item('facebook_app_id'); ?>',
                cookie: true, // enable cookies to allow the server to access
                // the session
                xfbml: true, // parse social plugins on this page
                version: 'v2.2' // use version 2.2
            });
            FB.getLoginStatus(function (response) {
                statusChangeCallback(response);
            });
        };

        // Load the SDK asynchronously
        (function (d, s, id) {
            var js, fjs = d.getElementsByTagName(s)[0];
            if (d.getElementById(id))
                return;
            js = d.createElement(s);
            js.id = id;
            js.src = "//connect.facebook.net/en_US/sdk.js";
            fjs.parentNode.insertBefore(js, fjs);
        }(document, 'script', 'facebook-jssdk'));

        function statusChangeCallback(response) {
            console.log('statusChangeCallback');
            console.log(response);

            if (response.status === 'connected') {
                // Logged into your app and Facebook.
                getFbUserInfo(response);
            } else if (response.status === 'not_authorized') {
                // The person is logged into Facebook, but not your app.
                document.getElementById('fbstatus').innerHTML = 'Please log ' +
                        'into this app.';
            } else {
                // The person is not logged into Facebook, so we're not sure if
                // they are logged into this app or not.
                if (response.status !== 'unknown') {
                    document.getElementById('fbstatus').innerHTML = 'Please log ' +
                            'into Facebook.';
                }
            }
        }

        function getFbUserInfo(auth) {
            console.log('Welcome!  Fetching your information.... ');
            FB.api('/me', function (me) {
                console.log('Successful login for: ' + me.name);

                $('#fbstatus').text('Үйлчлүүлсэнд баярлалаа, ' + me.name + '!').show();

                $.ajax({
                    type: "post",
                    url: "<?php echo site_url('api/auth/login'); ?>",
                    data: 'email=' + me.email + "&name=" + me.name + "&access=" + auth.authResponse.accessToken,
                    beforeSend: function () {
                        $('#loading').show();
                        alert(auth.authResponse.accessToken);
                    }
                }).done(function (data) {
                    $('#loading').hide('slow');
                    alert(data);
                });
            });
        }

        $(document).ready(function () {
//            setTimeout(function () {
//                $('.fb-login-button').show();
//            }, 2000);
        });
    </script>

Thursday, April 23, 2015

amazing codeigntier functions

<?php

define('FILE_READ_MODE', 0644);
define('FILE_WRITE_MODE', 0666);
define('DIR_READ_MODE', 0755);
define('DIR_WRITE_MODE', 0777);

define('FOPEN_READ', 'rb');
define('FOPEN_READ_WRITE', 'r+b');
define('FOPEN_WRITE_CREATE_DESTRUCTIVE', 'wb'); // truncates existing file data, use with care
define('FOPEN_READ_WRITE_CREATE_DESTRUCTIVE', 'w+b'); // truncates existing file data, use with care
define('FOPEN_WRITE_CREATE', 'ab');
define('FOPEN_READ_WRITE_CREATE', 'a+b');
define('FOPEN_WRITE_CREATE_STRICT', 'xb');
define('FOPEN_READ_WRITE_CREATE_STRICT', 'x+b');

define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
define('CHARSET', 'UTF-8');
define('CHARSET_NAMES', 'utf8');
define('CHARSET_COLLATION', 'utf8_general_ci');

//////////////////////////////////////////////////////////////////////////////

if (isset($_SERVER['HTTP_HOST'])) {
    if (
            (strpos($_SERVER['HTTP_HOST'], '.') === FALSE) || //from my computer
            (substr($_SERVER['HTTP_HOST'], 0, 8) === '192.168.') || //from private ip address
            ($_SERVER['HTTP_HOST'] === '127.0.0.1') || //from localhost
            ($_SERVER['HTTP_HOST'] === '10.0.2.2') //from android emulator
    ) {
        $user = "root";
        $pass = "";
        $db = "center_test";
    }
}

$base_url = 'http://localhost/';
if (isset($_SERVER['HTTP_HOST'])) {
    $base_url = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http';
    $base_url .= '://' . $_SERVER['HTTP_HOST'];
    $base_url .= str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);
}
$base_path = str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);

date_default_timezone_set('UTC');

//////////////////////////////////////////////////////////////////////////////
if (!function_exists('escape_date')) {

    function escape_date($str) {
        $timestamp = strtotime($str);
        return date("Y-m-d H:i:s", $timestamp);
    }

}

if (!function_exists('utf8_header')) {

    function utf8_header($type = 'text/html') {
        header('Content-Type: ' . $type . '; charset=utf-8');
    }

}

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

if (!function_exists('server_var')) {

    function server_var($id) {
        return isset($_SERVER[$id]) ? $_SERVER[$id] : '';
    }

}

if (!function_exists('is_post')) {

    function is_post() {
        return server_var('REQUEST_METHOD') == 'POST';
    }

}

if (!function_exists('is_get')) {

    function is_get() {
        return server_var('REQUEST_METHOD') == 'GET';
    }

}

// ---------------------------------------------------------------------------
if (!function_exists('debug_log')) {

    function debug_log($msg) {
        $filepath = 'log-' . date('Y-m-d') . '.php';
        $message = (' - ' . date('Y-m-d H:i:s') . ' --> ' . $msg . "\n");

        if (!$fp = @fopen($filepath, FOPEN_WRITE_CREATE)) {
            return FALSE;
        }

        flock($fp, LOCK_EX);
        fwrite($fp, $message);
        flock($fp, LOCK_UN);
        fclose($fp);

        @chmod($filepath, FILE_WRITE_MODE);
    }

}

if (!function_exists('escape_str')) {

    function escape_str($str, $like = FALSE) {
        if (is_array($str)) {
            foreach ($str as $key => $val) {
                $str[$key] = escape_str($val, $like);
            }

            return $str;
        }

        if (function_exists('mysql_escape_string')) {
            $str = mysql_escape_string($str);
        } else {
            $str = addslashes($str);
        }

        // escape LIKE condition wildcards
        if ($like === TRUE) {
            $str = str_replace(array('%', '_'), array('\\%', '\\_'), $str);
        }

        return $str;
    }

}

if (!function_exists('html_escape')) {

    function html_escape($var) {
        if (is_array($var)) {
            return array_map('html_escape', $var);
        } else {
            return htmlspecialchars($var, ENT_QUOTES, CHARSET);
        }
    }

}

Sunday, March 29, 2015

my custom application core changes for codeigniter

my custom system changes...

in application/core/Lang.php

function load($langfile = '', $idiom = '', $return = FALSE, $add_suffix = TRUE, $alt_path = '')
{
$langfile = str_replace('.php', '', $langfile);

if ($add_suffix == TRUE)
{
$langfile = str_replace('_lang.', '', $langfile).'_lang';
}

$langfile .= '.php';

if (in_array($langfile, $this->is_loaded, TRUE))
{
return;
}

$config =& get_config();

if ($idiom == '')
{
// BOROO edited this code [start]
            //урт нэрийг богино кодоор солиж хэлний санг зохицууллаа
$deft_lang = ( ! isset($config['language'])) ? 'mn' : $config['language'];
$idiom = ($deft_lang == '') ? 'mn' : $deft_lang;
            // BOROO edited this code [end]
}

// Determine where the language file is and load it
if ($alt_path != '' && file_exists($alt_path.'language/'.$idiom.'/'.$langfile))
{
include($alt_path.'language/'.$idiom.'/'.$langfile);
}
else
{
$found = FALSE;

foreach (get_instance()->load->get_package_paths(TRUE) as $package_path)
{
if (file_exists($package_path.'language/'.$idiom.'/'.$langfile))
{
include($package_path.'language/'.$idiom.'/'.$langfile);
$found = TRUE;
break;
}
}

if ($found !== TRUE)
{
show_error('Unable to load the requested language file: language/'.$idiom.'/'.$langfile);
}
}


if ( ! isset($lang))
{
log_message('error', 'Language file contains no data: language/'.$idiom.'/'.$langfile);
return;
}

if ($return == TRUE)
{
return $lang;
}

$this->is_loaded[] = $langfile;
$this->language = array_merge($this->language, $lang);
unset($lang);

log_message('debug', 'Language file loaded: language/'.$idiom.'/'.$langfile);
return TRUE;
}

in application/core/Router.php


function _set_routing()
{
// Are query strings enabled in the config file?  Normally CI doesn't utilize query strings
// since URI segments are more search-engine friendly, but they can optionally be used.
// If this feature is enabled, we will gather the directory/class/method a little differently
$segments = array();
if ($this->config->item('enable_query_strings') === TRUE AND isset($_GET[$this->config->item('controller_trigger')]))
{
if (isset($_GET[$this->config->item('directory_trigger')]))
{
$this->set_directory(trim($this->uri->_filter_uri($_GET[$this->config->item('directory_trigger')])));
$segments[] = $this->fetch_directory();
}

if (isset($_GET[$this->config->item('controller_trigger')]))
{
$this->set_class(trim($this->uri->_filter_uri($_GET[$this->config->item('controller_trigger')])));
$segments[] = $this->fetch_class();
}

if (isset($_GET[$this->config->item('function_trigger')]))
{
$this->set_method(trim($this->uri->_filter_uri($_GET[$this->config->item('function_trigger')])));
$segments[] = $this->fetch_method();
}
}

// Load the routes.php file.
if (defined('ENVIRONMENT') AND is_file(APPPATH.'config/'.ENVIRONMENT.'/routes.php'))
{
include(APPPATH.'config/'.ENVIRONMENT.'/routes.php');
}
elseif (is_file(APPPATH.'config/routes.php'))
{
include(APPPATH.'config/routes.php');
}

$this->routes = ( ! isset($route) OR ! is_array($route)) ? array() : $route;
unset($route);

// Set the default controller so we can display it in the event
// the URI doesn't correlated to a valid controller.
$this->default_controller = ( ! isset($this->routes['default_controller']) OR $this->routes['default_controller'] == '') ? FALSE : strtolower($this->routes['default_controller']);

        // BOROO added this code [start]
        $this->dashboard_controller = (!isset($this->routes['dashboard_controller']) OR $this->routes['dashboard_controller'] == '') ? FALSE : strtolower($this->routes['dashboard_controller']);
        $this->seo_controller = (!isset($this->routes['seo_controller']) OR $this->routes['seo_controller'] == '') ? FALSE : strtolower($this->routes['seo_controller']);
        $this->supported_languages = (!isset($this->routes['supported_languages']) OR empty($this->routes['supported_languages'])) ? array() : $this->routes['supported_languages'];
        // BOROO added this code [end]

// Were there any query string segments?  If so, we'll validate them and bail out since we're done.
if (count($segments) > 0)
{
return $this->_validate_request($segments);
}

// Fetch the complete URI string
$this->uri->_fetch_uri_string();

// Is there a URI string? If not, the default controller specified in the "routes" file will be shown.
if ($this->uri->uri_string == '')
{
return $this->_set_default_controller();
}

// Do we need to remove the URL suffix?
$this->uri->_remove_url_suffix();

// Compile the segments into an array
$this->uri->_explode_segments();

// Parse any custom routing that may exist
$this->_parse_routes();

// Re-index the segment array so that it starts with 1 rather than 0
$this->uri->_reindex_segments();

}


function _set_default_controller()
{
// BOROO edited this code [start]
        //админ санд ондоо контроллер ажиллана
        $default_controller = $this->admin_mode ? $this->dashboard_controller : $this->default_controller;

        if ($default_controller === FALSE) {
            show_error("Unable to determine what should be displayed. A default route has not been specified in the routing file.");
        }
// Is the method being specified?
if (strpos($default_controller, '/') !== FALSE)
{
$x = explode('/', $default_controller);

$this->set_class($x[0]);
$this->set_method($x[1]);
$this->_set_request($x);
}
else
{
$this->set_class($default_controller);
$this->set_method('index');
$this->_set_request(array($default_controller, 'index'));
}
        // BOROO edited this code [end]

// re-index the routed segments array so it starts with 1 rather than 0
$this->uri->_reindex_segments();

log_message('debug', "No URI present. Default controller set.");

}


function _validate_request($segments)
{
        // BOROO added this code [start]
        if (!empty($this->supported_languages) && count($this->supported_languages) > 0) {

            $lang_code = strtolower($segments[0]);

            if (array_key_exists($lang_code, $this->supported_languages)) {

                $this->config->set_item('language', $lang_code);
                $this->set_language($lang_code);

                $segments = array_slice($segments, 1);
            }
        }
        // BOROO added this code [end]
       
if (count($segments) == 0)
{
return $segments;
}

// Does the requested controller exist in the root folder?
if (file_exists(APPPATH.'controllers/'.$segments[0].'.php'))
{
return $segments;
}

// Is the controller in a sub-folder?
if (is_dir(APPPATH.'controllers/'.$segments[0]))
{
            // BOROO added this code [start]
            if (!empty($this->admin_uri) && $this->admin_uri == $segments[0]) {
                $this->admin_mode = TRUE;
            } else {
                if (!empty($this->api_uri) && $this->api_uri == $segments[0]) {
                    $this->api_mode = TRUE;
                }
            }
            // BOROO added this code [end]

// Set the directory and remove it from the segment array
$this->set_directory($segments[0]);
$segments = array_slice($segments, 1);

if (count($segments) > 0)
{
// Does the requested controller exist in the sub-folder?
if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$segments[0].'.php'))
{
if ( ! empty($this->routes['404_override']))
{
$x = explode('/', $this->routes['404_override']);

$this->set_directory('');
$this->set_class($x[0]);
$this->set_method(isset($x[1]) ? $x[1] : 'index');

return $x;
}
else
{
show_404($this->fetch_directory().$segments[0]);
}
}
}
else
{
                // BOROO edited this code [start]
                //админ санд ондоо контроллер ажиллана
                $default_controller = $this->admin_mode ? $this->dashboard_controller : $this->default_controller;

                // Is the method being specified in the route?
                if (strpos($default_controller, '/') !== FALSE) {
                    $x = explode('/', $default_controller);

                    $this->set_class($x[0]);
                    $this->set_method($x[1]);
                } else {
                    $this->set_class($default_controller);
                    $this->set_method('index');
                }
               
                // Does the default controller exist in the sub-folder?
                if (!file_exists(APPPATH . 'controllers/' . $this->fetch_directory() . $default_controller . '.php')) {
                    $this->directory = '';
                    return array();
                }
                // BOROO edited this code [end]

}

return $segments;
}

        // BOROO added this code [start]
        if (count($segments) > 0) {
            if (file_exists(APPPATH . 'controllers/' . $this->fetch_directory() . $segments[0] . '.php')) {
                return $segments;
            }
            if (file_exists(APPPATH . 'controllers/' . $this->fetch_directory() . $this->seo_controller . '.php')) {
                $this->set_class($this->seo_controller);
                array_unshift($segments, $this->seo_controller);
                return $segments;
            } else {
                show_404();
            }

            return $segments;
        }
        // BOROO added this code [end]

// If we've gotten this far it means that the URI does not correlate to a valid
// controller class.  We will now see if there is an override
if ( ! empty($this->routes['404_override']))
{
$x = explode('/', $this->routes['404_override']);

$this->set_class($x[0]);
$this->set_method(isset($x[1]) ? $x[1] : 'index');

return $x;
}


// Nothing else to do at this point but show a 404
show_404($segments[0]);

}

// BOROO added this code [start]
    function is_api_mode() {
        return $this->api_mode;
    }
   
    function is_admin_mode() {
        return $this->admin_mode;
    }
   
    function set_language($language) {
        $this->language = trim($language, '/') . '/';
    }
   
    function fetch_language() {
        return $this->language;
    }
   
    function get_supported_languages() {
        return $this->supported_languages;
    }
    // BOROO added this code [end]

Thursday, February 5, 2015

php codeigniter html pivot table example

IN CONTROLLER

<?php

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

class home extends HO_Site {

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

    public function index() {
        $this->load->model('article_model');
        $where = array();
        $where['limit'] = 5;
        $where['offset'] = 0;
        $model = $this->article_model->get_list($where, null, array('id,title,createddate'));
        $this->view(array('data' => $model));
    }

}

IN VIEW

<?php
header('Content-Type: text/html; charset=utf-8');
echo 'processing...<br>';
print_r($data);
?>
<table style="border:1px solid #000;padding:5px;">
    <thead>
        <tr>
            <?php
            echo '<th>Талбар:</th>';
            for ($i = 0; $i < count($data); $i++) {
                echo '<th>Хэрэглэгч-' . $i . '</th>';
            }
            ?>
        </tr>
    </thead>
    <tbody>
        <?php
        $fieldNames = array_keys($data[0]);
        for ($i = 0; $i < count($fieldNames); $i++) {
            echo '<tr>';
            for ($j = 0; $j < count($data); $j++) {
                $item = $data[$j];
                if ($j == 0) {
                    echo '<th>' . $fieldNames[$i] . '</th>';
                }
                echo '<td>' . $item[$fieldNames[$i]] . '</td>';
            }
            echo '</tr>';
        }
        ?>
    </tbody>
</table>

RESULT





Thursday, October 23, 2014

google map example using in codeigniter php page with session save Latitude and Longitude

HTML part

                                <div class="googlemap">
                                    <?php
                                    $this->load->library('session');
                                    $bounds = $this->session->userdata('googlemap_bounds');
                                    $bound_lat = 49.463251;
                                    $bound_lng = 105.964504;
                                    $gmap_zoom = 15;
                                    if (isset($bounds) && !empty($bounds)) {
                                        $bound_array = explode(',', $bounds);
                                        if (!empty($bound_array)) {
                                            $bound_lat = ($bound_array[0] + $bound_array[2]) / 2;
                                            $bound_lng = ($bound_array[1] + $bound_array[3]) / 2;
                                            $gmap_zoom = $bound_array[4];
                                        }
                                    }
                                    if (isset($zar['googlemap']) && !empty($zar['googlemap'])):
                                        ?>                               
                                        <div class="title">
                                            Газрын байршил
                                        </div>
                                        <div class="embed-responsive embed-responsive-16by9">
                                            <?php
                                            echo $zar['googlemap'];
                                            ?>                                           
                                        </div>
                                    <?php endif; ?>
                                    <div class="title">
                                        Газрын байршил
                                    </div>
                                   
                                    <div id="map_canvas" class="embed-responsive embed-responsive-16by9"></div>
                                   
                                </div>

JS code

<script src="https://maps.googleapis.com/maps/api/js"></script>
<script>
                                        function initialize() {
                                            var initialBounds = null;
                                            var mapCanvas = document.getElementById('map_canvas');
                                            var mapOptions = {
                                                center: new google.maps.LatLng(<?php echo $bound_lat; ?>, <?php echo $bound_lng; ?>),
                                                zoom: <?php echo $gmap_zoom; ?>,
                                                mapTypeId: google.maps.MapTypeId.HYBRID
                                            };
                                            var map = new google.maps.Map(mapCanvas, mapOptions);
                                            var styles = [
                                                {
                                                    featureType: "all",
                                                    elementType: "labels",
                                                    stylers: [
                                                        {visibility: "on"}
                                                    ]
                                                }
                                            ];
                                            map.setOptions({styles: styles});
                                            google.maps.event.addListener(map, 'bounds_changed', function () {
                                                try {
                                                    var zoom = map.getZoom();
                                                    var bounds = map.getBounds();
                                                    var ne = bounds.getNorthEast();
                                                    var sw = bounds.getSouthWest();
                                                    var msg = 'gmb=' + ne.lat() + ',' + ne.lng() + ',' + sw.lat() + ',' + sw.lng() + ',' + zoom;
                                                    if (initialBounds === null) {
                                                        initialBounds = bounds;
                                                    } else {
                                                        var link = '<?php echo site_url('zarwrite/gmap?'); ?>' + msg;
                                                        h2o.action(link, function (result) {
                                                            if (result.success) {
                                                                $('.googlemap .title').html(result.data);
                                                            }
                                                        });
                                                    }
                                                } catch (err) {
                                                    alert(err);
                                                }
                                            });
                                        }
                                        google.maps.event.addDomListener(window, 'load', initialize);
                                    </script>