Annotation of loncom/metadata_database/LONCAPA/lonmetadata.pm, revision 1.33
1.1 matthew 1: # The LearningOnline Network with CAPA
2: #
1.33 ! raeburn 3: # $Id: lonmetadata.pm,v 1.32 2011/05/31 02:40:05 raeburn Exp $
1.1 matthew 4: #
5: # Copyright Michigan State University Board of Trustees
6: #
7: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
8: #
9: # LON-CAPA is free software; you can redistribute it and/or modify
10: # it under the terms of the GNU General Public License as published by
11: # the Free Software Foundation; either version 2 of the License, or
12: # (at your option) any later version.
13: #
14: # LON-CAPA is distributed in the hope that it will be useful,
15: # but WITHOUT ANY WARRANTY; without even the implied warranty of
16: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17: # GNU General Public License for more details.
18: #
19: # You should have received a copy of the GNU General Public License
20: # along with LON-CAPA; if not, write to the Free Software
21: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22: #
23: # /home/httpd/html/adm/gpl.txt
24: #
25: # http://www.lon-capa.org/
26: #
27: ######################################################################
28:
29: package LONCAPA::lonmetadata;
30:
31: use strict;
32: use DBI;
1.16 raeburn 33: use HTML::TokeParser;
1.14 raeburn 34: use vars qw($Metadata_Table_Description $Portfolio_metadata_table_description
1.23 raeburn 35: $Portfolio_access_table_description $Fulltext_indicies $Portfolio_metadata_indices $Portfolio_access_indices $Portfolio_addedfields_table_description $Portfolio_addedfields_indices $Allusers_table_description $Allusers_indices);
1.1 matthew 36:
37: ######################################################################
38: ######################################################################
39:
40: =pod
41:
42: =head1 Name
43:
44: lonmetadata
45:
46: =head1 Synopsis
47:
48: lonmetadata holds a description of the metadata table and provides
49: wrappers for the storage and retrieval of metadata to/from the database.
50:
51: =head1 Description
52:
53: =head1 Methods
54:
55: =over 4
56:
57: =cut
58:
59: ######################################################################
60: ######################################################################
61:
62: =pod
63:
64: =item Old table creation command
65:
66: CREATE TABLE IF NOT EXISTS metadata
67: (title TEXT,
68: author TEXT,
69: subject TEXT,
70: url TEXT,
71: keywords TEXT,
72: version TEXT,
73: notes TEXT,
74: abstract TEXT,
75: mime TEXT,
76: language TEXT,
77: creationdate DATETIME,
78: lastrevisiondate DATETIME,
79: owner TEXT,
80: copyright TEXT,
1.12 matthew 81: domain TEXT
1.1 matthew 82:
83: FULLTEXT idx_title (title),
84: FULLTEXT idx_author (author),
85: FULLTEXT idx_subject (subject),
86: FULLTEXT idx_url (url),
87: FULLTEXT idx_keywords (keywords),
88: FULLTEXT idx_version (version),
89: FULLTEXT idx_notes (notes),
90: FULLTEXT idx_abstract (abstract),
91: FULLTEXT idx_mime (mime),
92: FULLTEXT idx_language (language),
93: FULLTEXT idx_owner (owner),
94: FULLTEXT idx_copyright (copyright))
95:
1.32 raeburn 96: ENGINE=MYISAM;
1.1 matthew 97:
98: =cut
99:
100: ######################################################################
101: ######################################################################
1.14 raeburn 102: $Metadata_Table_Description =
103: [
1.1 matthew 104: { name => 'title', type=>'TEXT'},
105: { name => 'author', type=>'TEXT'},
106: { name => 'subject', type=>'TEXT'},
107: { name => 'url', type=>'TEXT', restrictions => 'NOT NULL' },
108: { name => 'keywords', type=>'TEXT'},
109: { name => 'version', type=>'TEXT'},
110: { name => 'notes', type=>'TEXT'},
111: { name => 'abstract', type=>'TEXT'},
112: { name => 'mime', type=>'TEXT'},
113: { name => 'language', type=>'TEXT'},
114: { name => 'creationdate', type=>'DATETIME'},
115: { name => 'lastrevisiondate', type=>'DATETIME'},
116: { name => 'owner', type=>'TEXT'},
117: { name => 'copyright', type=>'TEXT'},
1.12 matthew 118: { name => 'domain', type=>'TEXT'},
1.1 matthew 119: #--------------------------------------------------
120: { name => 'dependencies', type=>'TEXT'},
121: { name => 'modifyinguser', type=>'TEXT'},
122: { name => 'authorspace', type=>'TEXT'},
123: { name => 'lowestgradelevel', type=>'INT'},
124: { name => 'highestgradelevel', type=>'INT'},
125: { name => 'standards', type=>'TEXT'},
126: { name => 'count', type=>'INT'},
127: { name => 'course', type=>'INT'},
128: { name => 'course_list', type=>'TEXT'},
129: { name => 'goto', type=>'INT'},
130: { name => 'goto_list', type=>'TEXT'},
131: { name => 'comefrom', type=>'INT'},
132: { name => 'comefrom_list', type=>'TEXT'},
133: { name => 'sequsage', type=>'INT'},
134: { name => 'sequsage_list', type=>'TEXT'},
135: { name => 'stdno', type=>'INT'},
136: { name => 'stdno_list', type=>'TEXT'},
137: { name => 'avetries', type=>'FLOAT'},
138: { name => 'avetries_list', type=>'TEXT'},
139: { name => 'difficulty', type=>'FLOAT'},
140: { name => 'difficulty_list',type=>'TEXT'},
1.9 matthew 141: { name => 'disc', type=>'FLOAT'},
142: { name => 'disc_list', type=>'TEXT'},
1.1 matthew 143: { name => 'clear', type=>'FLOAT'},
144: { name => 'technical', type=>'FLOAT'},
145: { name => 'correct', type=>'FLOAT'},
146: { name => 'helpful', type=>'FLOAT'},
147: { name => 'depth', type=>'FLOAT'},
148: { name => 'hostname', type=> 'TEXT'},
149: #--------------------------------------------------
1.14 raeburn 150: ];
1.1 matthew 151:
1.14 raeburn 152: $Fulltext_indicies = [ qw/
1.1 matthew 153: title
154: author
155: subject
156: url
157: keywords
158: version
159: notes
160: abstract
161: mime
162: language
163: owner
1.14 raeburn 164: copyright/ ];
165:
166: ######################################################################
167: ######################################################################
168: $Portfolio_metadata_table_description =
169: [
170: { name => 'title', type=>'TEXT'},
171: { name => 'author', type=>'TEXT'},
172: { name => 'subject', type=>'TEXT'},
173: { name => 'url', type=>'TEXT', restrictions => 'NOT NULL' },
174: { name => 'keywords', type=>'TEXT'},
175: { name => 'version', type=>'TEXT'},
176: { name => 'notes', type=>'TEXT'},
177: { name => 'abstract', type=>'TEXT'},
178: { name => 'mime', type=>'TEXT'},
179: { name => 'language', type=>'TEXT'},
180: { name => 'creationdate', type=>'DATETIME'},
181: { name => 'lastrevisiondate', type=>'DATETIME'},
182: { name => 'owner', type=>'TEXT'},
183: { name => 'copyright', type=>'TEXT'},
184: { name => 'domain', type=>'TEXT'},
185: { name => 'groupname', type=>'TEXT'},
186: { name => 'courserestricted', type=>'TEXT'},
187: #--------------------------------------------------
188: { name => 'dependencies', type=>'TEXT'},
189: { name => 'modifyinguser', type=>'TEXT'},
190: { name => 'authorspace', type=>'TEXT'},
191: { name => 'lowestgradelevel', type=>'INT'},
192: { name => 'highestgradelevel', type=>'INT'},
193: { name => 'standards', type=>'TEXT'},
194: { name => 'hostname', type=> 'TEXT'},
195: #--------------------------------------------------
196: ];
197:
198: $Portfolio_metadata_indices = [qw/
199: title
200: author
201: subject
202: url
203: keywords
204: version
205: notes
206: abstract
207: mime
208: language
209: owner/];
210:
211: ######################################################################
212: ######################################################################
213:
214: $Portfolio_access_table_description =
215: [
216: { name => 'url', type=>'TEXT', restrictions => 'NOT NULL' },
217: { name => 'keynum', type=>'TEXT', restrictions => 'NOT NULL' },
218: { name => 'scope', type=>'TEXT'},
219: { name => 'start', type=>'DATETIME'},
220: { name => 'end', type=>'DATETIME'},
221: ];
222:
223: $Portfolio_access_indices = [qw/
224: url
225: keynum
226: scope
227: start
228: end/];
1.1 matthew 229:
230: ######################################################################
231: ######################################################################
232:
1.14 raeburn 233: $Portfolio_addedfields_table_description =
234: [
235: { name => 'url', type=>'TEXT', restrictions => 'NOT NULL' },
236: { name => 'field', type=>'TEXT', restrictions => 'NOT NULL' },
237: { name => 'courserestricted', type=>'TEXT', restrictions => 'NOT NULL' },
238: { name => 'value', type=>'TEXT'},
239: ];
240:
241: $Portfolio_addedfields_indices = [qw/
242: url
243: field
244: value
245: courserestricted/];
246:
247: ######################################################################
248: ######################################################################
249:
1.23 raeburn 250: $Allusers_table_description =
251: [
252: { name => 'username', type=>'TEXT', restrictions => 'NOT NULL' },
253: { name => 'domain', type=>'TEXT', restrictions => 'NOT NULL' },
254: { name => 'lastname', type=>'TEXT',},
255: { name => 'firstname', type=>'TEXT'},
256: { name => 'middlename', type=>'TEXT'},
257: { name => 'generation', type=>'TEXT'},
258: { name => 'permanentemail', type=>'TEXT'},
259: { name => 'id', type=>'TEXT'},
260: ];
261:
262: $Allusers_indices = [qw/
263: username
264: domain
265: lastname
266: firstname/];
267:
268: ######################################################################
269: ######################################################################
1.14 raeburn 270:
1.1 matthew 271: =pod
272:
273: =item &describe_metadata_storage
274:
275: Input: None
276:
1.2 matthew 277: Returns: An array of hash references describing the columns and indicies
278: of the metadata table(s).
1.1 matthew 279:
280: =cut
281:
282: ######################################################################
283: ######################################################################
1.14 raeburn 284: sub describe_metadata_storage {
285: my ($tabletype) = @_;
286: my %table_description = (
287: metadata => $Metadata_Table_Description,
288: portfolio_metadata => $Portfolio_metadata_table_description,
289: portfolio_access => $Portfolio_access_table_description,
290: portfolio_addedfields => $Portfolio_addedfields_table_description,
1.23 raeburn 291: allusers => $Allusers_table_description,
1.14 raeburn 292: );
293: my %index_description = (
294: metadata => $Fulltext_indicies,
295: portfolio_metadata => $Portfolio_metadata_indices,
296: portfolio_access => $Portfolio_access_indices,
297: portfolio_addedfields => $Portfolio_addedfields_indices,
1.23 raeburn 298: allusers => $Allusers_indices,
1.14 raeburn 299: );
300: if ($tabletype eq 'portfolio_search') {
301: my @portfolio_search_table = @{$table_description{portfolio_metadata}};
302: foreach my $item (@{$table_description{portfolio_access}}) {
303: if (ref($item) eq 'HASH') {
304: if ($item->{'name'} eq 'url') {
305: next;
306: }
307: }
308: push(@portfolio_search_table,$item);
309: }
310: my @portfolio_search_indices = @{$index_description{portfolio_metadata}};
311: push(@portfolio_search_indices,('scope','keynum'));
312: return (\@portfolio_search_table,\@portfolio_search_indices);
313: } else {
314: return ($table_description{$tabletype},$index_description{$tabletype});
315: }
1.1 matthew 316: }
317:
318: ######################################################################
319: ######################################################################
320:
321: =pod
322:
323: =item create_metadata_storage()
324:
1.3 matthew 325: Inputs: table name (optional): the name of the table. Default is 'metadata'.
1.1 matthew 326:
327: Returns: A perl string which, when executed by MySQL, will cause the
328: metadata storage to be initialized.
329:
330: =cut
331:
332: ######################################################################
333: ######################################################################
334: sub create_metadata_storage {
1.14 raeburn 335: my ($tablename,$tabletype) = @_;
1.3 matthew 336: $tablename = 'metadata' if (! defined($tablename));
1.14 raeburn 337: $tabletype = 'metadata' if (! defined($tabletype));
1.1 matthew 338: my $request = "CREATE TABLE IF NOT EXISTS ".$tablename." ";
339: #
340: # Process the columns (this code is stolen from lonmysql.pm)
341: my @Columns;
342: my $col_des; # mysql column description
1.14 raeburn 343: my ($table_columns,$table_indices) =
344: &describe_metadata_storage($tabletype);
345: my %coltype;
346: foreach my $coldata (@{$table_columns}) {
1.1 matthew 347: my $column = $coldata->{'name'};
1.14 raeburn 348: $coltype{$column} = $coldata->{'type'};
1.1 matthew 349: $col_des = '';
350: if (lc($coldata->{'type'}) =~ /(enum|set)/) { # 'enum' or 'set'
351: $col_des.=$column." ".$coldata->{'type'}."('".
352: join("', '",@{$coldata->{'values'}})."')";
353: } else {
354: $col_des.=$column." ".$coldata->{'type'};
355: if (exists($coldata->{'size'})) {
356: $col_des.="(".$coldata->{'size'}.")";
357: }
358: }
1.30 raeburn 359: if (($tablename =~ /allusers/) && ($column eq 'username')) {
1.31 raeburn 360: $col_des .= ' CHARACTER SET latin1 COLLATE latin1_general_cs';
1.30 raeburn 361: }
1.1 matthew 362: # Modifiers
363: if (exists($coldata->{'restrictions'})){
364: $col_des.=" ".$coldata->{'restrictions'};
365: }
366: if (exists($coldata->{'default'})) {
367: $col_des.=" DEFAULT '".$coldata->{'default'}."'";
368: }
369: $col_des.=' AUTO_INCREMENT' if (exists($coldata->{'auto_inc'}) &&
370: ($coldata->{'auto_inc'} eq 'yes'));
371: $col_des.=' PRIMARY KEY' if (exists($coldata->{'primary_key'}) &&
372: ($coldata->{'primary_key'} eq 'yes'));
373: } continue {
374: # skip blank items.
375: push (@Columns,$col_des) if ($col_des ne '');
376: }
1.14 raeburn 377: foreach my $colname (@{$table_indices}) {
378: my $text;
379: if ($coltype{$colname} eq 'TEXT') {
380: $text = 'FULLTEXT ';
381: } else {
382: $text = 'INDEX ';
383: }
384: $text .= 'idx_'.$colname.' ('.$colname.')';
1.1 matthew 385: push (@Columns,$text);
386: }
1.33 ! raeburn 387: $request .= "(".join(", ",@Columns).") ENGINE=MyISAM";
1.1 matthew 388: return $request;
389: }
390:
391: ######################################################################
392: ######################################################################
393:
394: =pod
395:
396: =item store_metadata()
397:
1.14 raeburn 398: Inputs: database handle ($dbh), a table name, table type and a hash or hash
399: reference containing the metadata for a single resource.
1.1 matthew 400:
401: Returns: 1 on success, 0 on failure to store.
402:
403: =cut
404:
405: ######################################################################
406: ######################################################################
1.2 matthew 407: {
408: ##
409: ## WARNING: The following cleverness may cause trouble in cases where
410: ## the dbi connection is dropped and recreated - a stale statement
411: ## handler may linger around and cause trouble.
412: ##
413: ## In most scripts, this will work fine. If the dbi is going to be
414: ## dropped and (possibly) later recreated, call &clear_sth. Yes it
1.14 raeburn 415: ## is annoying but $sth apparently does not have a link back to the
1.2 matthew 416: ## $dbh, so we can't check our validity.
417: ##
418: my $sth = undef;
1.4 matthew 419: my $sth_table = undef;
1.2 matthew 420:
421: sub create_statement_handler {
1.14 raeburn 422: my ($dbh,$tablename,$tabletype) = @_;
1.4 matthew 423: $tablename = 'metadata' if (! defined($tablename));
1.14 raeburn 424: $tabletype = 'metadata' if (! defined($tabletype));
425: my ($table_columns,$table_indices) =
426: &describe_metadata_storage($tabletype);
1.4 matthew 427: $sth_table = $tablename;
428: my $request = 'INSERT INTO '.$tablename.' VALUES(';
1.14 raeburn 429: foreach (@{$table_columns}) {
1.2 matthew 430: $request .= '?,';
431: }
432: chop $request;
433: $request.= ')';
434: $sth = $dbh->prepare($request);
435: return;
436: }
437:
1.4 matthew 438: sub clear_sth { $sth=undef; $sth_table=undef;}
1.2 matthew 439:
1.1 matthew 440: sub store_metadata {
1.14 raeburn 441: my ($dbh,$tablename,$tabletype,@Metadata)=@_;
1.2 matthew 442: my $errors = '';
1.4 matthew 443: if (! defined($sth) ||
444: ( defined($tablename) && ($sth_table ne $tablename)) ||
445: (! defined($tablename) && $sth_table ne 'metadata')) {
1.14 raeburn 446: &create_statement_handler($dbh,$tablename,$tabletype);
1.2 matthew 447: }
448: my $successcount = 0;
1.14 raeburn 449: if (! defined($tabletype)) {
450: $tabletype = 'metadata';
451: }
452: my ($table_columns,$table_indices) =
453: &describe_metadata_storage($tabletype);
1.10 matthew 454: foreach my $mdata (@Metadata) {
1.2 matthew 455: next if (ref($mdata) ne "HASH");
456: my @MData;
1.14 raeburn 457: foreach my $field (@{$table_columns}) {
1.10 matthew 458: my $fname = $field->{'name'};
459: if (exists($mdata->{$fname}) &&
460: defined($mdata->{$fname}) &&
461: $mdata->{$fname} ne '') {
462: if ($mdata->{$fname} eq 'nan' ||
463: $mdata->{$fname} eq '') {
1.5 matthew 464: push(@MData,'NULL');
465: } else {
1.10 matthew 466: push(@MData,$mdata->{$fname});
1.5 matthew 467: }
1.2 matthew 468: } else {
469: push(@MData,undef);
470: }
471: }
472: $sth->execute(@MData);
473: if (! $sth->err) {
474: $successcount++;
475: } else {
476: $errors = join(',',$errors,$sth->errstr);
477: }
1.10 matthew 478: $errors =~ s/^,//;
1.2 matthew 479: }
480: if (wantarray()) {
481: return ($successcount,$errors);
482: } else {
483: return $successcount;
484: }
485: }
1.1 matthew 486:
487: }
488:
489: ######################################################################
490: ######################################################################
491:
492: =pod
493:
1.24 albertel 494: =item lookup_metadata()
1.1 matthew 495:
496: Inputs: database handle ($dbh) and a hash or hash reference containing
497: metadata which will be used for a search.
498:
1.2 matthew 499: Returns: scalar with error string on failure, array reference on success.
500: The array reference is the same one returned by $sth->fetchall_arrayref().
1.1 matthew 501:
502: =cut
503:
504: ######################################################################
505: ######################################################################
1.2 matthew 506: sub lookup_metadata {
1.10 matthew 507: my ($dbh,$condition,$fetchparameter,$tablename) = @_;
508: $tablename = 'metadata' if (! defined($tablename));
1.2 matthew 509: my $error;
510: my $returnvalue=[];
1.10 matthew 511: my $request = 'SELECT * FROM '.$tablename;
1.2 matthew 512: if (defined($condition)) {
513: $request .= ' WHERE '.$condition;
514: }
515: my $sth = $dbh->prepare($request);
516: if ($sth->err) {
517: $error = $sth->errstr;
518: }
519: if (! $error) {
520: $sth->execute();
521: if ($sth->err) {
522: $error = $sth->errstr;
523: } else {
524: $returnvalue = $sth->fetchall_arrayref($fetchparameter);
525: if ($sth->err) {
526: $error = $sth->errstr;
527: }
528: }
1.16 raeburn 529: }
1.2 matthew 530: return ($error,$returnvalue);
531: }
1.1 matthew 532:
533: ######################################################################
534: ######################################################################
535:
536: =pod
537:
538: =item delete_metadata()
539:
1.10 matthew 540: Removes a single metadata record, based on its url.
541:
542: Inputs: $dbh, the database handler.
543: $tablename, the name of the metadata table to remove from. default: 'metadata'
1.23 raeburn 544: $delitem, the resource to remove from the metadata database, in the form:
545: url = quoted url
1.10 matthew 546:
547: Returns: undef on success, dbh errorstr on failure.
548:
549: =cut
550:
551: ######################################################################
552: ######################################################################
553: sub delete_metadata {
1.23 raeburn 554: my ($dbh,$tablename,$delitem) = @_;
1.10 matthew 555: $tablename = 'metadata' if (! defined($tablename));
1.23 raeburn 556: my ($error,$delete_command);
557: if ($delitem eq '') {
558: $error = 'deletion aborted - no resource specified';
559: } else {
560: $delete_command = 'DELETE FROM '.$tablename.' WHERE '.$delitem;
561: $dbh->do($delete_command);
562: if ($dbh->err) {
563: $error = $dbh->errstr();
564: }
1.10 matthew 565: }
566: return $error;
567: }
568:
569: ######################################################################
570: ######################################################################
571:
572: =pod
573:
574: =item update_metadata
575:
576: Updates metadata record in mysql database. It does not matter if the record
577: currently exists. Fields not present in the new metadata will be taken
578: from the current record, if it exists. To delete an entry for a key, set
579: it to "" or undef.
580:
581: Inputs:
582: $dbh, database handle
583: $newmetadata, hash reference containing the new metadata
584: $tablename, metadata table name. Defaults to 'metadata'.
1.23 raeburn 585: $tabletype, type of table (metadata, portfolio_metadata, portfolio_access,
586: allusers)
587: $conditions, optional hash of conditions to use in SQL queries;
588: default used if none provided.
1.10 matthew 589:
590: Returns:
591: $error on failure. undef on success.
1.1 matthew 592:
593: =cut
594:
595: ######################################################################
596: ######################################################################
1.10 matthew 597: sub update_metadata {
1.23 raeburn 598: my ($dbh,$tablename,$tabletype,$newmetadata,$conditions)=@_;
599: my ($error,$condition);
1.10 matthew 600: $tablename = 'metadata' if (! defined($tablename));
1.14 raeburn 601: $tabletype = 'metadata' if (! defined($tabletype));
1.23 raeburn 602: if (ref($conditions) eq 'HASH') {
603: my @items;
604: foreach my $key (keys(%{$conditions})) {
605: if (! exists($newmetadata->{$key})) {
606: $error .= "Unable to update: no $key specified";
607: } else {
608: push(@items,"$key = ".$dbh->quote($newmetadata->{$key}));
609: }
610: }
611: $condition = join(' AND ',@items);
612: } else {
613: if (! exists($newmetadata->{'url'})) {
614: $error = 'Unable to update: no url specified';
615: } else {
616: $condition = 'url = '.$dbh->quote($newmetadata->{'url'});
617: }
1.10 matthew 618: }
619: return $error if (defined($error));
620: #
621: # Retrieve current values
622: my $row;
1.23 raeburn 623: ($error,$row) = &lookup_metadata($dbh,$condition,undef,$tablename);
1.10 matthew 624: return $error if ($error);
1.14 raeburn 625: my %metadata = &LONCAPA::lonmetadata::metadata_col_to_hash($tabletype,@{$row->[0]});
1.10 matthew 626: #
627: # Update metadata values
628: while (my ($key,$value) = each(%$newmetadata)) {
629: $metadata{$key} = $value;
630: }
631: #
632: # Delete old data (deleting a nonexistant record does not produce an error.
1.23 raeburn 633: $error = &delete_metadata($dbh,$tablename,$condition);
1.10 matthew 634: return $error if (defined($error));
635: #
636: # Store updated metadata
637: my $success;
1.14 raeburn 638: ($success,$error) = &store_metadata($dbh,$tablename,$tabletype,\%metadata);
1.10 matthew 639: return $error;
640: }
1.1 matthew 641:
642: ######################################################################
643: ######################################################################
1.5 matthew 644:
1.6 matthew 645: =pod
646:
647: =item metdata_col_to_hash
648:
649: Input: Array of metadata columns
650:
651: Return: Hash with the metadata columns as keys and the array elements
652: passed in as values
653:
654: =cut
655:
656: ######################################################################
657: ######################################################################
658: sub metadata_col_to_hash {
1.14 raeburn 659: my ($tabletype,@cols)=@_;
1.6 matthew 660: my %hash=();
1.14 raeburn 661: my ($columns,$indices) = &describe_metadata_storage($tabletype);
662: for (my $i=0; $i<@{$columns};$i++) {
663: $hash{$columns->[$i]->{'name'}}=$cols[$i];
664: unless ($hash{$columns->[$i]->{'name'}}) {
665: if ($columns->[$i]->{'type'} eq 'TEXT') {
666: $hash{$columns->[$i]->{'name'}}='';
667: } elsif ($columns->[$i]->{'type'} eq 'DATETIME') {
668: $hash{$columns->[$i]->{'name'}}='0000-00-00 00:00:00';
1.13 www 669: } else {
1.14 raeburn 670: $hash{$columns->[$i]->{'name'}}=0;
1.13 www 671: }
672: }
1.6 matthew 673: }
674: return %hash;
675: }
1.5 matthew 676:
677: ######################################################################
678: ######################################################################
679:
680: =pod
681:
1.8 matthew 682: =item nohist_resevaldata.db data structure
683:
684: The nohist_resevaldata.db file has the following possible keys:
685:
686: Statistics Data (values are integers, perl times, or real numbers)
687: ------------------------------------------
688: $course___$resource___avetries
689: $course___$resource___count
690: $course___$resource___difficulty
691: $course___$resource___stdno
692: $course___$resource___timestamp
693:
694: Evaluation Data (values are on a 1 to 5 scale)
695: ------------------------------------------
696: $username@$dom___$resource___clear
697: $username@$dom___$resource___comments
698: $username@$dom___$resource___depth
699: $username@$dom___$resource___technical
700: $username@$dom___$resource___helpful
1.11 www 701: $username@$dom___$resource___correct
1.8 matthew 702:
703: Course Context Data
704: ------------------------------------------
705: $course___$resource___course course id
706: $course___$resource___comefrom resource preceeding this resource
707: $course___$resource___goto resource following this resource
708: $course___$resource___usage resource containing this resource
709:
710: New statistical data storage
711: ------------------------------------------
712: $course&$sec&$numstud___$resource___stats
713: $sec is a string describing the sections: all, 1 2, 1 2 3,...
714: Value is a '&' deliminated list of key=value pairs.
715: Possible keys are (currently) disc,course,sections,difficulty,
716: stdno, timestamp
717:
718: =cut
719:
720: ######################################################################
721: ######################################################################
722:
723: =pod
724:
1.5 matthew 725: =item &process_reseval_data
726:
727: Process a nohist_resevaldata hash into a more complex data structure.
728:
729: Input: Hash reference containing reseval data
730:
731: Returns: Hash with the following structure:
732:
733: $hash{$url}->{'statistics'}->{$courseid}->{'avetries'} = $value
734: $hash{$url}->{'statistics'}->{$courseid}->{'count'} = $value
735: $hash{$url}->{'statistics'}->{$courseid}->{'difficulty'} = $value
736: $hash{$url}->{'statistics'}->{$courseid}->{'stdno'} = $value
737: $hash{$url}->{'statistics'}->{$courseid}->{'timestamp'} = $value
738:
739: $hash{$url}->{'evaluation'}->{$username}->{'clear'} = $value
740: $hash{$url}->{'evaluation'}->{$username}->{'comments'} = $value
741: $hash{$url}->{'evaluation'}->{$username}->{'depth'} = $value
742: $hash{$url}->{'evaluation'}->{$username}->{'technical'} = $value
743: $hash{$url}->{'evaluation'}->{$username}->{'helpful'} = $value
744:
745: $hash{$url}->{'course'} = \@Courses
746: $hash{$url}->{'comefrom'} = \@Resources
747: $hash{$url}->{'goto'} = \@Resources
748: $hash{$url}->{'usage'} = \@Resources
749:
750: $hash{$url}->{'stats'}->{$courseid\_$section}->{$key} = $value
751:
752: =cut
753:
754: ######################################################################
755: ######################################################################
756: sub process_reseval_data {
757: my ($evaldata) = @_;
758: my %DynamicData;
759: #
760: # Process every stored element
761: while (my ($storedkey,$value) = each(%{$evaldata})) {
762: my ($source,$file,$type) = split('___',$storedkey);
763: $source = &unescape($source);
764: $file = &unescape($file);
765: $value = &unescape($value);
766: " got ".$file."\n ".$type." ".$source."\n";
767: if ($type =~ /^(avetries|count|difficulty|stdno|timestamp)$/) {
768: #
769: # Statistics: $source is course id
770: $DynamicData{$file}->{'statistics'}->{$source}->{$type}=$value;
1.11 www 771: } elsif ($type =~ /^(clear|comments|depth|technical|helpful|correct)$/){
1.5 matthew 772: #
773: # Evaluation $source is username, check if they evaluated it
774: # more than once. If so, pad the entry with a space.
775: while(exists($DynamicData{$file}->{'evaluation'}->{$type}->{$source})) {
776: $source .= ' ';
777: }
778: $DynamicData{$file}->{'evaluation'}->{$type}->{$source}=$value;
779: } elsif ($type =~ /^(course|comefrom|goto|usage)$/) {
780: #
781: # Context $source is course id or resource
782: push(@{$DynamicData{$file}->{$type}},&unescape($source));
783: } elsif ($type eq 'stats') {
784: #
785: # Statistics storage...
786: # $source is $cid\_$sec\_$stdno
787: # $value is stat1=value&stat2=value&stat3=value,....
788: #
1.8 matthew 789: my ($cid,$sec,$stdno)=split('&',$source);
790: my $crssec = $cid.'&'.$sec;
1.5 matthew 791: my @Data = split('&',$value);
792: my %Statistics;
793: while (my ($key,$value) = split('=',pop(@Data))) {
794: $Statistics{$key} = $value;
795: }
1.8 matthew 796: $sec =~ s:("$|^")::g;
797: $Statistics{'sections'} = $sec;
1.5 matthew 798: #
799: # Only store the data if the number of students is greater
800: # than the data already stored
801: if (! exists($DynamicData{$file}->{'stats'}->{$crssec}) ||
802: $DynamicData{$file}->{'stats'}->{$crssec}->{'stdno'}<$stdno){
803: $DynamicData{$file}->{'stats'}->{$crssec}=\%Statistics;
804: }
805: }
806: }
807: return %DynamicData;
808: }
809:
810:
811: ######################################################################
812: ######################################################################
813:
814: =pod
815:
816: =item &process_dynamic_metadata
817:
818: Inputs: $url: the url of the item to process
819: $DynamicData: hash reference for the results of &process_reseval_data
820:
821: Returns: Hash containing the following keys:
822: avetries, avetries_list, difficulty, difficulty_list, stdno, stdno_list,
823: course, course_list, goto, goto_list, comefrom, comefrom_list,
824: usage, clear, technical, correct, helpful, depth, comments
825:
826: Each of the return keys is associated with either a number or a string
827: The *_list items are comma-seperated strings. 'comments' is a string
828: containing generically marked-up comments.
829:
830: =cut
831:
832: ######################################################################
833: ######################################################################
834: sub process_dynamic_metadata {
835: my ($url,$DynamicData) = @_;
836: my %data;
837: my $resdata = $DynamicData->{$url};
838: #
1.8 matthew 839: # Get the statistical data - Use a weighted average
840: foreach my $type (qw/avetries difficulty disc/) {
841: my $studentcount;
1.21 albertel 842: my %course_counted;
1.5 matthew 843: my $sum;
844: my @Values;
1.8 matthew 845: my @Students;
1.5 matthew 846: #
1.21 albertel 847: # New data
1.8 matthew 848: if (exists($resdata->{'stats'})) {
849: foreach my $identifier (sort(keys(%{$resdata->{'stats'}}))) {
850: my $coursedata = $resdata->{'stats'}->{$identifier};
1.21 albertel 851: next if (lc($coursedata->{$type}) eq 'nan');
852: $course_counted{$coursedata->{'course'}}++;
1.8 matthew 853: $studentcount += $coursedata->{'stdno'};
854: $sum += $coursedata->{$type}*$coursedata->{'stdno'};
855: push(@Values,$coursedata->{$type});
856: push(@Students,$coursedata->{'stdno'});
857: }
858: }
859: #
1.21 albertel 860: # Old data
861: foreach my $course (keys(%{$resdata->{'statistics'}})) {
862: next if (exists($course_counted{$course}));
863: my $coursedata = $resdata->{'statistics'}{$course};
864: if (ref($coursedata) eq 'HASH' && exists($coursedata->{$type})) {
865: next if (lc($coursedata->{$type}) eq 'nan');
866: $studentcount += $coursedata->{'stdno'};
867: $sum += ($coursedata->{$type}*$coursedata->{'stdno'});
868: push(@Values,$coursedata->{$type});
869: push(@Students,$coursedata->{'stdno'});
870: }
871: }
1.8 matthew 872: if (defined($studentcount) && $studentcount>0) {
873: $data{$type} = $sum/$studentcount;
1.5 matthew 874: $data{$type.'_list'} = join(',',@Values);
875: }
876: }
877: #
1.8 matthew 878: # Find out the number of students who have completed the resource...
879: my $stdno;
1.20 albertel 880: my %course_counted;
1.8 matthew 881: if (exists($resdata->{'stats'})) {
882: #
883: # For the number of students, take the maximum found for the class
884: my $current_course;
885: my $coursemax=0;
886: foreach my $identifier (sort(keys(%{$resdata->{'stats'}}))) {
887: my $coursedata = $resdata->{'stats'}->{$identifier};
888: if (! defined($current_course)) {
889: $current_course = $coursedata->{'course'};
890: }
891: if ($current_course ne $coursedata->{'course'}) {
892: $stdno += $coursemax;
1.20 albertel 893: $course_counted{$coursedata->{'course'}}++;
1.8 matthew 894: $coursemax = 0;
895: $current_course = $coursedata->{'course'};
896: }
897: if ($coursemax < $coursedata->{'stdno'}) {
898: $coursemax = $coursedata->{'stdno'};
899: }
900: }
901: $stdno += $coursemax; # pick up the final course in the list
902: }
1.20 albertel 903: # check for old data that has not been run since the format was changed
904: foreach my $course (keys(%{$resdata->{'statistics'}})) {
905: next if (exists($course_counted{$course}));
906: my $coursedata = $resdata->{'statistics'}{$course};
907: if (ref($coursedata) eq 'HASH' && exists($coursedata->{'stdno'})) {
908: $stdno += $coursedata->{'stdno'};
909: }
910: }
1.8 matthew 911: $data{'stdno'}=$stdno;
912: #
1.5 matthew 913: # Get the context data
914: foreach my $type (qw/course goto comefrom/) {
915: if (defined($resdata->{$type}) &&
916: ref($resdata->{$type}) eq 'ARRAY') {
917: $data{$type} = scalar(@{$resdata->{$type}});
918: $data{$type.'_list'} = join(',',@{$resdata->{$type}});
919: }
920: }
921: if (defined($resdata->{'usage'}) &&
922: ref($resdata->{'usage'}) eq 'ARRAY') {
923: $data{'sequsage'} = scalar(@{$resdata->{'usage'}});
924: $data{'sequsage_list'} = join(',',@{$resdata->{'usage'}});
925: }
926: #
927: # Get the evaluation data
928: foreach my $type (qw/clear technical correct helpful depth/) {
929: my $count;
930: my $sum;
931: foreach my $evaluator (keys(%{$resdata->{'evaluation'}->{$type}})){
932: $sum += $resdata->{'evaluation'}->{$type}->{$evaluator};
933: $count++;
934: }
935: if ($count > 0) {
936: $data{$type}=$sum/$count;
937: }
938: }
939: #
940: # put together comments
1.26 bisitz 941: my $comments = '';
1.5 matthew 942: foreach my $evaluator (keys(%{$resdata->{'evaluation'}->{'comments'}})){
1.7 matthew 943: $comments .=
944: '<p>'.
1.26 bisitz 945: '<b>'.$evaluator.'</b>: '.
1.7 matthew 946: $resdata->{'evaluation'}->{'comments'}->{$evaluator}.
947: '</p>';
1.5 matthew 948: }
1.26 bisitz 949: if ($comments) {
950: $comments = '<div class="LCevalcomments">'
951: .$comments
952: .'</div>';
1.27 bisitz 953: $data{'comments'} = $comments;
1.26 bisitz 954: }
1.5 matthew 955: #
1.8 matthew 956: if (exists($resdata->{'stats'})) {
957: $data{'stats'} = $resdata->{'stats'};
958: }
1.12 matthew 959: if (exists($DynamicData->{'domain'})) {
960: $data{'domain'} = $DynamicData->{'domain'};
961: }
1.8 matthew 962: #
1.5 matthew 963: return %data;
964: }
965:
1.8 matthew 966: sub dynamic_metadata_storage {
967: my ($data) = @_;
968: my %Store;
969: my $courseid = $data->{'course'};
970: my $sections = $data->{'sections'};
971: my $numstu = $data->{'num_students'};
972: my $urlres = $data->{'urlres'};
973: my $key = $courseid.'&'.$sections.'&'.$numstu.'___'.$urlres.'___stats';
974: $Store{$key} =
975: 'course='.$courseid.'&'.
976: 'sections='.$sections.'&'.
977: 'timestamp='.time.'&'.
978: 'stdno='.$data->{'num_students'}.'&'.
979: 'avetries='.$data->{'mean_tries'}.'&'.
980: 'difficulty='.$data->{'deg_of_diff'};
981: if (exists($data->{'deg_of_disc'})) {
982: $Store{$key} .= '&'.'disc='.$data->{'deg_of_disc'};
983: }
984: return %Store;
985: }
1.6 matthew 986:
1.16 raeburn 987: ###############################################################
988: ###############################################################
989: ### ###
990: ### &portfolio_metadata($filepath,$dom,$uname,$group) ###
991: ### Retrieve metadata for the given file ###
992: ### Returns array - ###
993: ### contains reference to metadatahash and ###
994: ### optional reference to addedfields hash ###
995: ### ###
996: ###############################################################
997: ###############################################################
998:
999: sub portfolio_metadata {
1000: my ($fullpath,$dom,$uname,$group)=@_;
1001: my ($mime) = ( $fullpath=~/\.(\w+)$/ );
1002: my %metacache=();
1003: if ($fullpath !~ /\.meta$/) {
1004: $fullpath .= '.meta';
1005: }
1006: my (@standard_fields,%addedfields);
1007: my $colsref = $Portfolio_metadata_table_description;
1008: if (ref($colsref) eq 'ARRAY') {
1009: my @columns = @{$colsref};
1010: foreach my $coldata (@columns) {
1011: push(@standard_fields,$coldata->{'name'});
1012: }
1013: }
1014: my $metastring=&getfile($fullpath);
1015: if (! defined($metastring)) {
1016: $metacache{'keys'}= 'owner,domain,mime';
1017: $metacache{'owner'} = $uname.':'.$dom;
1018: $metacache{'domain'} = $dom;
1019: $metacache{'mime'} = $mime;
1020: if ($group ne '') {
1021: $metacache{'keys'} .= ',courserestricted';
1022: $metacache{'courserestricted'} = 'course.'.$dom.'_'.$uname;
1023: }
1024: } else {
1025: my $parser=HTML::TokeParser->new(\$metastring);
1026: my $token;
1027: while ($token=$parser->get_token) {
1028: if ($token->[0] eq 'S') {
1029: my $entry=$token->[1];
1030: if ($metacache{'keys'}) {
1031: $metacache{'keys'}.=','.$entry;
1032: } else {
1033: $metacache{'keys'}=$entry;
1034: }
1035: my $value = $parser->get_text('/'.$entry);
1036: if (!grep(/^\Q$entry\E$/,@standard_fields)) {
1037: my $clean_value = lc($value);
1038: $clean_value =~ s/\s/_/g;
1039: if ($clean_value ne $entry) {
1040: if (defined($addedfields{$entry})) {
1041: $addedfields{$entry} .=','.$value;
1042: } else {
1043: $addedfields{$entry} = $value;
1044: }
1045: }
1046: } else {
1047: $metacache{$entry} = $value;
1048: }
1049: }
1050: } # End of ($token->[0] eq 'S')
1.22 albertel 1051:
1052: if (!exists($metacache{'domain'})) {
1053: $metacache{'domain'} = $dom;
1054: }
1.16 raeburn 1055: }
1056: return (\%metacache,$metacache{'courserestricted'},\%addedfields);
1057: }
1058:
1059: sub process_portfolio_access_data {
1060: my ($dbh,$simulate,$newnames,$url,$fullpath,$access_hash,$caller) = @_;
1061: my %loghash;
1062: if ($caller eq 'update') {
1063: # Delete old data (no error if deleting non-existent record).
1.23 raeburn 1064: my $error;
1065: if ($url eq '') {
1066: $error = 'No url specified';
1067: } else {
1068: my $delitem = 'url = '.$dbh->quote($url);
1069: $error=&delete_metadata($dbh,$newnames->{'access'},$delitem);
1070: }
1.16 raeburn 1071: if (defined($error)) {
1072: $loghash{'access'}{'err'} = "MySQL Error Delete: ".$error;
1073: return %loghash;
1074: }
1075: }
1076: # Check the file exists
1077: if (-e $fullpath) {
1078: foreach my $key (keys(%{$access_hash})) {
1079: my $acc_data;
1080: $acc_data->{url} = $url;
1081: $acc_data->{keynum} = $key;
1082: my ($num,$scope,$end,$start) =
1083: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1084: next if (($scope ne 'public') && ($scope ne 'guest'));
1085: $acc_data->{scope} = $scope;
1.28 raeburn 1086: my $sqltime_error;
1.16 raeburn 1087: if ($end != 0) {
1.28 raeburn 1088: $acc_data->{end} = &sqltime($end,\$sqltime_error);
1089: }
1090: $acc_data->{start} = &sqltime($start,\$sqltime_error);
1091: if ($sqltime_error) {
1092: $loghash{$key}{'err'} = $sqltime_error;
1.16 raeburn 1093: }
1094: if (! $simulate) {
1095: my ($count,$err) =
1096: &store_metadata($dbh,$newnames->{'access'},
1097: 'portfolio_access',$acc_data);
1098: if ($err) {
1099: $loghash{$key}{'err'} = "MySQL Error Insert: ".$err;
1100: }
1101: if ($count < 1) {
1102: $loghash{$key}{'count'} =
1103: "Unable to insert record into MySQL database for $url";
1104: }
1105: }
1106: }
1107: }
1108: return %loghash;
1109: }
1110:
1111: sub process_portfolio_metadata {
1112: my ($dbh,$simulate,$newnames,$url,$fullpath,$is_course,$dom,$uname,$group,$caller) = @_;
1113: my %loghash;
1114: if ($caller eq 'update') {
1115: # Delete old data (no error if deleting non-existent record).
1.23 raeburn 1116: my ($error,$delitem);
1117: if ($url eq '') {
1118: $error = 'No url specified';
1119: } else {
1120: $delitem = 'url = '.$dbh->quote($url);
1121: $error=&delete_metadata($dbh,$newnames->{'portfolio'},$delitem);
1122: }
1.16 raeburn 1123: if (defined($error)) {
1124: $loghash{'metadata'}{'err'} = "MySQL Error delete metadata: ".
1125: $error;
1126: return %loghash;
1127: }
1.23 raeburn 1128: $error=&delete_metadata($dbh,$newnames->{'addedfields'},$delitem);
1.16 raeburn 1129: if (defined($error)) {
1130: $loghash{'addedfields'}{'err'}="MySQL Error delete addedfields: ".$error;
1131: }
1132: }
1133: # Check the file exists.
1134: if (-e $fullpath) {
1135: my ($ref,$crs,$addedfields) = &portfolio_metadata($fullpath,$dom,$uname,
1136: $group);
1.28 raeburn 1137: my $sqltime_error;
1138: &getfiledates($ref,$fullpath,\$sqltime_error);
1.16 raeburn 1139: if ($is_course) {
1140: $ref->{'groupname'} = $group;
1141: }
1142: my %Data;
1143: if (ref($ref) eq 'HASH') {
1144: %Data = %{$ref};
1145: }
1146: %Data = (
1147: %Data,
1148: 'url'=>$url,
1149: 'version'=>'current',
1150: );
1151: my %loghash;
1152: if (! $simulate) {
1.28 raeburn 1153: if ($sqltime_error) {
1154: $loghash{'metadata'."\0"}{'err'} = $sqltime_error;
1155: }
1.16 raeburn 1156: my ($count,$err) =
1157: &store_metadata($dbh,$newnames->{'portfolio'},'portfolio_metadata',
1158: \%Data);
1159: if ($err) {
1160: $loghash{'metadata'."\0"}{'err'} = "MySQL Error Insert: ".$err;
1161: }
1162: if ($count < 1) {
1163: $loghash{'metadata'."\0"}{'count'} = "Unable to insert record into MySQL portfolio_metadata database table for $url";
1164: }
1165: if (ref($addedfields) eq 'HASH') {
1166: if (keys(%{$addedfields}) > 0) {
1167: foreach my $key (keys(%{$addedfields})) {
1168: my $added_data = {
1169: 'url' => $url,
1170: 'field' => $key,
1171: 'value' => $addedfields->{$key},
1172: 'courserestricted' => $crs,
1173: };
1174: my ($count,$err) =
1175: &store_metadata($dbh,$newnames->{'addedfields'},
1176: 'portfolio_addedfields',$added_data);
1177: if ($err) {
1178: $loghash{$key}{'err'} =
1179: "MySQL Error Insert: ".$err;
1180: }
1181: if ($count < 1) {
1182: $loghash{$key}{'count'} = "Unable to insert record into MySQL portfolio_addedfields database table for url = $url and field = $key";
1183: }
1184: }
1185: }
1186: }
1187: }
1188: }
1189: return %loghash;
1190: }
1191:
1.23 raeburn 1192: sub process_allusers_data {
1193: my ($dbh,$simulate,$newnames,$uname,$udom,$userdata,$caller) = @_;
1194: my %loghash;
1195: if ($caller eq 'update') {
1196: # Delete old data (no error if deleting non-existent record).
1197: my ($error,$delitem);
1198: if ($udom eq '' || $uname eq '' ) {
1199: $error = 'No domain and/or username specified';
1200: } else {
1.25 raeburn 1201: $delitem = 'domain = '.$dbh->quote($udom).' AND username '.
1202: 'COLLATE latin1_general_cs = '.$dbh->quote($uname);
1.23 raeburn 1203: $error=&delete_metadata($dbh,$newnames->{'allusers'},$delitem);
1204: }
1205: if (defined($error)) {
1206: $loghash{'err'} = 'MySQL Error in allusers delete: '.$error;
1207: return %loghash;
1208: }
1209: }
1210: if (!$simulate) {
1211: if ($udom ne '' && $uname ne '') {
1212: my ($count,$err) = &store_metadata($dbh,$newnames->{'allusers'},
1213: 'allusers',$userdata);
1214: if ($err) {
1215: $loghash{'err'} = 'MySQL Error in allusers insert: '.$err;
1216: }
1217: if ($count < 1) {
1218: $loghash{'count'} =
1219: 'Unable to insert record into MySQL allusers database for '.
1220: $uname.' in '.$udom;
1221: }
1222: } else {
1223: $loghash{'err'} =
1224: 'MySQL Error allusrs insert: missing username and/or domain';
1225: }
1226: }
1227: return %loghash;
1228: }
1229:
1.5 matthew 1230: ######################################################################
1231: ######################################################################
1.14 raeburn 1232:
1.16 raeburn 1233: sub getfile {
1234: my $file = shift();
1235: if (! -e $file ) {
1236: return undef;
1237: }
1.17 albertel 1238: open(my $fh,"<$file");
1.16 raeburn 1239: my $contents = '';
1240: while (<$fh>) {
1241: $contents .= $_;
1242: }
1243: return $contents;
1244: }
1245:
1246: ##
1.28 raeburn 1247: ## &getfiledates($ref,$target,$sqltime_error)
1.16 raeburn 1248: ## Converts creationdate and modifieddates to SQL format
1249: ## Applies stat() to file to retrieve dates if missing
1250: sub getfiledates {
1.28 raeburn 1251: my ($ref,$target,$sqltime_error) = @_;
1.16 raeburn 1252: if (! defined($ref->{'creationdate'}) ||
1253: $ref->{'creationdate'} =~ /^\s*$/) {
1254: $ref->{'creationdate'} = (stat($target))[9];
1255: }
1256: if (! defined($ref->{'lastrevisiondate'}) ||
1257: $ref->{'lastrevisiondate'} =~ /^\s*$/) {
1258: $ref->{'lastrevisiondate'} = (stat($target))[9];
1259: }
1.28 raeburn 1260: $ref->{'creationdate'} = &sqltime($ref->{'creationdate'},$sqltime_error);
1261: $ref->{'lastrevisiondate'} = &sqltime($ref->{'lastrevisiondate'},$sqltime_error);
1.16 raeburn 1262: }
1263:
1.15 raeburn 1264: ##
1.28 raeburn 1265: ## &sqltime($timestamp,$sqltime_error)
1.15 raeburn 1266: ##
1267: ## Convert perl $timestamp to MySQL time. MySQL expects YYYY-MM-DD HH:MM:SS
1268: ##
1269: sub sqltime {
1.28 raeburn 1270: my ($time,$sqltime_error) = @_;
1.15 raeburn 1271: my $mysqltime;
1272: if ($time =~
1273: /(\d+)-(\d+)-(\d+) # YYYY-MM-DD
1274: \s # a space
1275: (\d+):(\d+):(\d+) # HH:MM::SS
1276: /x ) {
1277: # Some of the .meta files have the time in mysql
1278: # format already, so just make sure they are 0 padded and
1279: # pass them back.
1280: $mysqltime = sprintf('%04d-%02d-%02d %02d:%02d:%02d',
1281: $1,$2,$3,$4,$5,$6);
1282: } elsif ($time =~ /^\d+$/) {
1283: my @TimeData = gmtime($time);
1284: # Alter the month to be 1-12 instead of 0-11
1285: $TimeData[4]++;
1286: # Alter the year to be from 0 instead of from 1900
1287: $TimeData[5]+=1900;
1288: $mysqltime = sprintf('%04d-%02d-%02d %02d:%02d:%02d',
1289: @TimeData[5,4,3,2,1,0]);
1290: } elsif (! defined($time) || $time == 0) {
1291: $mysqltime = 0;
1292: } else {
1.28 raeburn 1293: if (ref($sqltime_error) eq 'SCALAR') {
1294: $$sqltime_error = "sqltime:Unable to decode time ".$time;
1295: }
1.15 raeburn 1296: $mysqltime = 0;
1297: }
1298: return $mysqltime;
1299: }
1.14 raeburn 1300:
1301: ######################################################################
1302: ######################################################################
1.5 matthew 1303: ##
1304: ## The usual suspects, repeated here to reduce dependency hell
1305: ##
1306: ######################################################################
1307: ######################################################################
1308: sub unescape {
1309: my $str=shift;
1310: $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1311: return $str;
1312: }
1313:
1314: sub escape {
1315: my $str=shift;
1316: $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
1317: return $str;
1318: }
1.6 matthew 1319:
1.1 matthew 1320: 1;
1321:
1322: __END__;
1323:
1324: =pod
1325:
1326: =back
1327:
1328: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>