PageRenderTime 46ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/htdocs/download/CGI-FormBuilder-3.0302/lib/CGI/FormBuilder/Util.pm

https://github.com/formbuilder/fbwebsite
Perl | 498 lines | 376 code | 87 blank | 35 comment | 49 complexity | 63c24498039118ad08a36edeb08cee62 MD5 | raw file
  1. package CGI::FormBuilder::Util;
  2. =head1 NAME
  3. CGI::FormBuilder::Util - Utility functions for FormBuilder
  4. =head1 SYNOPSIS
  5. use CGI::FormBuilder::Util;
  6. belch "Badness";
  7. puke "Egads";
  8. debug 2, "Debug message for level 2";
  9. =head1 DESCRIPTION
  10. This module exports some common utility functions for B<FormBuilder>.
  11. These functions are intended for internal use, however I must admit
  12. that, from time to time, I just import this module and use some of
  13. the routines directly (like C<htmltag()> to generate HTML).
  14. =head1 USEFUL FUNCTIONS
  15. These can be used directly and are somewhat useful. Don't tell anyone
  16. I said that, though.
  17. =cut
  18. use strict;
  19. # Don't "use" or it collides with our basename()
  20. require File::Basename;
  21. our $VERSION = '3.0302';
  22. # Place functions you want to export by default in the
  23. # @EXPORT array. Any other functions can be requested
  24. # explicitly if you place them in the @EXPORT_OK array.
  25. use Exporter;
  26. use base 'Exporter';
  27. our @EXPORT = qw(
  28. debug belch puke indent escapeurl escapehtml escapejs
  29. autodata optalign optsort optval arglist arghash
  30. htmlattr htmltag toname tovar ismember basename rearrange
  31. );
  32. our $DEBUG = 0;
  33. # To clean up the HTML, instead of just allowing the HTML tags that
  34. # we interpret are "valid", instead we yank out all the options and
  35. # stuff that we use internally. This allows arbitrary tags to be
  36. # specified in the generation of HTML tags, and also means that this
  37. # module doesn't go out of date when the HTML spec changes next week.
  38. our @OURATTR = qw(
  39. attr autofill autofillshow body buttonname checknum cleanopts
  40. columns cookies comment debug delete dtd errorname fields
  41. fieldattr fieldsubs fieldtype fieldname fieldopts font force
  42. growable growname header idprefix inputname invalid javascript
  43. jsmessage jsname jsprefix jsfunc jshead keepextras labels labelname
  44. lalign linebreaks message messages nameopts newline other othername
  45. optgroups options override page pages pagename params render required
  46. reset resetname rowname selectname selectnum sessionidname sessionid
  47. smartness source sortopts static sticky stylesheet styleclass submit
  48. submitname submittedname table
  49. template validate values
  50. );
  51. # trick for speedy lookup
  52. our %OURATTR = map { $_ => 1 } @OURATTR;
  53. =head2 debug($level, $string)
  54. This prints out the given string only if C<$DEBUG> is greater than
  55. the C<$level> specified. For example:
  56. $CGI::FormBuilder::Util::DEBUG = 1;
  57. debug 1, "this is printed";
  58. debug 2, "but not this one";
  59. A newline is automatically included, so don't provide one of your own.
  60. =cut
  61. sub debug ($;@) {
  62. return unless $DEBUG >= $_[0]; # first arg is debug level
  63. my $l = shift; # using $_[0] directly above is just a little faster...
  64. my($func) = (caller(1))[3];
  65. $func =~ s/(.*)::/$1->/;
  66. warn "[$func] (debug$l) ", @_, "\n";
  67. }
  68. =head2 belch($string)
  69. A modified C<warn> that prints out a better message with a newline added.
  70. =cut
  71. sub belch (@) {
  72. my $i=1;
  73. my($pkg,$file,$line,$func);
  74. while (my @stk = caller($i++)) {
  75. ($pkg,$file,$line,$func) = @stk;
  76. }
  77. $func =~ s/(.*)::/$1->/;
  78. warn "[$func] Warning: ", @_, " at $file line $line\n";
  79. }
  80. =head2 puke($string)
  81. A modified C<die> that prints out a useful message.
  82. =cut
  83. sub puke (@) {
  84. my $i=1;
  85. my($pkg,$file,$line,$func);
  86. while (my @stk = caller($i++)) {
  87. ($pkg,$file,$line,$func) = @stk;
  88. }
  89. $func =~ s/(.*)::/$1->/;
  90. die "[$func] Fatal: ", @_, " at $file line $line\n";
  91. }
  92. =head2 escapeurl($string)
  93. Returns a properly escaped string suitable for including in URL params.
  94. =cut
  95. sub escapeurl ($) {
  96. # minimalist, not 100% correct, URL escaping
  97. my $toencode = shift;
  98. $toencode =~ s!([^a-zA-Z0-9_,.-/])!sprintf("%%%02x",ord($1))!eg;
  99. return $toencode;
  100. }
  101. =head2 escapehtml($string)
  102. Returns an HTML-escaped string suitable for embedding in HTML tags.
  103. =cut
  104. sub escapehtml ($) {
  105. my $toencode = shift;
  106. return '' unless defined $toencode;
  107. # use very basic built-in HTML escaping
  108. $toencode =~ s!&!&amp;!g;
  109. $toencode =~ s!<!&lt;!g;
  110. $toencode =~ s!>!&gt;!g;
  111. $toencode =~ s!"!&quot;!g;
  112. return $toencode;
  113. }
  114. =head2 escapejs($string)
  115. Returns a string suitable for including in JavaScript. Minimal processing.
  116. =cut
  117. sub escapejs ($) {
  118. my $toencode = shift;
  119. $toencode =~ s#'#\\'#g;
  120. return $toencode;
  121. }
  122. =head2 htmltag($name, %attr)
  123. This generates an XHTML-compliant tag for the name C<$name> based on the
  124. C<%attr> specified. For example:
  125. my $table = htmltag('table', cellpadding => 1, border => 0);
  126. No routines are provided to close tags; you must manually print a closing
  127. C<< </table> >> tag.
  128. =cut
  129. sub htmltag ($;@) {
  130. # called as htmltag('tagname', %attr)
  131. # creates an HTML tag on the fly, quick and dirty
  132. my $name = shift || return;
  133. my $attr = htmlattr($name, @_); # ref return faster
  134. my $htag = join(' ', $name,
  135. map { qq($_=") . escapehtml($attr->{$_}) . '"' } sort keys %$attr);
  136. $htag .= ' /' if $name eq 'input' || $name eq 'link'; # XHTML self-closing
  137. return '<' . $htag . '>';
  138. }
  139. =head2 htmlattr($name, %attr)
  140. This cleans any internal B<FormBuilder> attributes from the specified tag.
  141. It is automatically called by C<htmltag()>.
  142. =cut
  143. sub htmlattr ($;@) {
  144. # called as htmlattr('tagname', %attr)
  145. # returns valid HTML attr for that tag
  146. my $name = shift || return;
  147. my $attr = ref $_[0] ? $_[0] : { @_ };
  148. my %html;
  149. while (my($key,$val) = each %$attr) {
  150. # Anything but normal scalar data gets yanked
  151. next if ref $val || ! defined $val;
  152. # This cleans out all the internal junk kept in each data
  153. # element, returning everything else (for an html tag).
  154. # Crap, I used "text" here and body takes a text attr!!
  155. next if ($OURATTR{$key} || $key =~ /^_/
  156. || ($key eq 'text' && $name ne 'body')
  157. || ($key eq 'multiple' && $name ne 'select')
  158. || ($key eq 'type' && $name eq 'select')
  159. || ($key eq 'label' && ($name ne 'optgroup' && $name ne 'option'))
  160. || ($key eq 'title' && $name eq 'form'));
  161. $html{$key} = $val;
  162. }
  163. # "double-name" fields with an id for easier DOM scripting
  164. # do not override explictly set id attributes
  165. $html{id} = tovar($html{name}) if exists $html{name} and not exists $html{id};
  166. return wantarray ? %html : \%html;
  167. }
  168. =head2 toname($string)
  169. This is responsible for the auto-naming functionality of B<FormBuilder>.
  170. Since you know Perl, it's easiest to just show what it does:
  171. $name =~ s!\.\w+$!!; # lose trailing ".suf"
  172. $name =~ s![^a-zA-Z0-9.-/]+! !g; # strip non-alpha chars
  173. $name =~ s!\b(\w)!\u$1!g; # convert _ to space/upper
  174. This results in something like "cgi_script.pl" becoming "Cgi Script".
  175. =cut
  176. sub toname ($) {
  177. # creates a name from a var/file name (like file2name)
  178. my $name = shift;
  179. $name =~ s!\.\w+$!!; # lose trailing ".suf"
  180. $name =~ s![^a-zA-Z0-9.-/]+! !g; # strip non-alpha chars
  181. $name =~ s!\b(\w)!\u$1!g; # convert _ to space/upper
  182. return $name;
  183. }
  184. =head2 tovar($string)
  185. Turns a string into a variable name. Basically just strips C<\W>,
  186. and prefixes "fb_" on the front of it.
  187. =cut
  188. sub tovar ($) {
  189. my $name = shift;
  190. $name =~ s#\W+#_#g;
  191. $name =~ tr/_//s; # squish __ accidentally
  192. $name =~ s/_$//; # trailing _ on "[Yo!]"
  193. return $name;
  194. }
  195. =head2 ismember($el, @array)
  196. Returns true if C<$el> is in C<@array>
  197. =cut
  198. sub ismember ($@) {
  199. # returns 1 if is in set, undef otherwise
  200. # do so case-insensitively
  201. my $test = lc shift;
  202. for (@_) {
  203. return 1 if $test eq lc $_;
  204. }
  205. return;
  206. }
  207. =head1 USELESS FUNCTIONS
  208. These are totally useless outside of B<FormBuilder> internals.
  209. =head2 autodata($ref)
  210. This dereferences C<$ref> and returns the underlying data. For example:
  211. %hash = autodata($hashref);
  212. @array = autodata($arrayref);
  213. =cut
  214. sub autodata ($) {
  215. # auto-derefs appropriately
  216. my $data = shift;
  217. return unless defined $data;
  218. if (my $ref = ref $data) {
  219. if ($ref eq 'ARRAY') {
  220. return wantarray ? @{$data} : $data;
  221. } elsif ($ref eq 'HASH') {
  222. return wantarray ? %{$data} : $data;
  223. } else {
  224. puke "Sorry, can't handle odd data ref '$ref'";
  225. }
  226. }
  227. return $data; # return as-is
  228. }
  229. =head2 arghash(@_)
  230. This returns a hash of options passed into a sub:
  231. sub field {
  232. my $self = shift;
  233. my %opt = arghash(@_);
  234. }
  235. It will return a hashref in scalar context.
  236. =cut
  237. sub arghash (;@) {
  238. return $_[0] if ref $_[0]; # assume good struct verbatim
  239. belch "Odd number of arguments passed into ", (caller(1))[3]
  240. if @_ % 2 != 0;
  241. return wantarray ? @_ : { @_ }; # assume scalar hashref
  242. }
  243. =head2 arglist(@_)
  244. This returns a list of args passed into a sub:
  245. sub value {
  246. my $self = shift;
  247. $self->{value} = arglist(@_);
  248. It will return an arrayref in scalar context.
  249. =cut
  250. sub arglist (;@) {
  251. return $_[0] if ref $_[0]; # assume good struct verbatim
  252. return wantarray ? @_ : [ @_ ]; # assume scalar arrayref
  253. }
  254. =head2 indent($num)
  255. A simple sub that returns 4 spaces x C<$num>. Used to indent code.
  256. =cut
  257. sub indent (;$) {
  258. # return proper spaces to indent x 4 (code prettification)
  259. return ' ' x shift();
  260. }
  261. =head2 optalign(\@opt)
  262. This returns the options specified as an array of arrayrefs, which
  263. is what B<FormBuilder> expects internally.
  264. =cut
  265. sub optalign ($) {
  266. # This creates and returns the options needed based
  267. # on an $opt array/hash shifted in
  268. my $opt = shift;
  269. # "options" are the options for our select list
  270. my @opt = ();
  271. if (my $ref = ref $opt) {
  272. if ($ref eq 'CODE') {
  273. # exec to get options
  274. $opt = &$opt;
  275. }
  276. # we turn any data into ( ['key', 'val'], ['key', 'val'] )
  277. # have to check sub-data too, hence why this gets a little nasty
  278. @opt = ($ref eq 'HASH')
  279. ? map { (ref $opt->{$_} eq 'ARRAY')
  280. ? [$_, $opt->{$_}[0]] : [$_, $opt->{$_}] } keys %{$opt}
  281. : map { (ref $_ eq 'HASH') ? [ %{$_} ] : $_ } autodata $opt;
  282. } else {
  283. # this code should not be reached, but is here for safety
  284. @opt = ($opt);
  285. }
  286. return @opt;
  287. }
  288. =head2 optsort($sortref, @opt)
  289. This sorts and returns the options based on C<$sortref>. It expects
  290. C<@opt> to be in the format returned by C<optalign()>. The C<$sortref>
  291. spec can be the string C<NAME>, C<NUM>, or a reference to a C<&sub>
  292. which takes pairs of values to compare.
  293. =cut
  294. sub optsort ($@) {
  295. # pass in the sort and ref to opts
  296. my $sort = shift;
  297. my @opt = @_;
  298. debug 2, "optsort($sort) called for field";
  299. # Currently any CODEREF can only sort on the value, which sucks if the
  300. # value and label are substantially different. This is caused by the fact
  301. # that options as specified by the user only have one element, not two
  302. # as hashes or generated options do. This should really be an option,
  303. # since sometimes you want the labels sorted too. Patches welcome.
  304. if ($sort eq 'alpha' || $sort eq 'name' || $sort eq 'NAME' || $sort eq 1) {
  305. @opt = sort { (autodata($a))[0] cmp (autodata($b))[0] } @opt;
  306. } elsif ($sort eq 'numeric' || $sort eq 'num' || $sort eq 'NUM') {
  307. @opt = sort { (autodata($a))[0] <=> (autodata($b))[0] } @opt;
  308. } elsif ($sort eq 'LABELNAME' || $sort eq 'LABEL') {
  309. @opt = sort { (autodata($a))[1] cmp (autodata($b))[1] } @opt;
  310. } elsif ($sort eq 'LABELNUM') {
  311. @opt = sort { (autodata($a))[1] <=> (autodata($b))[1] } @opt;
  312. } elsif (ref $sort eq 'CODE') {
  313. @opt = sort { eval &{$sort}((autodata($a))[0], (autodata($b))[0]) } @opt;
  314. } else {
  315. puke "Unsupported sort type '$sort' specified - must be 'NAME' or 'NUM'";
  316. }
  317. # return our options
  318. return @opt;
  319. }
  320. =head2 optval($opt)
  321. This takes one of the elements of C<@opt> and returns it split up.
  322. Useless outside of B<FormBuilder>.
  323. =cut
  324. sub optval ($) {
  325. my $opt = shift;
  326. my @ary = (ref $opt eq 'ARRAY') ? @{$opt} : ($opt);
  327. return wantarray ? @ary : $ary[0];
  328. }
  329. =head2 rearrange($ref, $name)
  330. Rearranges arguments designed to be per-field from the global inheritor.
  331. =cut
  332. sub rearrange {
  333. my $from = shift;
  334. my $name = shift;
  335. my $ref = ref $from;
  336. my $tval;
  337. if ($ref && $ref eq 'HASH') {
  338. $tval = $from->{$name};
  339. } elsif ($ref && $ref eq 'ARRAY') {
  340. $tval = ismember($name, @$from) ? 1 : 0;
  341. } else {
  342. $tval = $from;
  343. }
  344. return $tval;
  345. }
  346. =head2 basename
  347. Returns the script name or $0 hacked up to the first dir
  348. =cut
  349. sub basename () {
  350. # Windows sucks so bad it's amazing to me.
  351. my $prog = File::Basename::basename($ENV{SCRIPT_NAME} || $0);
  352. $prog =~ s/\?.*//; # lose ?p=v
  353. belch "Script basename() undefined somehow" unless $prog;
  354. return $prog;
  355. }
  356. 1;
  357. __END__
  358. =head1 SEE ALSO
  359. L<CGI::FormBuilder>
  360. =head1 REVISION
  361. $Id: Util.pm,v 1.51 2006/02/24 01:42:29 nwiger Exp $
  362. =head1 AUTHOR
  363. Copyright (c) 2000-2006 Nate Wiger <nate@wiger.org>. All Rights Reserved.
  364. This module is free software; you may copy this under the terms of
  365. the GNU General Public License, or the Artistic License, copies of
  366. which should have accompanied your Perl kit.
  367. =cut