
######
Layout
######


****
NAME
****


Kernel::Output::HTML::Layout - all generic html functions


***********
DESCRIPTION
***********


All generic html functions. E. g. to get options fields, template processing, ...


****************
PUBLIC INTERFACE
****************


new()
=====


create a new object. Do not use it directly, instead use:


.. code-block:: perl

     use Kernel::System::ObjectManager;
     local $Kernel::OM = Kernel::System::ObjectManager->new(
         'Kernel::Output::HTML::Layout' => {
             Lang    => 'de',
         },
     );
     my $LayoutObject = $Kernel::OM->Get('Kernel::Output::HTML::Layout');


From the web installer, a special Option \ ``InstallerOnly``\  is passed
to indicate that a database connection is not yet available.


.. code-block:: perl

     use Kernel::System::ObjectManager;
     local $Kernel::OM = Kernel::System::ObjectManager->new(
         'Kernel::Output::HTML::Layout' => {
             InstallerOnly => 1,
         },
     );
     my $LayoutObject = $Kernel::OM->Get('Kernel::Output::HTML::Layout');



Block()
=======


call a block and pass data to it (optional) to generate the block's output.


.. code-block:: perl

     $LayoutObject->Block(
         Name => 'Row',
         Data => {
             Time => ...,
         },
     );



JSONEncode()
============


Encode perl data structure to JSON string


.. code-block:: perl

     my $JSON = $LayoutObject->JSONEncode(
         Data        => $Data,
         NoQuotes    => 0|1, # optional: no double quotes at the start and the end of JSON string
     );



Redirect()
==========


return html for browser to redirect


.. code-block:: perl

     my $HTML = $LayoutObject->Redirect(
         OP => "Action=AdminUserGroup;Subaction=User;ID=$UserID",
     );
 
     my $HTML = $LayoutObject->Redirect(
         ExtURL => "http://some.example.com/",
     );


During login action, \ ``Login =``\  1> should be passed to Redirect(),
which indicates that if the browser has cookie support, it is OK
for the session cookie to be not yet set.


Notify()
========


create notify lines


.. code-block:: perl

     infos, the text will be translated
 
     my $Output = $LayoutObject->Notify(
         Priority => 'Warning',
         Info => 'Some Info Message',
     );
 
     data with link, the text will be translated
 
     my $Output = $LayoutObject->Notify(
         Priority  => 'Warning',
         Data      => 'Template content',
         Link      => 'http://example.com/',
         LinkClass => 'some_CSS_class',              # optional
     );
 
     errors, the text will be translated
 
     my $Output = $LayoutObject->Notify(
         Priority => 'Error',
         Info => 'Some Error Message',
     );
 
     errors from log backend, if no error exists, a '' will be returned
 
     my $Output = $LayoutObject->Notify(
         Priority => 'Error',
     );



NotifyNonUpdatedTickets()
=========================


Adds notification about tickets which are not updated.


.. code-block:: perl

     my $Output = $LayoutObject->NotifyNonUpdatedTickets();



Header()
========


generates the HTML for the page begin in the Agent interface.


.. code-block:: perl

     my $Output = $LayoutObject->Header(
         Type              => 'Small',                # (optional) '' (Default, full header) or 'Small' (blank header)
         ShowToolbarItems  => 0,                      # (optional) default 1 (0|1)
         ShowPrefLink      => 0,                      # (optional) default 1 (0|1)
         ShowLogoutButton  => 0,                      # (optional) default 1 (0|1)
 
         DisableIFrameOriginRestricted => 1,          # (optional, default 0) - suppress X-Frame-Options header.
     );



Ascii2Html()
============


convert ASCII to html string


.. code-block:: perl

     my $HTML = $LayoutObject->Ascii2Html(
         Text            => 'Some <> Test <font color="red">Test</font>',
         Max             => 20,       # max 20 chars flowed by [..]
         VMax            => 15,       # first 15 lines
         NewLine         => 0,        # move \r to \n
         HTMLResultMode  => 0,        # replace " " with C<&nbsp;>
         StripEmptyLines => 0,
         Type            => 'Normal', # JSText or Normal text
         LinkFeature     => 0,        # do some URL detections
     );


also string ref is possible


.. code-block:: perl

     my $HTMLStringRef = $LayoutObject->Ascii2Html(
         Text => \$String,
     );



LinkQuote()
===========


detect links in text


.. code-block:: perl

     my $HTMLWithLinks = $LayoutObject->LinkQuote(
         Text => $HTMLWithOutLinks,
     );


also string ref is possible


.. code-block:: perl

     my $HTMLWithLinksRef = $LayoutObject->LinkQuote(
         Text => \$HTMLWithOutLinksRef,
     );



HTMLLinkQuote()
===============


detect links in HTML code


.. code-block:: perl

     my $HTMLWithLinks = $LayoutObject->HTMLLinkQuote(
         String => $HTMLString,
     );


also string ref is possible


.. code-block:: perl

     my $HTMLWithLinksRef = $LayoutObject->HTMLLinkQuote(
         String => \$HTMLString,
     );



LinkEncode()
============


perform URL encoding on query string parameter names or values.


.. code-block:: perl

     my $ParamValueEncoded = $LayoutObject->LinkEncode($ParamValue);


Don't encode entire URLs, because this will make them invalid
(?, & and ; will be encoded as well). Only pass one parameter name
or value at a time.


BuildSelection()
================


build a HTML option element based on given data


.. code-block:: perl

     my $HTML = $LayoutObject->BuildSelection(
         Data            => $ArrayRef,        # use $HashRef, $ArrayRef or $ArrayHashRef (see below)
         Name            => 'TheName',        # name of element
         ID              => 'HTMLID',         # (optional) the HTML ID for this element, if not provided, the name will be used as ID as well
         Multiple        => 0,                # (optional) default 0 (0|1)
         Size            => 1,                # (optional) default 1 element size
         Class           => 'class',          # (optional) a css class, include 'Modernize' to activate InputFields
         Disabled        => 0,                # (optional) default 0 (0|1) disable the element
         AutoComplete    => 'off',            # (optional)
         OnChange        => 'javascript',     # (optional)
         OnClick         => 'javascript',     # (optional)
 
         SelectedID     => 1,                 # (optional) use integer or arrayref (unable to use with ArrayHashRef)
         SelectedID     => [1, 5, 3],         # (optional) use integer or arrayref (unable to use with ArrayHashRef)
         SelectedValue  => 'test',            # (optional) use string or arrayref (unable to use with ArrayHashRef)
         SelectedValue  => ['test', 'test1'], # (optional) use string or arrayref (unable to use with ArrayHashRef)
 
         Sort           => 'NumericValue',    # (optional) (AlphanumericValue|NumericValue|AlphanumericKey|NumericKey|TreeView|IndividualKey|IndividualValue) unable to use with ArrayHashRef
         SortIndividual => ['sec', 'min']     # (optional) only sort is set to IndividualKey or IndividualValue
         SortReverse    => 0,                 # (optional) reverse the list
 
         Translation    => 1,                 # (optional) default 1 (0|1) translate value
         PossibleNone   => 0,                 # (optional) default 0 (0|1) add a leading empty selection
         TreeView       => 0,                 # (optional) default 0 (0|1)
         DisabledBranch => 'Branch',          # (optional) disable all elements of this branch (use string or arrayref)
         Max            => 100,               # (optional) default 100 max size of the shown value
         HTMLQuote      => 0,                 # (optional) default 1 (0|1) disable html quote
         Title          => 'C<Tooltip> Text',    # (optional) string will be shown as c<Tooltip> on c<mouseover>
         OptionTitle    => 1,                 # (optional) default 0 (0|1) show title attribute (the option value) on every option element
 
         Filters => {                         # (optional) filter data, used by InputFields
             LastOwners => {                  # filter id
                 Name   => 'Last owners',     # name of the filter
                 Values => {                  # filtered data structure
                     Key1 => 'Value1',
                     Key2 => 'Value2',
                     Key3 => 'Value3',
                 },
                 Active => 1,                 # (optional) default 0 (0|1) make this filter immediately active
             },
             InvolvedAgents => {
                 Name   => 'Involved in this ticket',
                 Values => \%HashWithData,
             },
         },
         ExpandFilters  => 1,                 # (optional) default 0 (0|1) expand filters list by default
 
         ValidateDateAfter  => '2016-01-01',  # (optional) validate that date is after supplied value
         ValidateDateBefore => '2016-01-01',  # (optional) validate that date is before supplied value
     );
 
     my $HashRef = {
         Key1 => 'Value1',
         Key2 => 'Value2',
         Key3 => 'Value3',
     };
 
     my $ArrayRef = [
         'KeyValue1',
         'KeyValue2',
         'KeyValue3',
         'KeyValue4',
     ];
 
     my $ArrayHashRef = [
         {
             Key   => '1',
             Value => 'Value1',
         },
         {
             Key      => '2',
             Value    => 'Value1::Subvalue1',
             Selected => 1,
         },
         {
             Key   => '3',
             Value => 'Value1::Subvalue2',
         },
         {
             Key      => '4',
             Value    => 'Value2',
             Disabled => 1,
         }
     ];



Permission()
============


check if access to a frontend module exists


.. code-block:: perl

     my $Access = $LayoutObject->Permission(
         Action => 'AdminCustomerUser',
         Type   => 'rw', # ro|rw possible
     );



Attachment()
============


returns browser output to display/download a attachment


.. code-block:: perl

     $HTML = $LayoutObject->Attachment(
         Type             => 'inline',          # optional, default: attachment, possible: inline|attachment
         Filename         => 'FileName.png',    # optional
         AdditionalHeader => $AdditionalHeader, # optional
         ContentType      => 'image/png',
         Content          => $Content,
         Sandbox          => 1,                 # optional, default 0; use content security policy to prohibit external
                                                #   scripts, flash etc.
     );
 
     or for AJAX html snippets
 
     $HTML = $LayoutObject->Attachment(
         Type        => 'inline',        # optional, default: attachment, possible: inline|attachment
         Filename    => 'FileName.html', # optional
         ContentType => 'text/html',
         Charset     => 'utf-8',         # optional
         Content     => $Content,
         NoCache     => 1,               # optional
     );



PageNavBar()
============


generates a page navigation bar


.. code-block:: perl

     my %PageNavBar = $LayoutObject->PageNavBar(
         Limit       => 100,         # marks result of TotalHits red if Limit is gerater then AllHits
         WindowSize  => 15,          # max shown pages to click
         StartHit    => 1,           # start to show items
         PageShown   => 15,          # number of shown items a page
         AllHits     => 56,          # number of total hits
         Action      => 'AgentXXX',  # e. g. 'Action=' . $Self->{LayoutObject}->{Action}
         Link        => $Link,       # e. g. 'Subaction=View;'
         AJAXReplace => 'IDElement', # IDElement which should be replaced
         IDPrefix    => 'Tickets',   # Prefix for the id parameter
     );
 
     return values of hash
 
         TotalHits  # total hits
         Result     # shown items e. g. "1-5" or "16-30"
         SiteNavBar # html for page nav bar e. g. "1 2 3 4"
 
         ResultLong     # shown items e. g. "1-5 of 32" or "16-30 of 64"
         SiteNavBarLong # html for page nav bar e. g. "Page: 1 2 3 4"



BuildDateSelection()
====================


build the HTML code to represent a date selection based on the given data.
Depending on the SysConfig settings the controls to set the date could be multiple select or input fields


.. code-block:: perl

     my $HTML = $LayoutObject->BuildDateSelection(
         Prefix           => 'some prefix',        # optional, (needed to specify other parameters)
         <Prefix>Year     => 2015,                 # optional, defaults to current year, used to set the initial value
         <Prefix>Month    => 6,                    # optional, defaults to current month, used to set the initial value
         <Prefix>Day      => 9,                    # optional, defaults to current day, used to set the initial value
         <Prefix>Hour     => 12,                   # optional, defaults to current hour, used to set the initial value
         <Prefix>Minute   => 26,                   # optional, defaults to current minute, used to set the initial value
         <Prefix>Second   => 59,                   # optional, defaults to current second, used to set the initial value
         <Prefix>Optional => 1,                    # optional, default 0, when active a checkbox is included to specify
                                                   #   if the values should be saved or not
         <Prefix>Used     => 1,                    # optional, default 0, used to set the initial state of the checkbox
                                                   #   mentioned above
         <Prefix>Required => 1,                    # optional, default 0 (Deprecated)
         <prefix>Class    => 'some class',         # optional, specify an additional class to the HTML elements
         Area     => 'some area',                  # optional, default 'Agent' (Deprecated)
         DiffTime => 123,                          # optional, default 0, used to set the initial time influencing the
                                                   #   current time (in seconds)
         OverrideTimeZone => 1,                    # optional (1 or 0), when active the time is not translated to the user
                                                   #   time zone
         YearPeriodFuture => 3,                    # optional, used to define the number of years in future to be display
                                                   #   in the year select
         YearPeriodPast   => 2,                    # optional, used to define the number of years in past to be display
                                                   #   in the year select
         YearDiff         => 0,                    # optional. used to define the number of years to be displayed
                                                   #   in the year select (alternatively to YearPeriodFuture and YearPeriodPast)
         ValidateDateInFuture     => 1,            # optional (1 or 0), when active sets an special class to validate
                                                   #   that the date set in the controls to be in the future
         ValidateDateNotInFuture  => 1,            # optional (1 or 0), when active sets an special class to validate
                                                   #   that the date set in the controls not to be in the future
         ValidateDateAfterPrefix  => 'Start',      # optional (Prefix), when defined sets a special class to validate
                                                   #   that the date set in the controls comes after the date with Prefix
         ValidateDateAfterValue   => '2016-01-01', # optional (Date), when defined sets a special data parameter to validate
                                                   #   that the date set in the controls comes after the supplied date
         ValidateDateBeforePrefix => 'End',        # optional (Prefix), when defined sets a special class to validate
                                                   #   that the date set in the controls comes before the date with Prefix
         ValidateDateBeforeValue  => '2016-01-01', # optional (Date), when defined sets a special data parameter to validate
                                                   #   that the date set in the controls comes before the supplied date
         Calendar => 2,                            # optional, used to define the SysConfig calendar on which the Datepicker
                                                   #   will be based on to show the vacation days and the start week day
         Format   => 'DateInputFormat',            # optional, or 'DateInputFormatLong', used to define if only date or
                                                   #   date/time components should be shown (DateInputFormatLong shows date/time)
         Validate => 1,                            # optional (1 or 0), defines if the date selection should be validated on
                                                   #   client side with JS
         Disabled => 1,                            # optional (1 or 0), when active select and checkbox controls gets the
                                                   #   disabled attribute and input fields gets the read only attribute
     );



HumanReadableDataSize()
=======================


Produces human readable data size.


.. code-block:: perl

     my $SizeStr = $LayoutObject->HumanReadableDataSize(
         Size => 123,  # size in bytes
     );


Returns


.. code-block:: perl

     $SizeStr = '123 B';         # example with decimal point: 123.4 MB



Ascii2RichText()
================


converts text to rich text


.. code-block:: perl

     my $HTMLString = $LayoutObject->Ascii2RichText(
         String => $TextString,
     );



RichText2Ascii()
================


converts text to rich text


.. code-block:: perl

     my $TextString = $LayoutObject->RichText2Ascii(
         String => $HTMLString,
     );



RichTextDocumentComplete()
==========================


1) add html, body, ... tags to be a valid html document
2) replace links of inline content e. g. images to <img src="cid:xxxx" />


.. code-block:: perl

     $HTMLBody = $LayoutObject->RichTextDocumentComplete(
         String => $HTMLBody,
     );



_RichTextReplaceLinkOfInlineContent()
=====================================


replace links of inline content e. g. images


.. code-block:: perl

     $HTMLBodyStringRef = $LayoutObject->_RichTextReplaceLinkOfInlineContent(
         String => $HTMLBodyStringRef,
     );




RichTextDocumentServe()
=======================


Serve a rich text (HTML) document for local view inside of an C<iframe> in correct charset and with correct links for
inline documents.

By default, all inline/active content (such as C<script>, C<object>, C<applet> or C<embed> tags) will be stripped. If
there are external images, they will be stripped too, but a message will be shown allowing the user to reload the page
showing the external images.


.. code-block:: perl

     my %HTMLFile = $LayoutObject->RichTextDocumentServe(
         Data => {
             Content     => $HTMLBodyRef,
             ContentType => 'text/html; charset="iso-8859-1"',
         },
         URL               => 'AgentTicketAttachment;Subaction=HTMLView;TicketID=123;ArticleID=123;FileID=',
         Attachments       => \%AttachmentListOfInlineAttachments,
 
         LoadInlineContent => 0,     # Serve the document including all inline content. WARNING: This might be dangerous.
 
         LoadExternalImages => 0,    # Load external images? If this is 0, a message will be included if
                                     # external images were found and removed.
     );



RichTextDocumentCleanup()
=========================


please see L<Kernel::System::HTML::Layout::DocumentCleanup()>


_BuildSelectionOptionRefCreate()
================================


create the option hash


.. code-block:: perl

     my $OptionRef = $LayoutObject->_BuildSelectionOptionRefCreate(
         %Param,
     );
 
     my $OptionRef = {
         Sort         => 'numeric',
         PossibleNone => 0,
         Max          => 100,
     }



_BuildSelectionAttributeRefCreate()
===================================


create the attribute hash


.. code-block:: perl

     my $AttributeRef = $LayoutObject->_BuildSelectionAttributeRefCreate(
         %Param,
     );
 
     my $AttributeRef = {
         name     => 'TheName',
         multiple => undef,
         size     => 5,
     }



_BuildSelectionDataRefCreate()
==============================


create the data hash


.. code-block:: perl

     my $DataRef = $LayoutObject->_BuildSelectionDataRefCreate(
         Data => $ArrayRef,              # use $HashRef, $ArrayRef or $ArrayHashRef
         AttributeRef => $AttributeRef,
         OptionRef => $OptionRef,
     );
 
     my $DataRef  = [
         {
             Key => 11,
             Value => 'Text',
         },
         {
             Key => 'abc',
             Value => '&nbsp;&nbsp;Text',
             Selected => 1,
         },
     ];



_BuildSelectionOutput()
=======================


create the html string


.. code-block:: perl

     my $HTMLString = $LayoutObject->_BuildSelectionOutput(
         AttributeRef       => $AttributeRef,
         DataRef            => $DataRef,
         TreeView           => 0,              # optional, see BuildSelection()
         FiltersRef         => \@Filters,      # optional, see BuildSelection()
         FilterActive       => $FilterActive,  # optional, see BuildSelection()
         ExpandFilters      => 1,              # optional, see BuildSelection()
         ValidateDateAfter  => '2016-01-01',   # optional, see BuildSelection()
         ValidateDateBefore => '2016-01-01',   # optional, see BuildSelection()
     );
 
     my $AttributeRef = {
         name => 'TheName',
         multiple => undef,
         size => 5,
     }
 
     my $DataRef  = [
         {
             Key => 11,
             Value => 'Text',
             Disabled => 1,
         },
         {
             Key => 'abc',
             Value => '&nbsp;&nbsp;Text',
             Selected => 1,
         },
     ];



_RemoveScriptTags()
===================


This function will remove the surrounding <script> tags of a
piece of JavaScript code, if they are present, and return the result.


.. code-block:: perl

     my $CodeContent = $LayoutObject->_RemoveScriptTags(Code => $SomeCode);



WrapPlainText()
===============


This sub has two main functionalities:
1. Check every line and make sure that "\n" is the ending of the line.
2. If the line does _not_ start with ">" (e.g. not cited text)
wrap it after the number of "MaxCharacters" (e.g. if MaxCharacters is "80" wrap after 80 characters).
Do this _just_ if the line, that should be wrapped, contains space characters at which the line can be wrapped.

If you need more info to understand what it does, take a look at the UnitTest WrapPlainText.t to see
use cases there.


.. code-block:: perl

     my $WrappedPlainText = $LayoutObject->WrapPlainText(
         PlainText     => "Some Plain text that is longer than the amount stored in MaxCharacters",
         MaxCharacters => 80,
     );



SetRichTextParameters()
=======================


set properties for rich text editor and send them to JS via AddJSData()


.. code-block:: perl

     $LayoutObject->SetRichTextParameters(
         Data => \%Param,
     );



CustomerSetRichTextParameters()
===============================


set properties for customer rich text editor and send them to JS via AddJSData()


.. code-block:: perl

     $LayoutObject->CustomerSetRichTextParameters(
         Data => \%Param,
     );



UserInitialsGet()
=================


Get initials from a full name of a user.


.. code-block:: perl

     my $UserInitials = $LayoutObject->UserInitialsGet(
         Fullname => 'John Doe',
     );


Returns string of exactly two uppercase characters that represent user initials:


.. code-block:: perl

     $UserInitials = 'JD';


Please note that this function will return 'O' if invalid name (without any word characters) was supplied.


_BuildLastViewsOutput()
=======================


Outputs links to the last views of the (customer) user in the avatar area, tool bar or menu bar.


.. code-block:: perl

     my $LastViewsHTML = $LayoutObject->_BuildLastViewsOutput(
         Interface => 'Agent',       # or Customer
         Position  => 'ToolBar',     # or MenuBar or Avatar, for customer interface only MenuBar is possible.
     );



_GetShortcutIconsForInterface()
===============================


Returns the paths to the shortcut icons of the given interface.


.. code-block:: perl

     my %ShortcutConfig = $LayoutObject->_GetShortcutIconsForInterface(
         Interface => 'Agent',    # or Customer
     );




