Tony Thomas

Father to two, husband to one, web developer and musician.


Archive for the ‘CakePHP’ Category


An Unexpected Problem with CakePHP and Email Elements

Monday, May 24th, 2010

For several months now I’ve been triggering functions in my CakePHP controllers using crontabs. It’s especially handy for summarizing data and sending out reports via email. I’m about to change jobs and I’m trying to set up as many systems as I can to help staff manage our data after I leave. Part of that means writing a few more crons to send out more emails. Today while trying to do just that, I ran into something unexpected that held me up for an hour or so until I had an epiphany on my way home. For the purposes of this post, I’m assuming you’ve already set up a cron dispatcher and know how to trigger cron jobs.

For one more week I’m working in a research clinic. One of the things we need to keep track of is who is late in getting us a sample. We need to check for blood and throat samples (which come from swishing some saline around in the mouth). This can be done by hand, but soon the study will grow and the number of participants will make that hard to manage. So I just want to check to see who is late and send out an email to staff to let them know.

This function exists in my Patient controller: (more…)

CakePHP: Containable Behavior is Your Friend

Thursday, February 18th, 2010

When it comes to optimizing your CakePHP queries, you need to abandon Recursive and adopt Containable.

In the example below I have the following models:

  • Patient
  • Specimen
  • Result
  • ResultType

The associations in the model are:

  • Result
    • belongsTo
      • ResultType
        • hasMany
          • Result
      • Patient
        • hasMany
          • Result
          • Specimen
      • Specimen
        • belongsTo
          • Patient
        • hasMany
          • Result

(more…)

Simple Security in CakePHP

Wednesday, July 22nd, 2009

When I started to dig in to investigate using the Security Component of CakePHP, I was a bit daunted. It took me quite a while to get my head around ACL after all. Then I found this article. Here’s the crux:

The Security component will create a hash based on the form fields produced by our Form Helper. If someone tampers with the form fields (by adding or removing or changing any field), the hash is not going to match with the expected one and the add() action will fail.

Yep, it’s that simple.

Really? It just can’t be that easy, can it? Yes. It can. I simply added the Security Component to my controller like so:

var $components = array('Security');

Sure enough, when I reloaded a page with a form in my browser, this hidden field was there:

<input id="TokenFields1483167134" name="data[_Token][fields]" type="hidden" value="f513aebc448fabe42c7feedf31d43fa5bd71ec79%3An%3A0%3A%7B%7D" />

I installed a Firefox Add-on that allowed me to tamper with the POST data, and when I submitted the form, it failed, or in CakePHP terms, it was “Blackholed.” Awesome.

This isn’t going to protect me from all attacks, but it certainly is a good, easy start to implementing security in my application.

CakePHP Console ACL Help File

Sunday, March 22nd, 2009

Every now and then I want to view my help files in pretty, formatted HTML instead of plain text in a text editor or terminal window. Right now I’m working on setting up some Access Control Lists (ACL) in the CakePHP Console. ACL is a powerful, yet sometimes hard-to-grasp concept. I always figure that if I want a resource like this, there has to be someone else out there who does, so for your reference and mine, here it is. (By the way, to get to this from the console, simply type cake acl help.)

Usage: cake acl <command> <arg1> <arg2>...
———————————————–
Commands:

create aro|aco <parent> <node>
Creates a new ACL object <node> under the parent specified by <parent>, an id/alias.
The <parent> and <node> references can be in one of the following formats:

  • – <model>.<id> – The node will be bound to a specific record of the given model
  • - <alias> – The node will be given a string alias (or path, in the case of <parent>),

i.e. ‘John’.  When used with <parent>, this takes the form of an alias path,
i.e. <group>/<subgroup>/<parent>.
To add a node at the root level, enter ‘root’ or ‘/’ as the <parent> parameter.

delete aro|aco <node>
Deletes the ACL object with the given <node> reference (see ‘create’ for info on node references).

setParent aro|aco <node> <parent>
Moves the ACL object specified by <node> beneath the parent ACL object specified by <parent>.
To identify the node and parent, use the row id.

getPath aro|aco <node>
Returns the path to the ACL object specified by <node>. This command is useful in determining the inhertiance of permissions for a certain object in the tree.
For more detailed parameter usage info, see help for the ‘create’ command.

check <aro_id> <aco_id> [<aco_action>] or all
Use this command to check ACL permissions.
For more detailed parameter usage info, see help for the ‘create’ command.

grant <aro_id> <aco_id> [<aco_action>] or all
Use this command to grant ACL permissions. Once executed, the ARO specified (and its children, if any) will have ALLOW access to the specified ACO action (and the ACO’s children, if any). For more detailed parameter usage info, see help for the ‘create’ command.

deny <aro_id> <aco_id> [<aco_action>]or all
Use this command to deny ACL permissions. Once executed, the ARO specified (and its children, if any) will have DENY access to the specified ACO action (and the ACO’s children, if any). For more detailed parameter usage info, see help for the ‘create’ command.

inherit <aro_id> <aco_id> [<aco_action>]or all
Use this command to force a child ARO object to inherit its permissions settings from its parent. For more detailed parameter usage info, see help for the ‘create’ command.

view aro|aco [<node>]
The view command will return the ARO or ACO tree. The optional id/alias parameter allows you to return only a portion of the requested tree. For more detailed parameter usage info, see help for the ‘create’ command.

initdb
Uses this command : cake schema run create DbAcl

help [<command>]
Displays this help message, or a message on a specific command.

The ‘create’ help file

Usage: cake acl <command> <arg1> <arg2>…
———————————————–

  • Commands:
    • create aro|aco <parent> <node>
      • Creates a new ACL object <node> under the parent specified by <parent>, an id/alias. The <parent> and <node> references can be in one of the following formats:
        • - <model>.<id> – The node will be bound to a specific record of the given model
        • - <alias> – The node will be given a string alias (or path, in the case of <parent>), i.e. ‘John’.  When used with <parent>, this takes the form of an alias path, i.e. <group>/<subgroup>/<parent>. To add a node at the root level, enter ‘root’ or ‘/’ as the <parent> parameter.

Use Functions from Other Controllers While Maintaining MVC Architecture in CakePHP

Wednesday, December 10th, 2008

UPDATE (7/22/2009)

requestionAction may not be the best solution. Read this.

At my day job, I’m working on an application to keep track of specimens for our lab. A specimen is sent to the lab, then divided into aliquots which are put into boxes and stored in freezers. The previous sentence ought to give you some idea of the architecture of the database, which in turn drives the Model for my application.

To take a step back for a second, I’m developing the application using the CakePHP framework which uses MVC architecture.

As you may have guessed I have specimen, aliquot, boxes and freezers tables. In turn then, I have Specimen, Aliquot, Box and Freezer Models.

The trick here is that I want to alert users when there are aliquots in the system that have not yet been assigned to boxes. It’s a simple query:

SELECT COUNT(aliquot.id)
FROM aliquots
WHERE aliquots.box_id IS NULL

The problem is that I want the number of unstored aliquots to be displayed on every page in the left column as a persistent reminder that there are are aliquots that need to be put away. I want to do that in a way that maintains the MVC architecture and doesn’t violate the DRY philosophy.

Since the query is run on the aliquots table and each view is generally specific to it’s own model, I either have to run a recursive query to access data across models–which adds overhead–or implement the solution below which lightens the load a bit and is a more elegant bit of code. (Tip of the hat to Jon Bennet for offering the solution.)

The solution involves CakePHP’s requestAction().

I can define the method in my aliquots controller and call it from anywhere. So if aliquots_controller.php has a method that retrieves the data from the model (in this case called ‘unstored’) I can simply put the following code into my layout:

$unstored = $this-&gt;requestAction('aliquots/unstored');
if(!empty($unstored)) {
echo $html-&gt;link('<strong>' . $unstored['unstored'] . ' aliquots have not been stored.</strong>', '/aliquots/store');
}

I only have to define the method once to use it throughout my application. Problem solved.

Getting Blueprint CSS & JavaScript Libraries Into Your CakePHP Layout

Wednesday, November 26th, 2008

Updated 12/3/2008

The other day I wrote about getting the Blueprint CSS framework into your WordPress theme. If you’re developing in CakePHP, it’s even easier to link multiple style sheets and JavaScript libraries to your layout file.

<?php

$css = array('blueprint/screen', 'blueprint/ie', 'style');
$jslibraries = array('prototype', 'scriptaculous', 'jquery');

echo $html->css('blueprint/print', 'stylesheet', 'media="print"');

echo $html->css($css, 'stylesheet', 'media=”screen, projection”');
echo $javascript->link($jslibraries);

?>

Let’s take these one at a time.

$css = array('blueprint/screen', 'blueprint/ie', 'style');

CakePHP’s html helper will load any css file you specify. First, make sure the css files are in app/webroot/css. Then put any css files you want to link to your layout in an array like I have above. You might have noticed that I didn’t include print in my array. That’s because we want to add an media=”print” as a separate attribute that the other style sheets won’t have.

Once they’re loaded into your array, simply put echo $html->css($css); in the head of your layout. The output will be:
<link rel="stylesheet" type="text/css" href="/app/webroot/css/blueprint/screen.css" />
<link rel="stylesheet" type="text/css" href="/app/webroot/css/blueprint/ie.css" />
<link rel="stylesheet" type="text/css" href="/app/webroot/css/style.css" />

We still haven’t linked our print style sheet. Make sure you link the print style sheet above the others so they override it. We can add media="print" by putting this into our layout head:

echo $html->css('blueprint/print', 'stylesheet', 'media="print"');

So now:

$css = array('blueprint/screen', 'blueprint/ie', 'style');
echo $html->css('blueprint/print', 'stylesheet', 'media="print"');
echo $html->css($css, 'stylesheet', 'media=”screen, projection”');

Results in:

<link rel="stylesheet" type="text/css" href="/cvp-msi/https/app/webroot/css/blueprint/print.css" media="print" />
<link rel="stylesheet" type="text/css" href="/cvp-msi/https/app/webroot/css/blueprint/screen.css" media="screen, projection" />
<link rel="stylesheet" type="text/css" href="/cvp-msi/https/app/webroot/css/blueprint/ie.css" media="screen, projection" />
<link rel="stylesheet" type="text/css" href="/cvp-msi/https/app/webroot/css/style.css" media="screen, projection" />

Two things to note. In $html->css($path, $attributes), the first argument is the path from app/webroot/css. The second argument is html attributes.

Linking JavaScript libraries is very similar.

$jslibraries = array('prototype', 'scriptaculous', 'jquery');

This will link to prototype.js, scriptaculous.js and jquery.js respectively as long as there in app/webroot/js.

Put echo $javascript->link($jslibraries); into the head of your layout and you’re done. You have all three JavaScript libraries at your disposal.

Other good resources:

And We’re Back!

Monday, September 22nd, 2008

I have been so incredibly busy the last few months that aside for 140 character Twitter updates, I haven’t been able to keep this blog updated with my exploits.

If you are still paying attention, I was complaining about ACL. After several attempts, I gave up using the built-in ACL component in CakePHP and just decided to keep things simple, use the Auth component with role-based access control. Problem solved.

The development of the application has progressed smoothly since getting over that hurdle.

In the meantime, I’ve been setting up my own virtual server for hosting websites for my freelance clients. That has been a learning experience in itself. I’ll post more about that as I formally launch that service.

I’m also way behind on podcasts for the Minneapoliscast podcast. I hope to resume that at a modest pace this fall.

More later as all of my respective projects get updates including SVN info on my CakePHP app.

Wow. ACL is Hard

Friday, June 20th, 2008

That is Access Control Lists. I’ve been developing with CakePHP this spring and summer and it was all going very well until I actually needed to control access to the application. It’s not even that CakePHP falls short here. There are apparently tons of built-in tools for managing access. They’re just poorly documented and the community is relatively new so no one has built a complete plug in. If you’re looking for a solution like I was, I’m afraid I’m not going to give you the best answer here. I did find something that works, so read on. Especially if you’re learning ACL or Modified Preorder Tree Traversal Algorithm (MPTTA) for the first time.

Disclosure: I’m not formally trained as a programmer/developer. Everything I’ve learned, I’ve taught myself. So there are definitely some silos in my knowledge as I’ve learned things on the basis of necessity. I have, however, been developing in PHP for over six years. So it’s not all that bad.

So the learning curve for implementing ACL has been relatively steep for me. First, I had to get my head around the concept. The big picture is easy. What we’re after is a tree of access with ‘admin’ at the root and everything else branching off from that with diminishing access. That’s not hard to conceptualize. What is hard is putting that into practice.

I messed around with this for a long time before stumbling upon this tutorial about the Modified Preorder Tree Traversal Algorithm. Stop now. Read it. Come back.

Now you should understand the concepts that drive CakePHP’s ACL. Unfortunately here is also where we depart from using CakePHP’s tools. At least until a decent plug-in comes along that allows you to manage Access Request Objects (ARO) and Access Control Objects (ACO) via a good, web-based interface.

After many attempts with various solutions that are currently avaliable, I finally settled on Authake.

Pros:

  • Works in CakePHP 1.2
  • User, ARO & ACO adminstration is a snap
  • Access control works immediately without modifying anything you’ve built in your app.

Cons:

  • Installation requires you replace the entire CakePHP engine with Authake’s modified version. This will make upgrading CakePHP a lot harder.
  • The developer has abandoned it in favor of developing in RoR. No hope for future versions unless the community continues development. Personally, I’d prefer a plug-in like Jeff Loiselle‘s ACL Management Plugin that I could just drop right into app/plugins without replacing the entire installation. (The issue I have with Jeff’s are all listed on his “Known Bugs” list. Namely, “does not show inherited permissions, does not show full path in finder & does not have crud fields”. Unfortunately, those are three very major elements of managing ACL.)

If you are reading this in the not so distant future and someone had developed a plugin that has an admin area like Authake’s but drops into app/plugins like Jeff’s plugin, please, please let me know.