Context.pm


NAME

Communiware::Context::Object - basic Communiware object-oriented context interface


SYNOPSIS

    my $ctx = new Communiware::Context;
    $attr = $ctx->get('ATTR');
    $ctx->put('ATTR',$value);


DESCRIPTION

This module is abstract descendant for all types of Communiware context objects.It provides following methods


METHODS


new

  $ctx=Communiware::Context->new(attr=>{attr=>value ..},
                type=>{attr=>type},parent=>$parent);


BASIC METHODS

get

        $ctx->get('ATTRNAME')

Returns value of specified context attribute. First, searches for attribute in local context, and then in global one.

In list context may return multiple values, if requested attribute is list. In scalar context, joins all values with comma.

Doesn't handle context function specifications, group attributes and other complicated cases of substitutions.

get_local

        ($found, @value) = $ctx->get_local($attr_name);

Returns value of an attribute $attr_name but only if it exists in a local context (does not call for a global one). If it does exist, $found will be true, otherwise - false.

fetch_attr

        $ctx->fetch_attr($name)

Internal virtual method to fetch attributes which are not cached in the context yet. Need to be overriden in any context which can extract data from database or somewhere else.

attr_type_by_ontology

        $attr_type = $ctx->attr_type_by_ontology('ATTRNAME');

Returns type of any attribute known by ontology.

attr_type

        $typespec = $ctx->attr_type('ATTRNAME');
        ($type, $is_list) = $ctx->attr_type('ATTRNAME');

Returns type of attribute. In scalar context, returns string representation, like in Define DE - just type-name or LIST/TYPENAME. In array context returns two-element list which first element is element type name, and second is either undef or word 'LIST'.

attr_type_local

        ($type, $is_list) = $ctx->attr_type_local($attr_name);

Returns type of locally known attribute, or empty list if attribute is not known locally.

fetch_type

        $ctx->fetch_type($name)

Internal virtual method to fetch attribute types which are not cached in the context yet. Need to be overriden in any context which can extract data from database or somewhere else.

get_typed

        ($values, $type) = $ctx->get_typed($attr_name);

Returns both value and type of an attribute $attr_name in a single call. Both elements of a resulting list are anonymous arrays containing results of calls to get and attr_type respectively in a list context.

evaluate

        $value = $ctx->evaluate("_TXT(TYPE_ID)");
        ($value, $type) = $ctx->evaluate("_TXT(TYPE_ID)");

Evaluates attribute specification as it can be specified in template language.

Handles:

context modifiers
Can address parent contextes using #n as well as special contexts.

substitution modifiers
Can transform substitution values using _,^,&, % and *

context functions
aggregate functions
group attributes
second-level substitution
Does not allow second-level substitution in the function or group attribute arguments

eval_type

Returns type of the result of expression, which can be evaluated with evaluate.

param_list

Parses value of list attribute with elements of name=value form and returns linearized hash name => value.

Doesn't allow additional substitution in the values

aggregate

 $value = $ctx->aggregate($where,$what);
 ($value,$type) = $ctx->aggregate($where,$what);

returns value of aggregate function $what on the filter $where. $what looks like max(PUBLISHED) or count(ITEM_ID).

Filter cannot be SQL or perl filter for perfomance reasons.

Result of this function is cached in the context.

prepare_filter

        ($sth,$type_info) = $ctx->prepare_filter($filter,@attributes)
    $child_ctx=Communiware::Context->new($sth->fetcrow_hashref,$type_info,$ctx);

Returns object with Communiware::Filter interface (may be really DBI::st) which items, satisfying given filter can be fetched from.

@attributes list contains list of attributes which should be (if possible) extracted from database by this filter.

Elements of attribute list can be prepended by '+' or '-' sign, which means that these attributes should be used as sort criteria. (ascending or descending respectively)

is_in_filter {

        if ($ctx->is_in_filter($value,$filter[,$attrname])) {
          ...
        }

Checks whether given value is among results of given filter. If no attrname is specified, ITEM_ID is assumed.

put

        $ctx->put('ATTRNAME',$value)
        $ctx->put('ATTRNAME',@values)

Sets value of given attribute of this context. If multiple values are used for non-list attribute, exception will be raised.

append

        $ctx->append('ATTR',@values)

Appends values to the value of given attribute. Attribute should have list type. Otherwise exception will be raised.

set_type

        $ctx->set_type($attr,$type[,$is_list])
        $ctx->set_type('ATTR','TYPE','LIST')->put('ATTR',@values)

Sets type of given attribute to the given type. If third argument is true, attribute would be considered list, if it is false - scalar, if undefined, type will be considered undefined (i.e. may be defined as scalar or list later) and treated as scalar.

Returns reference to the context object, so one may set type and value of attribute within one expression.

If set_type wasn't called before setting value via put or append, then attribute type is determined via suffix notation, and attribute considered as list for put with multiple values and append with any number of values.

put_typed

        $ctx->put_typed($name, $type, $is_list, @value);

Combines set_type and put.

document

        $doc = $ctx->document([$new_doc])

Returns, and optionally sets document object associated with this context.

parent

  $parent_ctx= $ctx->parent();

Returns parent context object, or undef if current context has no parent.

list_checkboxes

  @checkboxes = $ctx->list_checkboxes

Returns list of names, previously marked by mark_checkbox;

set_special_context

        Communiware::Context->set_special_context($id,$ctx);

Associates context $ctx with special context id $id If you need some specific descendant of Communiware::Context in this role, call it as method of appropriate class.

Also propagates some attributes of given special context into magic attributes of global context.

If undef passed instead of context, special context $id would became undefined as well as propagated attributes in the global context.

Returns passed context if any, or old context if called with undefined second argument.

action

Return name of action which is performed with given context. For Template contexts action is always 'VIEW'.

For Posting contexts it is one of 'SAVE','DELETE','SKIP' or 'BACK'

dbh

Returns database handler.

logger

Returns global Logger object.

asterisk

  item_id = $ctx->asterisk($page, $site, $lang);
  item_id = $ctx->asterisk($page, $site);
  item_id = $ctx->asterisk($page, undef, $lang);
  item_id = $ctx->asterisk($page);

Checks whether given item specification is explicit ITEM_ID or virtual page spec and expands it in explicit item_id. If given specification if virtual page, then returns value of context function VIRTUAL.

See more VIRTUAL.

make_item_url

  $url = $ctx->make_item_url($item, $template, $anchor, $attrs);

Constructs an URL to given item presented by given template. Adds, if neccessary given (as hash reference) attributes and attributes which are prevoisly marked as exported via pass_params method.


pass_params


   $ctx->pass_params('PARAM','PARAM')
   @attrlist=$ctx->pass_params();
   
Marks given attributes as exported via html hyperlink or form submission.

List of attributes is stored in the form special context if it exists or in the document_item special context.

Special attribute GET_PARAMS can by used for pass all arguments from GET request.

To clear list of parameters to pass use DE::PassParams without arguments.

make_pic_url

        $url= $ctx->make_pic_url($item, $filename, $attrs);

Constructs URL for given picture in given item. If item is not defined, constructs URL to picture in the design library of current site.

make_file_url

        $url= $ctx->make_file_url($item, $filename, $attrs);

Constructs URL for given file in given item.

make_helper_url

        $url= $ctx->make_helper_url($item, $filename, $attrs);

Constructs URL for given file in given helper.

prefix

        $prefix= $ctx->prefix

Returns prefix for input element names, if any in this context.


CONTEXT FUNCTIONS IMPLEMENTATION

context_function

  $type = Communiware::Context->context_function($fragment,$name,@args)

Checks for existence and returns result type of context function at compile-time.

If function doesn't exist, calls compile_error method of passed Communiware::Template::Fragment object.

Also raises error if function recieves wrong number of arguments.

@args contain results of calling param in the list context on each of arguments of the function as array references.

If result type of function can be determined in compile time, function returns this type. Otherwise it returns undef.

Compile-time information is stored in the %Communiware::Context::FUNCTIONS hash. Keys of this hash are names of functions, and values are hash references, which can have following key

type
Type of function result. Can be either valid Communiware datatype name if this function always return same type or number, which indicates number of argument, which type propagates as function result type.

mark_arg
If this key exists, compile_function would mark name of argument, specified by this hash element, as name of attribute used in current template (if it is constant).

arg_min
Minimal number of arguments allowed for this function

arg_max
Maximal number of arguments allowed for this function

If you are adding new context function via your own module, you should ensure that it is used by Template::Fragment and adds value to the %Communiware::Context::Functions, and that function with appropriate name is defined as method of Communiware::Context object.

ACTIVE

        @ACTIVE(linktype,item_id)

returns true if current item has specified (meta)link with given one, and act as active in it (direct connection is required)

PASSIVE

        @PASSIVE(linktype,item_id)

returns true if current item has specified (meta)link with given one, and act as passive in it (direct connection is required)

ANCESTOR

        @ANCESTOR(linkname,item_id)

returns true is if current item is an ancestor of specified one by given linktype (i.e. has a path of any length to specified item and is an active end of this path)

DESCENDANT

        @DESCENDANT(linkname,item_id)

returns true is if current item is an descendant of specified one by given linktype (i.e. has a path of any length to specified item and is an passive end of this path)

TYPE_CAN_BE

        @TYPE_CAN_BE(side,linktype)

Returns true if type of current item can be on given side in given linktype.

LINK_PARAMS

        @LINK_PARAMS(linkname,active,passive)

Returns params for given link.

LINK_DATE

        @LINK_DATE(linkname,active,passive)

Returns date of link creation in standard Communiware format.

DOM_ID

  DOM_ID(item)
  DOM_ID(posting)

With 'item' argument some string which is derived from item_id and can be used as Javascript or XML identifier With 'posting' argument returns posting container identifier. See Communiware::Context::Posting and Communiware::Context::Form for more information.

ENV

 @ENV(HTTPD_HOST)

Returns value of specified environment variable of httpd process. This is compile-time macros rather than real function.

LEN

 @LEN(ATTRNAME)

Returns length of attribute value. If attribute is RICHTEXT, strips out markup and and counts any entity as one char.

MAXLEN

 @MAXLEN(ATTRNAME)

Returns maximum length of attribute value.

NAME

@NAME(ATTRIBUTE)

Returns i18n description of attribute or link type

RANDOM

  @{RANDOM(n)}

Returns integer random number greater or equal to zero and strictly less than given number.

RIGHTS

   RIGHTS(rightname)
   RIGHTS(rightname,user)
   RIGHTS(rightname,user,item)
   RIGHTS(rightname,,item)

Checks given right of given (or current) user to given (or current) item.

If calling from perl to check current user's rights to specified item, use empty string instead of user name.

Rightname can be either (meta)link name or one of special keywords ACCESS (check if any authorizing metalink exists) or DELETE (check if item not special for given site or user have developer rights)

   
=cut

sub RIGHTS { my $ph = $Communiware::profiler->nested( 'execute', 'get_rights' ) if $Communiware::profiler; my $self = shift; my ( $right, $user, $item ) = @_; my $user_status = ``'';

    if ($user) {
        $user_status = $self->dbh->selectrow_cached( "get_status", $user );
    }
    elsif ( $self->special_context('user') ) {
        $user        = $self->special_context('user')->id;
        $user_status = $self->special_context('user')->get('STATUS');
    }
    return 9999 if $user_status && $user_status eq 'SUPERUSER';
    my $server;
    unless ($item) {
        $item   = $self->id;
        $server = $self->get('SERVER');
    }
    else {
        $item = $self->asterisk($item);
        ($server) = $self->dbh->selectrow_cached( 'checkserver', $item );
    }
    if ( $right eq 'ACCESS' ) {
        return ( !Communiware::Auth::need_read_auth( $item, $server )
              || Communiware::Auth::allow_read( $user, $item, $server ) );
    }
    elsif ( $right eq 'WRITES' ) {
        return ( Communiware::Auth::allow_write( $user, $item ) );
    }
    elsif ( $right eq 'DELETE' ) {
        return Communiware::Auth::allow_delete( $user, $item, $server );
    }
    return 0 unless $user;
    return check_path( $right, $user, $item );
}

TRANSLATE

        @TRANSLATE(message)

Outputs given message on the language of current document. Argument is assumed to be on the language of current template. This is compile-time macros, rather than real function.

See internal get_text_translation function of Communiware::Context::Item.

TXT

  @{TXT(ATTR_NAME}}
  @{TXT(VALUE:ATTR_NAME)}
  
Returns internationalized name of current value of given attribute. Attribute
should have enumerated type. In second form returns name of given value,
interpreted as value of given attribute.

TYPE

  @{TYPE(ATTR}}

Returns type of attribute

VALUE

  @VALUE(NAME)

Returns value of attribute, which is passed as argument. May be with substitution, This is not a real function, rather compile-time macros. which allows to double-derefernce attribute

DEFAULT_TEMPLATE

SYNOPSYS

        DEFAULT_TEMPLATE(ITEM_TYPE,PARENT_ID)

DESCRIPTION

Returns default template assigned for keyitem, nearest ascendant or ITEM_TYPE.

VIRTUAL

SYNOPSYS

        VIRTUAL(PAGE,SITE,LANG)
        VIRTUAL(PAGE,SITE)
        VIRTUAL(PAGE,,LANG)
        VIRTUAL(PAGE)

DESCRIPTION

Returns value of virtual page, which name is passed as argument. Finds virtual page on specified site, if ommited on current site. For virtual page *top, also valuable LANG parameter.

ALTERNATE_ITEM

SYNOPSYS

        ALTERNATE_ITEM(ITEM_ID,ALT_ITEM_ID,PICPATTERN);
        ALTERNATE_ITEM(ITEM_ID,ALT_ITEM_ID)

DESCRIPTION

If PICPATTERN argument exits find wich item contains file with this name and return it's id. If used in list context also returns name of file found.

If filename contains asterisk instead of extension, and there exists several files which satisfy this mask, newest one would be used.

If PICNAME argument is ommited returns id of first item which exists in database.

PIC_URL

SYNOPSYS

        PIC_URL(PICPATTERN,ITEM_ID,ALT_ITEM_ID);

DESCRIPTION

Find wich item contains file with PICPATTERN and return url of found picture.

LOGIN_TO_ID

        LOGIN_TO_ID(login,server)

Returns ITEM_ID of person from his/her login and server. Server parameter is optional.

ID_TO_LOGIN

 @ID_TO_LOGIN(item)

Returns LOGIN attribute of person by its ITEM_ID.

NEVER use this function as @{LOGIN_TO_ID(@AUTHOR_ID)}. @LOGIN#U does the same but much more effective.

Of course, @{LOGIN_TO_ID(@ITEM_ID)} is even more useless becouse equivalent to @LOGIN

LINK

@LINK(linktype)

Returns one of strings SIMPLE, HIERARCHY, META depends on linktype's kind or undef if linktype is not real linktype name.

CONTENT_TYPE

@CONTENT_TYPE(item_type) @CONTENT_TYPE()

Returns content type (Html, Template, None, Code...) of item_type. Without argument returns content_type of current item

PREFIX

 @{PREFIX(URL)}
 @{PREFIX(PIC)}

Returns one of predefined URL prefixes for current site. Parameter may be one of URL, PIC, FILE, SCRIPT or POST.

Value POST has special meaning - it returns prefix of current Post or Item container.

STATUS_VALUE

        @{STATUS_VALUE(value,item_type)}
        @{STATUS_VALUE(value)}
        @{STATUS_VALUE()}

Returns numeric value of a status 'value' for item type 'item_type' (status of a current item by default). If such an item type does not exist or does not have such a status, or current context is not an item context (to be exact, does not have a 'TYPE_ID' attribute), returns 0.

SELF_URL

        @{SELF_URL()}

Returns URL to current item/template. Reduces template if it is default for this item. Uses $Communiware::self_url if it is defined.

BACK_URL

        @{BACK_URL()}

Returns URL of previos page (referer).

REPLACE

        @{REPLACE(SOMESTR, PATTERN, REPLACEMENT, FLAGS)}


ARGUMENTS

SOMESTR
String or attribute name witch substitution flag '@'.

PATTERN
Search pattern - standart regual expression pattern see perlre, perlrequick, perretut for details.

REPLACEMENT
Standart for perl's regular expressions replacement expression perlre, perlrequick, prelretut for details.

FLAGS
Set of suffix flags for s/// operator. Allowed only i,m,g,s flags.

MATCH

        @{MATCH(SOMESTR, PATTERN, FLAGS)}


ARGUMENTS

SOMESTR, PATTERN and FLAGS are the same as for REPLACE function, except additional flag 'n'. When flag 'n' specified function will return count of pattern matches. This flag implies 'g'.

E.g:

        <:Define MATCHED @{MATCH('string with words', '\w+')}:>
        will return 'true', and
        <:Define MATCHED @{MATCH('string with words', '\w+','g')}:>
        will return LIST/STRING attr with 'sting', 'with', 'words'.
        And
        <:Define MATCHED @{MATCH('string with words', '\w+','n')}:>
        will return NUMBER 3.

SUBSTR

        @{SUBSTR(SOMESTR, OFFSET, LENGTH, REPLACEMENT)}

Extracts a substring out of SOMESTR and returns it. First character is at offset 0. If OFFSET is negative starts that far from the end of the string. If LENGTH is omitted, returns everything to the end of the string. If LENGTH is negative, leaves that many characters off the end of the string.

get_text_translation

  $ctx->get_text_translation($text,$lang)

Translates specified text from specified lang to the language of current document (LANG attribute of special context document_item).

to_html

  $ctx->to_html(attr,$format);
  $ctx->to_html(attr,{'DATE'=>$strftime_format,'STRING'=>$printf_format..})

Converts attribute to visualizable HTML representation. Allows to specify formats for all possible type simultaneously.

By default uses %s for string, %g for NUMBER, %c for DATE and 'p' for RICHTEXT.

If format is scalar, attempt to apply it to any type.

Takes into account ACCURACY for dates.

visualize_attr

        $formatted_text = $ctx->visualize_attr($attr_name, $format);

Calls to document to format attribute $attr_name for visualization according to format $format. Format specification is any acceptable by Communiware::Document::format.

format

        $ctx->format($value, $format);

Realizes `%' expression operator.


Unsorted ideas

get_global

Returns attribute from global context only. Needs companion method which returns corresponding type, even if local attribute with same name has different type.

origin

Returns origin of attribute - whether it is item attribute, or defined one, or come from user-filled form or cookie.


check_link

Syntax:

   check_link(link,active,passive);

Returns true if there exists link of given type (which may be metalink) between given items

check_path

Syntax

  check_path (link,active,passive)

Returns true if there exists path of given linktype, where link type can be either metalink, or non-hierarchy link (where direct link is only possible type of path) between given items

make_special_contexts

  Communiware::Context->make_special_contexts(site=>'default',
     document_item=>$item ...

Creates initial set of special contexts for request processing. Destroys all already existing special contexts if any.

Arguments site, template, user and document_item are interpreted as item identifiers for creation of corresponding special contexts.

All other arguments are passed to global context constructor.

If template argument is explicitely set to undef, and document_item argument present, creates template context for default template of this item.

anonymous_context

        Communiware::Context->anonymous_context

Creates special context for anonymous user. Might be called as package method or as instance method or as just subroutine. Arguments are ignored anyway.

clean_special_contexts

        Communiware::Context->clean_special_contexts();

Cleans all special contexts. For use before request handling.

assemble_prefix

        $prefix = assemble_prefix($type, $hostname, $urlprefix)
        ($prefix, $prefix_with_port) = assemble_prefix($type, $hostname, $urlprefix)

Assembles prefix of specified type ('URL', 'PIC', 'BINARY' etc.) from given hostname and urlprefix of site. In scalar context returns prefix for browser (forward operation), where standard port for current protocol is stripped. In list context returns both stripped and unstripped (if they are different) prefixes for use in ToInternal (backward operation).

This function does not use database and uses only %Communiware::config of global variables.

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