File Coverage

blib/lib/Data/Session.pm
Criterion Covered Total %
statement 311 352 88.3
branch 96 162 59.2
condition 24 53 45.2
subroutine 39 42 92.8
pod 22 30 73.3
total 492 639 77.0


line stmt bran cond sub pod time code
1             package Data::Session;
2              
3 2     2   501422 use parent 'Data::Session::Base';
  2         6  
  2         17  
4 2     2   109 no autovivification;
  2         10  
  2         12  
5 2     2   108 use strict;
  2         4  
  2         66  
6 2     2   10 use warnings;
  2         3  
  2         84  
7              
8 2     2   862 use Class::Load ':all'; # For try_load_class() and is_class_loaded().
  2         31966  
  2         341  
9              
10 2     2   17 use File::Spec; # For catdir.
  2         4  
  2         150  
11 2     2   2759 use File::Slurp; # For read_dir.
  2         40814  
  2         208  
12              
13 2     2   24 use Hash::FieldHash ':all';
  2         5  
  2         381  
14              
15 2     2   14 use Try::Tiny;
  2         5  
  2         16662  
16              
17             fieldhash my %my_drivers => 'my_drivers';
18             fieldhash my %my_id_generators => 'my_id_generators';
19             fieldhash my %my_serializers => 'my_serializers';
20              
21             our $errstr = '';
22             our $VERSION = '1.16';
23              
24             # -----------------------------------------------
25              
26             sub atime
27             {
28 134     134 1 223 my($self, $atime) = @_;
29 134         427 my($data) = $self -> session;
30              
31             # This is really only for use by load_session().
32              
33 134 100       354 if (defined $atime)
34             {
35 132         294 $$data{_SESSION_ATIME} = $atime;
36              
37 132         402 $self -> session($data);
38 132         572 $self -> modified(1);
39             }
40              
41 134         377 return $$data{_SESSION_ATIME};
42              
43             } # End of atime.
44              
45             # -----------------------------------------------
46              
47             sub check_expiry
48             {
49 132     132 1 195 my($self) = @_;
50              
51 132 100 66     467 if ($self -> etime && ( ($self -> atime + $self -> etime) < time) )
52             {
53 1 50       22 ($self -> verbose) && $self -> log('Expiring id: ' . $self -> id);
54              
55 1         8 $self -> delete;
56 1         6 $self -> expired(1);
57             }
58              
59             } # End of check_expiry.
60              
61             # -----------------------------------------------
62              
63             sub clear
64             {
65 243     243 1 335 my($self, $name) = @_;
66 243         695 my($data) = $self -> session;
67              
68 243 100       434 if (! $name)
    50          
69             {
70 242         446 $name = [$self -> param];
71             }
72             elsif (ref($name) ne 'ARRAY')
73             {
74 1         4 $name = [$name];
75             }
76             else
77             {
78 0         0 $name = [grep{! /^_/} @$name];
  0         0  
79             }
80              
81 243         614 for my $key (@$name)
82             {
83 386         802 delete $$data{$key};
84 386         739 delete $$data{_SESSION_PTIME}{$key};
85              
86 386         1553 $self -> modified(1);
87             }
88              
89 243         742 $self -> session($data);
90              
91 243         528 return 1;
92              
93             } # End of clear.
94              
95             # -----------------------------------------------
96              
97             sub cookie
98             {
99 1     1 1 3 my($self) = shift;
100 1         3 my($q) = $self -> query;
101 1         1119 my(@param) = ('-name' => $self -> name, '-value' => $self -> id, @_);
102 1         3 my($cookie) = '';
103              
104 1 50       5 if (! $q -> can('cookie') )
    50          
    50          
105             {
106             }
107             elsif ($self -> expired)
108             {
109 0         0 $cookie = $q -> cookie(@param, -expires => '-1d');
110             }
111             elsif (my($t) = $self -> expire)
112             {
113 1         30 $cookie = $q -> cookie(@param, -expires => "+${t}s");
114             }
115             else
116             {
117 0         0 $cookie = $q -> cookie(@param);
118             }
119              
120 1         407 return $cookie;
121              
122             } # End of cookie.
123              
124             # -----------------------------------------------
125              
126             sub ctime
127             {
128 0     0 1 0 my($self) = @_;
129 0         0 my($data) = $self -> session;
130              
131 0         0 return $$data{_SESSION_CTIME};
132              
133             } # End of ctime.
134              
135             # -----------------------------------------------
136              
137             sub delete
138             {
139 242     242 1 4693 my($self) = @_;
140 242         2724 my($result) = $self -> driver_class -> remove($self -> id);
141              
142 242         654 $self -> clear;
143 242         771 $self -> deleted(1);
144              
145 242         646 return $result;
146              
147             } # End of delete.
148              
149             # -----------------------------------------------
150              
151             sub DESTROY
152             {
153 251     251   11012 my($self) = @_;
154              
155 251         998 $self -> flush;
156              
157             } # End of DESTROY.
158              
159             # -----------------------------------------------
160              
161             sub dump
162             {
163 0     0 1 0 my($self, $heading) = @_;
164 0         0 my($data) = $self -> session;
165              
166 0 0       0 ($heading) && $self -> log($heading);
167              
168 0         0 for my $key (sort keys %$data)
169             {
170 0 0       0 if (ref($$data{$key}) eq 'HASH')
171             {
172 0         0 $self -> log("$key: " . join(', ', map{"$_: $$data{$key}{$_}"} sort keys %{$$data{$key} }) );
  0         0  
  0         0  
173             }
174             else
175             {
176 0         0 $self -> log("$key: $$data{$key}");
177             }
178             }
179              
180             } # End of dump.
181              
182             # -----------------------------------------------
183              
184             sub etime
185             {
186 227     227 1 13680 my($self) = @_;
187 227         697 my($data) = $self -> session;
188              
189 227         1623 return $$data{_SESSION_ETIME};
190              
191             } # End of etime.
192              
193             # -----------------------------------------------
194              
195             sub expire
196             {
197 6     6 1 68 my($self, @arg) = @_;
198              
199 6 100       21 if (! @arg)
200             {
201 2         7 return $self -> etime;
202             }
203              
204 4 100       18 if ($#arg == 0)
205             {
206             # Set the expiry time of the session.
207              
208 2         8 my($data) = $self -> session;
209 2         11 my($time) = $self -> validate_time($arg[0]);
210              
211 2 50       10 if ($$data{_SESSION_ETIME} != $time)
212             {
213 2         4 $$data{_SESSION_ETIME} = $time;
214              
215 2         8 $self -> session($data);
216 2         9 $self -> modified(1);
217             }
218             }
219             else
220             {
221             # Set the expiry times of session parameters.
222              
223 2         9 my($data) = $self -> session;
224 2         5 my($modified) = 0;
225 2         7 my(%arg) = @arg;
226              
227 2         3 my($time);
228              
229             # Warning: The next line ignores 'each %{@arg}'.
230              
231 2         12 while (my($key, $value) = each %arg)
232             {
233 2         8 $time = $self -> validate_time($value);
234              
235 2 100       11 ($time == 0) && next;
236              
237 1 50 33     16 if (! $$data{_SESSION_PTIME}{$key} || ($$data{_SESSION_PTIME}{$key} ne $time) )
238             {
239 1         3 $$data{_SESSION_PTIME}{$key} = $time;
240              
241 1         7 $modified = 1;
242             }
243             }
244              
245 2 100       8 if ($modified)
246             {
247 1         6 $self -> session($data);
248 1         5 $self -> modified(1);
249             }
250             }
251              
252 4         12 return 1;
253              
254             } # End of expire.
255              
256             # -----------------------------------------------
257              
258             sub flush
259             {
260 335     335 1 848 my($self) = @_;
261              
262 335 100 100     2533 if ($self -> modified && ! $self -> deleted)
263             {
264 92         883 $self -> driver_class -> store
265             (
266             $self -> id,
267             $self -> serializer_class -> freeze($self -> session),
268             $self -> etime
269             );
270             }
271              
272 335 50       1556 ($self -> verbose > 1) && $self -> dump('Flushing. New: ' . $self -> is_new . '. Modified: ' . $self -> modified . '. Deleted: ' . $self -> deleted);
273              
274 335         4031 return 1;
275              
276             } # End of flush.
277              
278             # -----------------------------------------------
279              
280             sub get_my_drivers
281             {
282 251     251 0 444 my($self) = @_;
283 251         2766 my($path) = File::Spec -> catdir($INC{'Data/Session.pm'}, 'Driver');
284 251         1446 $path =~ s/.pm//;
285              
286             # Warning: Use sort map{} read_dir, not map{} sort read_dir. But, why?
287              
288 251         1127 my(@driver) = sort map{s/.pm//; $_} read_dir($path);
  2008         29472  
  2008         5211  
289              
290 251 50       1219 ($#driver < 0) && die __PACKAGE__ . '. No drivers available';
291              
292 251 50       1254 ($self -> verbose > 1) && $self -> log('Drivers: ' . join(', ', @driver) );
293              
294 251         1531 $self -> my_drivers(\@driver);
295              
296             } # End of get_my_drivers.
297              
298             # -----------------------------------------------
299              
300             sub get_my_id_generators
301             {
302 251     251 0 433 my($self) = @_;
303 251         2122 my($path) = File::Spec -> catdir($INC{'Data/Session.pm'}, 'ID');
304 251         1155 $path =~ s/.pm//;
305              
306             # Warning: Use sort map{} read_dir, not map{} sort read_dir. But, why?
307              
308 251         725 my(@id_generator) = sort map{s/.pm//; $_} read_dir($path);
  2510         24470  
  2510         5306  
309              
310 251 50       1185 ($#id_generator < 0) && die __PACKAGE__ . '. No id generators available';
311              
312 251 50       992 ($self -> verbose > 1) && $self -> log('Id generators: ' . join(', ', @id_generator) );
313              
314 251         1152 $self -> my_id_generators(\@id_generator);
315              
316             } # End of get_my_id_generators.
317              
318             # -----------------------------------------------
319              
320             sub get_my_serializers
321             {
322 251     251 0 438 my($self) = @_;
323 251         2123 my($path) = File::Spec -> catdir($INC{'Data/Session.pm'}, 'Serialize');
324 251         1238 $path =~ s/.pm//;
325              
326             # Warning: Use sort map{} read_dir, not map{} sort read_dir. But, why?
327              
328 251         786 my(@serializer) = sort map{s/.pm//; $_} read_dir($path);
  1255         21757  
  1255         3137  
329              
330 251 50       844 ($#serializer < 0) && die __PACKAGE__ . '. No serializers available';
331              
332 251 50       1011 ($self -> verbose > 1) && $self -> log('Serializers: ' . join(', ', @serializer) );
333              
334 251         1363 $self -> my_serializers(\@serializer);
335              
336             } # End of get_my_serializers.
337              
338             # -----------------------------------------------
339              
340             sub http_header
341             {
342 1     1 1 5 my($self) = shift;
343 1         5 my($cookie) = $self -> cookie;
344              
345 1         2 my($header);
346              
347 1 50       5 if ($cookie)
348             {
349 1         159 $header = $self -> query -> header(-cookie => $cookie, @_);
350             }
351             else
352             {
353 0         0 $header = $self -> query -> header(@_);
354             }
355              
356 1         6210 return $header;
357              
358             } # End of http_header.
359              
360             # -----------------------------------------------
361              
362             sub load_driver
363             {
364 251     251 0 430 my($self, $arg) = @_;
365 251         960 my($class) = join('::', __PACKAGE__, 'Driver', $self -> driver_option);
366              
367 251         1049 try_load_class($class);
368              
369 251 50       19689 die __PACKAGE__ . ". Unable to load class '$class'" if (! is_class_loaded($class) );
370              
371 251 50       10190 ($self -> verbose > 1) && $self -> log("Loaded driver_option: $class");
372              
373 251         2656 $self -> driver_class($class -> new(%$arg) );
374              
375 251 50       1607 ($self -> verbose > 1) && $self -> log("Initialized driver_class: $class");
376              
377             } # End of load_driver.
378              
379             # -----------------------------------------------
380              
381             sub load_id_generator
382             {
383 251     251 0 420 my($self, $arg) = @_;
384 251         1019 my($class) = join('::', __PACKAGE__, 'ID', $self -> id_option);
385              
386 251         719 try_load_class($class);
387              
388 251 50       14788 die __PACKAGE__ . ". Unable to load class '$class'" if (! is_class_loaded($class) );
389              
390 251 50       14069 ($self -> verbose > 1) && $self -> log("Loaded id_option: $class");
391              
392 251         2896 $self -> id_class($class -> new(%$arg) );
393              
394 251 50       2918 ($self -> verbose > 1) && $self -> log("Initialized id_class: $class");
395              
396             } # End of load_id_generator.
397              
398             # -----------------------------------------------
399              
400             sub load_param
401             {
402 40     40 1 24200 my($self, $q, $name) = @_;
403              
404 40 50       125 if (! defined $q)
405             {
406 40         98 $q = $self -> load_query_class;
407             }
408              
409 40         147 my($data) = $self -> session;
410              
411 40 50       222 if (! $name)
    50          
412             {
413 0         0 $name = [sort keys %$data];
414             }
415             elsif (ref($name) ne 'ARRAY')
416             {
417 0         0 $name = [$name];
418             }
419              
420 40         83 for my $key (grep{! /^_/} @$name)
  80         335  
421             {
422 80         2297 $q -> param($key => $$data{$key});
423             }
424              
425 40         1866 return $q;
426              
427             } # End of load_param.
428              
429             # -----------------------------------------------
430              
431             sub load_query_class
432             {
433 154     154 1 246 my($self) = @_;
434              
435 154 100       757 if (! $self -> query)
436             {
437 119         420 my($class) = $self -> query_class;
438              
439 119         401 try_load_class($class);
440              
441 119 50       6476 die __PACKAGE__ . ". Unable to load class '$class'" if (! is_class_loaded($class) );
442              
443 119 50       4463 ($self -> verbose > 1) && $self -> log('Loaded query_class: ' . $class);
444              
445 119         748 $self -> query($class -> new);
446              
447 119 50       78589 ($self -> verbose > 1) && $self -> log('Called query_class -> new: ' . $class);
448             }
449              
450 154         458 return $self -> query;
451              
452             } # End of load_query_class.
453              
454             # -----------------------------------------------
455              
456             sub load_serializer
457             {
458 251     251 0 475 my($self, $arg) = @_;
459 251         1070 my($class) = join('::', __PACKAGE__, 'Serialize', $self -> serializer_option);
460              
461 251         848 try_load_class($class);
462              
463 251 50       14558 die __PACKAGE__ . ". Unable to load class '$class'" if (! is_class_loaded($class) );
464              
465 251 50       10080 ($self -> verbose > 1) && $self -> log("Loaded serializer_option: $class");
466              
467 251         2693 $self -> serializer_class($class -> new(%$arg) );
468              
469 251 50       1528 ($self -> verbose > 1) && $self -> log("Initialized serializer_class: $class");
470              
471             } # End of load_serializer.
472              
473             # -----------------------------------------------
474              
475             sub load_session
476             {
477 251     251 1 472 my($self) = @_;
478 251         832 my($id) = $self -> user_id;
479              
480 251 50       862 ($self -> verbose > 1) && $self -> log("Loading session for id: $id");
481              
482 251 100       477 if ($id)
483             {
484 137         797 my($raw_data) = $self -> driver_class -> retrieve($id);
485              
486 137 50       1909 ($self -> verbose > 1) && $self -> log("Tried to retrieve session for id: $id. Length of raw data: @{[length($raw_data)]}");
  0         0  
487              
488 137 100       296 if (! $raw_data)
489             {
490 5         17 $self -> new_session($id);
491             }
492             else
493             {
494             # Retrieved an old session, so flag it as accessed, and not-new.
495              
496 132         732 my($data) = $self -> serializer_class -> thaw($raw_data);
497              
498 132 50       22687 if ($self -> verbose > 1)
499             {
500 0         0 for my $key (sort keys %{$$data{_SESSION_PTIME} })
  0         0  
501             {
502 0         0 $self -> log("Recovered session parameter expiry time: $key: $$data{_SESSION_PTIME}{$key}");
503             }
504             }
505              
506 132         673 $self -> id($id);
507 132         665 $self -> is_new(0);
508 132         565 $self -> session($data);
509              
510 132 50       577 ($self -> verbose > 1) && $self -> dump('Loaded');
511              
512             # Check for session expiry.
513              
514 132         462 $self -> check_expiry;
515              
516 132 50       647 ($self -> verbose > 1) && $self -> dump('Loaded and checked expiry');
517              
518             # Check for session parameter expiry.
519             # Stockpile keys to be cleared. We can't call $self -> clear($key) inside the loop,
520             # because it updates $$data{_SESSION_PTIME}, which in turns confuses 'each'.
521              
522 132         234 my(@stack);
523              
524 132         205 while (my($key, $time) = each %{$$data{_SESSION_PTIME} })
  133         843  
525             {
526 1 50 33     9 if ($time && ( ($self -> atime + $time) < time) )
527             {
528 1         4 push @stack, $key;
529             }
530             }
531              
532 132         308 $self -> clear($_) for @stack;
533              
534             # We can't do this above, just after my($data)..., since it's used just above, as $self -> atime().
535              
536 132         435 $self -> atime(time);
537              
538 132 50       589 ($self -> verbose > 1) && $self -> dump('Loaded and checked parameter expiry');
539             }
540             }
541             else
542             {
543 114         365 $self -> new_session(0);
544             }
545              
546 251 50       931 ($self -> verbose > 1) && $self -> log("Loaded session for id: " . $self -> id);
547              
548 251         856 return 1;
549              
550             } # End of load_session.
551              
552             # -----------------------------------------------
553              
554             sub new
555             {
556 251     251 1 6355690 my($class, %arg) = @_;
557 251   50     1460 $arg{debug} ||= 0; # new(...).
558 251         481 $arg{deleted} = 0; # Internal.
559 251         513 $arg{expired} = 0; # Internal.
560 251   100     792 $arg{id} ||= 0; # new(...).
561 251         419 $arg{modified} = 0; # Internal.
562 251   100     926 $arg{name} ||= 'CGISESSID'; # new(...).
563 251   100     976 $arg{query} ||= ''; # new(...).
564 251   50     1065 $arg{query_class} ||= 'CGI'; # new(...).
565 251         528 $arg{session} = {}; # Internal.
566 251   50     572 $arg{type} ||= ''; # new(...).
567 251   50     530 $arg{verbose} ||= 0; # new(...).
568              
569 251         386 my($self);
570              
571             try
572             {
573 251     251   25600 $self = from_hash(bless({}, $class), \%arg);
574              
575 251         1458 $self -> get_my_drivers;
576 251         850 $self -> get_my_id_generators;
577 251         857 $self -> get_my_serializers;
578 251         903 $self -> parse_options;
579 251         729 $self -> validate_options;
580 251         720 $self -> load_driver(\%arg);
581 251         888 $self -> load_id_generator(\%arg);
582 251         882 $self -> load_serializer(\%arg);
583 251         755 $self -> load_session; # Calls user_id() which calls load_query_class() if necessary.
584             }
585             catch
586             {
587 0     0   0 $errstr = $_;
588 0         0 $self = undef;
589 251         2478 };
590              
591 251         7014 return $self;
592              
593             } # End of new.
594              
595             # -----------------------------------------------
596              
597             sub new_session
598             {
599 119     119 0 195 my($self, $id) = @_;
600 119 100       741 $id = $id ? $id : $self -> id_class -> generate;
601 119         7003 my($time) = time;
602              
603 119         1748 $self -> session
604             ({
605             _SESSION_ATIME => $time, # Access time.
606             _SESSION_CTIME => $time, # Create time.
607             _SESSION_ETIME => 0, # Session expiry time.
608             _SESSION_ID => $id, # Session id.
609             _SESSION_PTIME => {}, # Parameter expiry times.
610             });
611              
612 119         465 $self -> id($id);
613 119         714 $self -> is_new(1);
614              
615             } # End of new_session.
616              
617             # -----------------------------------------------
618              
619             sub param
620             {
621 692     692 1 94882 my($self, @arg) = @_;
622 692         1963 my($data) = $self -> session;
623              
624 692 100       2388 if ($#arg < 0)
    100          
625             {
626 242         1566 return grep{! /^_/} sort keys %$data;
  1491         3993  
627             }
628             elsif ($#arg == 0)
629             {
630             # If only 1 name is supplied, return the session's data for that name.
631              
632 283         1824 return $$data{$arg[0]};
633             }
634              
635             # Otherwise, loop over all the supplied data.
636              
637 167         629 my(%arg) = @arg;
638              
639 167         518 for my $key (keys %arg)
640             {
641 167 50       455 next if ($key =~ /^_/);
642              
643             # Don't update a value if it's the same as the original value.
644             # That way we don't update the last-access-time.
645             # We're effectively testing $x == $y, but we're not testing to ensure:
646             # o undef == undef
647             # o 0 == 0
648             # o '' == ''
649             # So changing undef to 0 or visa versa, etc, will all be ignored.
650              
651 167 100 33     885 (! $$data{$key} && ! $arg{$key}) && next;
652              
653 127 0 33     1717 if ( (! $$data{$key} && $arg{$key}) || ($$data{$key} && ! $arg{$key}) || ($$data{$key} ne $arg{$key}) )
      0        
      33        
      0        
654             {
655 127         288 $$data{$key} = $arg{$key};
656              
657 127         770 $self -> modified(1);
658             }
659             }
660              
661 167         557 $self -> session($data);
662              
663 167         527 return 1;
664              
665             } # End of param.
666              
667             # -----------------------------------------------
668             # Format expected: new(type => 'driver:File;id:MD5;serialize:DataDumper').
669              
670             sub parse_options
671             {
672 251     251 0 403 my($self) = @_;
673 251   50     1292 my($options) = $self -> type || '';
674              
675 251 50       1013 ($self -> verbose > 1) && $self -> log("Parsing type '$options'");
676              
677 251         616 $options =~ tr/ //d;
678 251         1250 my(%options) = map{split(/:/, $_)} split(/;/, lc $options); # lc!
  753         2447  
679 251         1121 my(%default) =
680             (
681             driver => 'File',
682             id => 'MD5',
683             serialize => 'DataDumper',
684             );
685              
686 251         1068 for my $key (keys %options)
687             {
688 753 50       2147 (! $default{$key}) && die __PACKAGE__ . ". Error in type: Unexpected component '$key'";
689             }
690              
691 251         529 my(%driver) = map{(lc $_ => $_)} @{$self -> my_drivers};
  2008         10418  
  251         1085  
692 251         957 my(%id_generator) = map{(lc $_ => $_)} @{$self -> my_id_generators};
  2510         6280  
  251         857  
693 251         1321 my(%serializer) = map{(lc $_ => $_)} @{$self -> my_serializers};
  1255         3060  
  251         780  
694              
695             # The sort is just to make the warnings ($required) appear in alphabetical order.
696              
697 251         1146 for my $required (sort keys %default)
698             {
699             # Set default if user does not supply the key:value pair.
700              
701 753 50       1627 if (! exists $options{$required})
702             {
703 0         0 $options{$required} = $default{$required};
704              
705 0 0       0 ($self -> verbose) && $self -> log("Warning for type: Defaulting '$required' to '$default{$required}'");
706             }
707              
708             # Ensure the value is set.
709              
710 753 50       1457 (! $options{$required}) && die __PACKAGE__ . ". Error in type: Missing value for option '$required'";
711              
712             # Ensure the case of the value is correct.
713              
714 753 100       1996 if ($required eq 'driver')
    100          
    50          
715             {
716 251 50       695 if ($driver{lc $options{$required} })
717             {
718 251         769 $options{$required} = $driver{lc $options{$required} };
719             }
720             else
721             {
722 0         0 die __PACKAGE__ . ". Unknown driver '$options{$required}'";
723             }
724             }
725             elsif ($required eq 'id')
726             {
727 251 50       605 if ($id_generator{lc $options{$required} })
728             {
729 251         602 $options{$required} = $id_generator{lc $options{$required} };
730             }
731             else
732             {
733 0         0 die __PACKAGE__ . ". Unknown id generator '$options{$required}'";
734             }
735             }
736             elsif ($required eq 'serialize')
737             {
738 251 50       574 if ($serializer{lc $options{$required} })
739             {
740 251         808 $options{$required} = $serializer{lc $options{$required} };
741             }
742             else
743             {
744 0         0 die __PACKAGE__ . ". Unknown serialize '$options{$required}'";
745             }
746             }
747             }
748              
749 251         1172 $self -> driver_option($options{driver});
750 251         997 $self -> id_option($options{id});
751 251         1005 $self -> serializer_option($options{serialize});
752 251         995 $self -> type(join(';', map{"$_:$options{$_}"} sort keys %default));
  753         2629  
753              
754 251 50       2778 if ($self -> verbose > 1)
755             {
756 0         0 $self -> log('type: ' . $self -> type);
757 0         0 $self -> log('driver_option: ' . $self -> driver_option);
758 0         0 $self -> log('id_option: ' . $self -> id_option);
759 0         0 $self -> log('serializer_option: ' . $self -> serializer_option);
760             }
761              
762             } # End of parse_options.
763              
764             # -----------------------------------------------
765             # Warning: Returns a hashref.
766              
767             sub ptime
768             {
769 1     1 1 11 my($self) = @_;
770 1         5 my($data) = $self -> session;
771              
772 1         5 return $$data{_SESSION_PTIME};
773              
774             } # End of ptime.
775              
776             # -----------------------------------------------
777              
778             sub save_param
779             {
780 40     40 1 409 my($self, $q, $name) = @_;
781              
782 40 50       133 if (! defined $q)
783             {
784 0         0 $q = $self -> load_query_class;
785             }
786              
787 40         135 my($data) = $self -> session;
788              
789 40 50       192 if (! $name)
    50          
790             {
791 0         0 $name = [$q -> param];
792             }
793             elsif (ref($name) ne 'ARRAY')
794             {
795 0         0 $name = [grep{! /^_/} $name];
  0         0  
796             }
797             else
798             {
799 40         79 $name = [grep{! /^_/} @$name];
  80         285  
800             }
801              
802 40         98 for my $key (@$name)
803             {
804 80         240 $$data{$key} = $q -> param($key);
805              
806 80         1687 $self -> modified(1);
807             }
808              
809 40         143 $self -> session($data);
810              
811 40         112 return 1;
812              
813             } # End of save_param.
814              
815             # -----------------------------------------------
816              
817             sub traverse
818             {
819 1     1 1 41 my($self, $sub) = @_;
820              
821 1         9 return $self -> driver_class -> traverse($sub);
822              
823             } # End of traverse.
824              
825             # -----------------------------------------------
826              
827             sub user_id
828             {
829 251     251 1 364 my($self) = @_;
830              
831             # Sources of id:
832             # o User supplied one in $session -> new(id => $id).
833             # o User didn't, so we try $self -> query -> cookie and/or $self -> query -> param.
834              
835 251         777 my($id) = $self -> id;
836              
837 251 100       664 if (! $id)
838             {
839 114         341 $self -> load_query_class;
840              
841 114         471 my($name) = $self -> name;
842 114         291 my($q) = $self -> query;
843              
844 114 50       576 if ($q -> can('cookie') )
845             {
846 114   33     6850 $id = $q -> cookie($name) || $q -> param($name);
847              
848 114 50 0     35191 ($self -> verbose > 1) && $self -> log('query can cookie(). id from cookie or param: ' . ($id || '') );
849             }
850             else
851             {
852 0         0 $id = $q -> param($name);
853              
854 0 0 0     0 ($self -> verbose > 1) && $self -> log("query can't cookie(). id from param: " . ($id || '') );
855             }
856              
857 114 50       324 if (! $id)
858             {
859 114         261 $id = 0;
860             }
861             }
862              
863 251         608 return $id;
864              
865             } # End of user_id.
866              
867             # -----------------------------------------------
868              
869             sub validate_options
870             {
871 251     251 1 343 my($self) = @_;
872              
873 251 50 66     1504 if ( ($self -> id_option eq 'Static') && ! $self -> id)
874             {
875 0         0 die __PACKAGE__ . '. When using id:Static, you must provide a (true) id to new(id => ...)';
876             }
877              
878             } # End of validate_options.
879              
880             # -----------------------------------------------
881              
882             sub validate_time
883             {
884 7     7 1 916 my($self, $time) = @_;
885              
886 7 100       41 (! $time) && return 0;
887              
888 6 100       36 $time = "${time}s" if ($time =~ /\d$/);
889              
890 6 50       33 ($time !~ /^([-+]?\d+)([smhdwMy])$/) && die __PACKAGE__ . ". Can't parse time: $time";
891              
892 6         37 my(%scale) =
893             (
894             s => 1,
895             m => 60,
896             h => 3600,
897             d => 86400,
898             w => 604800,
899             M => 2592000,
900             y => 31536000,
901             );
902              
903 6         67 return $scale{$2} * $1;
904              
905             } # End of validate_time.
906              
907             # -----------------------------------------------
908              
909             1;
910              
911             =pod
912              
913             =head1 NAME
914              
915             Data::Session - Persistent session data management
916              
917             =head1 Synopsis
918              
919             1: A self-contained CGI script (scripts/cgi.demo.cgi):
920              
921             #!/usr/bin/perl
922              
923             use CGI;
924              
925             use Data::Session;
926              
927             use File::Spec;
928              
929             # ----------------------------------------------
930              
931             sub generate_html
932             {
933             my($name, $id, $count) = @_;
934             $id ||= '';
935             my($title) = "CGI demo for Data::Session";
936             return <
937            
938             $title
939            
940             Number of times this script has been run: $count.
941             Current value of $name: $id.
942            
943            
944            
945            
946            
947            
948             EOS
949              
950             } # End of generate_html.
951              
952             # ----------------------------------------------
953              
954             my($q) = CGI -> new;
955             my($name) = 'sid'; # CGI form field name.
956             my($sid) = $q -> param($name);
957             my($dir_name) = '/tmp';
958             my($type) = 'driver:File;id:MD5;serialize:JSON';
959             my($session) = Data::Session -> new
960             (
961             directory => $dir_name,
962             name => $name,
963             query => $q,
964             type => $type,
965             );
966             my($id) = $session -> id;
967              
968             # First entry ever?
969              
970             my($count);
971              
972             if ($sid) # Not $id, which always has a value...
973             {
974             # No. The CGI form field called sid has a (true) value.
975             # So, this is the code for the second and subsequent entries.
976             # Count the # of times this CGI script has been run.
977              
978             $count = $session -> param('count') + 1;
979             }
980             else
981             {
982             # Yes. There is no CGI form field called sid (with a true value).
983             # So, this is the code for the first entry ever.
984             # Count the # of times this CGI script has been run.
985              
986             $count = 0;
987             }
988              
989             $session -> param(count => $count);
990              
991             print $q -> header, generate_html($name, $id, $count);
992              
993             # Calling flush() is good practice, rather than hoping 'things just work'.
994             # In a persistent environment, this call is mandatory...
995             # But you knew that, because you'd read the docs, right?
996              
997             $session -> flush;
998              
999             2: A basic session. See scripts/sqlite.pl:
1000              
1001             # The EXLOCK is for BSD-based systems.
1002             my($directory) = File::Temp::newdir('temp.XXXX', CLEANUP => 1, EXLOCK => 0, TMPDIR => 1);
1003             my($data_source) = 'dbi:SQLite:dbname=' . File::Spec -> catdir($directory, 'sessions.sqlite');
1004             my($type) = 'driver:SQLite;id:SHA1;serialize:DataDumper'; # Case-sensitive.
1005             my($session) = Data::Session -> new
1006             (
1007             data_source => $data_source,
1008             type => $type,
1009             ) || die $Data::Session::errstr;
1010              
1011             3: Using BerkeleyDB as a cache manager. See scripts/berkeleydb.pl:
1012              
1013             # The EXLOCK is for BSD-based systems.
1014             my($file_name) = File::Temp -> new(EXLOCK => 0, SUFFIX => '.bdb');
1015             my($env) = BerkeleyDB::Env -> new
1016             (
1017             Home => File::Spec -> tmpdir,
1018             Flags => DB_CREATE | DB_INIT_CDB | DB_INIT_MPOOL,
1019             );
1020             if (! $env)
1021             {
1022             print "BerkeleyDB is not responding. \n";
1023             exit;
1024             }
1025             my($bdb) = BerkeleyDB::Hash -> new(Env => $env, Filename => $file_name, Flags => DB_CREATE);
1026             if (! $bdb)
1027             {
1028             print "BerkeleyDB is not responding. \n";
1029             exit;
1030             }
1031             my($type) = 'driver:BerkeleyDB;id:SHA1;serialize:DataDumper'; # Case-sensitive.
1032             my($session) = Data::Session -> new
1033             (
1034             cache => $bdb,
1035             type => $type,
1036             ) || die $Data::Session::errstr;
1037              
1038             4: Using memcached as a cache manager. See scripts/memcached.pl:
1039              
1040             my($memd) = Cache::Memcached -> new
1041             ({
1042             namespace => 'data.session.id',
1043             servers => ['127.0.0.1:11211'],
1044             });
1045             my($test) = $memd -> set(time => time);
1046             if (! $test || ($test != 1) )
1047             {
1048             print "memcached is not responding. \n";
1049             exit;
1050             }
1051             $memd -> delete('time');
1052             my($type) = 'driver:Memcached;id:SHA1;serialize:DataDumper'; # Case-sensitive.
1053             my($session) = Data::Session -> new
1054             (
1055             cache => $memd,
1056             type => $type,
1057             ) || die $Data::Session::errstr;
1058              
1059             5: Using a file to hold the ids. See scripts/file.autoincrement.pl:
1060              
1061             # The EXLOCK is for BSD-based systems.
1062             my($directory) = File::Temp::newdir('temp.XXXX', CLEANUP => 1, EXLOCK => 0, TMPDIR => 1);
1063             my($file_name) = 'autoinc.session.dat';
1064             my($id_file) = File::Spec -> catfile($directory, $file_name);
1065             my($type) = 'driver:File;id:AutoIncrement;serialize:DataDumper'; # Case-sensitive.
1066             my($session) = Data::Session -> new
1067             (
1068             id_base => 99,
1069             id_file => $id_file,
1070             id_step => 2,
1071             type => $type,
1072             ) || die $Data::Session::errstr;
1073              
1074             6: Using a file to hold the ids. See scripts/file.sha1.pl (non-CGI context):
1075              
1076             my($directory) = '/tmp';
1077             my($file_name) = 'session.%s.dat';
1078             my($type) = 'driver:File;id:SHA1;serialize:DataDumper'; # Case-sensitive.
1079              
1080             # Create the session:
1081             my($session) = Data::Session -> new
1082             (
1083             directory => $directory,
1084             file_name => $file_name,
1085             type => $type,
1086             ) || die $Data::Session::errstr;
1087              
1088             # Time passes...
1089              
1090             # Retrieve the session:
1091             my($id) = $session -> id;
1092             my($session) = Data::Session -> new
1093             (
1094             directory => $directory,
1095             file_name => $file_name,
1096             id => $id, # <== Look! You must supply the id for retrieval.
1097             type => $type,
1098             ) || die $Data::Session::errstr;
1099              
1100             7: As a variation on the above, see scripts/cgi.sha1.pl (CGI context but command line program):
1101              
1102             # As above (scripts/file.sha1.pl), for creating the session. Then...
1103              
1104             # Retrieve the session:
1105             my($q) = CGI -> new; # CGI form data provides the id.
1106             my($session) = Data::Session -> new
1107             (
1108             directory => $directory,
1109             file_name => $file_name,
1110             query => $q, # <== Look! You must supply the id for retrieval.
1111             type => $type,
1112             ) || die $Data::Session::errstr;
1113              
1114             Also, much can be gleaned from t/basic.t and t/Test.pm. See L.
1115              
1116             =head1 Description
1117              
1118             L is typically used by a CGI script to preserve state data between runs of the script.
1119             This gives the end user the illusion that the script never exits.
1120              
1121             It can also be used to communicate between 2 scripts, as long as they agree beforehand what session id to use.
1122              
1123             See L for an extended discussion of the design changes between L
1124             and L.
1125              
1126             L stores user data internally in a hashref, and the module reserves key names starting with '_'.
1127              
1128             The current list of reserved keys is documented under L.
1129              
1130             Of course, the module also has a whole set of methods to help manage state.
1131              
1132             =head1 Methods
1133              
1134             =head2 new()
1135              
1136             Calling new() returns a object of type L, or - if new() fails - it returns undef.
1137             For details see L.
1138              
1139             new() takes a hash of key/value pairs, some of which might mandatory. Further, some combinations
1140             might be mandatory.
1141              
1142             The keys are listed here in alphabetical order.
1143              
1144             They are lower-case because they are (also) method names, meaning they can be called to set or get the value
1145             at any time.
1146              
1147             But a warning: In some cases, setting them after this module has used the previous value, will have no effect.
1148             All such cases should be documented.
1149              
1150             Beginners understandably confused by the quantity of options should consult the L for example code.
1151              
1152             The questions of combinations of options, and which option has priority over other options,
1153             are addressed in the section, L.
1154              
1155             =over 4
1156              
1157             =item o cache => $cache
1158              
1159             Specifies an object of type L or L to use for storage.
1160              
1161             Only needed if you use 'type' like 'driver:BerkeleyDB ...' or 'driver:Memcached ...'.
1162              
1163             See L and L.
1164              
1165             Default: '' (the empty string).
1166              
1167             =item o data_col_name => $string
1168              
1169             Specifies the name of the column holding the session data, in the session table.
1170              
1171             This key is optional.
1172              
1173             Default: 'a_session'.
1174              
1175             =item o data_source => $string
1176              
1177             Specifies a value to use as the 1st parameter in the call to L's connect() method.
1178              
1179             A typical value would be 'dbi:Pg:dbname=project'.
1180              
1181             This key is optional. It is only used if you do not supply a value for the 'dbh' key.
1182              
1183             Default: '' (the empty string).
1184              
1185             =item o data_source_attrs => $hashref
1186              
1187             Specify a hashref of options to use as the last parameter in the call to L's connect() method.
1188              
1189             This key is optional. It is only used if you do not supply a value for the 'dbh' key.
1190              
1191             Default: {AutoCommit => 1, PrintError => 0, RaiseError => 1}.
1192              
1193             =item o dbh => $dbh
1194              
1195             Specifies a database handle to use to access the session table.
1196              
1197             This key is optional.
1198              
1199             However, if not specified, you must specify a value for 'data_source', and perhaps also 'username' and 'password',
1200             so that this module can create a database handle.
1201              
1202             If this module does create a database handle, it will also destroy it, whereas if you supply a database
1203             handle, you are responsible for destroying it.
1204              
1205             =item o debug => $Boolean
1206              
1207             Specifies that debugging should be turned on (1) or off (0) in L and
1208             L.
1209              
1210             When debug is 1, $! is included in error messages, but because this reveals directory names, it is 0 by default.
1211              
1212             This key is optional.
1213              
1214             Default: 0.
1215              
1216             =item o directory => $string
1217              
1218             Specifies the directory in which session files are stored, when each session is stored in a separate file
1219             (by using 'driver:File ...' as the first component of the 'type').
1220              
1221             This key is optional.
1222              
1223             Default: Your temp directory as determined by L.
1224              
1225             See L for details.
1226              
1227             =item o file_name => $string_containing_%s
1228              
1229             Specifies the syntax for the names of session files, when each session is stored in a separate file
1230             (by using 'driver:File ...' as the first component of the 'type').
1231              
1232             This key is optional.
1233              
1234             Default: 'cgisess_%s', where the %s is replaced at run-time by the session id.
1235              
1236             The directory in which these files are stored is specified by the 'directory' option above.
1237              
1238             See L for details.
1239              
1240             =item o host => $string
1241              
1242             Specifies a host, typically for use with a data_source referring to MySQL.
1243              
1244             This key is optional.
1245              
1246             Default: '' (the empty string).
1247              
1248             =item o id => $string
1249              
1250             Specifies an id to retrieve from storage.
1251              
1252             This key is optional.
1253              
1254             Default: 0.
1255              
1256             Note: If you do not provide an id here, the module calls L to determine whether or not
1257             an id is available from a cookie or a form field.
1258              
1259             This complex topic is discussed in the section L.
1260              
1261             =item o id_col_name => $string
1262              
1263             Specifies the name of the column holding the session id, in the session table.
1264              
1265             This key is optional.
1266              
1267             Default: 'id'.
1268              
1269             =item o id_base => $integer
1270              
1271             Specifies the base from which to start ids when using the '... id:AutoIncrement ...' component in the 'type'.
1272              
1273             Note: The first id returned by L will be id_base + id_step.
1274             So, if id_base is 1000 and id_step is 10, then the lowest id will be 1010.
1275              
1276             This key is optional.
1277              
1278             Default: 0.
1279              
1280             =item o id_file => $file_path_and_name
1281              
1282             Specifies the file path and name in which to store the last used id, as calculated from id_base + id_step,
1283             when using the '... id:AutoIncrement ...' component in the 'type'.
1284              
1285             This value must contain a path because the 'directory' option above is only used for session files
1286             (when using L).
1287              
1288             This key is optional.
1289              
1290             Default: File::Spec -> catdir(File::Spec -> tmpdir, 'data.session.id').
1291              
1292             =item o id_step => $integer
1293              
1294             Specifies the step size between ids when using the '... id:AutoIncrement ...' component of the 'type'.
1295              
1296             This key is optional.
1297              
1298             Default: 1.
1299              
1300             =item o name => $string
1301              
1302             Specifies the name of the cookie or form field which holds the session id.
1303              
1304             This key is optional.
1305              
1306             Default: 'CGISESSID'.
1307              
1308             Usage of 'name' is discussed in the sections L and L.
1309              
1310             =item o no_flock => $boolean
1311              
1312             Specifies (no_flock => 1) to not use flock() to obtain a lock on a session file before processing it,
1313             or (no_flock => 0) to use flock().
1314              
1315             This key is optional.
1316              
1317             Default: 0.
1318              
1319             This value is used in these cases:
1320              
1321             =over 4
1322              
1323             =item o type => 'driver:File ...'
1324              
1325             =item o type => '... id:AutoIncrement ...'
1326              
1327             =back
1328              
1329             =item o no_follow => $boolean
1330              
1331             Influences the mode to use when calling sysopen() on session files.
1332              
1333             'Influences' means the value is bit-wise ored with O_RDWR for reading and with O_WRONLY for writing.
1334              
1335             This key is optional.
1336              
1337             Default: eval { O_NOFOLLOW } || 0.
1338              
1339             This value is used in this case:
1340              
1341             =over 4
1342              
1343             =item o type => 'driver:File ...'
1344              
1345             =back
1346              
1347             =item o password => $string
1348              
1349             Specifies a value to use as the 3rd parameter in the call to L's connect() method.
1350              
1351             This key is optional. It is only used if you do not supply a value for the 'dbh' key.
1352              
1353             Default: '' (the empty string).
1354              
1355             =item o pg_bytea => $boolean
1356              
1357             Specifies that you're using a Postgres-specific column type of 'bytea' to hold the session data,
1358             in the session table.
1359              
1360             This key is optional, but see the section, L for how it interacts with the pg_text key.
1361              
1362             Default: 0.
1363              
1364             Warning: Columns of type bytea can hold null characters (\x00), whereas columns of type text cannot.
1365              
1366             =item o pg_text => $boolean
1367              
1368             Specifies that you're using a Postgres-specific column type of 'text' to hold the session data, in the session table.
1369              
1370             This key is optional, but see the section, L for how it interacts with the pg_bytea key.
1371              
1372             Default: 0.
1373              
1374             Warning: Columns of type bytea can hold null characters (\x00), whereas columns of type text cannot.
1375              
1376             =item o port => $string
1377              
1378             Specifies a port, typically for use with a data_source referring to MySQL.
1379              
1380             This key is optional.
1381              
1382             Default: '' (the empty string).
1383              
1384             =item o query => $q
1385              
1386             Specifies the query object.
1387              
1388             If not specified, the next option - 'query_class' - will be used to create a query object.
1389              
1390             Either way, the object will be accessible via the $session -> query() method.
1391              
1392             This key is optional.
1393              
1394             Default: '' (the empty string).
1395              
1396             =item o query_class => $class_name
1397              
1398             Specifies the class of query object to create if a value is not provided for the 'query' option.
1399              
1400             This key is optional.
1401              
1402             Default: 'CGI'.
1403              
1404             =item o socket => $string
1405              
1406             Specifies a socket, typically for use with a data_source referring to MySQL.
1407              
1408             The reason this key is called socket and not mysql_socket is in case other drivers permit a socket
1409             option.
1410              
1411             This key is optional.
1412              
1413             Default: '' (the empty string).
1414              
1415             =item o table_name => $string
1416              
1417             Specifies the name of the table holding the session data.
1418              
1419             This key is optional.
1420              
1421             Default: 'sessions'.
1422              
1423             =item o type => $string
1424              
1425             Specifies the type of L object you wish to create.
1426              
1427             This key is optional.
1428              
1429             Default: 'driver:File;id:MD5;serialize:DataDumper'.
1430              
1431             This complex topic is discussed in the section L.
1432              
1433             =item o umask => $octal_number
1434              
1435             Specifies the mode to use when calling sysopen() on session files.
1436              
1437             This value is used in these cases:
1438              
1439             =over 4
1440              
1441             =item o type => 'driver:File ...'
1442              
1443             =item o type => '... id:AutoIncrement ...'
1444              
1445             =back
1446              
1447             Default: 0660 (octal).
1448              
1449             =item o username => $string
1450              
1451             Specifies a value to use as the 2nd parameter in the call to L's connect() method.
1452              
1453             This key is optional. It is only used if you do not supply a value for the 'dbh' key.
1454              
1455             Default: '' (the empty string).
1456              
1457             =item o verbose => $integer
1458              
1459             Print to STDERR more or less information.
1460              
1461             Typical values are 0, 1 and 2.
1462              
1463             This key is optional.
1464              
1465             Default: 0, meaings nothing is printed.
1466              
1467             See L for what happens when verbose is 2.
1468              
1469             =back
1470              
1471             =head3 Specifying Session Options
1472              
1473             See also L.
1474              
1475             The default 'type' string is 'driver:File;id:MD5;serialize:DataDumper'. It consists of 3 optional components
1476             separated by semi-colons.
1477              
1478             Each of those 3 components consists of 2 fields (a key and a value) separated by a colon.
1479              
1480             The keys:
1481              
1482             =over 4
1483              
1484             =item o driver
1485              
1486             This specifies what type of persistent storage you wish to use for session data.
1487              
1488             Values for 'driver':
1489              
1490             =over 4
1491              
1492             =item o BerkeleyDB
1493              
1494             Use L for storage. In this case, you must pass an object of type L
1495             to new() as the value of the 'cache' option.
1496              
1497             See L.
1498              
1499             =item o File
1500              
1501             The default, 'File', says sessions are each stored in a separate file.
1502              
1503             The directory for these files is specified with the 'directory' option to new().
1504              
1505             If a directory is not specified in that way, L is used to find your temp directory.
1506              
1507             The names of the session files are generated from the 'file_name' option to new().
1508              
1509             The default file name (pattern) is 'cgisess_%s', where the %s is replaced by the session id.
1510              
1511             See L.
1512              
1513             =item o Memcached
1514              
1515             Use C for storage. In this case, you must pass an object of type L to new() as the
1516             value of the 'cache' option.
1517              
1518             See L.
1519              
1520             =item o mysql
1521              
1522             This says each session is stored in a separate row of a database table using the L database server.
1523              
1524             These rows have a unique primary id equal to the session id.
1525              
1526             See L.
1527              
1528             =item o ODBC
1529              
1530             This says each session is stored in a separate row of a database table using the L database connector.
1531              
1532             These rows have a unique primary id equal to the session id.
1533              
1534             See L.
1535              
1536             =item o Oracle
1537              
1538             This says each session is stored in a separate row of a database table using the L database server.
1539              
1540             These rows have a unique primary id equal to the session id.
1541              
1542             See L.
1543              
1544             =item o Pg
1545              
1546             This says each session is stored in a separate row of a database table using the L database server.
1547              
1548             These rows have a unique primary id equal to the session id.
1549              
1550             See L.
1551              
1552             =item o SQLite
1553              
1554             This says each session is stored in a separate row of a database table using the SQLite database server.
1555              
1556             These rows have a unique primary id equal to the session id.
1557              
1558             The advantage of SQLite is that a client I are shipped with all recent versions of Perl.
1559              
1560             See L.
1561              
1562             =back
1563              
1564             =item o id
1565              
1566             This specifies what type of id generator you wish to use.
1567              
1568             Values for 'id':
1569              
1570             =over 4
1571              
1572             =item o AutoIncrement
1573              
1574             This says ids are generated starting from a value specified with the 'id_base' option to new(),
1575             and the last-used id is stored in the file name given by the 'id_file' option to new().
1576              
1577             This file name must include a path, since the 'directory' option to new() is I used here.
1578              
1579             When a new id is required, the value in the file is incremented by the value of the 'id_step' option to new(),
1580             with the new value both written back to the file and returned as the new session id.
1581              
1582             The default value of id_base is 0, and the default value of id_step is 1. Together, the first id available
1583             as a session id is id_base + id_step = 1.
1584              
1585             The sequence starts when the module cannot find the given file, or when its contents are not numeric.
1586              
1587             See L.
1588              
1589             =item o MD5
1590              
1591             The default, 'MD5', says ids are to be generated by L.
1592              
1593             See L.
1594              
1595             =item o SHA1
1596              
1597             This says ids are to be generated by L, using a digest algorithm of 1.
1598              
1599             See L.
1600              
1601             =item o SHA256
1602              
1603             This says ids are to be generated by L, using a digest algorithm of 256.
1604              
1605             See L.
1606              
1607             =item o SHA512
1608              
1609             This says ids are to be generated by L, using a digest algorithm of 512.
1610              
1611             See L.
1612              
1613             =item o Static
1614              
1615             This says that the id passed in to new(), as the value of the 'id' option, will be used as the
1616             session id for every session.
1617              
1618             Of course, this id must have a true value. L dies on all values Perl regards as false.
1619              
1620             See L.
1621              
1622             =item o UUID16
1623              
1624             This says ids are to be generated by L, to generate a 16 byte long binary UUID.
1625              
1626             See L.
1627              
1628             =item o UUID34
1629              
1630             This says ids are to be generated by L, to generate a 34 byte long string UUID.
1631              
1632             See L.
1633              
1634             =item o UUID36
1635              
1636             This says ids are to be generated by L, to generate a 36 byte long string UUID.
1637              
1638             See L.
1639              
1640             =item o UUID64
1641              
1642             This says ids are to be generated by L, to generate a 24 (sic) byte long, base-64 encoded, UUID.
1643              
1644             See L.
1645              
1646             =back
1647              
1648             See scripts/digest.pl which prints the length of each type of digest.
1649              
1650             =item o serialize
1651              
1652             The specifies what type of mechanism you wish to use to convert the in-memory session data into a form
1653             appropriate for your chosen storage type.
1654              
1655             Values for 'serialize':
1656              
1657             =over 4
1658              
1659             =item o DataDumper
1660              
1661             Use L to freeze/thaw sessions.
1662              
1663             See L.
1664              
1665             =item o FreezeThaw
1666              
1667             Use L to freeze/thaw sessions.
1668              
1669             See L.
1670              
1671             =item o JSON
1672              
1673             Use L to freeze/thaw sessions.
1674              
1675             See L.
1676              
1677             =item o Storable
1678              
1679             Use L to freeze/thaw sessions.
1680              
1681             See L.
1682              
1683             Warning: Storable should be avoided until this problem is fixed: http://rt.cpan.org/Public/Bug/Display.html?id=36087
1684              
1685             =item o YAML
1686              
1687             Use L to freeze/thaw sessions.
1688              
1689             See L.
1690              
1691             =back
1692              
1693             =back
1694              
1695             =head3 Case-sensitive Options
1696              
1697             Just to emphasize: The names of drivers, etc follow the DBD::* (or similar) style of case-sensitivity.
1698              
1699             The following classes for drivers, id generators and serializers, are shipped with this package.
1700              
1701             Drivers:
1702              
1703             =over 4
1704              
1705             =item o L
1706              
1707             This name comes from L.
1708              
1709             And yes, the module uses L and not L.
1710              
1711             =item o L
1712              
1713             =item o L
1714              
1715             This name comes from L even though the external program you run is called memcached.
1716              
1717             =item o L
1718              
1719             =item o L
1720              
1721             =item o L
1722              
1723             =item o L
1724              
1725             =item o L
1726              
1727             =back
1728              
1729             ID generators:
1730              
1731             =over 4
1732              
1733             =item o L
1734              
1735             =item o L
1736              
1737             =item o L
1738              
1739             =item o L
1740              
1741             =item o L
1742              
1743             =item o L
1744              
1745             =item o L
1746              
1747             =item o L
1748              
1749             =item o L
1750              
1751             =item o L
1752              
1753             =back
1754              
1755             Serializers:
1756              
1757             =over 4
1758              
1759             =item o L
1760              
1761             =item o L
1762              
1763             =item o L
1764              
1765             =item o L
1766              
1767             Warning: Storable should be avoided until this problem is fixed: http://rt.cpan.org/Public/Bug/Display.html?id=36087
1768              
1769             =item o L
1770              
1771             =back
1772              
1773             =head3 Specifying an Id
1774              
1775             L is called to determine if an id is available from a cookie or a form field.
1776              
1777             There are several cases to consider:
1778              
1779             =over 4
1780              
1781             =item o You specify an id which exists in storage
1782              
1783             You can check this with the call $session -> is_new, which will return 0.
1784              
1785             $session -> id will return the old id.
1786              
1787             =item o You do not specify an id
1788              
1789             The module generates a new session and a new id.
1790              
1791             You can check this with the call $session -> is_new, which will return 1.
1792              
1793             $session -> id will return the new id.
1794              
1795             =item o You specify an id which does not exist in storage
1796              
1797             You can check this with the call $session -> is_new, which will return 1.
1798              
1799             $session -> id will return the old id.
1800              
1801             =back
1802              
1803             So, how to tell the difference between the last 2 cases? Like this:
1804              
1805             if ($session -> id == $session -> user_id)
1806             {
1807             # New session using user-supplied id.
1808             }
1809             else
1810             {
1811             # New session with new id.
1812             }
1813              
1814             =head3 Combinations of Options
1815              
1816             See also L, for options-related combinations.
1817              
1818             =over 4
1819              
1820             =item o dbh
1821              
1822             If you don't specify a value for the 'dbh' key, this module must create a database handle in those cases
1823             when you specify a database driver of some sort in the value for 'type'.
1824              
1825             To create that handle, we needs a value for 'data_source', and that in turn may require values for 'username'
1826             and 'password'.
1827              
1828             When using SQLite, just specify a value for 'data_source'. The default values for 'username' and 'password' -
1829             empty strings - will work.
1830              
1831             =item o file_name and id_file
1832              
1833             When using new(type => 'driver:File;id:AutoIncrement;...'), then file_name is ignored and id_file is used.
1834              
1835             If id_file is not supplied, it defaults to File::Spec -> catdir(File::Spec -> tmpdir, 'data.session.id').
1836              
1837             When using new(type => 'driver:File;id:;...'), then id_file is ignored and file_name is used.
1838              
1839             If file_name is not supplied, it defaults to 'cgisess_%s'. Note the mandatory %s.
1840              
1841             =item o pg_bytea and pg_text
1842              
1843             If you set 'pg_bytea' to 1, then 'pg_text' will be set to 0.
1844              
1845             If you set 'pg_text' to 1, then 'pg_bytea' will be set to 0.
1846              
1847             If you set them both to 0 (i.e. the default), then 'pg_bytea' will be set to 1.
1848              
1849             If you set them both to 1, 'pg_bytea' will be left as 1 and 'pg_text' will be set to 0.
1850              
1851             This choice was made because you really should be using a column type of 'bytea' for a_session
1852             in the sessions table, since the type 'text' does not handle null (\x00) characters.
1853              
1854             =back
1855              
1856             =head2 atime([$atime])
1857              
1858             The [] indicates an optional parameter.
1859              
1860             Returns the last access time of the session.
1861              
1862             By default, the value comes from calling Perl's time() function, or you may pass in a time,
1863             which is then used to set the last access time of the session.
1864              
1865             This latter alternative is used by L.
1866              
1867             See also L, L and L.
1868              
1869             =head2 check_expiry()
1870              
1871             Checks that there is an expiry time set for the session, and, if (atime + etime) < time():
1872              
1873             =over 4
1874              
1875             =item o Deletes the session
1876              
1877             See L for precisely what this means.
1878              
1879             =item o Sets the expired flag
1880              
1881             See L.
1882              
1883             =back
1884              
1885             This is used when the session is loaded, when you call L, and by scripts/expire.pl.
1886              
1887             =head2 clear([$name])
1888              
1889             The [] indicates an optional parameter.
1890              
1891             Returns 1.
1892              
1893             Specifies that you wish to delete parameters stored in the session, i.e. stored by previous calls to param().
1894              
1895             $name is a parameter name or an arrayref of parameter names.
1896              
1897             If $name is not specified, it is set to the list of all unreserved keys (parameter names) in the session.
1898              
1899             See L for details.
1900              
1901             =head2 cookie([@arg])
1902              
1903             The [] indicates an optional parameter.
1904              
1905             Returns a cookie, or '' (the empty string) if the query object does not have a cookie() method.
1906              
1907             Use the @arg parameter to pass any extra parameters to the query object's cookie() method.
1908              
1909             Warning: Parameters which are handled by L, and hence should I be passed in, are:
1910              
1911             =over 4
1912              
1913             =item o -expires
1914              
1915             =item o -name
1916              
1917             =item o -value
1918              
1919             =back
1920              
1921             See L and scripts/cookie.pl.
1922              
1923             =head2 ctime()
1924              
1925             Returns the creation time of the session.
1926              
1927             The value comes from calling Perl's time() function when the session was created.
1928              
1929             This is not the creation time of the session I, except for new sessions.
1930              
1931             See also L, L and L.
1932              
1933             =head2 delete()
1934              
1935             Returns the result of calling the driver's remove() method.
1936              
1937             Specifies that you want to delete the session. Here's what it does:
1938              
1939             =over 4
1940              
1941             =item o Immediately deletes the session from storage
1942              
1943             =item o Calls clear()
1944              
1945             This deletes all non-reserved parameters from the session object, and marks it as modified.
1946              
1947             =item o Marks the session object as deleted
1948              
1949             =back
1950              
1951             The latter step means that when (or if) the session object goes out of scope, it will not be flushed
1952             to storage.
1953              
1954             Likewise, if you call flush(), the call will be ignored.
1955              
1956             Nevertheless, the session object is still fully functional - it just can't be saved or retrieved.
1957              
1958             See also L and L.
1959              
1960             =head2 deleted()
1961              
1962             Returns a Boolean (0/1) indicating whether or not the session has been deleted.
1963              
1964             See also L and L.
1965              
1966             =head2 dump([$heading])
1967              
1968             The [] indicates an optional parameter.
1969              
1970             Dumps the session's contents to STDERR, with a prefix of '# '.
1971              
1972             The $heading, if any, is written first, on a line by itself, with the same prefix.
1973              
1974             This is especially useful for testing, since it fits in with the L method diag().
1975              
1976             When verbose is 2, dump is called at these times:
1977              
1978             =over 4
1979              
1980             =item o When a session is flushed
1981              
1982             =item o As soon as a session is loaded
1983              
1984             =item o As soon as expiry is checked on a just-loaded session
1985              
1986             =item o As soon as parameter expiry is checked on a just-loaded session
1987              
1988             =back
1989              
1990             =head2 etime()
1991              
1992             Returns the expiry time of the session.
1993              
1994             This is the same as calling $session -> expiry(). In fact, this just calls $session -> etime.
1995              
1996             See also L, L and L.
1997              
1998             =head2 expire([@arg])
1999              
2000             The [] indicates an optional parameter.
2001              
2002             Specifies that you wish to set or retrieve the session's expiry time, or set the expiry times of session
2003             parameters.
2004              
2005             Integer time values ($time below) are assumed to be seconds. The value may be positive or 0 or negative.
2006              
2007             These expiry times are relative to the session's last access time, not the session's creation time.
2008              
2009             In all cases, a time of 0 disables expiry.
2010              
2011             This affects users of L. See below and L.
2012              
2013             When a session expires, it is deleted from storage. See L for details.
2014              
2015             The test for whether or not a session has expired only takes place when a session is loaded from storage.
2016              
2017             When a session parameter expires, it is deleted from the session object. See L
2018             for details.
2019              
2020             The test for whether or not a session parameter has expired only takes place when a session is loaded from storage.
2021              
2022             =over 4
2023              
2024             =item o $session -> expire()
2025              
2026             Use $session -> expire() to return the session's expiry time. This just calls $session -> etime.
2027              
2028             The default expiry time is 0, meaning the session will never expire. Likewise, by default, session
2029             parameters never expire.
2030              
2031             =item o $session -> expire($time)
2032              
2033             Use $session -> expire($time) to set the session's expiry time.
2034              
2035             Use these suffixes to change the interpretation of the integer you specify:
2036              
2037             +-----------+---------------+
2038             | Suffix | Meaning |
2039             +-----------+---------------+
2040             | s | Second |
2041             | m | Minute |
2042             | h | Hour |
2043             | d | Day |
2044             | w | Week |
2045             | M | Month |
2046             | y | Year |
2047             +-----------+---------------+
2048              
2049             Hence $session -> expire('2h') means expire the session in 2 hours.
2050              
2051             expire($time) calls validate_time($time) to perform the conversion from '2h' to seconds,
2052             so L is available to you too.
2053              
2054             If setting a time like this, expire($time) returns 1.
2055              
2056             Note: The time set here is passed as the 3rd parameter to the storage driver's store() method (for all
2057             types of storage), and from there as the 3rd parameter to the set() method of L.
2058             Of course, this doesn't happen immediately - it only happens when the session is saved.
2059              
2060             =item o $session -> expire($key_1 => $time_1[, $key_2 => $time_2...])
2061              
2062             Use $session -> expire($key_1 => $time_1[, $key_2 => $time_2...]) to set the expiry times of session parameters.
2063              
2064             =back
2065              
2066             Special cases:
2067              
2068             =over 4
2069              
2070             =item o To expire the session immediately, call delete()
2071              
2072             =item o To expire a session parameter immediately, call clear($key)
2073              
2074             =back
2075              
2076             See also L, L, L, L and
2077             L.
2078              
2079             =head2 expired()
2080              
2081             Returns a Boolean (0/1) indicating whether or not the session has expired.
2082              
2083             See L.
2084              
2085             =head2 flush()
2086              
2087             Returns 1.
2088              
2089             Specifies that you want the session object immediately written to storage.
2090              
2091             If you have previously called delete(), the call to flush() is ignored.
2092              
2093             If the object has not been modified, the call to flush() is ignored.
2094              
2095             Warning: With persistent environments, you object may never go out of scope that way you think it does.
2096             See L for details.
2097              
2098             These reserved session parameters are included in what's written to storage:
2099              
2100             =over 4
2101              
2102             =item o _SESSION_ATIME
2103              
2104             The session's last access time.
2105              
2106             =item o _SESSION_CTIME
2107              
2108             The session's creation time.
2109              
2110             =item o _SESSION_ETIME
2111              
2112             The session's expiry time.
2113              
2114             A time of 0 means there is no expiry time.
2115              
2116             This affect users of L. See L and L.
2117              
2118             =item o _SESSION_ID
2119              
2120             The session's id.
2121              
2122             =item o _SESSION_PTIME
2123              
2124             A hashref of session parameter expiry times.
2125              
2126             =back
2127              
2128             =head2 http_header([@arg])
2129              
2130             The [] indicate an optional parameter.
2131              
2132             Returns a HTTP header. This means it does I print the header. You have to do that, when appropriate.
2133              
2134             Unlike L, L does I force the document type to be 'text/html'.
2135              
2136             You must pass in a document type to http_header(), as $session -> http_header('-type' => 'text/html'),
2137             or use the query object's default.
2138              
2139             Both L and L default to 'text/html'.
2140              
2141             L handles the case where the query object does not have a cookie() method, by calling
2142             $session -> cookie() to generate either a cookie, or '' (the empty string).
2143              
2144             The @arg parameter, if any, is passed to the query object's header() method, after the cookie parameter, if any.
2145              
2146             =head2 id()
2147              
2148             Returns the id of the session.
2149              
2150             =head2 is_new()
2151              
2152             Returns a Boolean (0/1).
2153              
2154             Specifies you want to know if the session object was created from scratch (1) or was retrieved
2155             from storage (0).
2156              
2157             =head2 load_param([$q][, $name])
2158              
2159             The [] indicate optional parameters.
2160              
2161             Returns $q.
2162              
2163             Loads (copies) all non-reserved parameters from the session object into the query object.
2164              
2165             L performs the opposite operation.
2166              
2167             $q is a query object, and $name is a parameter name or an arrayref of names.
2168              
2169             If the query object is not specified, generates one by calling $session -> load_query_class,
2170             and stores it in the internal 'query' attribute.
2171              
2172             If you don't provide $q, use undef, don't just omit the parameter.
2173              
2174             If $name is specified, only the session parameters named in the arrayref are processed.
2175              
2176             If $name is not specified, copies all parameters belonging to the query object.
2177              
2178             =head2 load_query_class()
2179              
2180             Returns the query object.
2181              
2182             This calls $session -> query_class -> new if the session object's query object is not defined.
2183              
2184             =head2 load_session()
2185              
2186             Returns a session.
2187              
2188             Note: This method does not take any parameters, and hence does not function in the same way as
2189             load(...) in L.
2190              
2191             Algorithm:
2192              
2193             =over 4
2194              
2195             =item o If user_id() returns a session id, try to load that session
2196              
2197             If that succeeds, return the session.
2198              
2199             If it fails, generate a new session, and return it.
2200              
2201             You can call is_new() to tell the difference between these 2 cases.
2202              
2203             =item o If user_id() returns 0, generate a new session, and return it
2204              
2205             =back
2206              
2207             =head2 modified()
2208              
2209             Returns a Boolean (0/1) indicating whether or not the session's parameters have been modified.
2210              
2211             However, changing a value from one form of not-defined, e.g. undef, to another form of not-defined,
2212             e.g. 0, is ignored, meaning the modified flag is not set. In such cases, you could set the flag youself.
2213              
2214             Note: Loading a session from storage changes the session's last access time, which means the session
2215             has been modified.
2216              
2217             If you wish to stop the session being written to storage, without deleting it, you can reset the
2218             modified flag with $session -> modified(0).
2219              
2220             =head2 param([@arg])
2221              
2222             The [] indicates an optional parameter.
2223              
2224             Specifies that you wish to retrieve data stored in the session, or you wish to store data in the session.
2225              
2226             Data is stored in the session object as in a hash, via a set of $key => $value relationships.
2227              
2228             Use $session -> param($key_1 => $value_1[, $key_2 => $value_2...]) to store data in the session.
2229              
2230             If storing data, param() returns 1.
2231              
2232             The values stored in the session may be undef.
2233              
2234             Note: If the value being stored is the same as the pre-existing value, the value in the session is not updated,
2235             which means the last access time does not change.
2236              
2237             Use $session -> param() to return a sorted list of all keys.
2238              
2239             That call returns a list of the keys you have previously stored in the session.
2240              
2241             Use $session -> param('key') to return the value associated with the given key.
2242              
2243             See also L.
2244              
2245             =head2 ptime()
2246              
2247             Returns the hashref of session parameter expiry times.
2248              
2249             Keys are parameter names and values are expiry times in seconds.
2250              
2251             These expiry times are set by calling L.
2252              
2253             See also L, L and L.
2254              
2255             =head2 save_param([$q][, $name])
2256              
2257             The [] indicate optional parameters.
2258              
2259             Returns 1.
2260              
2261             Loads (copies) all non-reserved parameters from the query object into the session object.
2262              
2263             L performs the opposite operation.
2264              
2265             $q is a query object, and $name is a parameter name or an arrayref of names.
2266              
2267             If the query object is not specified, generates one by calling $session -> load_query_class,
2268             and stores it in the internal 'query' attribute. This means you can retrieve it with $session -> query.
2269              
2270             If you don't provide $q, use undef, don't just omit the parameter.
2271              
2272             If $name is specified, only the session parameters named in the arrayref are processed.
2273              
2274             If $name is not specified, copies all parameters.
2275              
2276             =head2 traverse($sub)
2277              
2278             Returns 1.
2279              
2280             Specifies that you want the $sub called for each session id found in storage, with one (1) id as the only
2281             parameter in each call.
2282              
2283             Note: traverse($sub) does not load the sessions, and hence has no effect on the session's last access time.
2284              
2285             See scripts/expire.pl.
2286              
2287             =head2 user_id()
2288              
2289             Returns either a session id, or 0.
2290              
2291             Algorithm:
2292              
2293             =over 4
2294              
2295             =item o If $session -> id() returns a true value, return that
2296              
2297             E.g. The user supplied one in $session -> new(id => $id).
2298              
2299             Return this id.
2300              
2301             =item o Try to recover an id from the cookie object or the query object.
2302              
2303             If the query object supports the cookie method, call
2304             $self -> query -> cookie and (if that doesn't find an id), $self -> query -> param.
2305              
2306             If the query object does not support the cookie method, just call $self -> query -> param.
2307              
2308             Return any id found, or 0.
2309              
2310             Note: The name of the cookie, and the name of the CGI form field, is passed to new() by the 'name' option.
2311              
2312             =back
2313              
2314             =head2 validate_options()
2315              
2316             Cross-check a few things.
2317              
2318             E.g. When using type => '... id:Static ...', you must supply a (true) id to new(id => ...').
2319              
2320             =head2 validate_time($time)
2321              
2322             Dies for an invalid time string, or returns the number of seconds corresponding to $time,
2323             which may be positive or negative.
2324              
2325             See L for details on the time string format.
2326              
2327             =head1 Test Code
2328              
2329             t/basic.ini and t/bulk.ini contain DSNs for BerkeleyDB, File, Memcache, MySQL, Pg and SQLite.
2330             Actually, they're the same file, just with different DSNs activated.
2331              
2332             So, you can use t/basic.t to run minimal tests (with only File and SQLite activated) like this:
2333              
2334             perl -Ilib t/basic.t
2335              
2336             or you can edit t/bulk.ini as desired, and pass it in like this:
2337              
2338             perl -Ilib t/basic.t t/bulk.ini
2339              
2340             Simple instructions for installing L (Oracle and Perl) are in L.
2341              
2342             Simple instructions for installing L and memcached are in L.
2343              
2344             =head1 FAQ
2345              
2346             =head2 Guidelines re Sources of Confusion
2347              
2348             This section discusses various issues which confront beginners:
2349              
2350             =over 4
2351              
2352             =item o 1: Both Data::Session and L have a I method
2353              
2354             Let's say your L script sub-classes L or it's successor L.
2355              
2356             Then inside your sub-class's methods, this works:
2357              
2358             $self -> param(a_key => 'a_value');
2359              
2360             Time passes...
2361              
2362             my($value) = $self -> param('a_key');
2363              
2364             because those 2 modules each implement a method called I. Basically, you're storing a value (via
2365             'param') inside $self.
2366              
2367             But when you store an object of type Data::Session using I, it looks like this:
2368              
2369             $self -> param(session => Data::Session -> new(...) );
2370              
2371             Now, Data::Session itself I implements a method called I. So, to store something in the
2372             session (but not in $self), you must do:
2373              
2374             $self -> param('session') -> param(a_key => 'a_value');
2375              
2376             Time passes...
2377              
2378             my($value) = $self -> param('session') -> param('a_key');
2379              
2380             It should be obvious that confusion can arise here because the 2 objects represented by $self and
2381             $self -> param('session') both have I methods.
2382              
2383             =item o 2: How exactly should a L script save a session?
2384              
2385             The first example in the Synopsis shows a very simple L script doing the right thing by calling
2386             I just before it exits.
2387              
2388             Alternately, if you sub-class L, the call to I is best placed in your I
2389             method, which is where you override L. The point here is that your I
2390             is called automatically at the end of each run mode.
2391              
2392             This important matter is also discussed in L below.
2393              
2394             =item o 3: Storing array and hashes
2395              
2396             Put simply: Don't do that!
2397              
2398             This will fail:
2399              
2400             $self -> param('session') -> param(my_hash => %my_hash);
2401              
2402             Time passes...
2403              
2404             my(%my_hash) = $self -> param('session') -> param('my_hash');
2405              
2406             Likewise for an array instead of a hash.
2407              
2408             But why? Because the part 'param(my_hash => %my_hash)' is basically assigning a list (%my_hash) to a
2409             scalar (my_hash). Hence, only 1 element of the list (the 'first' key in some unknown order) will be
2410             assigned.
2411              
2412             So, when you try to restore the hash with 'my(%my_hash) ...', all you'll get back is a scalar, which will
2413             generate the classic error message 'Odd number of elements in hash assignment...'.
2414              
2415             The solution is to use arrayrefs and hashrefs:
2416              
2417             $self -> param('session') -> param(my_hash => {%my_hash});
2418              
2419             Time passes...
2420              
2421             my(%my_hash) = %{$self -> param('session') -> param('my_hash')};
2422              
2423             Likewise for an array:
2424              
2425             $self -> param('session') -> param(my_ara => [@my_ara]);
2426              
2427             Time passes...
2428              
2429             my(@my_ara) = @{$self -> param('session') -> param('my_ara')};
2430              
2431             =back
2432              
2433             =head2 General Questions
2434              
2435             =over 4
2436              
2437             =item o My sessions are not getting written to disk!
2438              
2439             This is because you haven't stored anything in them. You're probably thinking sessions are saved just because they exist.
2440              
2441             Actually, sessions are only saved if they have at least 1 parameter set. The session id and access/etc times are
2442             not enough to trigger saving.
2443              
2444             Just do something like $session -> param(ok => 1); if you want a session saved just to indicate it exists. Code like this
2445             sets the modified flag on the session, so that flush() actually does the save.
2446              
2447             Also, see L, below, to understand why flush() must be called explicitly in persistent environments.
2448              
2449             =item o Why don't the test scripts use L?
2450              
2451             I decided to circumvent it by using L and adopting the wonders of nested testing.
2452             But, since V 1.11, I've replaced that module with L, to reduce dependencies, and hence to make it easier
2453             to get L into Debian.
2454              
2455             See t/basic.t, and in particular this line: subtest $driver => sub.
2456              
2457             =item o Why didn't you use OSSP::uuid as did L?
2458              
2459             Because when I tried to build that module (under Debian), ./configure died, saying I had set 2
2460             incompatible options, even though I hadn't set either of them.
2461              
2462             =item o What happens when 2 processes write sessions with the same id?
2463              
2464             The last-to-write wins, by overwriting what the first wrote.
2465              
2466             =item o Params::Validate be adopted to validate parameters?
2467              
2468             Not yet.
2469              
2470             =back
2471              
2472             =head1 Troubleshooting
2473              
2474             =head2 Trouble with Errors
2475              
2476             When object construction fails, new() sets $Data::Session::errstr and returns undef.
2477             This means you can use this idiom:
2478              
2479             my($session) = Data::Session -> new(...) || process_error($Data::Session::errstr);
2480              
2481             However, when methods detect errors they die, so after successful object construction, you can do:
2482              
2483             use Try::Tiny;
2484              
2485             try
2486             {
2487             $session -> some_method_which_may_die;
2488             }
2489             catch
2490             {
2491             process_error($_); # Because $_ holds the error message.
2492             };
2493              
2494             =head2 Trouble with Exiting
2495              
2496             If the session object's clean-up code is called, in DESTROY(), the session data is automatically flushed to
2497             storage (except when it's been deleted, or has not been modified).
2498              
2499             However, as explained below, there can be problems with your code (i.e. not with L) such that
2500             this clean-up code is not called, or, if called, it cannot perform as expected.
2501              
2502             The general guideline, then, is that you should explicitly call C on the session object before your
2503             program exits.
2504              
2505             Common traps for beginners:
2506              
2507             =over 4
2508              
2509             =item o Creating 2 CGI-like objects
2510              
2511             If your code creates an object of type L or similar, but you don't pass that object into
2512             L via the 'query' parameter to new(), this module will create one for you,
2513             which can be very confusing.
2514              
2515             The solution is to always create such a object yourself, and to always pass that into L.
2516              
2517             In the case that the user of a CGI script runs your code for the first time, there will be no session id,
2518             either from a cookie or from a form field.
2519              
2520             In such a case, L will do what you expect, which is to generate a session id.
2521              
2522             =item o Letting your database handle go out of scope too early
2523              
2524             When your script is exiting, and you're trying to save session data to storage via a database handle,
2525             the save will fail if the handle goes out of scope before the session data is flushed to storage.
2526              
2527             So, don't do that.
2528              
2529             =item o Assuming your session object goes out of scope when it doesn't
2530              
2531             In persistent environments such as L, FastCGI and mod_perl, your code exits as expected, but the
2532             session object does not go out of scope in the normal way.
2533              
2534             In cases like this, it is mandatory for you to call flush() on the session object before your
2535             code exits, since persistent environments operate in such a way that the session object's clean-up
2536             code does not get called. This means that flush() is not called automatically by DESTROY() as you would expect,
2537             because DESTROY() is not being called.
2538              
2539             =item o Creating circular references anywhere in your code
2540              
2541             In these cases, Perl's clean-up code may not run to completion, which means the session object may
2542             not have its clean-up code called at all. As above, flush() may not get called.
2543              
2544             If you must create circular references, it's vital you debug the exit logic using a module such as
2545             L before assuming the fault is with L.
2546              
2547             =item o Using signal handlers
2548              
2549             Write your code defensively, if you wish to call the session object's flush() method when a signal
2550             might affect program exit logic.
2551              
2552             =back
2553              
2554             =head2 Trouble with IDs
2555              
2556             The module uses code like if (! $self -> id), which means ids must be (Perl) true values, so undef, 0 and ''
2557             will not work.
2558              
2559             =head2 Trouble with UUID16
2560              
2561             While testing with UUID16 as the id generator, I got this message:
2562             ... invalid byte sequence for encoding "UTF8" ...
2563              
2564             That's because when I create a database (in Postgres) I use "create database d_name owner d_owner encoding 'UTF8';"
2565             and UUID16 simply produces a 16 byte binary value, which is not guaranteed to be or contain a valid UTF8 character.
2566              
2567             This also means you should never try to use 'driver:File;id:UUID16 ...', since the ids generated by
2568             this module would rarely if ever be valid as a part of a file name.
2569              
2570             =head2 Trouble with UUID64
2571              
2572             While testing with UUID64 as the id generator, I got this message:
2573             ... Session ids cannot contain \ or / ...
2574              
2575             That's because I was using a File driver, and UUID's encoded in base 64 can contain /.
2576              
2577             So, don't do that.
2578              
2579             =head1 Version Numbers
2580              
2581             Version numbers < 1.00 represent development versions. From 1.00 up, they are production versions.
2582              
2583             =head1 Support
2584              
2585             Log a bug on RT: L.
2586              
2587             The L mailing list often discusses issues relating to L,
2588             and the author of L monitors that list, so that is another forum available to you.
2589              
2590             See L for details.
2591              
2592             =head1 Thanks
2593              
2594             Many thanks are due to all the people who contributed to both L and L.
2595              
2596             Likewise, many thanks to the implementors of nesting testing. See L.
2597              
2598             =head1 Author
2599              
2600             L was written by Ron Savage Iron@savage.net.auE> in 2010.
2601              
2602             Home page: L.
2603              
2604             =head1 Copyright
2605              
2606             Australian copyright (c) 2010, Ron Savage.
2607              
2608             All Programs of mine are 'OSI Certified Open Source Software';
2609             you can redistribute them and/or modify them under the terms of
2610             The Artistic License, a copy of which is available at:
2611             http://www.opensource.org/licenses/index.html
2612              
2613             =cut