tagproj: Require POST method to add tags
[girocco.git] / Girocco / Util.pm
blob994494ca034b6588e285761041e4b9f9a08f90b5
1 package Girocco::Util;
3 use strict;
4 use warnings;
6 use Girocco::Config;
7 use Time::Local;
9 BEGIN {
10 use base qw(Exporter);
11 our @EXPORT = qw(scrypt jailed_file
12 lock_file unlock_file
13 filedb_atomic_append filedb_atomic_edit filedb_grep
14 filedb_atomic_grep valid_email valid_email_multi
15 valid_repo_url valid_web_url url_path
16 projects_html_list parse_rfc2822_date);
20 sub scrypt {
21 my ($pwd) = @_;
22 crypt($pwd||'', join ('', ('.', '/', 0..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64]));
25 sub jailed_file {
26 my ($filename) = @_;
27 $filename =~ s,^/,,;
28 $Girocco::Config::chroot."/$filename";
31 sub lock_file {
32 my ($path) = @_;
34 $path .= '.lock';
36 use Errno qw(EEXIST);
37 use Fcntl qw(O_WRONLY O_CREAT O_EXCL);
38 use IO::Handle;
39 my $handle = new IO::Handle;
41 unless (sysopen($handle, $path, O_WRONLY|O_CREAT|O_EXCL)) {
42 my $cnt = 0;
43 while (not sysopen($handle, $path, O_WRONLY|O_CREAT|O_EXCL)) {
44 ($! == EEXIST) or die "$path open failed: $!";
45 ($cnt++ < 16) or die "$path open failed: cannot open lockfile";
46 sleep(1);
49 # XXX: filedb-specific
50 chmod 0664, $path or die "$path g+w failed: $!";
52 $handle;
55 sub unlock_file {
56 my ($path, $noreplace) = @_;
58 if (!$noreplace) {
59 rename "$path.lock", $path or die "$path unlock failed: $!";
60 } else {
61 unlink "$path.lock" or die "$path unlock failed: $!";
65 sub filedb_atomic_append {
66 my ($file, $line) = @_;
67 my $id = 65536;
69 open my $src, '<', $file or die "$file open for reading failed: $!";
70 my $dst = lock_file($file);
72 while (<$src>) {
73 my $aid = (split /:/)[2];
74 $id = $aid + 1 if ($aid >= $id);
76 print $dst $_ or die "$file(l) write failed: $!";
79 $line =~ s/\\i/$id/g;
80 print $dst "$line\n" or die "$file(l) write failed: $!";
82 close $dst or die "$file(l) close failed: $!";
83 close $src;
85 unlock_file($file);
87 $id;
90 sub filedb_atomic_edit {
91 my ($file, $fn) = @_;
93 open my $src, '<', $file or die "$file open for reading failed: $!";
94 my $dst = lock_file($file);
96 while (<$src>) {
97 print $dst $fn->($_) or die "$file(l) write failed: $!";
100 close $dst or die "$file(l) close failed: $!";
101 close $src;
103 unlock_file($file);
106 sub filedb_atomic_grep {
107 my ($file, $fn) = @_;
108 my @results = ();
110 open my $src, '<', $file or die "$file open for reading failed: $!";
111 my $dst = lock_file($file);
113 while (<$src>) {
114 my $result = $fn->($_);
115 push(@results, $result) if $result;
118 close $dst or die "$file(l) close failed: $!";
119 close $src;
121 unlock_file($file, 1);
122 return @results;
125 sub filedb_grep {
126 my ($file, $fn) = @_;
127 my @results = ();
129 open my $src, '<', $file or die "$file open for reading failed: $!";
131 while (<$src>) {
132 my $result = $fn->($_);
133 push(@results, $result) if $result;
136 close $src;
138 return @results;
141 sub valid_email {
142 $_ = $_[0];
143 /^[a-zA-Z0-9+._-]+@[a-zA-Z0-9.-]+$/;
145 sub valid_email_multi {
146 $_ = $_[0];
147 # More relaxed, we just want to avoid too dangerous characters.
148 /^[a-zA-Z0-9+._, @-]+$/;
150 sub valid_web_url {
151 $_ = $_[0];
152 /^https?:\/\/[a-zA-Z0-9.:-]+(\/[_\%a-zA-Z0-9.\/~:?&=;-]*)?(#[a-zA-Z0-9._-]+)?$/;
154 sub valid_repo_url {
155 $_ = $_[0];
156 /^(https?|git|svn(\+http)?|svn(\+https)?|darcs|bzr):\/\/[a-zA-Z0-9.:-]+(\/[_\%a-zA-Z0-9.\/~-]*)?$/;
159 # If the passed in argument looks like a URL, return only the stuff following
160 # the host:port part otherwise return the entire argument.
161 sub url_path {
162 my $url = shift || '';
163 # See RFC 3968
164 $url = $1 if $url =~ m,^(?: [A-Za-z][A-Za-z0-9+.-]*: ) # scheme
165 (?: // ) # // separator
166 (?: [^\@]+\@ )? # optional userinfo
167 (?: [^/?#]+ ) # host and port
168 ((?:[/?#].*)?)$,x; # path and optional query string and/or anchor
169 return $url;
172 sub _escapeHTML {
173 my $str = shift;
174 $str =~ s/\&/\&amp;/gs;
175 $str =~ s/\</\&lt;/gs;
176 $str =~ s/\>/\&gt;/gs;
177 $str =~ s/\"/\&quot;/gs; #"
178 return $str;
181 # create relative time string from passed in age in seconds
182 sub _rel_age {
183 my $age = shift;
184 my $age_str;
186 if ($age > 60*60*24*365*2) {
187 $age_str = (int $age/60/60/24/365);
188 $age_str .= " years ago";
189 } elsif ($age > 60*60*24*(365/12)*2) {
190 $age_str = int $age/60/60/24/(365/12);
191 $age_str .= " months ago";
192 } elsif ($age > 60*60*24*7*2) {
193 $age_str = int $age/60/60/24/7;
194 $age_str .= " weeks ago";
195 } elsif ($age > 60*60*24*2) {
196 $age_str = int $age/60/60/24;
197 $age_str .= " days ago";
198 } elsif ($age > 60*60*2) {
199 $age_str = int $age/60/60;
200 $age_str .= " hours ago";
201 } elsif ($age > 60*2) {
202 $age_str = int $age/60;
203 $age_str .= " mins ago";
204 } elsif ($age > 2) {
205 $age_str = int $age;
206 $age_str .= " secs ago";
207 } elsif ($age >= 0) {
208 $age_str = "right now";
209 } else {
210 $age_str = "future time";
212 return $age_str;
215 # Take a list of project names and produce a nicely formated table that
216 # includes owner links and descriptions. If the list is empty returns ''.
217 # The first argument may be a hash ref that contains options. The following
218 # options are available:
219 # target -- sets the target value of the owner link
220 # emptyok -- if true returns an empty table rather than ''
221 # typecol -- if true include type column with hover info
222 # changed -- if true include a changed column
223 sub projects_html_list {
224 my $options = {};
225 if (defined($_[0]) && ref($_[0]) eq 'HASH') {
226 $options = shift;
228 return '' unless @_ || (defined($options->{emptyok}) && $options->{emptyok});
229 require Girocco::Project;
230 my $count = 0;
231 my $target = '';
232 $target = " target=\""._escapeHTML($options->{target})."\""
233 if defined($options->{target});
234 my $withtype = defined($options->{typecol}) && $options->{typecol};
235 my $withchanged = defined($options->{changed}) && $options->{changed};
236 my $typehead = '';
237 $typehead = '<th>Type</th>' if $withtype;
238 my $chghead = '';
239 $chghead = '<th>Changed</th>' if $withchanged;
240 my $html = <<EOT;
241 <table class='projectlist'><tr><th>Project</th>$typehead$chghead<th class="desc">Description</th></tr>
243 my $trclass = ' class="odd"';
244 foreach (sort({lc($a) cmp lc($b)} @_)) {
245 if (Girocco::Project::does_exist($_)) {
246 my $proj = Girocco::Project->load($_);
247 my $projname = $proj->{name}.".git";
248 my $projdesc = $proj->{desc}||'';
249 utf8::decode($projdesc) if utf8::valid($projdesc);
250 my $typecol = '';
251 if ($withtype) {
252 if ($proj->{mirror}) {
253 $typecol = substr(<<EOT, 0, -1);
254 <td class="type"><span class="hover">mirror<span class="nowrap">@{[_escapeHTML($proj->{url})]}</span></span></td>
256 } else {
257 my $users = @{$proj->{users}};
258 $users .= ' user';
259 $users .= 's' unless @{$proj->{users}} == 1;
260 my $userlist = join(', ', sort({lc($a) cmp lc($b)} @{$proj->{users}}));
261 my $spncls = length($userlist) > 25 ? '' : ' class="nowrap"';
262 $typecol = $userlist ? substr(<<EOT, 0, -1) : substr(<<EOT, 0, -1);
263 <td class="type"><span class="hover">$users<span$spncls>$userlist</span></span></td>
265 <td class="type">$users</td>
269 my $changecol = '';
270 if ($withchanged) {
271 my $rel = '';
272 my $changetime = $proj->{lastchange};
273 if ($changetime) {
274 $rel = "<span class=\"hover\">" .
275 _rel_age(time - parse_rfc2822_date($changetime)) .
276 "<span class=\"nowrap\">$changetime</span></span>";
277 } else {
278 $rel = "no commits";
280 $changecol = substr(<<EOT, 0, -1);
281 <td class="change">$rel</td>
284 $html .= <<EOT;
285 <tr$trclass><td><a href="@{[url_path($Girocco::Config::gitweburl)]}/$projname"$target
286 >@{[_escapeHTML($projname)]}</td>$typecol$changecol<td>@{[_escapeHTML($projdesc)]}</td></tr>
288 $trclass = $trclass ? '' : ' class="odd"';
289 ++$count;
292 $html .= <<EOT;
293 </table>
295 return ($count || (defined($options->{emptyok}) && $options->{emptyok})) ? $html : '';
298 my %_month_names;
299 BEGIN {
300 %_month_names = (
301 jan => 0, feb => 1, mar => 2, apr => 3, may => 4, jun => 5,
302 jul => 6, aug => 7, sep => 8, oct => 9, nov => 10, dec => 11
306 # Should be in "date '+%a, %d %b %Y %T %z'" format as saved to lastgc, lastrefresh and lastchange
307 # The leading "%a, " is optional, returns undef if unrecognized date. This is also known as
308 # RFC 2822 date format and git's '%cD', '%aD' and --date=rfc2822 format.
309 sub parse_rfc2822_date {
310 my $dstr = shift || '';
311 $dstr = $1 if $dstr =~/^[^\s]+,\s*(.*)$/;
312 return undef unless $dstr =~
313 /^\s*(\d{1,2})\s+([A-Za-z]{3})\s+(\d{4})\s+(\d{1,2}):(\d{2}):(\d{2})\s+([+-]\d{4})/;
314 my ($d,$b,$Y,$H,$M,$S,$z) = ($1,$2,$3,$4,$5,$6,$7);
315 my $m = $_month_names{lc($b)};
316 return undef unless defined($m);
317 my $seconds = timegm(0+$S, 0+$M, 0+$H, 0+$d, 0+$m, $Y-1900);
318 my $offset = 60 * (60 * (0+substr($z,1,2)) + (0+substr($z,3,2)));
319 $offset = -$offset if substr($z,0,1) eq '-';
320 return $seconds - $offset;