codeigniter, JavaScript, jquery

Integrating Elfinder and ckeditor


1. In view file

// link the required js and css

<script src=”<?php echo assets_url( ‘admin/lib/jquery-1.7.2.min.js’ );?>” type=”text/javascript”></script>
<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js”></script&gt;
<link rel=”stylesheet” type=”text/css” media=”screen” href=”<?php echo assets_url( ‘js/plugins/elfinder/css/elfinder.min.css’ );?>”>
<link rel=”stylesheet” type=”text/css” media=”screen” href=”<?php echo assets_url( ‘js/plugins/elfinder/css/theme.css’ );?>”>

<script src=”<?php echo assets_url( ‘js/plugins/ckeditor/ckeditor.js’ );?>”></script>
<script src=”<?php echo assets_url( ‘js/plugins/ckeditor/ckeditor.js’ );?>”></script>
<script src=”<?php echo assets_url( ‘js/plugins/ckeditor/adapters/jquery.js’ );?>”></script>
<script src=”<?php echo assets_url( “js/plugins/elfinder/js/elfinder.min.js” ) ?>”></script>

2. initialize the elfinder

<script type=”text/javascript”>
    $(document).ready(function(){
 // setting base url for javascript [ using codeigniter ]
 var base_url = ‘<?php echo base_url(); ?>’;
// new config for ckeditor dialog box
CKEDITOR.on(‘dialogDefinition’, function (event) {
    var editor = event.editor;
    var dialogDefinition = event.data.definition;
   // var dialogName = event.data.name;
    var dialogName = “image”;
    var tabCount = dialogDefinition.contents.length;
    for (var i = 0; i < tabCount; i++) { //цикл для замены клика всех кнопок “Посмотреть на сервере”
        var browseButton = dialogDefinition.contents[i].get(‘browse’);
        if (browseButton !== null) {
            browseButton.hidden = false;
            browseButton.onClick = function (dialog, i) {
                $(‘<div id=”elfinderz” \>’).dialog({
                    modal: true,
                    width: “70%”,
                    title: ‘Togally Assets’,
                    dialogClass: “elfinderz-filez”,
                    zIndex: 9999999,
                    create: function (event, ui) {
                        $(this).elfinder({
                            resizable: false,
                            lang: ‘en’,
                            url: base_url + ‘assets/js/plugins/elfinder/php/connector.php?mode=’ + dialogName,
                            getFileCallback: function (url) {
                                var dialog = CKEDITOR.dialog.getCurrent();
                                if (dialog._.name == “image”) {
                                    var urlObj = ‘txtUrl’
                                } else if (dialog._.name == “flash”) {
                                    var urlObj = ‘src’
                                } else if (dialog._.name == “link”) {
                                    var urlObj = ‘url’
                                } else {
                                    return false
                                };
                                dialog.setValueOf(dialog._.currentTabId, urlObj, url);
                                $(‘a.ui-dialog-titlebar-close[role=”button”]’).click();
                return false;
                            }
                        }).elfinder(‘instance’)
                    }
                })
            }
        }
    }
});
// initializing elfinder
$( ‘textarea.editor-ck’ ).ckeditor({height:”500px”})
});
</script>
Resource
=============
// for stand alone purpose with out ckeditor ( in elfinder/elfinder.html )

<script type=”text/javascript” charset=”utf-8″>
// Helper function to get parameters from the query string.
function getUrlParam(paramName) {
var reParam = new RegExp(‘(?:[\?&]|&amp;)’ + paramName + ‘=([^&]+)’, ‘i’) ;
var match = window.location.search.match(reParam) ;

return (match && match.length > 1) ? match[1] : ” ;
}
$().ready(function() {
var funcNum = getUrlParam(‘CKEditorFuncNum’);

var elf = $(‘#elfinder’).elfinder({
url : “http://192.168.123.10/togally-dev/assets/js/plugins/elfinder/php/connector.php&#8221;,
getFileCallback : function(file) {
window.opener.CKEDITOR.tools.callFunction(funcNum, file);
window.close();
},
resizable: false
})
});
</script>

Advertisements
codeigniter, jquery

CodeIgniter Uploadify problem


CodeIgniter Uploadify problem

I tried to implement Uploadify with CodeIgniter upload class, and had some issues with recognising proper mime types.

First issue was solved by extending application/config/mimes.php with code:

1 'gif'   =>   array('image/gif','application/octet-stream'),
2 'jpeg'  =>   array('image/jpeg', 'image/pjpeg', 'application/octet-stream'),
3 'jpg'   =>   array('image/jpeg', 'image/pjpeg', 'application/octet-stream'),
4 'jpe'   =>   array('image/jpeg', 'image/pjpeg', 'application/octet-stream'),
5 'png'   =>   array('image/png''image/x-png', 'application/octet-stream'),

You also need to extend Upload.php by uploading this extension:
Download
to application/library

Result from controller should looks like this

1   if ( ! $this->upload->do_upload('Filedata')) {
2                 $error = array('error' => $this->upload->display_errors());
3         } else {
4                 $data = $this->upload->data();
5         }
6 $return = array('name' => $data['file_name'],
7                 'size' => round($data['file_size'] * 100),
8                 'type' => $data['file_type']);
9 echo json_encode(array('Filedata' => $return));
codeigniter, mysql, php

Exporting your MySQL table data with PHPExcel + CodeIgniter


Exporting your MySQL table data with PHPExcel + CodeIgniter

http://www.facebook.com/plugins/like.php?channel_url=https%3A%2F%2Fs-static.ak.fbcdn.net%2Fconnect%2Fxd_proxy.php%3Fversion%3D3%23cb%3Df195a68dc416bf4%26origin%3Dhttp%253A%252F%252Fwww.dannyherran.com%252Ff100e4067be86da%26relation%3Dparent.parent%26transport%3Dpostmessage&extended_social_context=false&href=http%3A%2F%2Fwww.dannyherran.com%2F2011%2F03%2Fexporting-your-mysql-table-data-with-phpexcel-codeigniter%2F&layout=button_count&locale=en_US&node_type=link&sdk=joey&show_faces=false&width=90 http://platform.twitter.com/widgets/tweet_button.html#_=1323938558067&_version=2&count=horizontal&enableNewSizing=false&id=twitter-widget-0&lang=en&original_referer=http%3A%2F%2Fwww.dannyherran.com%2F2011%2F03%2Fexporting-your-mysql-table-data-with-phpexcel-codeigniter%2F&size=m&text=Exporting%20your%20MySQL%20table%20data%20with%20PHPExcel%20%2B%20CodeIgniter&url=http%3A%2F%2Fwww.dannyherran.com%2F2011%2F03%2Fexporting-your-mysql-table-data-with-phpexcel-codeigniter%2F&via=DannyHerran

 

PHPExcel + CodeIgniter Most of the time my clients need to download data from their database tables. Exporting to CSV is a pain in the rear for users and it leads to confusion (you know the colon and semicolon stuff). Today, I decided to make a very small controller that is portable and efficient for exporting full MySQL tables to Excel 2003 using PHPExcel and CodeIgniter.

First of all, you need PHPExcel which should be installed as a CodeIgniter library. In order to do this, you should follow the steps posted in the CodeIgniter Wiki.

Once you have PHPExcel installed and configured, make a controller exactly like this one:

Code:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class Table_export extends Controller {
    function __construct()
    {
        parent::Controller();
        // Here you should add some sort of user validation
        // to prevent strangers from pulling your table data
    }
    function index($table_name)
    {
        $query = $this->db->get($table_name);
        if(!$query)
            return false;
        // Starting the PHPExcel library
        $this->load->library('PHPExcel');
        $this->load->library('PHPExcel/IOFactory');
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->getProperties()->setTitle("export")->setDescription("none");
        $objPHPExcel->setActiveSheetIndex(0);
        // Field names in the first row
        $fields = $query->list_fields();
        $col = 0;
        foreach ($fields as $field)
        {
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, 1, $field);
            $col++;
        }
        // Fetching the table data
        $row = 2;
        foreach($query->result() as $data)
        {
            $col = 0;
            foreach ($fields as $field)
            {
                $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $data->$field);
                $col++;
            }
            $row++;
        }
        $objPHPExcel->setActiveSheetIndex(0);
        $objWriter = IOFactory::createWriter($objPHPExcel, 'Excel5');
        // Sending headers to force the user to download the file
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="Products_'.date('dMy').'.xls"');
        header('Cache-Control: max-age=0');
        $objWriter->save('php://output');
    }
}

Whenever you need to export data from a MySQL table, you just need to call this controller and pass the table name as a parameter, sort of like http://www.yoursite.com/table_export/products. Obviously, you should always add some sort of security measure in order to prevent strangers from pulling all your table information. Just add some session protection to your constructor and you’re set.

codeigniter, php

renaming file and folders name with codeigniter


if ( ! $this->upload->do_upload())
{
return $this->upload->display_errors();
}
else
{
$res = $this->upload->data();

$file_path     = $res[‘file_path’];
$file         = $res[‘full_path’];
$file_ext     = $res[‘file_ext’];

$final_file_name = time().$file_ext;
 

// here is the renaming functon
rename($file, $file_path . $final_file_name);

}

codeigniter

Easy Reverse Routing with CodeIgniter


Easy Reverse Routing with CodeIgniter

By Kenny Katzgrau | Published: September 21, 2010

I really can’t stand hard-coding URLs in the views or controllers of my application — and I’m sure most other people can’t either. Here’s an extension for the CodeIgniter Router class that I wrote that gives you a nice way to write routes that are reversible and also have the ability to take parameters.

<?php

class MY_Router extends CI_Router
{
    private $_reverseRoutes = NULL;

    CONST ARR_ROUTE_POS      = 0;
    CONST ARR_ROUTE_NAME_POS = 1;

    function _parse_routes()
    {
		// Do we even have any custom routing to deal with?
		// There is a default scaffolding trigger, so we'll look just for 1
		if (count($this->routes) == 1)
		{
			$this->_set_request($this->uri->segments);
			return;
		}

		// Turn the segment array into a URI string
		$uri = implode('/', $this->uri->segments);

		// Is there a literal match?  If so we're done
		if (isset($this->routes[$uri]))
		{
			$this->_set_request(explode('/', $this->routes[$uri][self::ARR_ROUTE_POS]));
			return;
		}

		// Loop through the route array looking for wild-cards
		foreach ($this->routes as $key => $val)
		{
			// Convert wild-cards to RegEx
            //echo "$key --> ";
			$key = preg_replace('/\:\w+/', '[\w\-_]+', $key);
            //echo "$key <br />";
			// Does the RegEx match?
			if (preg_match('#^'.$key.'$#', $uri))
			{
				// Do we have a back-reference?
				if (strpos($val[self::ARR_ROUTE_POS], '$') !== FALSE AND strpos($key, '(') !== FALSE)
				{
					$val = preg_replace('#^'.$key.'$#', $val[self::ARR_ROUTE_POS], $uri);   
				}

				$this->_set_request(explode('/', $val));
				return;
			}
		}

		// If we got this far it means we didn't encounter a
		// matching route so we'll set the site default route
		$this->_set_request($this->uri->segments);
    }

    function _buildReverseRoutes()
    {
        $reverse_routes = array();

        foreach($this->routes as $route => $info)
        {
            # If this is a default route or scaffolding key, ignore it
            if(!is_array($info)) continue;

            $name = $info[self::ARR_ROUTE_NAME_POS];
            $reverse_routes[$name] = $route;
        }

        $this->_reverseRoutes = & $reverse_routes;
    }

    function reverseRoute($route_name, $args_keyval = array())
    {
        if($this->_reverseRoutes === NULL)
            $this->_buildReverseRoutes();

        if(!array_key_exists($route_name, $this->_reverseRoutes))
            show_error("No reverse route found for '$route_name'");

        $route = $this->_reverseRoutes[$route_name];

        foreach($args_keyval as $key => $val)
        {
            $route = str_replace("(:$key)", $val, $route);
        }

        return $route;
    }
}

Drop that into application/libraries, then rewrite your routes to look like this:

$route['users/(:username)']  = array('users/$1', 'user-homepage');
$route['companies/(:slug)']  = array('companies/$1', 'company-homepage');

Let me explain that.

CodeIgniter lets you use wildcards in your routes like (:any) or (:num). That’s no more with this extension. Basically, anything you put in (:[name]) format with be treated like (:any). That’s handy, and I’ll tell you why.

Once you rewrite you routes, you can now call a new method on the routing class when you need to, say, redirect the user to his homepage after login:

  # login was successful, and we now have a $user object
  $this->load->helper('url');
  redirect($this->router->reverseRoute('user-homepage', array('username' => $user->username));

The reverseRoute method takes two parameters: The route you want to send the use on, and any wildcards that you need to fill in the url. For the user-homepage route, there is a (:username) wildcard in the route. We can pass the appropriate fill-in for that wilcard with the second parameter with an associative key-value array.

A redirect to a company-homepage would look like:

  # ...
  redirect($this->router->reverseRoute('company-homepage', array('slug' => $company->slug));

Then in the future, if you feel like changing your routes, go no further than the routes file! Mucking around in views is a recipe for broken links.

 

source:

http://codefury.net/2010/09/easy-reverse-routing-with-codeigniter/

 

codeigniter

MSSQL Server 2005 and CodeIgniter


MSSQL Server 2005 and CodeIgniter

During development work on one of our larger projects, we uncovered some rather alarming problems when using php_mssql.dll in conjunction with SQL Server 2005 Express. Just by perusing some of the comments over at the PHP manual, you can see that we weren’t alone.

Refreshing the page would cause the mssql_connect function to fail. A further three or four refreshes would result in further failures, until suddenly one more refresh manages to establish a connection. This situation would repeat itself, and is completely random. Despite months of trying to track it down when we had spare time, we just could not get to the bottom of it.

A few months ago, a result began cropping up on Google that appeared to contain some answers. Part of Microsoft’s data programmability team announced they were working a new driver for PHP for use with SQL Server 2005. Excellent, we thought! Of course, we haven’t been able to use this driver in a production environment yet as it is still in beta and subject to change (and change it has). However, we’ve ran tests using the driver and so far, it does appear to be more stable. The only issue is that the symptom we were experiencing is very difficult to replicate (if nigh-on impossible), and so we cannot know for sure if the driver has alleviated the problem.

Parts of the project are written using an excellent framework known as CodeIgniter. We took the liberty of also writing an php_sqlsrv.dll compatible driver for it which you can download here. To use the driver, just unzip it into a folder called “system/database/drivers/sqlsrv” and change your database.php to reflect the changes (change the driver to “sqlsrv“). Hopefully this will help one person that was in the same boat as us!

The Microsoft SQL Server 2005 driver for PHP is a PHP 5 only extension. It allows the reading and writing of SQL Server data from within PHP scripts. The extension provides a procedural interface for accessing data in all editions (importantly, including Express) of SQL Server 2005 and also SQL Server 2000. The API makes use of PHP features such as PHP streams to read and write large objects.

 

reference:

http://www.kaweb.co.uk/blog/mssql-server-2005-and-codeigniter/