Posted 2 months ago

#Social #Startup #nackt. #Fairnopoly - konsequent #transparent.

Posted 1 year ago

Using Appcelerator Titanium with Vim commands

You might belong to the majority of people who can only wonder why, oh WHY, some #?@! nutheads decide to use vi. Or you might already be converted and try to find ways to use similar commands in all kinds of different places. Did you know you can even control firefox with vi-like commands?

Well, I recently got into programming iOS/Android apps with Titanium. It’s a really neat IDE. Based on Eclipse … so how bad can it be right? Not bad at all. If only getting around the code wasn’t so tedious (at least when compared to good old vi editing).

Well, there’s a pretty simple way to get your precious Escape-key back. The answer is called Vrapper.

Here’s what you do:

1. Start up Titanium

2. In the menu bar go to “Help” -> “Install new Software…”

3. After the “Work with:” field click on “Add…”

4. For the location enter:

5. Click OK. Make sure your new addition is selected in the “Work with:” field.

6. Wait a moment for Titanium to pull the data.

7. Select Vrapper as soon as it shows up in the field below.

8+ The rest is basically just accepting to the terms and clicking “Next” a few times. Restart Titanium, open a file, hit Esc and breathe a deep breath of victory.

It’s not actually vim, just edited Eclipse commands and navigation to feel like vim. Still, good enough for me.


PS: Wanna get started with vim? When you have it installed, open a console, type ‘vimtutor’, and practice, practice, practice.

Posted 1 year ago
Okay, I tried implementing the mathcaptcha component with Cakephp 2.0 and received an illegal offset error message. I narrowed down the problem to the component inclusion in the controller public $components = array('MathCaptcha', array('timer' => 3)). When I removed the timer array, the problem went away. Is there another way to include the timer without causing this error to occur?
eldorado2768 asked

Could this be related to this issue?

Otherwise it’s hard to answer you without knowing your exact code. If you really did nothing else in regards to the component I unfortunately can’t reproduce your error.

Posted 1 year ago

CakePHP 2 - Sessions are not persisting between actions/controllers

When migrating a project from 1.3 to 2.0 I just had the strangest problem: Suddenly sessions would be deleted the instant a redirect or page switch would happen.

Looking around on the internet the most common solution suggestion was to check the rights of the tmp folder, clearing the tmp folder, checking Session settings in the config .. but none of that helped me.

Well, long story short: It turns out that in 2.0 you can’t call $this->Session->destroy(); right before another $this->Session->write(…);

This was done in the project to clear out residual session variables. Destroy should start a fresh session, but it turns out it’s not that quick. Using $this->Session->delete(…);instead it works again.

Yes, I am aware that you would actually use the AuthComponent for most of that stuff. But that’s for later to implement.

Hope that helped someone out there.

Posted 2 years ago

CakePHP - Generating Unique Slugs

This is about a code snippet I use in a project to generate a unique string that is

  • search engine optimized
  • url-safe
  • readable by humans

Those are generally called “slugs” and used to get urls for posts by their title.

The original code was published by Harmen Janssen a few years ago on his blog and Harmen, I hope you read this through a trackback or so. I would just have written this in your comments but you disabled them.

Anyway, this is the original code:

class AppModel extends Model {
function createSlug ($string, $id=null) {
$slug = Inflector::slug ($string,'-');
$slug = low ($slug);
$i = 0;
$params = array ();
$params ['conditions']= array();
$params ['conditions'][$this->name.'.slug']= $slug;
if (!is_null($id)) {
$params ['conditions']['not'] = array($this->name.'.id'=>$id);
while (count($this->find ('all',$params))) {
if (!preg_match ('/-{1}[0-9]+$/', $slug )) {
$slug .= '-' . ++$i;
} else {
$slug = preg_replace ('/[0-9]+$/', ++$i, $slug );
$params ['conditions'][$this->name . '.slug']= $slug;
return $slug;

However, there is a problem with it. It sucks. Sorry :-)

My main beef with it:

  1. It has 2 regex calls where none is needed. Regexes are pure resource hogs and should be avoided wherever possible.
  2. No need to trouble the database by retrieving all the fields all of the time, you basically need one, sometimes two.
  3. low()? Never heard of it, if it was ever a function in cakePHP it’s not supported anymore. I’m gonna assume you meant strtolower().

Here my revised version:

private function createSlug($string, $id = null) {
    $slug = Inflector::slug($string, '-');
    $slug = strtolower($slug);

    $i = 0;
    $params = array(
      'conditions' => array($this->name.'.slug' => $slug),
      'fields' => array($this->name.'.id', $this->name.'.slug'));

    if (!is_null($id))
      $params['conditions']['not'] = array($this->name.'.id'=>$id);

    while (count($this->find('all', $params)))  {
      $params['conditions'][$this->name . '.slug'] = $slug."-".$i;
    if ($i) $slug .= "-".$i;

    return $slug;

Works in CakePHP 2 but should work in 1.3 and 1.2 as well. Have fun! And if you want a more detailed explanation of the underlying principles used in that code, check out Harmen’s blog.

Posted 2 years ago

List of Valid and Invalid Email Addresses

For my own and your reference when testing email regexes or other email validation processes, here a copy&paste list of test samples:

Thanks goes out to who published a major part of this list on the msdn blog, unfortunately it’s in a table there so you can’t just copy & paste them. That’s why I’m saving this here. If you want to know why those emails are valid or invalid, check out his post.

Stranger valid and invalid email addresses where copied directly from Wikipedia.

List of Valid Email Addresses

List of Strange Valid Email Addresses

much.”more\ unusual”
very.”(),:;<>[]”.VERY.”very@\\ "very”

List of Invalid Email Addresses

Joe Smith <>
あいうえお (Joe Smith)

List of Strange Invalid Email Addresses

this\ is"really"not\

And there you have it.

Finally for your pleasure here a php code snippet to test your regex against. Feel free to just copy the array where I have already put in the escaping backslashes and build your own tests around it.

$emails = array(

    'much."more\ unusual"',
    'very."(),:;<>[]".VERY."very@\\\\\\ \"very"',

    'Joe Smith <>',
    ' (Joe Smith)',

    'this\ is\"really\"not\\\\'

foreach ($emails as $email) {
    if (preg_match("/YOURREGEX/", $email))
        echo "<div style='color:green'>".$email." is valid.</div>";
        echo "<div style='color:red'>".$email." is invalid.</div>";

PS: Yes, email addresses are a pain in the behind to validate. Wanna see the perfect regex for email addresses? Here it is.

Wanna see the second best email regex? Here you go: /^.+@.+\..+$/
It basically says “There is an at-sign, a period, stuff before/after/between them, and no line breaks.” Of course that’s just my personal opinion.

If someone wants to spam your form, they will do so regardless of your precious regex. - There you go. And really, how often have you mistyped your email address and a form validation helped you see it? I know I never have.

But that list is good for other stuff as well. Right now I’m generating default usernames from the emails people put in. That’s why I made that list to begin with. Anyway, I’m off!

Posted 2 years ago

CakePHP - disable SecurityComponent for a single action

It took me surprisingly long to figure this out and in the end the solution was so simple that I’m almost embarrassed to post this here.

Well, mainly it took me so long because I banged my head against the wall when neither

$this->Security->checkCSRF = false;


$this->Security->validatePost = false;

stopped the component from black-holing my call from an external API (called by a Flash AS3 swf) every freaking time, not even when those where set in the AppController’s beforeFilter.

Well, in the end I simly disabled the component for that request and everything’s fine.

Following code applies to CakePHP 2:

// in Controller’s beforeFilter
if(‘actionname’ == $this->request->params[‘action’])

Please tell me I’m not the only dumb fudge who couldn’t think of this right away

Posted 2 years ago

CakePHP 2 - Link Helper, give Html->Link classes based on their relation to the currently opened page

It’s surprising that this isn’t something already buildt into CakePHP from the get go: The ability to create links but have them markers for CSS styling based on their relation to the currently opened page.

But it apparently isnt, so here is a nice little helper for this. Just use $this->Link->link(…); instead of $this->Html->link(…);

Nearly all the credit goes to Richard and the user Rajesh Sharma and Leimi who commented on Richard’s blog. I basically switched just a few lines around to make it CakePHP 2.0 compliant. I haven’t thoroughly tested it, as it is it works for what I’m doing at the moment. If I run into troubles and fix them, I’ll update the script on here.

<?php class LinkHelper extends AppHelper {
	var $helpers = array(
	function link($title, $url = null, $htmlAttributes = array(), $confirmMessage = false, $escapeTitle = true) {
			// parse the current url into its components
			$here = $this->params->params);
			// parse the destination url into its components
			if (is_array($url)) {
				$destination = $url;
			else {
				$destination = Router::parse($url);
			if (!isset($destination['controller'])) {
				$destination['controller'] = $this->params['controller'];
			$class = "";
			if ($here['controller'] == $destination['controller']) {
				// link is to another action within this controller
				$class .= " current_controller";
				if ($here['action'] == $destination['action']) {
					// link is to the current action in this controller
					$class .= " current_action";
					if(isset($here['pass']) && !empty($here['pass'])){
						$match = false;
						foreach($here['pass'] as $key => $val){
							if(isset($destination['pass'][$key]) && $destination['pass'][$key] == $val){
								$match = true;
								$match = false;
							$class .= " active withallmatch";
						$class .= " active";
				if (isset($htmlAttributes['class'])) {
					// we already have a class attribute, append our classes
					$htmlAttributes['class'] .= $class;
				else {
					// class not set, add ours
					$htmlAttributes['class'] = trim($class);

               if ($here['action'] == $destination['action']) {
                    // link is to the current action in this controller
                   $class .= " current_action";
                   if ($here['action'] == 'view') {
                        if ($here['slug'] == $destination['slug']) {
                            $class .= " current_view"; 
			// build the link
			$link = $this->Html->link($title, $url, $htmlAttributes, $confirmMessage);
			// return the link
			return $this->output($link);

Again, thanks Richard, Rajesh and Leimi and as always if you find any bugs, please report them in the comments.

Edit: There was indeed a bug that didn’t give all active links the active class. Now it should work.

Posted 2 years ago

Browser Addon: Markdown Viewer

MarkupViewer Icon

Download Page:

Fed up with only being able to see the finished markdown of my readmes AFTER I have uploaded it somewhere, I developed a firefox addon that lets me view converted markdown right in my browser. It took me the whole day … and a very helpful answer by canuckistani on stackoverflow.

A basic screenshot

Just click the widget icon on a .md or .markdown file and see it work it’s wonders. Careful though: Just use it on real markdown files. Anywhere else it will screw up the current website-view (it’s only enabled on markdown files but some pages on websites like github or google code pretend to be markdown files when they really aren’t).

If you find any bugs, please report them here.

Posted 2 years ago

CakePHP 2 - Simple Math Captcha Component


Download at:

A few years ago Jamie Nay published a cakephp 1.2 component with the caption:

I don’t like CAPTCHAs. I don’t know anyone who does. But most forms need some sort of protection against spam, especially where heavyweight spam detection services (e.g. Akismet) aren’t suitable. The downfalls of CAPTCHAs are many – hard to read, annoying, impossible for those with vision difficulties – and the benefits are slim. So, a few months ago I wrote a little function (and I do mean little – like 10 lines of code) to generate a random math question to ask the user in plain text instead of a CAPTCHA. The idea was that a bot wouldn’t be able to answer it, since it requires some human logic. And you know what? It worked – spam went way down on our websites.

I liked the idea but didn’t like some of the workings inside the component. Also it didn’t work for cakePHP 2 unmodified.

Sooo I wrote my own component that uses some of Jamie’s code and also changes the wording of the math problem with every reload, has a timer functionality and can detect words such as “five” as correct answers instead of just “5”.

You can download it from my git repo, link is at the very top of this article.


Simply copy the MathCaptchaComponent into your app/Controller/Component directory.

Make sure to include public $components = array('MathCaptcha'); into every Controller you want to use this from.


In any controller that uses this component you can call $this->MathCaptcha->getCaptcha(); and it will return a randomly generated and always differently phrased math problem.

By default the answer will automatically be saved as a session variable and can be checked in the next step with $this->MathCaptcha->validate($data); This returns true if the answer is correct. By default the function allows loose validation, so if the user typed “one” instead of “1” the answer will also be correct.

Finally you can also set some options when instantiating the component. Do this by giving extra parameters in the $components, like this:

public $components = array(
    'MathCaptcha' => array(
        'setting' => 'value',
        'setting2' => 1));

Available settings with their defaults are:

  • 'timer' => 0 - Sets the seconds after which a correct answer becomes valid. Generally automated bots will submit forms a lot faster than a human ever could.

  • 'autoload' => false - Setting this to true will cause a captcha to be generated as soon as the component is instanciated. Generally this isn’t necessary anymore since the last changes and is therefore deprecated.

  • 'godmode' => false - This feature allows you to pass any captcha by answering “42”. This is useful for the development phase when you do manual testing.

For more advanced options please check the documentation inside the source code.


In the controller:

class UsersController extends AppController
    public $name = 'Users';
    public $components = array('MathCaptcha', array('timer' => 3));

    public function add() {
        $this->set('captcha', $this->MathCaptcha->getCaptcha());

    if ($this->request->is('post')) {
      if ($this->MathCaptcha->validate($this->request->data['User']['captcha'])) {
      } else {
        $this->Session->setFlash('The result of the calculation was incorrect. Please, try again.');

And in the View:

// Users/add.ctp
echo $this->Form->create('User');
# ...
echo $this->Form->input('captcha', array('label' => 'Calculate this: '.$captcha));
echo $this->Form->end('Submit');