Archive for the ‘Development’ Category

Effectively repair MySQL Tables

on Wednesday 27th January, 2010 Gabe speculated thusly…

$ cd /var/lib/mysql

find -type f -name '*.MYI' -exec myisamchk --silent --force --fast --update-state --key_buffer_size=64M --sort_buffer_size=64M --read_buffer_size=1M --write_buffer_size=1M {} \;

Posted in Development, HowTo, Information, Linux, MySQL, Operating System, Programming

No Comments »

Access denied for user ‘debian-sys-maint’@'localhost’ (using password: YES)

on Tuesday 26th January, 2010 Gabe speculated thusly…

Find your debian-sys-maint password in /etc/mysql/debian.cnf.

GRANT ALL PRIVILEGES ON *.* TO 'debian-sys-maint'@'localhost' IDENTIFIED BY ' ' WITH GRANT OPTION;

Replace with your debian-sys-maint password.

Posted in Debian, Development, MySQL, Operating System, Ubuntu

No Comments »

Creating a PHP array of ISO 3166-1 Country Codes

on Thursday 7th January, 2010 Gabe speculated thusly…

I recently came across http://opencountrycodes.appspot.com/ which has an ISO 3166-1 list of country codes for various programming languages. I wanted to generate an HTML drop down list for customer to choose from based on these codes. However, there is no PHP version provoided. So taking the XML version found at http://opencountrycodes.appspot.com/xml/ I made a trivial script that would take the codes found in the XML document and organise them in to a PHP array called $XML2PHPCountryCodes and save that array in a file called country_names.php. The output file can then be included in any PHP script making the contained array available.

< ?php
$str = file_get_contents('http://opencountrycodes.appspot.com/xml/');
$xml = new SimpleXMLElement($str);
$out = '$countries'." = array(\n";
foreach ($xml->country as $country)
{
	$out .= "'{$country['code']}' => \"{$country['name']}\",\n";
}
$out .= ");";

file_put_contents('country_names.php', $out);

Posted in Development, PHP, Programming

4 Comments »

Bzr over SMB/CIFS using SMBMOUNT

on Wednesday 16th September, 2009 Gabe speculated thusly…

Ensure that the remote uig and gid are set correctly!

smbmount //foo/bar /media/bar -o username=myusername, password=mypassword, dir_mode=0755, file_mode=0664, noperm, uid=501, gid=501

Posted in Bazaar, Development, Programming, Revision Control, Server

No Comments »

CodeIgniter 1.7: The URI you submitted has disallowed characters.

on Tuesday 14th July, 2009 Gabe speculated thusly…

I was getting the above error from CodeIgniter after urlencoding some base64 encoded binary data and passing it as a URI parameter to CodeIgniter. I looked in the config.php file and found that percent signs were allowed here:
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';

After some hunting around I found that CodeIgniter is not accepting this in the URI because the actual characters (that are encoded) fall outside the ASCII range. CodeIgniter is actually decoding the characters before testing them. The fix was quite simple, open up libraries/URI.php and go to line 189 where it says:
if ( ! preg_match("|^[".preg_quote($this->config->item('permitted_uri_chars'))."]+$|i", $str))
and change it to:

if ( ! preg_match("|^[".preg_quote($this->config->item('permitted_uri_chars'))."]+$|i", rawurlencode($str)))

Basically wrapping $str in the urlencode() function.

Posted in CodeIgniter, Development, Frameworks, Information, Programming

6 Comments »

Apache Virtual Hosts on OS X Leopard

on Sunday 31st May, 2009 Gabe speculated thusly…

If you develop multiple sites and you need virtual hosting functionality, scroll down to the end of the /private/etc/apache2/httpd.conf file and uncomment the following:

# Include /private/etc/apache2/extra/httpd-vhosts.conf

Next, you’ll need to setup whatever virtual hosts you have in the virtual hosts file /private/etc/apache2/extra/httpd-vhosts.conf

You need to make an entry in the httpd-vhosts.conf file like so:

<virtualhost *:80>
   ServerName beta-site-1.com
   ServerAlias www.beta-site-1.com
   ServerAdmin webmaster@beta-site-1.com
   ErrorLog "/private/var/log/apache2/dummy-host2.example.com-error_log"
   CustomLog "/private/var/log/apache2/dummy-host2.example.com-access_log" common

   DocumentRoot "/Library/WebServer/beta-site-1"
   ScriptAlias /cgi-bin/ "/Library/WebServer/beta-site-1/cgi-bin"
   
     Options FollowSymLinks MultiViews Includes
     AllowOverride All
     Order allow,deny
     Allow from all
   
</virtualhost>

The examples provided by Apple in the vhosts file are slightly incorrect and if you use the CustomLog lines as is you will get errors the following errors if you run: apachectl -t -D DUMP_VHOSTS:
Syntax error on line 40 of /private/etc/apache2/extra/httpd-vhosts.conf:
CustomLog takes two or three arguments, a file name, a custom log format string or format name, and an optional "env=" clause (see docs)

This is because
CustomLog "/private/var/log/apache2/dummy-host.example.com-access_log common

Should actually read:
CustomLog "/private/var/log/apache2/dummy-host.example.com-access_log" common

Posted in Development, Frameworks, HowTo, Information, Leopard, Linux, Operating System, OS X, PHP, Server, Ubuntu

2 Comments »

An alternative img() helper function for CodeIgniter

on Wednesday 20th May, 2009 Gabe speculated thusly…

It is my opinion that CodeIgniter’s default img() function that comes in the HTML Helper could have been easier to use. As it is if you want to give your image a name css class you have to define an array consisting of these attributes.

That takes up space and makes the code less readable for non-PHP programmers. Since I work closely with a web designer who is good with HTML but gets lost in PHP I want to leverage the pragmatic power of PHP to automate repetitive tasks (like typing out an entire HTML image tag), but at the same time the result needs to be obvious to a non-programmer but also shorter than the HTML equivalent. I feel the img() helper in CodeIgniter falls short of both these requirements.

CodeIgniter’s img() helper also takes a second parameter, a boolean, this decides whether the index.php file is included in the image path, good if you are using a media controller. For 99.9% of my sites I don’t need these. Therefore I wrote my own helper.

The file is called MY_html_helper.php and lives inside the folder system/application/helpers. As with other extensions to the CI core the prefix MY_ is determined in your config file, so change MY_ to whatever it should be. Add the following code to the file:

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

function img($imgName, $attrs=FALSE)
{
	$CI =& get_instance();

	if (strpos($imgName, 'http') === 0) return;

	$imgPath = $CI->config->item('base_url');

	if ( ! $imgDir = $CI->config->item('image_dir')) $imgDir = 'assets/images/';

	$img = $imgPath.$imgDir.$imgName;

	$str = '<img src="'.$img.'" ';

	if ($attrs) $str .= $attrs." ";

	$str .= "/>";

	return $str;
}

All you have to make sure you do is load the html helper: $this->load->helper('html'); in your controller,
or put it in the array of helpers in system/application/config/autoload.php.

The helper assumes images live in the folder assets/images which lives alongside the system folder. If this is not where you put your images then you can specify an alternative directory in your config.php file. Simply add a line that looks like this to config.php: $config['image_dir'] = 'alternative/path/images/';. Don’t forget the trailing slash at the end. This alternative folder would live at the very top level of your application, alongside index.php.

Using the helper is easy and straightforward: <?=img('example.gif')?>

Will produce <img src="http://mysite.com/assets/images/example.gif" />.

Any additional attributes you want in the html tag can be written as per usual as the second parameter. For example if you want to give the image an alt attribute and class:
<?=img('example.gif', 'class="myclass" alt="Example Image"')?>

Will produce:

<img src="http://mysite.com/assets/images/example.gif" class="myclass" alt="Example Image" />

The only hard part about this is making sure you get the single and double quotes correct in the second parameter.

Cheers

Posted in CodeIgniter, Development, Frameworks, Information, Linux, Operating System, Programming, Server

1 Comment »

Installing Hpricot from Ruby Gems errors out

on Tuesday 31st March, 2009 Gabe speculated thusly…

I was recently trying to get a Ruby script working on Ubuntu. This script required Hpricot and using Ruby Gems to install Hpricot always resulted in an error:

 gem install hpricot --remote
ERROR:  While executing gem ... (Gem::FilePermissionError)
    You don't have write permissions into the /var/lib/gems/1.8 directory.
gabriel@windsor-telecom-2874:~/Music$ sudo gem install hpricot --remote
Building native extensions.  This could take a while...
ERROR:  Error installing hpricot:
	ERROR: Failed to build gem native extension.

/usr/bin/ruby1.8 extconf.rb install hpricot --remote
extconf.rb:1:in `require': no such file to load -- mkmf (LoadError)
	from extconf.rb:1

Gem files will remain installed in /var/lib/gems/1.8/gems/hpricot-0.7 for inspection.
Results logged to /var/lib/gems/1.8/gems/hpricot-0.7/ext/hpricot_scan/gem_make.out

The answer was simple:
sudo aptitude install ruby-dev

Just install the Ruby Dev package, this will also allow you to install lots of other gems such as SQLite3, etc.

Posted in Development, Ruby, Ubuntu

1 Comment »

Recursive text find and replace in linux

on Thursday 29th January, 2009 Gabe speculated thusly…

Always forget how to do this:
find ./ -type f -exec sed -i.bk ’s/string1/string2/g’ {} \;

Posted in Development, HowTo, Information, Linux, Operating System

No Comments »

Making CodeIgniter’s Profiler AJAX compatible

on Tuesday 13th January, 2009 Gabe speculated thusly…

Modern web applications almost all make use of AJAX to enhance their user appeal. However, AJAX can be hard to debug, especially when all the traditional tools do little to help. When doing standard PHP coding CodeIgniter (CI) offers a profiler which will be appended to the bottom of generated pages. This gives you information on the request that was recently processed, including any POST or GET values passed to the script, how long execution took and how long any SQL queries took as well as what those queries actually were. During development I find this information indispensable to make sure my SQL queries are correct and things are working as I want.

However, when coding up AJAX aspects of the application this doesn’t work very well, any page fragments fed back to the JavaScript will have the profiler stuck at the bottom, and since these fragments are usually inserted inside DIVs the profiler cannot be read in it’s entirety, or it breaks the layout, or more likely, both of the above. Therefore I set out to find a way of making it AJAX compatible, so that it would always end up at the bottom of the page, even when it was originally returned appended to a page fragment. In the end this turned out easier than anticipated.

One small change needs to be made to your footer, you need to create an empty div with an ID of “debug”, this div will hold the profiler, so place the div where you want the profiler. The advantage with this is that you cannot see it when it is empty so it could even be left in for production code. The div looks like this:
<div id="debug"></div>

Now we need to extend, or rather override the CI profiler so create the file system/application/libraries/MY_Profiler.php

Replace MY_ with the value of $config['subclass_prefix'] found in your config file, by default it is MY_.

Next paste the following code in to it. Remember to change the name of the class as dictated by the filename you use, also change the name of the constructor function too. You can also change the script line to load the jQuery library from one of your servers, or even rewrite the entire script section to use any JavaScript you like.

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

class MY_Profiler extends CI_Profiler
{
    function MY_profiler()
    {
        parent::CI_Profiler();
    }

    function run()
    {
            $output = <<<ENDJS
<script src="http://code.jquery.com/jquery-latest.js" />
<script type="text/javascript" language="javascript" charset="utf-8">
// < ![CDATA[
    $(document).ready(function() {
        var html = $('#codeigniter_profiler').clone();
        $('#codeigniter_profiler').remove();
        $('#debug').hide().empty().append(html).fadeIn('slow');
    });
// ]]>
</script>
ENDJS;
            $output .= "<div id='codeigniter_profiler' style='font-size: 0.7em; clear:both;background-color:#fff;padding:10px;'>";
            $output .= $this->_compile_uri_string();
            $output .= $this->_compile_controller_info();
            $output .= $this->_compile_memory_usage();
            $output .= $this->_compile_benchmarks();
            $output .= $this->_compile_get();
            $output .= $this->_compile_post();
            $output .= $this->_compile_queries();
            $output .= '</div>';
            return $output;
    }
}

If you have already loaded a jQuery library in your header somewhere then make sure this ajax fragment doesn’t load jQuery again – otherwise all your event bindings and everything else will fail. If this is the case simply remove the line:

<script src="http://code.jquery.com/jquery-latest.js" />

From the above code.

That should be it, hit me back if you have any feedback, questions, or need some help.

Posted in CodeIgniter, Development, Frameworks, Operating System, PHP, Programming

9 Comments »