Annotation of loncom/metadata_database/LONCAPA/lonmetadata.pm, revision 1.20

1.1       matthew     1: # The LearningOnline Network with CAPA
                      2: #
1.20    ! albertel    3: # $Id: lonmetadata.pm,v 1.19 2007/01/19 14:23:46 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 
                     35: $Portfolio_access_table_description $Fulltext_indicies $Portfolio_metadata_indices $Portfolio_access_indices $Portfolio_addedfields_table_description $Portfolio_addedfields_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: 
                     96: TYPE=MYISAM;
                     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: 
                    250: 
1.1       matthew   251: =pod
                    252: 
                    253: =item &describe_metadata_storage
                    254: 
                    255: Input: None
                    256: 
1.2       matthew   257: Returns: An array of hash references describing the columns and indicies
                    258: of the metadata table(s).
1.1       matthew   259: 
                    260: =cut
                    261: 
                    262: ######################################################################
                    263: ######################################################################
1.14      raeburn   264: sub describe_metadata_storage {
                    265:     my ($tabletype) = @_;
                    266:     my %table_description = (
                    267:         metadata              => $Metadata_Table_Description,
                    268:         portfolio_metadata    => $Portfolio_metadata_table_description,
                    269:         portfolio_access      => $Portfolio_access_table_description,
                    270:         portfolio_addedfields => $Portfolio_addedfields_table_description, 
                    271:     );
                    272:     my %index_description = (
                    273:         metadata              => $Fulltext_indicies,
                    274:         portfolio_metadata    => $Portfolio_metadata_indices,
                    275:         portfolio_access      => $Portfolio_access_indices,
                    276:         portfolio_addedfields => $Portfolio_addedfields_indices,
                    277:     );
                    278:     if ($tabletype eq 'portfolio_search') {
                    279:         my @portfolio_search_table = @{$table_description{portfolio_metadata}};
                    280:         foreach my $item (@{$table_description{portfolio_access}}) {
                    281:             if (ref($item) eq 'HASH') {
                    282:                 if ($item->{'name'} eq 'url') {
                    283:                     next;
                    284:                 }
                    285:             }
                    286:             push(@portfolio_search_table,$item);
                    287:         }
                    288:         my @portfolio_search_indices = @{$index_description{portfolio_metadata}};
                    289:         push(@portfolio_search_indices,('scope','keynum'));
                    290:         return (\@portfolio_search_table,\@portfolio_search_indices);
                    291:     } else {
                    292:         return ($table_description{$tabletype},$index_description{$tabletype});
                    293:     }
1.1       matthew   294: }
                    295: 
                    296: ######################################################################
                    297: ######################################################################
                    298: 
                    299: =pod
                    300: 
                    301: =item create_metadata_storage()
                    302: 
1.3       matthew   303: Inputs: table name (optional): the name of the table.  Default is 'metadata'.
1.1       matthew   304: 
                    305: Returns: A perl string which, when executed by MySQL, will cause the
                    306: metadata storage to be initialized.
                    307: 
                    308: =cut
                    309: 
                    310: ######################################################################
                    311: ######################################################################
                    312: sub create_metadata_storage { 
1.14      raeburn   313:     my ($tablename,$tabletype) = @_;
1.3       matthew   314:     $tablename = 'metadata' if (! defined($tablename));
1.14      raeburn   315:     $tabletype = 'metadata' if (! defined($tabletype));
1.1       matthew   316:     my $request = "CREATE TABLE IF NOT EXISTS ".$tablename." ";
                    317:     #
                    318:     # Process the columns  (this code is stolen from lonmysql.pm)
                    319:     my @Columns;
                    320:     my $col_des; # mysql column description
1.14      raeburn   321:     my ($table_columns,$table_indices) = 
                    322:                           &describe_metadata_storage($tabletype);
                    323:     my %coltype;
                    324:     foreach my $coldata (@{$table_columns}) {
1.1       matthew   325:         my $column = $coldata->{'name'};
1.14      raeburn   326:         $coltype{$column} = $coldata->{'type'};
1.1       matthew   327:         $col_des = '';
                    328:         if (lc($coldata->{'type'}) =~ /(enum|set)/) { # 'enum' or 'set'
                    329:             $col_des.=$column." ".$coldata->{'type'}."('".
                    330:                 join("', '",@{$coldata->{'values'}})."')";
                    331:         } else {
                    332:             $col_des.=$column." ".$coldata->{'type'};
                    333:             if (exists($coldata->{'size'})) {
                    334:                 $col_des.="(".$coldata->{'size'}.")";
                    335:             }
                    336:         }
                    337:         # Modifiers
                    338:         if (exists($coldata->{'restrictions'})){
                    339:             $col_des.=" ".$coldata->{'restrictions'};
                    340:         }
                    341:         if (exists($coldata->{'default'})) {
                    342:             $col_des.=" DEFAULT '".$coldata->{'default'}."'";
                    343:         }
                    344:         $col_des.=' AUTO_INCREMENT' if (exists($coldata->{'auto_inc'}) &&
                    345:                                         ($coldata->{'auto_inc'} eq 'yes'));
                    346:         $col_des.=' PRIMARY KEY'    if (exists($coldata->{'primary_key'}) &&
                    347:                                         ($coldata->{'primary_key'} eq 'yes'));
                    348:     } continue {
                    349:         # skip blank items.
                    350:         push (@Columns,$col_des) if ($col_des ne '');
                    351:     }
1.14      raeburn   352:     foreach my $colname (@{$table_indices}) {
                    353:         my $text;
                    354:         if ($coltype{$colname} eq 'TEXT') {
                    355:             $text = 'FULLTEXT ';
                    356:         } else {
                    357:             $text = 'INDEX ';
                    358:         }
                    359:         $text .= 'idx_'.$colname.' ('.$colname.')';
1.1       matthew   360:         push (@Columns,$text);
                    361:     }
1.3       matthew   362:     $request .= "(".join(", ",@Columns).") TYPE=MyISAM";
1.1       matthew   363:     return $request;
                    364: }
                    365: 
                    366: ######################################################################
                    367: ######################################################################
                    368: 
                    369: =pod
                    370: 
                    371: =item store_metadata()
                    372: 
1.14      raeburn   373: Inputs: database handle ($dbh), a table name, table type and a hash or hash 
                    374: reference containing the metadata for a single resource.
1.1       matthew   375: 
                    376: Returns: 1 on success, 0 on failure to store.
                    377: 
                    378: =cut
                    379: 
                    380: ######################################################################
                    381: ######################################################################
1.2       matthew   382: {
                    383:     ##
                    384:     ##  WARNING: The following cleverness may cause trouble in cases where
                    385:     ##  the dbi connection is dropped and recreated - a stale statement
                    386:     ##  handler may linger around and cause trouble.
                    387:     ##
                    388:     ##  In most scripts, this will work fine.  If the dbi is going to be
                    389:     ##  dropped and (possibly) later recreated, call &clear_sth.  Yes it
1.14      raeburn   390:     ##  is annoying but $sth apparently does not have a link back to the 
1.2       matthew   391:     ##  $dbh, so we can't check our validity.
                    392:     ##
                    393:     my $sth = undef;
1.4       matthew   394:     my $sth_table = undef;
1.2       matthew   395: 
                    396: sub create_statement_handler {
1.14      raeburn   397:     my ($dbh,$tablename,$tabletype) = @_;
1.4       matthew   398:     $tablename = 'metadata' if (! defined($tablename));
1.14      raeburn   399:     $tabletype = 'metadata' if (! defined($tabletype));
                    400:     my ($table_columns,$table_indices) = 
                    401:           &describe_metadata_storage($tabletype);
1.4       matthew   402:     $sth_table = $tablename;
                    403:     my $request = 'INSERT INTO '.$tablename.' VALUES(';
1.14      raeburn   404:     foreach (@{$table_columns}) {
1.2       matthew   405:         $request .= '?,';
                    406:     }
                    407:     chop $request;
                    408:     $request.= ')';
                    409:     $sth = $dbh->prepare($request);
                    410:     return;
                    411: }
                    412: 
1.4       matthew   413: sub clear_sth { $sth=undef; $sth_table=undef;}
1.2       matthew   414: 
1.1       matthew   415: sub store_metadata {
1.14      raeburn   416:     my ($dbh,$tablename,$tabletype,@Metadata)=@_;
1.2       matthew   417:     my $errors = '';
1.4       matthew   418:     if (! defined($sth) || 
                    419:         ( defined($tablename) && ($sth_table ne $tablename)) || 
                    420:         (! defined($tablename) && $sth_table ne 'metadata')) {
1.14      raeburn   421:         &create_statement_handler($dbh,$tablename,$tabletype);
1.2       matthew   422:     }
                    423:     my $successcount = 0;
1.14      raeburn   424:     if (! defined($tabletype)) {
                    425:         $tabletype = 'metadata';
                    426:     }
                    427:     my ($table_columns,$table_indices) = 
                    428:                         &describe_metadata_storage($tabletype);
1.10      matthew   429:     foreach my $mdata (@Metadata) {
1.2       matthew   430:         next if (ref($mdata) ne "HASH");
                    431:         my @MData;
1.14      raeburn   432:         foreach my $field (@{$table_columns}) {
1.10      matthew   433:             my $fname = $field->{'name'};
                    434:             if (exists($mdata->{$fname}) && 
                    435:                 defined($mdata->{$fname}) &&
                    436:                 $mdata->{$fname} ne '') {
                    437:                 if ($mdata->{$fname} eq 'nan' ||
                    438:                     $mdata->{$fname} eq '') {
1.5       matthew   439:                     push(@MData,'NULL');
                    440:                 } else {
1.10      matthew   441:                     push(@MData,$mdata->{$fname});
1.5       matthew   442:                 }
1.2       matthew   443:             } else {
                    444:                 push(@MData,undef);
                    445:             }
                    446:         }
                    447:         $sth->execute(@MData);
                    448:         if (! $sth->err) {
                    449:             $successcount++;
                    450:         } else {
                    451:             $errors = join(',',$errors,$sth->errstr);
                    452:         }
1.10      matthew   453:         $errors =~ s/^,//;
1.2       matthew   454:     }
                    455:     if (wantarray()) {
                    456:         return ($successcount,$errors);
                    457:     } else {
                    458:         return $successcount;
                    459:     }
                    460: }
1.1       matthew   461: 
                    462: }
                    463: 
                    464: ######################################################################
                    465: ######################################################################
                    466: 
                    467: =pod
                    468: 
                    469: =item lookup_metadata()
                    470: 
                    471: Inputs: database handle ($dbh) and a hash or hash reference containing 
                    472: metadata which will be used for a search.
                    473: 
1.2       matthew   474: Returns: scalar with error string on failure, array reference on success.
                    475: The array reference is the same one returned by $sth->fetchall_arrayref().
1.1       matthew   476: 
                    477: =cut
                    478: 
                    479: ######################################################################
                    480: ######################################################################
1.2       matthew   481: sub lookup_metadata {
1.10      matthew   482:     my ($dbh,$condition,$fetchparameter,$tablename) = @_;
                    483:     $tablename = 'metadata' if (! defined($tablename));
1.2       matthew   484:     my $error;
                    485:     my $returnvalue=[];
1.10      matthew   486:     my $request = 'SELECT * FROM '.$tablename;
1.2       matthew   487:     if (defined($condition)) {
                    488:         $request .= ' WHERE '.$condition;
                    489:     }
                    490:     my $sth = $dbh->prepare($request);
                    491:     if ($sth->err) {
                    492:         $error = $sth->errstr;
                    493:     }
                    494:     if (! $error) {
                    495:         $sth->execute();
                    496:         if ($sth->err) {
                    497:             $error = $sth->errstr;
                    498:         } else {
                    499:             $returnvalue = $sth->fetchall_arrayref($fetchparameter);
                    500:             if ($sth->err) {
                    501:                 $error = $sth->errstr;
                    502:             }
                    503:         }
1.16      raeburn   504:     } 
1.2       matthew   505:     return ($error,$returnvalue);
                    506: }
1.1       matthew   507: 
                    508: ######################################################################
                    509: ######################################################################
                    510: 
                    511: =pod
                    512: 
                    513: =item delete_metadata()
                    514: 
1.10      matthew   515: Removes a single metadata record, based on its url.
                    516: 
                    517: Inputs: $dbh, the database handler.
                    518: $tablename, the name of the metadata table to remove from. default: 'metadata'
                    519: $url, the url of the resource to remove from the metadata database.
                    520: 
                    521: Returns: undef on success, dbh errorstr on failure.
                    522: 
                    523: =cut
                    524: 
                    525: ######################################################################
                    526: ######################################################################
                    527: sub delete_metadata {
                    528:     my ($dbh,$tablename,$url) = @_;
                    529:     $tablename = 'metadata' if (! defined($tablename));
                    530:     my $error;
                    531:     my $delete_command = 'DELETE FROM '.$tablename.' WHERE url='.
                    532:         $dbh->quote($url);
                    533:     $dbh->do($delete_command);
                    534:     if ($dbh->err) {
                    535:         $error = $dbh->errstr();
                    536:     }
                    537:     return $error;
                    538: }
                    539: 
                    540: ######################################################################
                    541: ######################################################################
                    542: 
                    543: =pod
                    544: 
                    545: =item update_metadata
                    546: 
                    547: Updates metadata record in mysql database.  It does not matter if the record
                    548: currently exists.  Fields not present in the new metadata will be taken
                    549: from the current record, if it exists.  To delete an entry for a key, set 
                    550: it to "" or undef.
                    551: 
                    552: Inputs: 
                    553: $dbh, database handle
                    554: $newmetadata, hash reference containing the new metadata
                    555: $tablename, metadata table name.  Defaults to 'metadata'.
1.14      raeburn   556: $tabletype, type of table (metadata, portfolio_metadata, portfolio_access)  
1.10      matthew   557: 
                    558: Returns:
                    559: $error on failure.  undef on success.
1.1       matthew   560: 
                    561: =cut
                    562: 
                    563: ######################################################################
                    564: ######################################################################
1.10      matthew   565: sub update_metadata {
1.14      raeburn   566:     my ($dbh,$tablename,$tabletype,$newmetadata)=@_;
1.10      matthew   567:     my $error;
                    568:     $tablename = 'metadata' if (! defined($tablename));
1.14      raeburn   569:     $tabletype = 'metadata' if (! defined($tabletype));
1.10      matthew   570:     if (! exists($newmetadata->{'url'})) {
                    571:         $error = 'Unable to update: no url specified';
                    572:     }
                    573:     return $error if (defined($error));
                    574:     # 
                    575:     # Retrieve current values
                    576:     my $row;
                    577:     ($error,$row) = &lookup_metadata($dbh,
                    578:                                    ' url='.$dbh->quote($newmetadata->{'url'}),
                    579:                                      undef,$tablename);
                    580:     return $error if ($error);
1.14      raeburn   581:     my %metadata = &LONCAPA::lonmetadata::metadata_col_to_hash($tabletype,@{$row->[0]});
1.10      matthew   582:     #
                    583:     # Update metadata values
                    584:     while (my ($key,$value) = each(%$newmetadata)) {
                    585:         $metadata{$key} = $value;
                    586:     }
                    587:     #
                    588:     # Delete old data (deleting a nonexistant record does not produce an error.
                    589:     $error = &delete_metadata($dbh,$tablename,$newmetadata->{'url'});
                    590:     return $error if (defined($error));
                    591:     #
                    592:     # Store updated metadata
                    593:     my $success;
1.14      raeburn   594:     ($success,$error) = &store_metadata($dbh,$tablename,$tabletype,\%metadata);
1.10      matthew   595:     return $error;
                    596: }
1.1       matthew   597: 
                    598: ######################################################################
                    599: ######################################################################
1.5       matthew   600: 
1.6       matthew   601: =pod
                    602: 
                    603: =item metdata_col_to_hash
                    604: 
                    605: Input: Array of metadata columns
                    606: 
                    607: Return: Hash with the metadata columns as keys and the array elements
                    608: passed in as values
                    609: 
                    610: =cut
                    611: 
                    612: ######################################################################
                    613: ######################################################################
                    614: sub metadata_col_to_hash {
1.14      raeburn   615:     my ($tabletype,@cols)=@_;
1.6       matthew   616:     my %hash=();
1.14      raeburn   617:     my ($columns,$indices) = &describe_metadata_storage($tabletype);
                    618:     for (my $i=0; $i<@{$columns};$i++) {
                    619:         $hash{$columns->[$i]->{'name'}}=$cols[$i];
                    620: 	unless ($hash{$columns->[$i]->{'name'}}) {
                    621: 	    if ($columns->[$i]->{'type'} eq 'TEXT') {
                    622: 		$hash{$columns->[$i]->{'name'}}='';
                    623: 	    } elsif ($columns->[$i]->{'type'} eq 'DATETIME') {
                    624: 		$hash{$columns->[$i]->{'name'}}='0000-00-00 00:00:00';
1.13      www       625: 	    } else {
1.14      raeburn   626: 		$hash{$columns->[$i]->{'name'}}=0;
1.13      www       627: 	    }
                    628: 	}
1.6       matthew   629:     }
                    630:     return %hash;
                    631: }
1.5       matthew   632: 
                    633: ######################################################################
                    634: ######################################################################
                    635: 
                    636: =pod
                    637: 
1.8       matthew   638: =item nohist_resevaldata.db data structure
                    639: 
                    640: The nohist_resevaldata.db file has the following possible keys:
                    641: 
                    642:  Statistics Data (values are integers, perl times, or real numbers)
                    643:  ------------------------------------------
                    644:  $course___$resource___avetries
                    645:  $course___$resource___count
                    646:  $course___$resource___difficulty
                    647:  $course___$resource___stdno
                    648:  $course___$resource___timestamp
                    649: 
                    650:  Evaluation Data (values are on a 1 to 5 scale)
                    651:  ------------------------------------------
                    652:  $username@$dom___$resource___clear
                    653:  $username@$dom___$resource___comments
                    654:  $username@$dom___$resource___depth
                    655:  $username@$dom___$resource___technical
                    656:  $username@$dom___$resource___helpful
1.11      www       657:  $username@$dom___$resource___correct
1.8       matthew   658: 
                    659:  Course Context Data
                    660:  ------------------------------------------
                    661:  $course___$resource___course       course id
                    662:  $course___$resource___comefrom     resource preceeding this resource
                    663:  $course___$resource___goto         resource following this resource
                    664:  $course___$resource___usage        resource containing this resource
                    665: 
                    666:  New statistical data storage
                    667:  ------------------------------------------
                    668:  $course&$sec&$numstud___$resource___stats
                    669:     $sec is a string describing the sections: all, 1 2, 1 2 3,...
                    670:     Value is a '&' deliminated list of key=value pairs.
                    671:     Possible keys are (currently) disc,course,sections,difficulty, 
                    672:     stdno, timestamp
                    673: 
                    674: =cut
                    675: 
                    676: ######################################################################
                    677: ######################################################################
                    678: 
                    679: =pod
                    680: 
1.5       matthew   681: =item &process_reseval_data 
                    682: 
                    683: Process a nohist_resevaldata hash into a more complex data structure.
                    684: 
                    685: Input: Hash reference containing reseval data
                    686: 
                    687: Returns: Hash with the following structure:
                    688: 
                    689: $hash{$url}->{'statistics'}->{$courseid}->{'avetries'}   = $value
                    690: $hash{$url}->{'statistics'}->{$courseid}->{'count'}      = $value
                    691: $hash{$url}->{'statistics'}->{$courseid}->{'difficulty'} = $value
                    692: $hash{$url}->{'statistics'}->{$courseid}->{'stdno'}      = $value
                    693: $hash{$url}->{'statistics'}->{$courseid}->{'timestamp'}  = $value
                    694: 
                    695: $hash{$url}->{'evaluation'}->{$username}->{'clear'}     = $value
                    696: $hash{$url}->{'evaluation'}->{$username}->{'comments'}  = $value
                    697: $hash{$url}->{'evaluation'}->{$username}->{'depth'}     = $value
                    698: $hash{$url}->{'evaluation'}->{$username}->{'technical'} = $value
                    699: $hash{$url}->{'evaluation'}->{$username}->{'helpful'}   = $value
                    700: 
                    701: $hash{$url}->{'course'}    = \@Courses
                    702: $hash{$url}->{'comefrom'}  = \@Resources
                    703: $hash{$url}->{'goto'}      = \@Resources
                    704: $hash{$url}->{'usage'}     = \@Resources
                    705: 
                    706: $hash{$url}->{'stats'}->{$courseid\_$section}->{$key} = $value
                    707: 
                    708: =cut
                    709: 
                    710: ######################################################################
                    711: ######################################################################
                    712: sub process_reseval_data {
                    713:     my ($evaldata) = @_;
                    714:     my %DynamicData;
                    715:     #
                    716:     # Process every stored element
                    717:     while (my ($storedkey,$value) = each(%{$evaldata})) {
                    718:         my ($source,$file,$type) = split('___',$storedkey);
                    719:         $source = &unescape($source);
                    720:         $file = &unescape($file);
                    721:         $value = &unescape($value);
                    722:          "    got ".$file."\n        ".$type." ".$source."\n";
                    723:         if ($type =~ /^(avetries|count|difficulty|stdno|timestamp)$/) {
                    724:             #
                    725:             # Statistics: $source is course id
                    726:             $DynamicData{$file}->{'statistics'}->{$source}->{$type}=$value;
1.11      www       727:         } elsif ($type =~ /^(clear|comments|depth|technical|helpful|correct)$/){
1.5       matthew   728:             #
                    729:             # Evaluation $source is username, check if they evaluated it
                    730:             # more than once.  If so, pad the entry with a space.
                    731:             while(exists($DynamicData{$file}->{'evaluation'}->{$type}->{$source})) {
                    732:                 $source .= ' ';
                    733:             }
                    734:             $DynamicData{$file}->{'evaluation'}->{$type}->{$source}=$value;
                    735:         } elsif ($type =~ /^(course|comefrom|goto|usage)$/) {
                    736:             #
                    737:             # Context $source is course id or resource
                    738:             push(@{$DynamicData{$file}->{$type}},&unescape($source));
                    739:         } elsif ($type eq 'stats') {
                    740:             #
                    741:             # Statistics storage...
                    742:             # $source is $cid\_$sec\_$stdno
                    743:             # $value is stat1=value&stat2=value&stat3=value,....
                    744:             #
1.8       matthew   745:             my ($cid,$sec,$stdno)=split('&',$source);
                    746:             my $crssec = $cid.'&'.$sec;
1.5       matthew   747:             my @Data = split('&',$value);
                    748:             my %Statistics;
                    749:             while (my ($key,$value) = split('=',pop(@Data))) {
                    750:                 $Statistics{$key} = $value;
                    751:             }
1.8       matthew   752:             $sec =~ s:("$|^")::g;
                    753:             $Statistics{'sections'} = $sec;
1.5       matthew   754:             #
                    755:             # Only store the data if the number of students is greater
                    756:             # than the data already stored
                    757:             if (! exists($DynamicData{$file}->{'stats'}->{$crssec}) ||
                    758:                 $DynamicData{$file}->{'stats'}->{$crssec}->{'stdno'}<$stdno){
                    759:                 $DynamicData{$file}->{'stats'}->{$crssec}=\%Statistics;
                    760:             }
                    761:         }
                    762:     }
                    763:     return %DynamicData;
                    764: }
                    765: 
                    766: 
                    767: ######################################################################
                    768: ######################################################################
                    769: 
                    770: =pod
                    771: 
                    772: =item &process_dynamic_metadata
                    773: 
                    774: Inputs: $url: the url of the item to process
                    775: $DynamicData: hash reference for the results of &process_reseval_data
                    776: 
                    777: Returns: Hash containing the following keys:
                    778:     avetries, avetries_list, difficulty, difficulty_list, stdno, stdno_list,
                    779:     course, course_list, goto, goto_list, comefrom, comefrom_list,
                    780:     usage, clear, technical, correct, helpful, depth, comments
                    781: 
                    782:     Each of the return keys is associated with either a number or a string
                    783:     The *_list items are comma-seperated strings.  'comments' is a string
                    784:     containing generically marked-up comments.
                    785: 
                    786: =cut
                    787: 
                    788: ######################################################################
                    789: ######################################################################
                    790: sub process_dynamic_metadata {
                    791:     my ($url,$DynamicData) = @_;
                    792:     my %data;
                    793:     my $resdata = $DynamicData->{$url};
                    794:     #
1.8       matthew   795:     # Get the statistical data - Use a weighted average
                    796:     foreach my $type (qw/avetries difficulty disc/) {
                    797:         my $studentcount;
1.5       matthew   798:         my $sum;
                    799:         my @Values;
1.8       matthew   800:         my @Students;
1.5       matthew   801:         #
1.8       matthew   802:         # Old data
1.5       matthew   803:         foreach my $coursedata (values(%{$resdata->{'statistics'}}),
                    804:                                 values(%{$resdata->{'stats'}})) {
                    805:             if (ref($coursedata) eq 'HASH' && exists($coursedata->{$type})) {
1.8       matthew   806:                 $studentcount += $coursedata->{'stdno'};
                    807:                 $sum += ($coursedata->{$type}*$coursedata->{'stdno'});
1.5       matthew   808:                 push(@Values,$coursedata->{$type});
1.8       matthew   809:                 push(@Students,$coursedata->{'stdno'});
1.5       matthew   810:             }
                    811:         }
1.8       matthew   812:         if (exists($resdata->{'stats'})) {
                    813:             foreach my $identifier (sort(keys(%{$resdata->{'stats'}}))) {
                    814:                 my $coursedata = $resdata->{'stats'}->{$identifier};
                    815:                 $studentcount += $coursedata->{'stdno'};
                    816:                 $sum += $coursedata->{$type}*$coursedata->{'stdno'};
                    817:                 push(@Values,$coursedata->{$type});                
                    818:                 push(@Students,$coursedata->{'stdno'});
                    819:             }
                    820:         }
                    821:         #
                    822:         # New data
                    823:         if (defined($studentcount) && $studentcount>0) {
                    824:             $data{$type} = $sum/$studentcount;
1.5       matthew   825:             $data{$type.'_list'} = join(',',@Values);
                    826:         }
                    827:     }
                    828:     #
1.8       matthew   829:     # Find out the number of students who have completed the resource...
                    830:     my $stdno;
1.20    ! albertel  831:     my %course_counted;
1.8       matthew   832:     if (exists($resdata->{'stats'})) {
                    833:         #
                    834:         # For the number of students, take the maximum found for the class
                    835:         my $current_course;
                    836:         my $coursemax=0;
                    837:         foreach my $identifier (sort(keys(%{$resdata->{'stats'}}))) {
                    838:             my $coursedata = $resdata->{'stats'}->{$identifier};
                    839:             if (! defined($current_course)) {
                    840:                 $current_course = $coursedata->{'course'};
                    841:             }
                    842:             if ($current_course ne $coursedata->{'course'}) {
                    843:                 $stdno += $coursemax;
1.20    ! albertel  844: 		$course_counted{$coursedata->{'course'}}++;
1.8       matthew   845:                 $coursemax = 0;
                    846:                 $current_course = $coursedata->{'course'};                
                    847:             }
                    848:             if ($coursemax < $coursedata->{'stdno'}) {
                    849:                 $coursemax = $coursedata->{'stdno'};
                    850:             }
                    851:         }
                    852:         $stdno += $coursemax; # pick up the final course in the list
                    853:     }
1.20    ! albertel  854:     # check for old data that has not been run since the format was changed
        !           855:     foreach my $course (keys(%{$resdata->{'statistics'}})) {
        !           856: 	next if (exists($course_counted{$course}));
        !           857: 	my $coursedata = $resdata->{'statistics'}{$course};
        !           858:         if (ref($coursedata) eq 'HASH' && exists($coursedata->{'stdno'})) {
        !           859: 	    $stdno += $coursedata->{'stdno'};
        !           860:         }
        !           861:     }
1.8       matthew   862:     $data{'stdno'}=$stdno;
                    863:     #
1.5       matthew   864:     # Get the context data
                    865:     foreach my $type (qw/course goto comefrom/) {
                    866:         if (defined($resdata->{$type}) && 
                    867:             ref($resdata->{$type}) eq 'ARRAY') {
                    868:             $data{$type} = scalar(@{$resdata->{$type}});
                    869:             $data{$type.'_list'} = join(',',@{$resdata->{$type}});
                    870:         }
                    871:     }
                    872:     if (defined($resdata->{'usage'}) && 
                    873:         ref($resdata->{'usage'}) eq 'ARRAY') {
                    874:         $data{'sequsage'} = scalar(@{$resdata->{'usage'}});
                    875:         $data{'sequsage_list'} = join(',',@{$resdata->{'usage'}});
                    876:     }
                    877:     #
                    878:     # Get the evaluation data
                    879:     foreach my $type (qw/clear technical correct helpful depth/) {
                    880:         my $count;
                    881:         my $sum;
                    882:         foreach my $evaluator (keys(%{$resdata->{'evaluation'}->{$type}})){
                    883:             $sum += $resdata->{'evaluation'}->{$type}->{$evaluator};
                    884:             $count++;
                    885:         }
                    886:         if ($count > 0) {
                    887:             $data{$type}=$sum/$count;
                    888:         }
                    889:     }
                    890:     #
                    891:     # put together comments
                    892:     my $comments = '<div class="LCevalcomments">';
                    893:     foreach my $evaluator (keys(%{$resdata->{'evaluation'}->{'comments'}})){
1.7       matthew   894:         $comments .= 
                    895:             '<p>'.
                    896:             '<b>'.$evaluator.'</b>:'.
                    897:             $resdata->{'evaluation'}->{'comments'}->{$evaluator}.
                    898:             '</p>';
1.5       matthew   899:     }
                    900:     $comments .= '</div>';
1.7       matthew   901:     $data{'comments'} = $comments;
1.5       matthew   902:     #
1.8       matthew   903:     if (exists($resdata->{'stats'})) {
                    904:         $data{'stats'} = $resdata->{'stats'};
                    905:     }
1.12      matthew   906:     if (exists($DynamicData->{'domain'})) {
                    907:         $data{'domain'} = $DynamicData->{'domain'};
                    908:     }
1.8       matthew   909:     #
1.5       matthew   910:     return %data;
                    911: }
                    912: 
1.8       matthew   913: sub dynamic_metadata_storage {
                    914:     my ($data) = @_;
                    915:     my %Store;
                    916:     my $courseid = $data->{'course'};
                    917:     my $sections = $data->{'sections'};
                    918:     my $numstu = $data->{'num_students'};
                    919:     my $urlres = $data->{'urlres'};
                    920:     my $key = $courseid.'&'.$sections.'&'.$numstu.'___'.$urlres.'___stats';
                    921:     $Store{$key} =
                    922:         'course='.$courseid.'&'.
                    923:         'sections='.$sections.'&'.
                    924:         'timestamp='.time.'&'.
                    925:         'stdno='.$data->{'num_students'}.'&'.
                    926:         'avetries='.$data->{'mean_tries'}.'&'.
                    927:         'difficulty='.$data->{'deg_of_diff'};
                    928:     if (exists($data->{'deg_of_disc'})) {
                    929:         $Store{$key} .= '&'.'disc='.$data->{'deg_of_disc'};
                    930:     }
                    931:     return %Store;
                    932: }
1.6       matthew   933: 
1.16      raeburn   934: ###############################################################
                    935: ###############################################################
                    936: ###                                                         ###
                    937: ###  &portfolio_metadata($filepath,$dom,$uname,$group)      ###
                    938: ###   Retrieve metadata for the given file                  ###
                    939: ###   Returns array -                                       ###
                    940: ###      contains reference to metadatahash and             ###
                    941: ###         optional reference to addedfields hash          ###
                    942: ###                                                         ###
                    943: ###############################################################
                    944: ###############################################################
                    945: 
                    946: sub portfolio_metadata {
                    947:     my ($fullpath,$dom,$uname,$group)=@_;
                    948:     my ($mime) = ( $fullpath=~/\.(\w+)$/ );
                    949:     my %metacache=();
                    950:     if ($fullpath !~ /\.meta$/) {
                    951:         $fullpath .= '.meta';
                    952:     }
                    953:     my (@standard_fields,%addedfields);
                    954:     my $colsref = $Portfolio_metadata_table_description;
                    955:     if (ref($colsref) eq 'ARRAY') {
                    956:         my @columns = @{$colsref};
                    957:         foreach my $coldata (@columns) {
                    958:             push(@standard_fields,$coldata->{'name'});
                    959:         }
                    960:     }
                    961:     my $metastring=&getfile($fullpath);
                    962:     if (! defined($metastring)) {
                    963:         $metacache{'keys'}= 'owner,domain,mime';
                    964:         $metacache{'owner'} = $uname.':'.$dom;
                    965:         $metacache{'domain'} = $dom;
                    966:         $metacache{'mime'} = $mime;
                    967:         if ($group ne '') {
                    968:             $metacache{'keys'} .= ',courserestricted';
                    969:             $metacache{'courserestricted'} = 'course.'.$dom.'_'.$uname;
                    970:         }
                    971:     } else {
                    972:         my $parser=HTML::TokeParser->new(\$metastring);
                    973:         my $token;
                    974:         while ($token=$parser->get_token) {
                    975:             if ($token->[0] eq 'S') {
                    976:                 my $entry=$token->[1];
                    977:                 if ($metacache{'keys'}) {
                    978:                     $metacache{'keys'}.=','.$entry;
                    979:                 } else {
                    980:                     $metacache{'keys'}=$entry;
                    981:                 }
                    982:                 my $value = $parser->get_text('/'.$entry);
                    983:                 if (!grep(/^\Q$entry\E$/,@standard_fields)) {
                    984:                     my $clean_value = lc($value);
                    985:                     $clean_value =~ s/\s/_/g;
                    986:                     if ($clean_value ne $entry) {
                    987:                         if (defined($addedfields{$entry})) {
                    988:                             $addedfields{$entry} .=','.$value;
                    989:                         } else {
                    990:                             $addedfields{$entry} = $value;
                    991:                         }
                    992:                     }
                    993:                 } else {
                    994:                     $metacache{$entry} = $value;
                    995:                 }
                    996:             }
                    997:         } # End of ($token->[0] eq 'S')
                    998:     }
                    999:     return (\%metacache,$metacache{'courserestricted'},\%addedfields);
                   1000: }
                   1001: 
                   1002: sub process_portfolio_access_data {
                   1003:     my ($dbh,$simulate,$newnames,$url,$fullpath,$access_hash,$caller) = @_;
                   1004:     my %loghash;
                   1005:     if ($caller eq 'update') {
                   1006:         # Delete old data (no error if deleting non-existent record).
                   1007:         my $error=&delete_metadata($dbh,$newnames->{'access'},$url);
                   1008:         if (defined($error)) {
                   1009:             $loghash{'access'}{'err'} = "MySQL Error Delete: ".$error;
                   1010:             return %loghash;
                   1011:         }
                   1012:     }
                   1013:     # Check the file exists
                   1014:     if (-e $fullpath) {
                   1015:         foreach my $key (keys(%{$access_hash})) {
                   1016:             my $acc_data;
                   1017:             $acc_data->{url} = $url;
                   1018:             $acc_data->{keynum} = $key;
                   1019:             my ($num,$scope,$end,$start) =
                   1020:                             ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   1021:             next if (($scope ne 'public') && ($scope ne 'guest'));
                   1022:             $acc_data->{scope} = $scope;
                   1023:             if ($end != 0) {
                   1024:                 $acc_data->{end} = &sqltime($end);
                   1025:             }
                   1026:             $acc_data->{start} = &sqltime($start);
                   1027:             if (! $simulate) {
                   1028:                 my ($count,$err) =
                   1029:                      &store_metadata($dbh,$newnames->{'access'},
                   1030:                                      'portfolio_access',$acc_data);
                   1031:                 if ($err) {
                   1032:                     $loghash{$key}{'err'} = "MySQL Error Insert: ".$err;
                   1033:                 }
                   1034:                 if ($count < 1) {
                   1035:                     $loghash{$key}{'count'} = 
                   1036:                         "Unable to insert record into MySQL database for $url";
                   1037:                 }
                   1038:             }
                   1039:         }
                   1040:     }
                   1041:     return %loghash;
                   1042: }
                   1043: 
                   1044: sub process_portfolio_metadata {
                   1045:     my ($dbh,$simulate,$newnames,$url,$fullpath,$is_course,$dom,$uname,$group,$caller) = @_;
                   1046:     my %loghash;
                   1047:     if ($caller eq 'update') {
                   1048:         # Delete old data (no error if deleting non-existent record).
                   1049:         my $error=&delete_metadata($dbh,$newnames->{'portfolio'},$url);
                   1050:         if (defined($error)) {
                   1051:             $loghash{'metadata'}{'err'} = "MySQL Error delete metadata: ".
                   1052:                                                $error;
                   1053:             return %loghash;
                   1054:         }
                   1055:         $error=&delete_metadata($dbh,$newnames->{'addedfields'},$url);
                   1056:         if (defined($error)) {
                   1057:             $loghash{'addedfields'}{'err'}="MySQL Error delete addedfields: ".$error;
                   1058:         }
                   1059:     }
                   1060:     # Check the file exists.
                   1061:     if (-e $fullpath) {
                   1062:         my ($ref,$crs,$addedfields) = &portfolio_metadata($fullpath,$dom,$uname,
                   1063:                                                           $group);
                   1064:         &getfiledates($ref,$fullpath);
                   1065:         if ($is_course) {
                   1066:             $ref->{'groupname'} = $group;
                   1067:         }
                   1068:         my %Data;
                   1069:         if (ref($ref) eq 'HASH') {
                   1070:             %Data = %{$ref};
                   1071:         }
                   1072:         %Data = (
                   1073:                  %Data,
                   1074:                  'url'=>$url,
                   1075:                  'version'=>'current',
                   1076:         );
                   1077:         my %loghash;
                   1078:         if (! $simulate) {
                   1079:             my ($count,$err) =
                   1080:             &store_metadata($dbh,$newnames->{'portfolio'},'portfolio_metadata',
                   1081:                             \%Data);
                   1082:             if ($err) {
                   1083:                 $loghash{'metadata'."\0"}{'err'} = "MySQL Error Insert: ".$err;
                   1084:             }
                   1085:             if ($count < 1) {
                   1086:                 $loghash{'metadata'."\0"}{'count'} = "Unable to insert record into MySQL portfolio_metadata database table for $url";
                   1087:             }
                   1088:             if (ref($addedfields) eq 'HASH') {
                   1089:                 if (keys(%{$addedfields}) > 0) {
                   1090:                     foreach my $key (keys(%{$addedfields})) {
                   1091:                         my $added_data = {
                   1092:                                     'url'   => $url,
                   1093:                                     'field' => $key,
                   1094:                                     'value' => $addedfields->{$key},
                   1095:                                     'courserestricted' => $crs,
                   1096:                         };
                   1097:                         my ($count,$err) = 
                   1098:                             &store_metadata($dbh,$newnames->{'addedfields'},
                   1099:                                    'portfolio_addedfields',$added_data);
                   1100:                         if ($err) {
                   1101:                             $loghash{$key}{'err'} = 
                   1102:                                 "MySQL Error Insert: ".$err;
                   1103:                         }
                   1104:                         if ($count < 1) {
                   1105:                             $loghash{$key}{'count'} = "Unable to insert record into MySQL portfolio_addedfields database table for url = $url and field = $key";
                   1106:                         }
                   1107:                     }
                   1108:                 }
                   1109:             }
                   1110:         }
                   1111:     }
                   1112:     return %loghash;
                   1113: }
                   1114: 
1.5       matthew  1115: ######################################################################
                   1116: ######################################################################
1.14      raeburn  1117: 
1.16      raeburn  1118: sub getfile {
                   1119:     my $file = shift();
                   1120:     if (! -e $file ) { 
                   1121:         return undef; 
                   1122:     }
1.17      albertel 1123:     open(my $fh,"<$file");
1.16      raeburn  1124:     my $contents = '';
                   1125:     while (<$fh>) { 
                   1126:         $contents .= $_;
                   1127:     }
                   1128:     return $contents;
                   1129: }
                   1130: 
                   1131: ##
                   1132: ## &getfiledates()
                   1133: ## Converts creationdate and modifieddates to SQL format
                   1134: ## Applies stat() to file to retrieve dates if missing
                   1135: sub getfiledates {
                   1136:     my ($ref,$target) = @_;
                   1137:     if (! defined($ref->{'creationdate'}) ||
                   1138:         $ref->{'creationdate'} =~ /^\s*$/) {
                   1139:         $ref->{'creationdate'} = (stat($target))[9];
                   1140:     }
                   1141:     if (! defined($ref->{'lastrevisiondate'}) ||
                   1142:         $ref->{'lastrevisiondate'} =~ /^\s*$/) {
                   1143:         $ref->{'lastrevisiondate'} = (stat($target))[9];
                   1144:     }
                   1145:     $ref->{'creationdate'}     = &sqltime($ref->{'creationdate'});
                   1146:     $ref->{'lastrevisiondate'} = &sqltime($ref->{'lastrevisiondate'});
                   1147: }
                   1148:  
1.15      raeburn  1149: ##
                   1150: ## &sqltime($timestamp)
                   1151: ##
                   1152: ## Convert perl $timestamp to MySQL time.  MySQL expects YYYY-MM-DD HH:MM:SS
                   1153: ##
                   1154: sub sqltime {
                   1155:     my ($time) = @_;
                   1156:     my $mysqltime;
                   1157:     if ($time =~
                   1158:         /(\d+)-(\d+)-(\d+) # YYYY-MM-DD
                   1159:         \s                 # a space
                   1160:         (\d+):(\d+):(\d+)  # HH:MM::SS
                   1161:         /x ) {
                   1162:         # Some of the .meta files have the time in mysql
                   1163:         # format already, so just make sure they are 0 padded and
                   1164:         # pass them back.
                   1165:         $mysqltime = sprintf('%04d-%02d-%02d %02d:%02d:%02d',
                   1166:                              $1,$2,$3,$4,$5,$6);
                   1167:     } elsif ($time =~ /^\d+$/) {
                   1168:         my @TimeData = gmtime($time);
                   1169:         # Alter the month to be 1-12 instead of 0-11
                   1170:         $TimeData[4]++;
                   1171:         # Alter the year to be from 0 instead of from 1900
                   1172:         $TimeData[5]+=1900;
                   1173:         $mysqltime = sprintf('%04d-%02d-%02d %02d:%02d:%02d',
                   1174:                              @TimeData[5,4,3,2,1,0]);
                   1175:     } elsif (! defined($time) || $time == 0) {
                   1176:         $mysqltime = 0;
                   1177:     } else {
                   1178:         &log(0,"    sqltime:Unable to decode time ".$time);
                   1179:         $mysqltime = 0;
                   1180:     }
                   1181:     return $mysqltime;
                   1182: }
1.14      raeburn  1183: 
                   1184: ######################################################################
                   1185: ######################################################################
1.5       matthew  1186: ##
                   1187: ## The usual suspects, repeated here to reduce dependency hell
                   1188: ##
                   1189: ######################################################################
                   1190: ######################################################################
                   1191: sub unescape {
                   1192:     my $str=shift;
                   1193:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   1194:     return $str;
                   1195: }
                   1196: 
                   1197: sub escape {
                   1198:     my $str=shift;
                   1199:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
                   1200:     return $str;
                   1201: }
1.6       matthew  1202: 
1.1       matthew  1203: 1;
                   1204: 
                   1205: __END__;
                   1206: 
                   1207: =pod
                   1208: 
                   1209: =back
                   1210: 
                   1211: =cut

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>