[system] / trunk / webwork2 / lib / WeBWorK / Utils.pm Repository:
ViewVC logotype

Annotation of /trunk/webwork2/lib/WeBWorK/Utils.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1287 - (view) (download) (as text)

1 : sh002i 440 ################################################################################
2 : sh002i 494 # WeBWorK mod_perl (c) 2000-2002 WeBWorK Project
3 : sh002i 440 # $Id$
4 :     ################################################################################
5 :    
6 : sh002i 410 package WeBWorK::Utils;
7 : sh002i 818 use base qw(Exporter);
8 : sh002i 410
9 : sh002i 455 =head1 NAME
10 :    
11 :     WeBWorK::Utils - useful utilities used by other WeBWorK modules.
12 :    
13 :     =cut
14 :    
15 : sh002i 412 use strict;
16 :     use warnings;
17 : sh002i 1257 #use Apache::DB;
18 : sh002i 412 use Date::Format;
19 :     use Date::Parse;
20 : sh002i 1145 use Errno;
21 : sh002i 1150 use File::Path qw(rmtree);
22 : sh002i 412
23 : sh002i 1145 use constant MKDIR_ATTEMPTS => 10;
24 :    
25 : sh002i 410 our @EXPORT = ();
26 : sh002i 424 our @EXPORT_OK = qw(
27 :     runtime_use
28 :     readFile
29 : sh002i 1150 readDirectory
30 : sh002i 424 formatDateTime
31 :     parseDateTime
32 : sh002i 562 writeLog
33 :     writeTimingLogEntry
34 : malsyned 970 list2hash
35 :     max
36 : sh002i 427 dbDecode
37 :     dbEncode
38 : sh002i 429 decodeAnswers
39 :     encodeAnswers
40 : sh002i 424 ref2string
41 : sh002i 1111 sortByName
42 : sh002i 1145 makeTempDirectory
43 : sh002i 1150 removeTempDirectory
44 : sh002i 1145 pretty_print_rh
45 : malsyned 1287 cryptPassword
46 : sh002i 424 );
47 : sh002i 410
48 :     sub runtime_use($) {
49 :     return unless @_;
50 : sh002i 424 eval "package Main; require $_[0]; import $_[0]";
51 : sh002i 410 die $@ if $@;
52 :     }
53 :    
54 : sh002i 1257 #sub backtrace {
55 :     # my ($style) = @_;
56 :     # $style = "warn" unless $style;
57 :     # my @bt = DB->backtrace;
58 :     # shift @bt; # Remove "backtrace" from the backtrace;
59 :     # if ($style eq "die") {
60 :     # die join "\n", @bt;
61 :     # } elsif ($style eq "warn") {
62 :     # warn join "\n", @bt;
63 :     # } elsif ($style eq "print") {
64 :     # print join "\n", @bt;
65 :     # } elsif ($style eq "return") {
66 :     # return @bt;
67 :     # }
68 :     #}
69 : malsyned 1045
70 : sh002i 410 sub readFile($) {
71 :     my $fileName = shift;
72 : sh002i 1150 local $/ = undef; # slurp the whole thing into one string
73 :     open my $dh, "<", $fileName
74 :     or die "failed to read file $fileName: $!";
75 :     my $result = <$dh>;
76 :     close $dh;
77 : sh002i 410 return $result;
78 :     }
79 : sh002i 412
80 : malsyned 974 sub readDirectory($) {
81 : sh002i 1150 my $dirName = shift;
82 :     opendir my $dh, $dirName
83 :     or die "failed to read directory $dirName: $!";
84 :     my @result = readdir $dh;
85 :     close $dh;
86 :     return @result;
87 : malsyned 974 }
88 :    
89 : sh002i 412 sub formatDateTime($) {
90 :     my $dateTime = shift;
91 : sh002i 558 # "standard" WeBWorK date/time format (for set definition files):
92 : sh002i 412 # %m month number, starting with 01
93 :     # %d numeric day of the month, with leading zeros (eg 01..31)
94 :     # %y year (2 digits)
95 :     # %I hour, 12 hour clock, leading 0's)
96 :     # %M minute, leading 0's
97 :     # %P am or pm (Yes %p and %P are backwards :)
98 : sh002i 562 return time2str("%m/%d/%y %I:%M%P", $dateTime);
99 : sh002i 412 }
100 :    
101 :     sub parseDateTime($) {
102 : sh002i 424 my $string = shift;
103 : sh002i 737 return str2time($string);
104 : sh002i 412 }
105 : sh002i 422
106 : sh002i 562 sub writeLog($$@) {
107 :     my ($ce, $facility, @message) = @_;
108 :     unless ($ce->{webworkFiles}->{logs}->{$facility}) {
109 :     warn "There is no log file for the $facility facility defined.\n";
110 :     return;
111 :     }
112 :     my $logFile = $ce->{webworkFiles}->{logs}->{$facility};
113 :     local *LOG;
114 :     if (open LOG, ">>", $logFile) {
115 :     print LOG "[", time2str("%a %b %d %H:%M:%S %Y", time), "] @message\n";
116 :     close LOG;
117 :     } else {
118 :     warn "failed to open $logFile for writing: $!";
119 :     }
120 :     }
121 : sh002i 558
122 : sh002i 631 # $ce - a WeBWork::CourseEnvironment object
123 :     # $function - fully qualified function name
124 :     # $details - any information, do not use the characters '[' or ']'
125 : sh002i 692 # $beginEnd - the string "begin", "intermediate", or "end"
126 :     # use the intermediate step begun or completed for INTERMEDIATE
127 : sh002i 631 # use an empty string for $details when calling for END
128 : sh002i 562 sub writeTimingLogEntry($$$$) {
129 :     my ($ce, $function, $details, $beginEnd) = @_;
130 :     return unless defined $ce->{webworkFiles}->{logs}->{timing};
131 : sh002i 692 $beginEnd = ($beginEnd eq "begin") ? ">" : ($beginEnd eq "end") ? "<" : "-";
132 : sh002i 562 writeLog($ce, "timing", "$$ ".time." $beginEnd $function [$details]");
133 :     }
134 :    
135 : malsyned 970 sub list2hash {
136 :     map {$_ => "0"} @_;
137 :     }
138 :    
139 :     sub max {
140 :     my $soFar;
141 :     foreach my $item (@_) {
142 :     $soFar = $item unless defined $soFar;
143 :     if ($item > $soFar) {
144 :     $soFar = $item;
145 :     }
146 :     }
147 : malsyned 979 return defined $soFar ? $soFar : 0;
148 : malsyned 970 }
149 :    
150 : sh002i 429 sub decodeAnswers($) {
151 :     my $string = shift;
152 :     return unless defined $string and $string;
153 :     my @array = split m/##/, $string;
154 :     $array[$_] =~ s/\\#\\/#/g foreach 0 .. $#array;
155 : sh002i 445 push @array, "" if @array%2;
156 : sh002i 429 return @array; # it's actually a hash ;)
157 :     }
158 :    
159 :     sub encodeAnswers(\%\@) {
160 :     my %hash = %{ shift() };
161 :     my @order = @{ shift() };
162 :     my $string;
163 :     foreach my $name (@order) {
164 :     my $value = defined $hash{$name} ? $hash{$name} : "";
165 :     $name =~ s/#/\\#\\/g; # this is a WEIRD way to escape things
166 :     $value =~ s/#/\\#\\/g; # and it's not my fault!
167 : sh002i 1095 if ($value =~ m/\\$/) {
168 :     # if the value ends with a backslash, string2hash will
169 :     # interpret that as a normal escape sequence (not part
170 :     # of the weird pound escape sequence) if the next
171 :     # character is &. So we have to protect against this.
172 :     # will adding a spcae at the end of the last answer
173 :     # hurt anything? i don't think so...
174 :     $value .= " ";
175 :     }
176 : sh002i 429 $string .= "$name##$value##"; # this is also not my fault
177 :     }
178 :     $string =~ s/##$//; # remove last pair of hashs
179 :     return $string;
180 :     }
181 :    
182 : sh002i 424 sub ref2string($;$);
183 :     sub ref2string($;$) {
184 :     my $ref = shift;
185 :     my $dontExpand = shift || {};
186 :     my $refType = ref $ref;
187 : sh002i 422 my $result;
188 : sh002i 424 if ($refType and not $dontExpand->{$refType}) {
189 :     my $baseType = refBaseType($ref);
190 :     $result .= '<font size="1" color="grey">' . $refType;
191 : sh002i 425 $result .= " ($baseType)" if $baseType and $refType ne $baseType;
192 : sh002i 424 $result .= ":</font><br>";
193 :     $result .= '<table border="1" cellpadding="2">';
194 :     if ($baseType eq "HASH") {
195 :     my %hash = %$ref;
196 :     foreach (sort keys %hash) {
197 :     $result .= '<tr valign="top">';
198 :     $result .= "<td>$_</td>";
199 :     $result .= "<td>" . ref2string($hash{$_}, $dontExpand) . "</td>";
200 :     $result .= "</tr>";
201 :     }
202 :     } elsif ($baseType eq "ARRAY") {
203 :     my @array = @$ref;
204 : sh002i 429 # special case for Problem, Set, and User objects, which are defined
205 :     # using lists and contain a @FIELDS package variable:
206 :     no strict 'refs';
207 :     my @FIELDS = eval { @{$refType."::FIELDS"} };
208 :     use strict 'refs';
209 :     undef @FIELDS unless scalar @FIELDS == scalar @array and not $@;
210 : sh002i 424 foreach (0 .. $#array) {
211 :     $result .= '<tr valign="top">';
212 :     $result .= "<td>$_</td>";
213 : sh002i 429 $result .= "<td>".$FIELDS[$_]."</td>" if @FIELDS;
214 : sh002i 424 $result .= "<td>" . ref2string($array[$_], $dontExpand) . "</td>";
215 :     $result .= "</tr>";
216 :     }
217 :     } elsif ($baseType eq "SCALAR") {
218 :     my $scalar = $$ref;
219 :     $result .= '<tr valign="top">';
220 :     $result .= "<td>$scalar</td>";
221 :     $result .= "</tr>";
222 : sh002i 422 } else {
223 : sh002i 424 # perhaps a coderef? in any case, i don't feel like dealing with it!
224 :     $result .= '<tr valign="top">';
225 :     $result .= "<td>$ref</td>";
226 :     $result .= "</tr>";
227 : sh002i 422 }
228 : sh002i 424 $result .= "</table>"
229 : sh002i 422 } else {
230 : sh002i 424 $result .= defined $ref ? $ref : '<font color="red">undef</font>';
231 :     }
232 : sh002i 422 }
233 :    
234 : sh002i 424 sub refBaseType($) {
235 :     my $ref = shift;
236 : sh002i 984 $ref =~ m/(\w+)\(/; # this might not be robust...
237 :     return $1;
238 : sh002i 422 }
239 :    
240 : sh002i 1111 # p. 101, Camel, 3rd ed.
241 :     # The <=> and cmp operators return -1 if the left operand is less than the
242 :     # right operand, 0 if they are equal, and +1 if the left operand is greater
243 :     # than the right operand.
244 :    
245 :     sub sortByName {
246 :     my ($field, @items) = @_;
247 :     return sort {
248 :     my @aParts = split m/(?<=\D)(?=\d)|(?<=\d)(?=\D)/, $a->$field;
249 :     my @bParts = split m/(?<=\D)(?=\d)|(?<=\d)(?=\D)/, $b->$field;
250 :     while (@aParts and @bParts) {
251 :     my $aPart = shift @aParts;
252 :     my $bPart = shift @bParts;
253 :     my $aNumeric = $aPart =~ m/^\d*$/;
254 :     my $bNumeric = $bPart =~ m/^\d*$/;
255 :    
256 :     # numbers should come before words
257 :     return -1 if $aNumeric and not $bNumeric;
258 :     return +1 if not $aNumeric and $bNumeric;
259 :    
260 :     # both have the same type
261 :     if ($aNumeric and $bNumeric) {
262 :     next if $aPart == $bPart; # check next pair
263 :     return $aPart <=> $bPart; # compare numerically
264 :     } else {
265 :     next if $aPart eq $bPart; # check next pair
266 :     return $aPart cmp $bPart; # compare lexicographically
267 :     }
268 :     }
269 :     return +1 if @aParts; # a has more sections, should go second
270 :     return -1 if @bParts; # a had fewer sections, should go first
271 :     } @items;
272 :     }
273 :    
274 : sh002i 1145 sub makeTempDirectory($$) {
275 :     my ($parent, $basename) = @_;
276 :     # Loop until we're able to create a directory, or it fails for some
277 :     # reason other than there already being something there.
278 :     my $triesRemaining = MKDIR_ATTEMPTS;
279 :     my ($fullPath, $success);
280 :     do {
281 :     my $suffix = join "", map { ('A'..'Z','a'..'z','0'..'9')[int rand 62] } 1 .. 8;
282 :     $fullPath = "$parent/$basename.$suffix";
283 :     $success = mkdir $fullPath;
284 :     } until ($success or not $!{EEXIST});
285 :     die "Failed to create directory $fullPath: $!"
286 :     unless $success;
287 :     return $fullPath;
288 :     }
289 :    
290 : sh002i 1150 sub removeTempDirectory($) {
291 :     my ($dir) = @_;
292 :     rmtree($dir, 0, 0);
293 :     }
294 :    
295 : gage 1137 sub pretty_print_rh {
296 :     my $rh = shift;
297 :     foreach my $key (sort keys %{$rh}) {
298 :     warn " $key => ",$rh->{$key},"\n";
299 :     }
300 :     }
301 : sh002i 1145
302 : malsyned 1287 sub cryptPassword {
303 :     my ($clearPassword) = @_;
304 :     my $salt = join("", ('.','/','0'..'9','A'..'Z','a'..'z')[rand 64, rand 64]);
305 :     my $cryptPassword = crypt($clearPassword, $salt);
306 :     return $cryptPassword;
307 :     }
308 :    
309 : sh002i 422 1;

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9