LJSUP-17669: Login.bml form refactoring
[livejournal.git] / cgi-bin / LJ / Knob.pm
blobadb4271a5805490ce1eae3427bcf642a4a5243eb
1 package LJ::Knob;
2 use strict;
3 use String::CRC32 ();
5 my %singleton;
7 # fields:
8 # name
9 # value -- if defined, loaded. value in range [0,100] (inclusive)
11 sub instance {
12 my ($class, $knobname) = @_;
13 return $singleton{$knobname} ||= LJ::Knob->new($knobname);
16 sub new {
17 my ($class, $knobname) = @_;
18 my $self = {
19 name => $knobname,
21 return bless $self, $class;
24 sub memkey {
25 my $self = shift;
26 return "knob:$self->{name}";
29 sub set_value {
30 my ($self, $val) = @_;
31 $val += 0;
33 my $memkey = $self->memkey;
34 LJ::MemCache::set($memkey, $val);
35 my $dbh = LJ::get_db_writer();
36 $dbh->do("REPLACE INTO knob (knobname, val) VALUES (?, ?)", undef,
37 $self->{name}, $val);
39 # broadcast to other apache nodes to change
40 $self->{value} = $val;
42 return 1;
45 sub value {
46 my $self = shift;
47 return $self->{value} if defined $self->{value};
48 my $name = $self->{name};
50 my $memkey = $self->memkey;
51 my $rv = LJ::MemCache::get($memkey);
52 if (defined $rv) {
53 return $self->{value} = $rv;
56 my $dbh = LJ::get_db_writer();
57 $rv = $dbh->selectrow_array("SELECT val FROM knob WHERE knobname=?", undef, $name) + 0;
58 LJ::MemCache::add($memkey, $rv);
59 return $self->{value} = $rv;
62 sub check {
63 my ($self, $checkon) = @_;
64 my $rand = (127 & int(String::CRC32::crc32($checkon))); # [0 .. 127]
65 my $val = int(127 * $self->value / 100); # [0 .. 127]
66 return $rand <= $val;