# PHP pagination code by Stranger Studios (http://www.strangerstudios.com/). # Converted to Perl by Andrew Cantino, 2006. sub getPagination { my ($adjacents, # How many adjacent pages should be shown on each side? $limit, # Number of items you will show per page. $page, # The current starting page. $total_items, # The total number of items you are paginating. $scriptName, # The name of the CGI script in . $extra # A string with any extra CGI params to include, of the form "&parm1=value1&parm2=value2&...". ) = @_; $page = 1 if ($page == 0); # if no page var is given, default to 1. my $prev = $page - 1; # previous page is page - 1 my $next = $page + 1; # next page is page + 1 my $lastpage = ceil($total_items/$limit); # lastpage is = total pages / items per page, rounded up. my $lpm1 = $lastpage - 1; # last page minus 1 # Now we apply our rules and draw the pagination object. # We're actually saving the HTML to a variable in case we want to draw it more than once. my $pagination = ""; my $counter = 0; if ($lastpage > 1) { $pagination .= "
"; # previous button if ($page > 1) { $pagination .= "« previous"; } else { $pagination .= "« previous"; } # pages if ($lastpage < 7 + ($adjacents * 2)) { # not enough pages to bother breaking it up for ($counter = 1; $counter <= $lastpage; $counter++) { if ($counter == $page) { $pagination .= "$counter"; } else { $pagination .= "$counter"; } } } elsif ($lastpage > 5 + ($adjacents * 2)) { # enough pages to hide some # close to beginning; only hide later pages if ($page < 1 + ($adjacents * 2)) { for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++) { if ($counter == $page) { $pagination .= "$counter"; } else { $pagination .= "$counter"; } } $pagination .= "..."; $pagination .= "$lpm1"; $pagination .= "$lastpage"; } elsif ($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2)) { # in middle; hide some front and some back $pagination .= "1"; $pagination .= "2"; $pagination .= "..."; for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++) { if ($counter == $page) { $pagination .= "$counter"; } else { $pagination .= "$counter"; } } $pagination .= "..."; $pagination .= "$lpm1"; $pagination .= "$lastpage"; } else { # close to end; only hide early pages $pagination .= "1"; $pagination .= "2"; $pagination .= "..."; for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++) { if ($counter == $page) { $pagination .= "$counter"; } else { $pagination .= "$counter"; } } } } # next button if ($page < $counter - 1) { $pagination .= "next »"; } else { $pagination .= "next »"; } $pagination .= "
\n"; } return $pagination; }