]> git.decadent.org.uk Git - maypole.git/blob - doc/Flox.pod
f42bc2e3b73e9549d408bde29368be1f311b3c0a
[maypole.git] / doc / Flox.pod
1 =head1 Flox: A Free Social Networking Site
2
3 Friendster, Tribe, and now Google's Orkut - it seems like in early 2004,
4 everyone wanted to be a social networking site. At the time, I was too
5 busy to be a social networking site, as I was working on my own project
6 at the time - Maypole. However, I realised that if I could implement a
7 social networking system using Maypole, then Maypole could probably do
8 anything.
9
10 I'd already decided there was room for a free, open-source networking
11 site, and then Peter Sergeant came up with the hook - localizing it to
12 universities and societies, and tying in meet-ups with restaurant
13 bookings. I called it Flox, partially because it flocks people together
14 and partially because it's localised for my home town of Oxford and its
15 university student population.
16
17 Flox is still in, uh, flux, but it does the essentials. We're going to
18 see how it was put together, and how the techniques shown in the
19 L<Request.pod> chapter can help to create a sophisticated web
20 application. Of course, I didn't have this manual available at the time,
21 so it took a bit longer than it should have done...
22
23 =head2 Mapping the concepts
24
25 Any Maypole application should start with two things: a database schema,
26 and some idea of what the pages involved are going to look like.
27 Usually, these pages will be tying to displaying or editing some element
28 of the database, so these two concepts should come hand in hand.
29
30 When I started looking at social networking sites, I began by
31 identifying the concepts which were going to make up the tables of the
32 application. At its most basic, a site like Orkut or Flox has two
33 distinct concepts: a user, and a connection between two users.
34 Additionally, there's the idea of an invitation to a new user, which can
35 be extended, accepted, declined or ignored. These three will make up the
36 key tables; there are an extra two tables in Flox, but they're
37 essentially enumerations that are a bit easier to edit: each user has an
38 affiliation to a particular college or department, and a status in the
39 university. (Undergraduate, graduate, and so on.)
40
41 For this first run-through, we're going to ignore the ideas of societies
42 and communities, and end up with a schema like so:
43
44     CREATE TABLE user (
45         id int not null auto_increment primary key,
46         first_name varchar(50),
47         last_name varchar(50),
48         email varchar(255),
49         profile text,
50         password varchar(255),
51         affiliation int,
52         unistatus int,
53         status ENUM("real", "invitee"),
54         photo blob,
55         photo_type varchar(30)
56     );
57
58     CREATE TABLE connection (
59         id int not null auto_increment primary key,
60         from_user int,
61         to_user int,
62         status ENUM("offered", "confirmed")
63     );
64
65     CREATE TABLE invitation (
66         id char(32) not null primary key,
67         issuer int,
68         recipient int,
69         expires date
70     );
71
72 Plus the definition of our two auxilliary tables:
73
74     CREATE TABLE affiliation (
75         id int not null auto_increment primary key,
76         name varchar(255)
77     );
78
79     CREATE TABLE unistatus (
80         id int not null auto_increment primary key,
81         name varchar(255)
82     );
83
84 Notice that, for simplicity, invitations and friendship connections are
85 quite similar: they are extended from one user to another. This means
86 that people who haven't accepted an invite yet still have a place in the
87 user table, with a different C<status>. Similarly, a connection between
88 users can be offered, and when it is accepted, its status is changed to
89 "confirmed" and a reciprocal relationship put in place.
90
91 We also have some idea, based on what we want to happen, of what pages
92 and actions we're going to define. Leaving the user aside for the
93 moment, we want an action which extends an invitation from the current
94 user to a new user. We want a page the new user can go to in order to
95 accept that invitation. Similarly, we want an action which offers a
96 friendship connection to an existing user, and a page the user can go to
97 to accept or reject it. This gives us five pages so far:
98
99     invitation/issue
100     invitation/accept
101
102     user/befriend
103     connection/accept
104     connection/reject
105
106 Notice that the C<befriend> action is performed on a user, not a
107 connection. This is distinct from C<invitation/issue> because when
108 befriending, we have a real user on the system that we want to do
109 something to. This makes sense if you think of it in terms of object
110 oriented programming - we could say
111
112     Flox::Connection->create(to => $user)
113
114 but it's clearer to say
115
116     $user->befriend
117
118 Similarly, we could say
119
120     Flox::User->create({ ... })->issue_invitation_to
121
122 but it's clearer to say
123
124     Flox::Invitation->issue( to => Flox::User->create({ ... }) )
125
126 because it more accurately reflects the principal subject and object of
127 these actions.
128
129 Returning to look at the user class, we want to be able to view a user's
130 profile, edit one's own profile, set up the profile for the first
131 time, upload pictures and display pictures. We also need to handle the
132 concepts of logging in and logging out.
133
134 As usual, though, we'll start with a handler class which sets up the
135 database:
136
137     package Flox;
138     use base qw(Apache::MVC);
139     Flox->setup("dbi:mysql:flox");
140     Flox->config->{display_tables} = [qw[user invitation connection]];
141     1;
142
143 Very simple, as these things are meant to be. Now let's build on it.
144
145 =head2 Authentication
146
147 The concept of a current user is absolutely critical in a site like
148 Flox; it represents "me", the viewer of the page, as the site explores
149 the connections in my world. We've described the authentication hacks
150 briefly in the L<Request.pod> chapter, but now it's time to go into a
151 little more detail about how user handling is done.
152
153 XXX
154
155 We also want to be able to refer to the current user from the templates,
156 so we use the overridable C<additional_data> method to give us a C<my>
157 template variable:
158
159     sub additional_data { 
160         my $r = shift; $r->{template_args}{my} = $r->{user}; 
161     }
162
163 I've called it C<my> rather than C<me> because we it lets us check 
164 C<[% my.name %]>, and so on.
165
166 =head2 Viewing a user
167
168 The first page that a user will see after logging in will be their own
169 profile, so in order to speed development, we'll start by getting a
170 C<user/view> page up.
171
172 The only difference from a programming point of view between this action
173 and the default C<view> action is that, if no user ID is given, then we
174 want to view "me", the current user. Remembering that the default view
175 action does nothing, our C<Flox::User::view> action only needs to do
176 nothing plus ensure it has a user in the C<objects> slot, putting
177 C<$r-E<gt>{user}> in there if not:
178
179     sub view :Exported {
180         my ($class, $r) = @_;
181         $r->{objects} = [ $r->{user} ] unless @{$r->{objects}||[]};
182     }
183
184 Maypole, unfortunately, is very good at making programming boring. The
185 downside of having to write very little code at all is that we now have
186 to spend most of our time writing nice HTML for the templates.
187
188 XXX
189
190 The next stage is viewing the user's photo. Assuming we've got the photo
191 stored in the database already (which is a reasonable assumption for the
192 moment since we don't have a way to upload a photo quite yet) then we
193 can use the a variation of the "Displaying pictures" hack from the 
194 Requests chapter:
195
196     sub view_picture :Exported {
197         my ($self, $r) = @_;
198         my $user = $r->{objects}->[0] || $r->{user};
199         if ($r->{content_type} = $user->photo_type) {
200            $r->{output} = $user->photo;
201         } else {
202            # Read no-photo photo
203            $r->{content_type} = "image/png";
204            $r->{output} = slurp_file("images/no-photo.png");
205         }
206     }
207
208 We begin by getting a user object, just like in the C<view> action: either
209 the user whose ID was passed in on the URL, or the current user. Then
210 we check if a C<photo_type> has been set in this user's record. If so,
211 then we'll use that as the content type for this request, and the data
212 in the C<photo> attribute as the data to send out. The trick here is
213 that setting C<$r-E<gt>{output}> overrides the whole view class processing
214 and allows us to write the content out directly.
215
216 In our template, we can now say
217
218     <IMG SRC="/user/view_picture/[% user.id %]">
219
220 and the appropriate user's mugshot will appear.
221
222 However, if we're throwing big chunks of data around like C<photo>, it's
223 now worth optimizing the C<User> class to ensure that only pertitent
224 data is fetched by default, and C<photo> and friends are only fetched on
225 demand. The "lazy population" section of C<Class::DBI>'s man page
226 explains how to group the columns by usage so that we can optimize
227 fetches:
228
229     Flox::User->columns(Primary   => qw/id/);
230     Flox::User->columns(Essential => qw/status/);
231     Flox::User->columns(Helpful   => qw/ first_name last_name email password/)
232     Flox::User->columns(Display   => qw/ profile affiliation unistatus /);
233     Flox::User->columns(Photo     => qw/ photo photo_type /);
234
235 This means that the status and ID columns will always be retrieved when
236 we deal with a user; next, any one of the name, email or password
237 columns will cause that group of data to be retrieved; if we go on to
238 display more information about a user, we also load up the profile,
239 affiliation and university status; finally, if we're throwing around
240 photos, then we load in the photo type and photo data.
241
242 These groupings are somewhat arbitrary, and there needs to be a lot of
243 profiling to determine the most efficient groupings of columns to load,
244 but they demonstrate one principle about working in Maypole: this is the
245 first time in dealing with Maypole that we've had to explicitly list the
246 columns of a table, but Maypole has so far Just Worked. There's a
247 difference, though, between Maypole just working and Maypole working
248 well, and if you want to optimize your application, then you need to
249 start putting in the code to do that. The beauty of Maypole is that you
250 can do as much or as little of such optimization as you want or need.
251
252 So now we can view users and their photos. It's time to allow the users
253 to edit their profiles and upload a new photo.
254
255 =head2 Editing users
256
257 XXX Editing a profile
258
259 I introduced Flox to a bunch of friends and told them to be as ruthless
260 as possible in finding bugs and trying to break it. And break it they
261 did; within an hour the screens were thoroughly messed up as users had
262 nasty HTML tags in their profiles, names, email addresses and so on. 
263 This spawned another hack in the request cookbook: "Limiting data for
264 display". I changed the untaint columns to use C<html> untainting, and
265 all was better:
266
267     Flox::User->untaint_columns(
268         html      => [qw/first_name last_name profile/],
269         printable => [qw/password/],
270         integer   => [qw/affiliation unistatus /],
271         email     => [qw/email/]
272     );
273
274 The next stage was the ability to upload a photo. We unleash the "Uploading
275 files" recipe, with an additional check to make sure the photo is of a
276 sensible size:
277
278     use constant MAX_IMAGE_SIZE => 512 * 1024;
279     sub do_upload :Exported {
280         my ($class, $r) = @_;
281         my $user = $r->{user};
282         my $upload = $r->{ar}->upload("picture");
283         if ($upload) {
284             my $ct = $upload->info("Content-type");
285             return $r->error("Unknown image file type $ct")
286                 if $ct !~ m{image/(jpeg|gif|png)};
287             return $r->error("File too big! Maximum size is ".MAX_IMAGE_SIZE)
288                 if $upload->size > MAX_IMAGE_SIZE;
289
290             my $fh = $upload->fh;
291             my $image = do { local $/; <$fh> };
292
293             use Image::Size;
294             my ($x, $y) = imgsize(\$image);
295             return $r->error("Image too big! ($x, $y) Maximum size is 350x350")
296                 if $y > 350 or $x > 350;
297             $r->{user}->photo_type($ct);
298             $r->{user}->photo($image);
299         }
300
301         $r->objects([ $user ]);
302         $r->{template} = "view";
303     }
304
305 Now we've gone as far as we want to go about user editing at the moment.
306 Let's have a look at the real meat of a social networking site: getting
307 other people involved, and registering connections between users. 
308
309 =head2 Invitations
310
311 We need to do two things to invitations working: first provide a way to
312 issue an invitation, and then provide a way to accept it. Since what
313 we're doing in issuing an invitation is essentially creating a new
314 one, we'll use our usual practice of having a page to display the form
315 to offer an invitation, and then use a C<do_edit> method to actually do
316 the work. So our C<issue> method is just an empty action:
317
318     sub issue :Exported {}
319
320 and the template proceeds as normal:
321
322     [% PROCESS header %]
323     <h2> Invite a friend </h2>
324
325     <FORM ACTION="[%base%]/invitation/do_edit/" METHOD="post">
326     <TABLE>
327
328 Now we use the "Catching errors in a form" recipe from L<Request.pod> and
329 write our form template:
330
331     <TR><TD>
332     First name: <INPUT TYPE="text" NAME="forename"
333     VALUE="[%request.params.forename%]">
334     </TD>
335     <TD>
336     Last name: <INPUT TYPE="text" NAME="surname"
337     VALUE="[%request.params.surname%]"> 
338     </TD></TR>
339     [% IF errors.forename OR errors.surname %]
340         <TR>
341         <TD><SPAN class="error">[% errors.forename %]</SPAN> </TD>
342         <TD><SPAN class="error">[% errors.surname %]</SPAN> </TD>
343         </TR>
344     [% END %]
345     <TR>
346     ...
347
348 Now we need to work on the C<do_edit> action. This has to validate the
349 form parameters, create the invited user, create the row in the C<invitation>
350 table, and send an email to the new user asking them to join.
351
352 We'd normally use C<create_from_cgi> to do the first two stages, but this time
353 we handle the untainting manually, because there are a surprising number of
354 things we need to check before we actually do the create. So here's the
355 untainting of the parameters:
356
357     my ($self, $r) = @_;
358     my $h = CGI::Untaint->new(%{$r->{params}});
359     my (%errors, %ex);
360     for (qw( email forename surname )) {
361         $ex{$_} = $h->extract(
362                 "-as_".($_ eq "email" ? "email" : "printable") => $_
363         ) or $errors{$_} = $h->error;
364     }
365
366 Next, we do the usual dance of throwing the user back at the form in case
367 of errors:
368
369     if (keys %errors) {
370         $r->{template_args}{message} = "There was something wrong with that...";
371         $r->{template_args}{errors} = \%errors;
372         $r->{template} = "issue";
373         return;
374     }
375
376 We've introduced a new template variable here, C<message>, which we'll use
377 to display any important messages to the user.
378
379 The first check we need to do is whether or not we already have a user
380 with that email address. If we have, and they're a real user, then we
381 abort the invite progress and instead redirect them to viewing that user's 
382 profile.
383
384     my ($user) = Flox::User->search({ email => $ex{email} });
385     if ($user) {
386         if ($user->status eq "real") {
387             $r->{template_args}{message} =
388                 "That user already seems to exist on Flox. ".
389                 "Is this the one you meant?";
390
391             $self->redirect_to_user($r,$user);
392         } 
393
394 Where C<redirect_to_user> looks like this:
395
396     sub redirect_to_user {
397         my ($self, $r, $user) = @_;
398         $r->{objects} = [ $user ];
399         $r->{template} = "view";
400         $r->{model_class} = "Flox::User"; # Naughty.
401     }
402
403 This is, as the comment quite rightly points out, naughty. We're currently
404 doing a C</invitation/do_edit/> and we want to turn this into a
405 C</user/view/xxx>, changing the table, template and arguments all at once.
406 To do this, we have to change the Maypole request object's idea of the model
407 class, since this determines where to look for the template: if we didn't,
408 we'd end up with C<invitation/view> instead of C<user/view>.
409
410 Ideally, we'd do this with a Apache redirect, but we want to get that
411 C<message> in there as well, so this will have to do. This isn't good practice;
412 we put it into a subroutine so that we can fix it up if we find a better way
413 to do it.
414
415 Anyway, this is what we should do if a user already exists on the system
416 and has accepted an invite already. What if we're trying to invite a user but
417 someone else has invited them first and they haven't replied yet?
418
419          } else {
420             # Put it back to the form
421             $r->{template_args}{message} =
422             "That user has already been invited; ".
423             "please wait for them to accept";
424             $r->{template} = "issue";
425         }
426         return;
427     }
428
429 Race conditions suck.
430
431 Okay. Now we know that the user doesn't exist, and so can create the new 
432 one:
433
434     my $new_user = Flox::User->create({
435         email => $ex{email},
436         first_name => $ex{forename},
437         last_name  => $ex{surname},
438         status => "invitee"
439     });
440
441 We want to give the invitee a URL that they can go to in order to
442 accept the invite. Now we don't just want the IDs of our invites to
443 be sequential, since someone could get one invite, and then guess the
444 rest of the invite codes. We provide a relatively secure MD5 hash as
445 the invite ID:
446
447     my $random = md5_hex(time.(0+{}).$$.rand);
448
449 For additional security, we're going to have the URL in the form
450 C</invitation/accept/I<id>/I<from_id>/I<to_id>>, encoding the user ids
451 of the two users. Now we can send email to the invitee to ask them to
452 visit that URL:
453
454     my $newid = $new_user->id;
455     my $myid  = $r->{user}->id;
456     _send_mail(to => $ex{email}, url => "$random/$myid/$newid", 
457                user => $r->{user});
458
459 I'm not going to show the C<_send_mail> routine, since it's boring.
460 We haven't actually created the C<Invitation> object yet, so let's
461 do that now.
462
463     Flox::Invitation->create({
464         id => $random,
465         issuer => $r->{user},
466         recipient => $new_user,
467         expires => Time::Piece->new(time + LIFETIME)->datetime
468     });
469
470 You can also imagine a daily cron job that cleans up the C<Invitation>
471 table looking for invitations that ever got replied to within their
472 lifetime:
473
474    ($_->expires > localtime && $_->delete)
475        for Flox::Invitation->retrieve_all;
476
477 Notice that we don't check whether the ID is already used. We could, but,
478 you know, if MD5 sums start colliding, we have much bigger problems on
479 our hands.
480
481 Anyway, now we've got the invitation created, we can go back to whence we
482 came: viewing the original user:
483
484     $self->redirect_to_user($r, $r->{user});
485
486 Now our invitee has an email, and goes B<click> on the URL. What happens?
487
488 XXX
489
490 =head2 Friendship Connections
491
492 =head2