PHP and LDAP

I’m taking a break from my usual posting routine and topics because I’m currently working on my bachelors’ degree, but the fact that I spent what seems to me an unreasonable amount of time trying to do a routine setup for a directory server kind of made me want to post this.

Basically user management on a website is a subject of great debate nowadays, I don’t really want to get into it because it’s something I’m currently studying, suffice to say that if you can avoid having to keep and manage user credentials in your database then by all means, do it.

Normally I’d suggest OAuth because of its’ popularity, but because of the nature of my project (shhh, top secret) I went for a directory server instead, namely the Apache Directory Server.

Setting up the server itself wasn’t much of a problem, I just downloaded the Apache Directory Studio and clicked my way through the entire process, if you need a tutorial and can’t seem to find a decent one you can look here. My advice here would be don’t dive right in trying to figure it out on your own by randomly clicking stuff, it will confuse the shit out of you and it would be a pity to give up because Directory Servers are awesome, try and find some documentation and spend a few hours figuring the basics.

So let’s say we’re finished, the server is up and running, telnet localhost <server_port> works and gives you a protocol error when you try to type something etc. and now you have to use PHP to get data out of it. This  is where it gets awkward.

The first thing you have to know is that from what I can gather the PHP LDAP module gets its’ error messages from the server (list here) because if you have any other error it will happily spit out “Cannot connect to server” and be done with it. For instance I had a malformed search filter and that’s the error I got even though ldap_bind and ldap_connect both returned success.

Now first thing you have to know about the LDAP module is that you can’t really trust ldap_connect. It always returned “Success” even when the port was wrong, so here just so you know the proper way to use that function is this:

$connection = ldap_connect(LDAP_HOST,LDAP_PORT);

//example:

$connection = ldap_connect(“localhost”,389);

When you’re finished with that one, you have to use bind before you can get anything from the connection. This is the tricky part. If you get a Cannot connect to server here then there was something wrong with ldap_connect. Try to telnet to the server to see if it works and double check the ldap_connect parameters. If you get a Protocol Error, do not panic, it means it’s reached the server, but your library uses a different protocol version (most likely 2). You can solve this like so:

ldap_set_option($this->connection, LDAP_OPT_PROTOCOL_VERSION, 3);

//optionally also use the following command to force the server not to tell to search

//on other ldap servers when giving an answer

ldap_set_option($this->connection, LDAP_OPT_REFERRALS, 0);

And then the bind:

$result = ldap_bind($connection,LDAP_RDN,LDAP_RDN_PASS);

If you don’t know what RDN means, then you are a naughty reader, head on over here.

And when that is done you can finally use ldap_search to get some data out of that server. Keep in mind that it won’t work unless you specify a filter and that an empty filter will make it spit out a Search: Cannot connect to server error, but other than that you should be fine now.

And that would be the end of the adventure. I’ll most likely update this post with weird behavior and what may cause generic errors to be thrown at runtime, but until then cheers.

A Dev Story: Functors

Picking up where we left off, the next logical step in building a parser would be to somehow define the interactions between data types. Now because this is 2012 and the olden days where procedural programming was the de facto standard are way behind us, we’d like for this script parser to support these minimum requirements:

  • Operators for every possible combination of Invariants ( +, – etc)
  • Function scope
  • Objects
  • Duck Typing

And we want to be able to do this in a reasonable amount of time, so of course hardcoding behavior on a per Invariant basis being a massive overkill from this point of view falls from the start. What we actually need here is a way to generate an abstractization of this behavior on which we can build when time comes.

Luckily here’s where we can take a lesson from the C++ architecture. You see, in C++ object orientedness is somewhat of an illusion propagated by the compiler, every member function you declare in a class is ultimately transformed into a procedural style function to which compiler passes the this pointer, which is why you can abuse the compiler and do stuff like the following:
//Foo.h

class Foo{

private:
 Foo();
public:
 int Bar();
};
 //Foo.cpp
#include"Foo.h"
int Foo::Bar(){
 return8;
} 
//main.cpp
#include "Foo.h" #include<cstdio> 
int main()
{
 Foo*foo=NULL;
 foo->Bar();
 return0;
}

without fear of a crash. Beyond the fact that this serves to prove that C++ can sometimes resemble the goatse of object oriented programming, we can take a mental note on implementing the architecture we want. So we need a way to store functions in a invariant object and pass the this pointer at runtime when we call a function that we previously added to an invariant.

The next thing C++ can teach is that we can think of operators as functions, which is indeed particularly interesting because having decided that we want objects, we can now store operators as one of the functions the object has and call it when  we encounter it in our parser. This also has the advantage that we can name it to match the operator it represents so that when the time comes to interpret the parse tree, when you encounter an operator node all you have to do is call the method that matches the operators’ string.

This is where Functors ( short for Function Objects ) come in. You know how we defined an interface for the Invariant, something that all invariants should have so that we could let them worry about managing the state of the underlying data so that we can use types interchangeably in our script. Well this is what we’re going to do with Functors:

class Functor{

public:
 InvUnknown* (*Func)(InvUnknown* args);
 Functor(InvUnknown* (*function)(InvUnknown* args)){
 Func = function;
 }
 virtual InvUnknown* apply(InvUnknown* args){return Func(args);}
};

So basically we took a function pointer and wrapped it in an object that has the apply method so that we can call this function at our convenience.

Now here is where it gets interesting because as you can see the Functor apply method takes a InvUnkown pointer as a argument and returns a InvUnknown pointer itself. Well because the Invariant was designed to abstract data and since we can pass any type of invariant to the function, this means that not only can we abuse the List invariant to pass as many arguments as we want to the function (not to mention return as many values as we want from the function), but this way we get the Duck Typing as well.

And last but not least the function scope can be implemented by adding a map to the Functor object so that we can store temporary objects.

Up until now all is good in theory, but a real world example wouldn’t hurt, so allow me to demonstrate this by implementing a push function for a list.

First of all we need to update the InvUnknown class to take advantage of these functors:

class InvUnknown{
public:
virtual bool inline is(inttype){returninv_type==type;}
virtual const string toString() = 0;
virtual void nativeCall(InvUnknown*param) = 0;
virtual InvUnknown* call(string& name,InvUnknown* params)
{
 Functor* method=methods[name];
 if(!method)printf("No method with name %s found",name.c_str());
   assert(params->is(LIST) && "Function parameters must be passed as LIST invariants");
 params->nativeCall(this);
 return method->apply(params);
}
protected:
 InvUnknown(int type){inv_type=type;} 
 map<string,Functor*>methods;
 void inline addMethod(string&name,InvUnknown* (*function)(InvUnknown*)){
 Functor* method = new Functor(function); 
 methods.insert(pair<string,Functor*>(name,method));
 }
private:
 int inv_type;
};

Now we have the means to store and access Functors from our Invariant. Notice the native call though. In my opinion this is a hack that is unfortunately needed because upcasting in a base class is a definite no go and because the push Functor needs to take a list of values as a parameter, so the list has to be full when we call push.

Of course another solution would be to overload the apply method to take a vector<InvUnknown*> instead and it would basically be the same thing seeing as our list is in fact a wrapper for a vector<InvUnknown*>, but that wouldn’t be fair because that way you create an opening for bad practices. If the API you have to use in your code is the same as the one you expose to the script, this ensures that you are actually using what you create and you eliminate furstrations as you use it. Having a separate API that gives you more flexibility and or power than whatever you expose to the script usually shows that something isn’t planned right.

Onto the list definition:

class List:public Invariant<vector<InvUnknown*>,LIST>
{
 public:
 List();
 virtual const string toString();
 void inline nativeCall(InvUnknown* elem){data.insert(data.begin(),elem);}
 static InvUnknown* push(InvUnknown* args); } 

And the implementation

List::List(){
stringpush_name="push";
addMethod(push_name,&push);
}
const string List::toString()
{
 stringstream buffer;
 string retval;
 buffer << "[";
 vector<InvUnknown*>::iterator paramIt = data.begin();
 for(;paramIt != data.end();++paramIt)
 {
 if((*paramIt) == this) buffer << "this";
 else buffer << (*paramIt)->toString();
 if(paramIt != data.end()-1) buffer << ",";
 }
 buffer << "]";
 buffer >> retval;
 return retval;
}
InvUnknown*List::push(InvUnknown*params)
{
assert(params->is(LIST) && " ALL function parameters need to be passed as LIST objects");
List* paramList = (List*)params;
vector<InvUnknown*>data = paramList->getData();
assert(data[0]->is(LIST) && "List function push called on non list");
List*parent=(List*)data[0];
for(unsigned int paramIt = 1;paramIt < data.size();++paramIt)
 parent->nativeCall(data[paramIt]);
 return parent;  
}

And last but not least the actual usage of the push function:

InvUnknown* l1 = new List();

InvUnknown* l3 = new List();
InvUnknown* l2 = new Primitive();
InvUnknown* args = new List();
string push_name = "push";
args->nativeCall(l3);
args->nativeCall(l2);
l3->call(push_name,args);
args->nativeCall(l1);
args->nativeCall(l1);
args->nativeCall(l2);
args->nativeCall(l2);
l1->call(push_name,args);
delete l1;
delete l2;
delete args;

Which produces the following output:

[this,0x227d858]
[[this,0x227d858],0x227d858,[this,0x227d858],this,this,0x227d858,0x227d858]

Which means that I can add Primitives (Invariant) and Lists and I can just as easily add just about any other Invariant I fancy, success.
Next time we talk a bit about scope.

A Dev Story: Invariants

Todays’ post is about a small hobby of mine of looking into the details of creating a fully featured dev environment, more precisely I’m going to talk about how to start designing your own scripting language. This series will revolve around C++ because of reasons, but if anyone should request it I can easily port it to any compatible language

Anyway hype words aside let’s say you want to start creating your own scripting language. The first thing that comes to mind is storing data.

Now like everybody knows, the whole idea behind a scripting language is to be able to forget about the burdens of having to use cryptic language features, or wasting time on the planning required for writing programs in statically typed languages, so it only feels natural that our scripting language will feature dynamic typing. In other words if I have a variable a and I do
a = 'b';
a = 10;
a +=100;
print(a)

It should work as expected and not complain about anything.

Well back in the real world we have two solutions for this, either use another language that already has this feature (but of course that would most likely have little to no sense) which leaves having to build this thing in a boilerplate code friendly environment.

So first of all we want to create a base on which to build this system. We don’t want to expose too much information here, just the bare minimum to get a context in case it’s needed. This is achieved via a class that will have a member variable to describe what it holds

class InvUnknown{
public:
 virtual bool inline is(int type){return inv_type == type;}
 virtual int inline getType(){return inv_type;}
protected:
 InvUnknown(int type){inv_type = type;}
private:
 int inv_type;
}; 

Now like we specified earlier, we want our invariant to be able to hold any type of data we might encounter in the script, ideally it would have to do this without grabbing every last bit of memory it can get its hands on and without having to force the construction of another invariant when we want to set the value, which is why we’ll be using unions.

 union Data{
 double doubleData;
 int integerData;
 float floatData;
 string *stringData;
 InvUnknown *invariantData;
};

We’d like to somehow limit the amount of datatypes we put into this union though because having a plethora of datatypes + data storage combinations would eventually become cumbersome, so we’ll have the union store only simple primitives and objects and if the need arrives to hold an array for instance we will just use an invariant.

And now that the base is set we define the invariant as such:

template <typenameT,intType>
class Invariant:public InvUnknown
{
public:
 Invariant():InvUnknown(Type){}
 Invariant(T&_data):InvUnknown(Type), data(_data){}
 virtual T inline getData(){return data;}
 virtual const string toString(){
 stringstream buffer;
 string retval;
 buffer << &data;
 buffer >> retval;
 return retval;
};
protected:
 T data;
}; 

And this is it, now all there is to do is to define the set of methods that can be applied given any type T you want to support and then particularize the invariant by deriving it like so:

class Primitive:public Invariant<Data,PRIMITIVE>{
};

Next time we’ll talk about applying the same principle to functions

Game Design: Cheating

Following up on my last post, it seems to work, but unfortunately having an idea is not enough, bringing it to life requires time to actually write it , but in any case I feel like talking about design again right now so here it goes.

Ask any game designer and he will tell you that cheating is bad, it;s something you want to prevent because it’s that type of behavior that will kill the enthusiasm you have when playing a game (more so in a multiplayer game where not only you ruin your fun, but you ruin other peoples’ fun too), it’s something that you’d normally want to discourage.

Well I say fight fire with fire, cheating is only bad if it enables someone to make an action you are actively trying to discourage, but what if you were to plan ahead to include behavior that would normally be associated with cheating to give the player the sense that he is in fact breaking the rules and add to the sense of achievement when you finish your task.

So for instance let’s say you have a physics game and a level built so that the obvious solution requires a minimum of 3 steps to complete. What I’m proposing is that you add some way of completing it in say 1 or 2 moves preferably by exploiting a side effect of a mechanic to make the person that finds it feel like he is smarter than you.

What do you think would it be a good idea ?

And yes this thing dawned on me while playing physics games, but I guess I can come up with a way to use this in other games as well.

Another Year

It is as it seems, another year has passed, when is irrelevant, but it got me thinking.

Every year when I look back in time and think about what I knew back then and how I handled stuff I always get the impression that I used to be stupid to such an extent that if I were to travel back in time one year back, I probably wouldn’t consider myself worthy of a conversation.

In any case I’ve been experimenting with a technique to pass writer’s block that seems to work ok, and this place seems as good as any to make some experiments so basically if you’ll see posts that are under a month apart from each other in the near future then it means it worked.

Installing FreePBX

Yes nowadays you can tell it’s autumn because I start posting again, but leaving that aside, today’s post will be something a bit more software oriented.

See I had the occasion of fiddling with a xeon server rack to install asterisk as a SIP daemon and FreePBX to administer it. Now, I imagine that there aren’t that many people doing this kind of thing for fun, unless of course you want to call your friends from your computer without using skype, but if you do, you most likely ended up here because like me you’re having trouble making it start.

Skipping the obvious steps like download the code, run make, etc. after I installed asterisk, it just didn’t want to start, it just blurted a big red WARNING in console mode and died. In this case the problem was that there were two modules conflicting with each other, if you don’t want to have this problem then don’t install the addons, otherwise just blacklist them from modules configuration file in /etc/asterisk/.

Now onto the next step, I installed FreePBX, again leaving out that the install script requires you to run the sql scripts in the ./sql directory beforehand which made me think there was a problem with the asterisk install and convinced me that I have to start over, but still there I was thinking I was finally over when the damn webserver wouldn’t show me anything when I tried to connect to the portal via http on localhost, the response was 0 length. This was actually a two part problem, first a 403 because silly old me forgot to chmod +x the directories in the html location, but the other one, not that lucky. And so after spending 4 hours in total installing the software, it still wouldn’t work.

In any case, I thought, hey this has to be a database problem, I’ll just redo that part and hope it goes away when that didn’t work, I thought, hey maybe it has something to do with the html, I redid that step too, but no, it just wouldn’t go away. At this point I started hacking away at the code and what do you know, this portal keeps its’ database connection settings locked away in a obscure file hidden well in the system, which is totally fine I guess, but then it goes on and includes a fucking .php file with an absolute path, so if you are like me and change the directory of the install after running that script, it won’t work until you update freepbx.conf.

All in all it took me one whole day to make this thing run, but I guess in the end that just made me feel a whole lot better when it was finally over.

Game Design: Chekpoints

Well I started tis blog to talk about design (system design, if you came here for art you’re in the wrong place) so I’m now going to pick up where I left off.

I was playing a lot of mass effect recently and what can I say, the game really stands out. Generally it is a model you can follow, but apart from the small collision glitches and the fact that the button that skips cutscenes doubles as the button that selects conversation options, that game has just one serious flaw: checkpoints.

I don’t know, maybe I’m a pretentious prick, but it just doesn’t seem normal to let the user redo more than let’s say 10 minutes worth of gameplay. What this means is not necessarily that the game engine should feature a timer that saves the game every 10 minutes, rather that at the beginning and the end of EVERY mission (yes, that includes side quests) there should be a checkpoint. Or even more general, let’s say you’re working at a game that doesn’t feature any sort of quest. If there is a sequence during which a player might fail his objectives and have to restart his progress, make a checkpoint before and one after that sequence.

What this means for the user is that he won’t have to redo the boring sequences in between missions like say for instance how I have to run around and talk to every NPC on Feros right now because I got killed when I was returning to the quest giver.

So to sum it up: Checkpoints are your friends, use them often.

Realism

This is a topic I’ve been discussing for a very long time with a whole lot of people.

For some reason, it seems people managed to get it in their heads that realism is cool, that is make something sufficiently close to real and people will buy it. Well news flash, that’s about as true as carrots running on the field after you pour radioactive waste on them.

People don’t like real, if they would they’d just pop out their heads on the window and call their neighbors to a football match. No people don’t like real, people like almost real. There is a fine line between fun and real and most will cross it thinking that’s the right thing to do.

My guess is that computer games and TV programs have influenced our culture enough to warp our perception of reality to the point where we perceive their struggle to make everything look as real as possible as well, reality. Let’s take this for instance, it’s probably the sound every predator bird makes in very movie ever made. Up until a month ago I could’ve sworn that if you ever saw a bald headed eagle, that would be the sound coming out of his beak. Turns out I was wrong.

Truth is reality is just not cool enough, you want to make something extraordinary, make it believable instead, mix everything you can to form something perfect, yet believable and present that as reality. People want a model, something to inspire and amaze them, not a costly CGI through their everyday life, so you have to make something up and you have to be careful when you do it, too much innovation and they’re gonna call bullshit, too little and it’s gonna be boring.

Anyway, to summarize this post, this is cool and this is real, you decide what you’d like to see in a production value anything.

Workplace Toilets

Following up on my other posts on the lack of toilets, I’m starting to wonder, I’ve seen many company establishments with very elaborate ( and more importantly squeaky clean ) toilets,  so I think it’s natural to ask:

How many times do you shit during work hours ? ( or use the toilet in any other way )

We Need More Toilets

Ever walked down the street just to find yourself in desperate need of a toilet of any kind to relieve the pressure.

Well I have, many many times and while some of you might not feel this is a major problem due to the abundance of public toilets in your area, let me tell you, in this part of the world it’s not the case.

Finding a public toilet in this region is like escaping the labyrinth in the old descent games, you have to memorize everything the first time, or else you find yourself out of time and bam, you can guess what follows.

There are oh so many funds allocated to renew and beautify the surroundings, adding statues and complex structures with no particular meaning, why can’t they just hollow them out and build a public toilet inside, I would certainly be happier.

Funny enough, this is a mistake a game designer would never ever do, it’s a relatively urgent need that has to be satisfied, it’s like making someone play doom with 2-3 ammo packs scattered around the level, hardcore gamers might find it a challenge, but mostly people are going to get frustrated.

So yeah, it’s bad design, don’t do that.