DB.pm


NAME

Communiware::DB - Transaction interface module


SYNOPSIS

  identity($site,$user);
  create_item($dbh,-attr=>value,...);
  update_item($dbh,$item, -attr=>value,...);
  delete_item($dbh,$item,-option=>value,...);
  add_link($dbh,$item,$type,\@linked_items,\%order);


DESCRIPTION

This module is main and only interface which allows to change of Communiware database. It contains procedures to create updae and delete database objects (items and links.


FUNCTIONS

return_error([ $dbh ]) procedure

Writes into error.log an error message from $dbh->errstr (use $Communiware::dbh if parameter have not been specified). Assings to $Communiware::DB::errmsg a value of ``Internla error (SQL). '' concatenated with $dbh->errstr. Returns an undef so in is posible to call it in sucj way:

        $sth->execute() or return return_error($dbh);

set_errmsg(``FORMAT'', LIST) procedure

Assings to $Communiware::DB::errmsg & localized $Communiware::DB::errmsg_gt a value of given error message. Returns an undef so in is posible to call it in sucj way:

        do {some checks} or return set_errmsg("FORMAT", LIST);

create_item

        $new_item_id = create_item(
                $dbh,
                ITEM_ID => $item_id,
                TYPE_ID => $type_id,
                ...
        );

Standard interface to item creation. Arguments are DBI database handle and list of key-value pairs which gives values for attributes and links. Key is attribute or link name.

Attribute `TYPE_ID' (key `-type') must be specified. Attribute `SERVER' (key `-server') must either be specified or can be computed from environment such as current site. All other standard attributes may be omitted.

When the item is being created, links in which this item is passive member can be specified (like ``this item has an author A'', ``this item belongs to a rubric R'' etc.). If the item should have multiple links of given type, reference to an array of ITEM_IDs should be passed to create_item. ORDNUMs for that link can be passed as hash reference of the form {ITEM_ID=>ORDNUM,...}. Note that these are ORDNUMs from the peer's point of view.

This procedure performs access checks for user and server defined by previous call of identity(). Key `LIGHTWEIGHT' allows to skip access check.

Returns ID of the created item or undef if item creation failed. In this case some meaningful explanation can be stored in $Communiware::DB::errmsg variable.

preprocess_create_author

Internal proc processing operations specific for type AUTHOR returns undef if failed and 1 if success

process_user_password

        process_user_password($item_id, \%attrs)

Function accepts new password for user $item_id either unencrypted as value of $attrs{'PASSWD'} or encrypted as value of $attrs{'CRYPTED_PASSWD'} (or maybe it is not supplied with new password at all).

If user's status does not allow storing of unencrypted password, its password is sheduled for deletion from storage of unencrypted passwords.

If function is supplied with unencrypted password, it will be used and stored if allowed.

If function is supplied with encrypted password only, it will be used. If current unencrypted password (if any) is incompatible with the new encrypted password, current unencrypted password is sheduled for deletion.

In all cases, if password is specified, upon return $attrs{'PASSWD'} contains new encrypted password.

getcontentype

syntax

getcontenttype($dbh,type)

retrieves name of Content-Type for given item type

identity

This procedure should be called before any database alteration is attempted. It recieves two argunements - virtual server to modify and user who is performing modifications.

update_item

        update_item($dbh,$item_id[,$key=>$value,...]);

This procedure modifies existing item. Arguments are DBI database handle, item ID and a list of key-value pairs. Keys are generated from attribute or link names in the same way as for create_item() (see create_item). As for create_item(), you can update (create and delete) only those links that have (or will have) the item being updated as passive end.

Attribute `TYPE_ID' (key `TYPE_ID') must be specified. Attribute `item_id' cannot be specified (i.e. you cannot rename items).

Returns undef if failed or item ID if succeded. In the latter case error message is stored in $Communiware::DB::errmsg variable.

check_server_status

        check_server_status(\%attrs)

If we process server item with empty url prefix and its status is 'NORMAL' or is not defined, sets 'OWNS_ROOT' as status value.

make_update

Recieves DBI database handle, hash of attributes, item_id and table name (where table is ITEM or one of EXTENDED_ATTR_TABLEs. Constructs update query which updates only fields which present in the hash and executes it. Not exported. Must be called within transaction

AddLink

Internal procedure which adds links to item See the add_link manpage. AddLink must be called within transaction, while the add_link manpage creates its own transaction. AddLink is not exported

add_link

Arguments DBI database handle, item_id, link type, reference to list of active items, hash reference to hash of order numbers. Type name should be specified as it stored in database, i.e. in capital etters LINKTYPE rather than -linktype as passed to create_item and update_item.

ReLink

recieves same arguments as the add_link manpage and sets links of given item to exactly this set of items, removing all links of given type which do not present in list and adding missing ones. Not exported. Should be called within transaction.

    if (@e) {
        $sth = $dbh->prepare(<<EOS);
update item_link
   set ordnum = ?, link_date = tdate(?), link_params = ?
 where active = ?
   and passive = ?
   and linktype_id = ?
EOS
        for my $i (@e) {
            set_errmsg("Cannot update link of type '%s' from '%s' to '%s'", $type, $i, $id);
            # special pricessing ORDNUM & LINK_DATE must be in correct data format of undef
            $order->{$i} = undef if defined($order->{$i}) && !length($order->{$i});
            $date->{$i} = undef if defined($date->{$i}) && !length($date->{$i});
            $sth->execute($order->{$i}, $date->{$i}, $params->{$i}, $i, $id, $type);
        }
    }
    $sth = $dbh->prepare('insert into item_link values (?, ?, ?, ?, tdate(?), ?)');
    for my $i (keys %h) {
        if ($i) {
            set_errmsg("Adding link of type %s between %s and %s", $type, $i, $id);
            # special pricessing ORDNUM & LINK_DATE must be in correct data format of undef
            $order->{$i} = undef if defined($order->{$i}) && !length($order->{$i});
            $date->{$i} = undef if defined($date->{$i}) && !length($date->{$i});
            check_linkable($i, $type, 'ACTIVE');
            check_order($i, $type, $order->{$i}) if $order->{$i};
            $sth->execute($i, $id, $type, $order->{$i}, $date->{$i}, $params->{$i});
            $sth->execute($id, $i, $type, $order->{$i}, $date->{$i}, $params->{$i}) if $bidir;
        }
    }
    set_errmsg();
}

re_link

Exported wrapper around ReLink.

check_order

checkorder $item,$linktype,$ordnum

Checks whether there is link with given ordnum among links of given type from given item, and, if so, increments all ordnums above given by one.

ReLinkFor

Same as ReLink except that changes links where given item is active

AddFilterLinks

Sets list of filters which are used by given template to given list Syntax AddFilterLinks($dbh,$template_id,$listref); Should be called within transaction

cache_fields

Recieves DBI database handle. Retrieves attribute names and linktype names and caches them in package variables

check_fields_length

Argument of the function - reference to the same attribute-value hash as in create_item. Function checks if all the given attributes fit into them size.

get_item_info

Recieves dbi handle item id and hash ref and extacts some attributes from database and places them into hash. These are attributes, required to correct preprocessing

get_field_length

Returns length of field in DB. Argument of the function - reference to the same attribute-value

delete_item

        delete_item($dbh,$item_id[,$flag,$extended_action,$ea_arg]);

Removes item from Communiware database. Arguments are DBI database handle and item ID.

If LIGHTWEIGHT flag is specified access check is skipped.

Returns true value on success. Returns false or throws an exception on failure.

Possible values for $extended_action are

MOVE_UNDER
$ea_arg specifies item which should be ``parent'' for descendants of deleting item

CASCADE_DELETE
$ea_arg specifies linktype. All items - descendants of deleting item from item_rel on specified liktype are deleted

check_moderator

Arguments DBI database handle and item_id. Checks if user, set by the identity manpage have right to moderate given item

check_related_user

Arguments: DBI database handle, item_id - checks if user, specified by identity is linked to given item by any type of link (i.e. is an AUTHOR, PUBLISHER, or TASK item is ASSIGNED to him

fixdates

Convert dates entered without time to standard communiware format YYYY.MM.DD HH:SS Recieves date string and returns date string.

check_item_existence

Returns true if item with given item_id exists.

check_user_existence

Returns status of user with given item_id or undef if user doesn't exists.

check_user_existence

Returns true if link with given attributes exists.

cmpstatus

Compares values of two given user statuses. Returns same as <=> operator

create_server

Creates new virtual site. Parameter - list of key-value pairs. Keys:

NAME
Mandatory. name for new virtual server

TITLE
Title for top item of new virtual server. Optional, but default is quite silly.

TOPURL
Optional, defaults to /name - url prefix for this serber

VHOST
Optional - hostname of virtual server. If not specified, Communiware would not perform virtual server configuration for this site at start time

AUTHORIZE
Optional, defaults to 0. Authorization level of this server.

MODERATOR
Mandatory. User id of moderator.

TEMPLATE_ID
Optional, defaults to 'default'. Server, whose virtual pages and standard templates would be used for new site.

DEFAULT_USER_STATUS
Optional, defaults to 'NEWCOMER' - status to assign to users which would register on new server.

prepare_id

Defines value for id for item being created.


Syntax
  prepare_id proposed_id

If called with ID, returns ID, otherwise generates uniquie id from database sequience and returns it.

start_transaction

Used to implement nested transaction. Disables autocommit in DBI, sets RaiseError and pushes old value of autocommit into @Communiware::DB::TransactionStack

Should be called just before or at start of eval block which implements transaction.

end_transaction

Used to implement nested transaction. Pops out of @Communiware::DB::TransactionStack value of autocommit and if it still 0 throws back any error caught in preceding eval, or just returns success.

If transaction stack is empty, then commits successful transaction, or appends Communiware::DB::errmsg with caught error.

Returns true on success, undef on failure (if returns and not throws error for nesting end_transaction).

If called with true argument, returns its value if success;

in_transaction {

        if (in_transaction())

Returns true from inside transaction and false from outside.

translate_errmsg

 Syntax:

translate_errmsg($addinfo)

Function takes result of $dbh->error_info call and tries to translate native error messages from DB (like 'DBD::Pg::db do failed: ERROR: Cannot insert a duplicate key into unique index item_key') into localized and more understandable for users, such as 'Already exists item named mynewitem'. It may be called immediately before end_transaction.

As a result function changes $@ variable used to make $Communiware::DB::errmsg.

Does nothing unless $@ variable is set.

check_linkable

Syntax:

check_linkable(item,linktype,side)

Checks if current user can link current item with item in question. Side is 'ACTIVE' when item passed as 1st arg is active in link or 'PASSIVE' otherwise

Performs following check

  1. If current user is allowed to see this item

  2. If items belongs to same site and if not so, if item in question is exportable

process_keywords

This internal proc put keywords from attribute keywords of item into table keywords

receives action (create|update), item_id and separated list of keywords

log_history

        log_history($item_id,\%attrs,$action);

Writes event `action' and technical information from supplied attributes `%attrs' (hope these are relevant to `$item_id' :)) into change history (table edit_history) of item `$item_id'.

rename_item

        rename_item($dbh, $old_id, $new_id, $flag);
        rename_item(undef, $item_ctx, $new_id, $flag);


FILE CONTENT MANAGEMENT

Following functions deal with data which are not stored in the SQL database - illustrations and downloadable files.

These files are accessable via @PIC_PREFIX/@ITEM_ID/@PICTURE_NAME or @FILE_PREFIX/@ITEM_ID/<any_name><ext> URLs, but their actual location on the server's filesystem may vary.

store_pic

Syntax

        $handle = store_pic($item_id,$picname)

Receives item_id and illustration name and returns file handle, opened for writing, where to write this illustration.

get_picdir


lock_pic

Syntax:

  $path = lock_pic($item,$pic[,$need_old_copy])

Informs Communiware transaction system that calling code wants to modify picture bypassing Communiware picture API (for instance by calling external image processing utility, such as convert(1)).

$item is item picture belongs to, $pic is filename (without path) of picture to be modified, and $need_old_copy specifies whether old copy of the picture should be available for in-place editing.

One should call this function whenever he creates or modifies pictures using external software to be sure that modifications would be commited or rolled back correctly.

This function also ensures that picture storage area for this item would be created, if it doesn't already exist.

Returns full path to the picture in question, whenever it exists or not.

pic_name

Syntax

  $pathname = pic_name($item_id,$filename)

Returns full pathname for given illustration, or undef if no such illusration exists. If filename contains wildcards (such as logo.*) croaks if more than one file matches this wildcard


=cut

sub pic_name { my $item_id = shift; return undef unless defined $item_id; my $picname = shift; my $dirname = get_picdir($item_id); if ($picname =~ tr/*?[]/*?[]/) { my @piclist = _files_by_pattern($dirname, $picname); return undef unless @piclist; croak(``Multiple files match wildcard pattern $picname'') if @piclist > 1; return $piclist[0]; } else { $picname = ``$dirname/$picname''; return $picname if (-f $picname); return undef; } }

list_pics

Syntax:

   @pics = list_pics($item_id,[$pattern]);

Returns list of illustrations for given item which match given pattern. If pattern is not specified, it equals to '*' (return all pictures);

Only short names are returned.


=cut

sub list_pics { my ($item_id, $pattern) = @_; $pattern ||= ``*''; my $dirname = get_picdir($item_id); my @piclist = map {(split ``/'', $_)[-1]} _files_by_pattern($dirname, $pattern); return @piclist; }

sub list_datafile { my @list = list_pics(@_); return $list[0]; }

datafile_name

Syntax:

  $filename  = datafile_name($item_id)

Returns full pathname in the filesystem of the server for file which is a content of item with content-type Binary

del_pic

Syntax:

  del_pic($item_id, $picture)

Deletes specified picture file from specified item. Picture name may contain wildcards. If so, all the matching names would be removed.

del_pics

Syntax:

  del_pics($item_id)

Removes all pictures from specified item, and unlinks pictures directory

del_datafile

Syntax:

  del_datafile($item_id)

Removes datafile from specified item with content type binary


INTERNAL FILEHANDLING FUNCTION

make_picdir

Syntax

  make_picdir($item_id, [$tmp])

Creates directory where to store illustrations for given item, if neccessary and returns its name. Croacks if it is impossible.

If second parameter is true, creates temporary dir for specified item, used in file transactions.

_del_pic

 _del_pic(picture_dir,$pattern)

Removes picture files, but doesn't try to remove directory

_files_by_pattern

This is ``secure'' glob

16 октябрь 2007 13:44