otrs developer book

95
OTRS 2.2 - Developer Manual

Upload: pavan-kumar

Post on 26-Nov-2014

152 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Otrs Developer Book

OTRS 2.2 - Developer Manual

Page 2: Otrs Developer Book

OTRS 2.2 - Developer ManualPlayground EditionCopyright © 2003-2007 OTRS AG

Christian Schöpplein, Richard Kammermeyer, Stefan Rother, Thomas Raith, Burchard Steinbild, Andre Mindermann, Christopher Kuhn, Martin

Edenhofer

This work is copyrighted by OTRS AG.

You may copy it in whole or in part as long as the copies retain this copyright statement.

UNIX is a registered trademark of X/Open Company Limited. Linux is a registered trademark of Linus Torvalds.

MS-DOS, Windows, Windows 95, Windows 98, Windows NT, Windows 2000, Windows XP and Windows 2003 are registered trademarks of

Microsoft Corporation. Other trademarks and registered trademarks are: SUSE and YaST of SUSE GmbH, Red Hat and Fedora are registered

trademarks of Red Hat, Inc. Mandrake is a registered trademark of MandrakeSoft, SA. Debian is a registered trademark of Software in the Public

Interest, Inc. MySQL and the MySQL Logo are registered trademarks of MySQL AB.

All trade names are used without the guarantee for their free use and are possibly registered trade marks.

OTRS AG essentially follows the notations of the manufacturers. Other products mentioned in this manual may be trademarks of the respective

manufacturer.

Page 3: Otrs Developer Book

Table of Contents1. Introduction............................................................................................................................................12. Coding Style Guide ................................................................................................................................2

2.1. Formatting ...................................................................................................................................22.2. Naming........................................................................................................................................22.3. Source Code Header and Charset................................................................................................22.4. Version Comments ......................................................................................................................32.5. Objects and their allocation.........................................................................................................32.6. Special comments .......................................................................................................................42.7. Restrictions for some functions...................................................................................................42.8. Using of the MainObject.............................................................................................................42.9. Perldoc ........................................................................................................................................52.10. Length of lines ..........................................................................................................................5

3. Architecture............................................................................................................................................63.1. Directories ...................................................................................................................................63.2. Files .............................................................................................................................................73.3. Core Modules ..............................................................................................................................73.4. Frontend Handle..........................................................................................................................83.5. Frontend Modules .......................................................................................................................83.6. CMD Frontend ............................................................................................................................83.7. Database ......................................................................................................................................8

4. Config Mechanism .................................................................................................................................94.1. Default Config.............................................................................................................................94.2. Custom Config ..........................................................................................................................104.3. Accessing Config Options.........................................................................................................104.4. XML Config Options ................................................................................................................10

4.4.1. Types of XML Config Variables...................................................................................114.4.2. String ............................................................................................................................114.4.3. Textarea ........................................................................................................................114.4.4. Options .........................................................................................................................124.4.5. Array.............................................................................................................................124.4.6. Hash..............................................................................................................................124.4.7. Hash with SubArray, SubOptions, SubHash ................................................................134.4.8. FrontendModuleReg (NavBar).....................................................................................134.4.9. FrontendModuleReg (NavBarModule) ........................................................................14

5. Database Mechanism...........................................................................................................................155.1. How it works .............................................................................................................................15

5.1.1. SQL...............................................................................................................................155.1.2. XML .............................................................................................................................16

5.2. Database Drivers .......................................................................................................................185.3. Supported Databases .................................................................................................................18

6. Log Mechanism....................................................................................................................................196.1. Use and Syntax..........................................................................................................................196.2. Example ....................................................................................................................................19

iii

Page 4: Otrs Developer Book

7. Module Format ....................................................................................................................................207.1. Auth Module .............................................................................................................................207.2. Notify Module...........................................................................................................................217.3. Navigation Module....................................................................................................................227.4. Frontend Modules .....................................................................................................................237.5. Core Modules ............................................................................................................................277.6. Customer Auth Module.............................................................................................................287.7. Customer User Module .............................................................................................................297.8. Customer Navigation Module ...................................................................................................307.9. Stats Module .............................................................................................................................31

7.9.1. Dynamic stats ...............................................................................................................317.9.2. Static stats .....................................................................................................................327.9.3. Using old static stats .....................................................................................................34

7.10. Ticket Modules........................................................................................................................347.10.1. Ticket Number Module...............................................................................................357.10.2. Ticket PostMaster Module..........................................................................................357.10.3. Ticket Menu Module ..................................................................................................387.10.4. Ticket Event Module ..................................................................................................417.10.5. More Modules ............................................................................................................43

8. Templates..............................................................................................................................................448.1. Formatting .................................................................................................................................44

8.1.1. Comment ......................................................................................................................448.1.2. $Data{""} .....................................................................................................................458.1.3. $QData{""}...................................................................................................................458.1.4. $LQData{""} ................................................................................................................458.1.5. $Env{""}.......................................................................................................................468.1.6. $QEnv{""}....................................................................................................................468.1.7. $Quote{""} ...................................................................................................................468.1.8. $Text{""} ......................................................................................................................478.1.9. $Config{""} ..................................................................................................................478.1.10. $Include{""} ...............................................................................................................478.1.11. Block...........................................................................................................................488.1.12. set................................................................................................................................498.1.13. if..................................................................................................................................498.1.14. system-call ..................................................................................................................50

8.2. Example ....................................................................................................................................50

9. Layout ...................................................................................................................................................529.1. CSS Style ..................................................................................................................................52

9.1.1. View..............................................................................................................................529.1.2. Edit/New/Search...........................................................................................................529.1.3. Overview/Search Result ...............................................................................................539.1.4. Delete............................................................................................................................54

9.2. Images .......................................................................................................................................559.3. Special CSS Definitions ............................................................................................................56

iv

Page 5: Otrs Developer Book

10. Language Translations ......................................................................................................................5710.1. How it works ...........................................................................................................................57

10.1.1. Default Framework Translation File...........................................................................5710.1.2. Frontend Translation File ...........................................................................................5810.1.3. Custom Translation File .............................................................................................59

10.2. Add a new default framework translation ...............................................................................60

11. Object Basics ......................................................................................................................................6111.1. Object Options ........................................................................................................................6111.2. Search Options ........................................................................................................................6111.3. Config Naming........................................................................................................................6111.4. Config File...............................................................................................................................6211.5. NavBar Settings ......................................................................................................................6311.6. Screen flow..............................................................................................................................65

12. Development Environment................................................................................................................6712.1. Framework checkout (CVS)....................................................................................................6712.2. Linking Expansion Modules ...................................................................................................6712.3. Necessary Actions after Linking.............................................................................................68

13. Writing an OTRS module for a new object.....................................................................................6913.1. What we want to write ............................................................................................................6913.2. Default Config File..................................................................................................................6913.3. Frontend Module.....................................................................................................................7013.4. Core Module ...........................................................................................................................7113.5. dtl Template File .....................................................................................................................7213.6. Language File..........................................................................................................................7313.7. Summary .................................................................................................................................73

14. Package Management........................................................................................................................7514.1. Package Distribution ...............................................................................................................75

14.1.1. Package Repository Index ..........................................................................................7514.2. Package Commands ................................................................................................................75

14.2.1. Install ..........................................................................................................................7614.2.2. Uninstall .....................................................................................................................7614.2.3. Upgrade ......................................................................................................................7614.2.4. List ..............................................................................................................................76

15. Package Building ...............................................................................................................................7815.1. Package Spec File ...................................................................................................................78

15.1.1. Name...........................................................................................................................7815.1.2. Version........................................................................................................................7815.1.3. Framework..................................................................................................................7815.1.4. Vendor.........................................................................................................................7815.1.5. URL ............................................................................................................................7915.1.6. License........................................................................................................................7915.1.7. ChangeLog .................................................................................................................7915.1.8. Description .................................................................................................................7915.1.9. BuildHost....................................................................................................................8015.1.10. BuildDate..................................................................................................................8015.1.11. PackageRequired ......................................................................................................80

v

Page 6: Otrs Developer Book

15.1.12. OS (^M)....................................................................................................................8015.1.13. Filelist .......................................................................................................................8015.1.14. DatabaseInstall .........................................................................................................8115.1.15. DatabaseUpgrade......................................................................................................8115.1.16. DatabaseReinstall .....................................................................................................8115.1.17. DatabaseUninstall.....................................................................................................8215.1.18. CodeInstall................................................................................................................8215.1.19. CodeUninstall ...........................................................................................................8215.1.20. CodeReinstall ...........................................................................................................8315.1.21. CodeUpgrade............................................................................................................8315.1.22. IntroInstall(Pre|Post).................................................................................................8315.1.23. IntroUninstall(Pre|Post) ............................................................................................8315.1.24. IntroReinstall(Pre|Post) ............................................................................................8415.1.25. IntroUpgrade(Pre|Post) .............................................................................................84

15.2. Example .sopm........................................................................................................................8415.3. Package Build..........................................................................................................................85

16. Unit Tests ............................................................................................................................................8616.1. Creating a test file ...................................................................................................................8616.2. Testing .....................................................................................................................................8616.3. True().......................................................................................................................................8716.4. False()......................................................................................................................................8716.5. Is() ...........................................................................................................................................88

A. Additional Ressources ........................................................................................................................89A.1. OTRS.org .................................................................................................................................89A.2. Online API Library ..................................................................................................................89A.3. Developer Mailing List ............................................................................................................89A.4. Commercial Support ................................................................................................................89

vi

Page 7: Otrs Developer Book

Chapter 1. Introduction

OTRS is a multi-platform web application framework which was originally developed for a trouble ticketsystem. It supports different web servers and databases.

This manual shows how to develop your own OTRS modules and applications based on the OTRSstyleguides.

1

Page 8: Otrs Developer Book

Chapter 2. Coding Style Guide

In order to preserve the consistent development of the OTRS project, we have set up a few guidelinesregarding style.

2.1. Formatting

TAB: We use 4 spaces. Examples for braces:

if ($Condition) {Foo();

}else {

Bar();}

while ($Condition == 1) {Foo();

}

2.2. Naming

Names and comments are written in English. Variables, Objects and Methods must be descriptive nounsor noun phrases with the first letter set upper case.

e. g. @TicktIDs or $Output or BuildQueueView()

2.3. Source Code Header and Charset

Attach the following header to each and every source file. Source files are saved in Charset ISO-8859-1.

# --

2

Page 9: Otrs Developer Book

Chapter 2. Coding Style Guide

# (file name) - a short description what it does# Copyright (C) (year) (name of author) (email of author)# --# $Id: codesyntax.xml,v 1.13 2007/07/02 14:30:53 tr Exp $# --# This software comes with ABSOLUTELY NO WARRANTY. For details, see# the enclosed file COPYING for license information (GPL). If you# did not receive this file, see http://www.gnu.org/licenses/gpl.txt.# --

The following line is updated by the CVS:

# $Id: codesyntax.xml,v 1.13 2007/07/02 14:30:53 tr Exp $

2.4. Version Comments

Some functions may not be available in the current framework version. Thus, sometimes settings have tobe changed when a new module and framework version will be released. If you use version comments,you can search for information (e.g. using grep) on what must be changed when a new version ispublished. The keyword for version comments is ’FRAMEWORK’ For perl use ’#’ and for xml use thexml comments.

e.g. for perl-code# FRAMEWORK-2.1: the function ID2UserName is first available in OTRS 2.1

2.5. Objects and their allocation

In OTRS many objects are available. But it is not allowed to use every object in each script. Please notethe following definitions

• don’t use the LayoutObject in core modules

• don’t use the ParamObject in core modules

3

Page 10: Otrs Developer Book

Chapter 2. Coding Style Guide

• don’t use the DBObject in frontend modules

2.6. Special comments

The only ways to create special comments are the following ways. Example 1 - especially for subactionsof frontend modules

# -----------------------------## here starts a special area# -----------------------------#

Example 2 - especially for customizing standard OTRS files

# --- customizing for bsi

2.7. Restrictions for some functions

Some functions are not useful in every script. Please pay attention to the following restrictions.

• don’t use "die" and "exit" in .pm-files

• don’t use the "Dumper" function in released files

• don’t use "print" in .pm files

• use OTRS specific function "SystemTime2Date" instead of "localtime"

2.8. Using of the MainObject

Information about the MainObject

4

Page 11: Otrs Developer Book

Chapter 2. Coding Style Guide

• initialize the MainObject in the basic .pl-file

• in .pm files only pass it to the next Object you initialize

• don’t use the Perl "require" function any more

2.9. Perldoc

Every function which could be used outside of its package must have a perldoc. It should look like thefollowing example.

=item SystemTime2TimeStamp()

returns a time stamp in "yyyy-mm-dd 23:59:59" format.

my $TimeStamp = $TimeObject->SystemTime2TimeStamp(SystemTime => $SystemTime,

);

If you need the short format "23:59:59" if the date is today (if needed).

my $TimeStamp = $TimeObject->SystemTime2TimeStamp(SystemTime => $SystemTime,Type => ’Short’,

);=cut

2.10. Length of lines

Please see that a line of code is not langer then 80 charactars.

5

Page 12: Otrs Developer Book

Chapter 3. Architecture

The OTRS framework is modular. The following picture shows the basic layer architecture of OTRS.

3.1. Directories

Directory Descriptionbin/ CMD programmes

bin/cgi-bin/ web handle

bin/fcgi-bin/ fast cgi web handle

Kernel modules

Kernel/Config/ config

Kernel/Config/Files config files

Kernel/Language language translation

Kernel/System/ core modules, e.g. Log, Ticket...

Kernel/Modules/ frontend modules, e.g. QueueView...

Kernel/Output/HTML/ html templates

6

Page 13: Otrs Developer Book

Chapter 3. Architecture

Directory Descriptionvar/ variable data

var/log logfiles

var/cron/ cron files

var/httpd/htdocs/ htdocs directory with index.html

var/httpd/htdocs/images/Standard/ icons and pictures

scripts/ misc

scripts/test/ test files

scripts/sample/ sample files

3.2. Files

.pl = Perl

.pm = Perl Modul

.dtl = Dynamic Template Language (html template file)

.dist = Default Templates of Files

3.3. Core Modules

Core modules are located under $OTRS_HOME/Kernel/System/*. This layer is for the logical work.Core modules are used to handle system routines like "lock ticket" and "create ticket". A few main coremodules are:

• Kernel::System::Config (to access config options)

• Kernel::System::Log (to log into OTRS log backend)

• Kernel::System::DB (to access the database backend)

• Kernel::System::Auth (to check a user authentication)

• Kernel::System::User (to manage users)

• Kernel::System::Group (to manage groups)

• Kernel::System::email (for sending emails)

7

Page 14: Otrs Developer Book

Chapter 3. Architecture

For more information, see: http://dev.otrs.org/

3.4. Frontend Handle

The interface between the browser, web server and the frontend modules. A frontend module can be usedvia the http-link.

http://localhost/otrs/index.pl?Action=Modul ()

3.5. Frontend Modules

Frontend modules are located under "$OTRS_HOE/Kernel/Modules/*.pm". There are two publicfunctions in there - "new()" and "run()" - which are accessed from the Frontend Handle (e.g. index.pl).

"new()" is used to create a frontend module object. The Frontend Handle provides the used frontendmodule with the basic framework objects. These are, for example: ParamObject (to get formular params),DBObject (to use existing databse connects), LayoutObject (to use templates and other html layoutfunctions), ConfigObject (to access config settings), LogObject (to use the framework log system),UserObject (to get the user functions from the current user), GroupObject (to get the group functions).

For more information on core modules see: http://dev.otrs.org/

3.6. CMD Frontend

The CMD (Command) Frontend is like the Web Frontend Handle and the Web Frontend Module in one(just without the LayoutObject) and uses the core modules for some actions in the system.

3.7. Database

The database interface supports different databases.

For tables on database relation see otrs-database.png: ftp://ftp.otrs.org/pub/otrs/misc/

8

Page 15: Otrs Developer Book

Chapter 4. Config Mechanism

4.1. Default Config

There are different default config files. The main one, which comes with the framework, is:

Kernel/Config/Defaults.pm

This file should be left untouched as it is automatically updated on framework updates. There is also asub directory where you can store the default config files of your own modules. These files are usedautomatically.

The directory is located under:

$OTRS_HOME/Kernel/Config/Defaults/Files/*.pm

And could look as follows:

Kernel/config/Files/Calendar.pm

# module reg and nav bar$Self->{’Frontend::Module’}->{’AgentCalendar’} = {

Description => ’Calendar’,NavBarName => ’Ticket’,NavBar => [

{Description => ’Calendar’,Name => ’Calendar’,Image => ’calendar.png’,Link => ’Action=AgentCalendar’,NavBar => ’Ticket’,Prio => 5000,AccessKey => ’c’,

},],

};

# show online customers$Self->{’Frontend::NotifyModule’}->{’80-ShowCalendarEvents’} = {

Module => ’Kernel::Output::HTML::NotificationCalendar’,};

9

Page 16: Otrs Developer Book

Chapter 4. Config Mechanism

4.2. Custom Config

If you want to change a config option, copy it to

Kernel/Config.pm

and set the new option. This file will be read out last and so all default config options are overwrittenwith your settings.

This way it is easy to handle updates - you just need the Kernel/Config.pm.

4.3. Accessing Config Options

You can read and write (for one request) the config options via the core module "Kernel::Config". Theconfig object is a base object and thus available in each Frontend Module.

If you want to access a config option:

my $ConfigOption = $Self->{ConfigObject}->Get(’Prefix::Option’);

If you want to change a config option at runtime and just for this one request/process:

$Self->{ConfigObject}->Set(Key => ’Prefix::Option’Value => ’SomeNewValue’,

);

10

Page 17: Otrs Developer Book

Chapter 4. Config Mechanism

4.4. XML Config Options

If you want to add a config option:

<ConfigItem Name="Ticket::Hook" Required="1" Valid="1"><Description Lang="en">The identifyer for a ticket. The default is Ticket#.</Description><Description Lang="de">Ticket-Identifikator. Als Standard wird Ticket# verwendet.</Description><Group>Ticket</Group><SubGroup>Core::Ticket</SubGroup><Setting>

<String Regex="">Ticket#</String></Setting>

</ConfigItem>

If "required" is set to "1", the config variable is included and cannot be disabled.

If "valid" is set to "1", the config variable is active. If it is set to "0", the config variable is inactive.

The config variable is defined in the "setting" element.

4.4.1. Types of XML Config Variables

The XML config settings support various types of variables.

4.4.2. String

A config element for numbers and single-line strings. Checking the validity with regex is possible. Thecheck attribute checks elements of the file system. This contains files and directories.

<Setting><String Regex="" Check="File"></String>

</Setting>

11

Page 18: Otrs Developer Book

Chapter 4. Config Mechanism

4.4.3. Textarea

A config element for multiline text.

<Setting><TextArea Regex=""></TextArea>

</Setting>

4.4.4. Options

This config element offers preset values as a pull-down menu.

<Setting><Option SelectedID="Key">

<Item Key=""></Item><Item Key=""></Item>

</Option></Setting>

4.4.5. Array

With this config element arrays can be displayed.

<Setting><Array>

<Item></Item><Item></Item>

</Array></Setting>

12

Page 19: Otrs Developer Book

Chapter 4. Config Mechanism

4.4.6. Hash

With this config element hashes can be displayed.

<Setting><Hash>

<Item Key=""></Item><Item Key=""></Item>

</Hash></Setting>

4.4.7. Hash with SubArray, SubOptions, SubHash

A hash can contain content arrays, hashes or pull-down menus.

<Setting><Hash>

<Item Key=""></Item><Item Key="">

<Hash><Item Key=""></Item><Item Key=""></Item>

</Hash></Item><Item Key="">

<Array><Item Key=""></Item><Item Key=""></Item>

</Array></Item><Item Key="">

<Option SelectedID="Key"><Item Key=""></Item><Item Key=""></Item>

</Hash></Item><Item Key=""></Item>

</Hash></Setting>

13

Page 20: Otrs Developer Book

Chapter 4. Config Mechanism

4.4.8. FrontendModuleReg (NavBar)

Module registration for Agent Interface.

<Setting><FrontendModuleReg>

<Description>Logout</Description><Title></Title><NavBarName></NavBarName><NavBar>

<Description>Logout</Description><Name>Logout</Name><Image>exit.png</Image><Link>Action=Logout</Link><NavBar></NavBar><Type></Type><Block>ItemPre</Block><AccessKey>l</AccessKey><Prio>100</Prio>

</NavBar></FrontendModuleReg>

</Setting>

4.4.9. FrontendModuleReg (NavBarModule)

Module registration for Admin Interface

<Setting><FrontendModuleReg>

<Group>admin</Group><Description>Admin</Description><Title>User</Title><NavBarName>Admin</NavBarName><NavBarModule>

<Module>Kernel::Output::HTML::NavBarModuleAdmin</Module><Name>Users</Name><Block>Block1</Block><Prio>100</Prio>

</NavBarModule></FrontendModuleReg>

</Setting>

14

Page 21: Otrs Developer Book

Chapter 5. Database Mechanism

OTRS comes with a database layer that supports different databases.

5.1. How it works

The database layer (Kernel::System::DB) has two input options: SQL and XML.

5.1.1. SQL

The SQL interface should be used for normal database actions (SELECT, INSERT, UPDATE, ...). It canbe used like a normal Perl DBI interface.

5.1.1.1. INSERT/UPDATE/DELETE

$Self->{DBObject}->Do(SQL=> "INSERT INTO table (name, id) VALUES (’SomeName’, 123)",

);

$Self->{DBObject}->Do(SQL=> "UPDATE table SET name = ’SomeName’, id = 123",

);

$Self->{DBObject}->Do(SQL=> "DELETE FROM table WHERE id = 123",

);

5.1.1.2. SELECT

my $SQL = "SELECT id FROM table WHERE tn = ’123’";

$Self->{DBObject}->Prepare(SQL => $SQL, Limit => 15);

while (my @Row = $Self->{DBObject}->FetchrowArray()) {$Id = $Row[0];

}return $Id;

Note: Take care to use Limit as param and not in the SQL string because not all databases supportLIMIT in SQL strings.

15

Page 22: Otrs Developer Book

Chapter 5. Database Mechanism

5.1.1.3. QUOTE

String:

my $QuotedString = $Self->{DBObject}->Quote("It’s a problem!");

Integer:

my $QuotedInteger = $Self->{DBObject}->Quote(’123’, ’Integer’);

Number:

my $QuotedNumber = $Self->{DBObject}->Quote(’21.35’, ’Number’);

5.1.2. XML

The XML interface should be used for INSERT, CREATE TABLE, DROP TABLE and ALTER TABLE.As this syntax is different from database to database, using it makes sure that you write applications thatcan be used in all of them.

Note: The <Insert> has chnaged in >=2.2. Values are now used in content area (not longer in attributValue).

5.1.2.1. INSERT

<Insert Table="some_table"><Data Key="id">1</Data><Data Key="description" Type="Quote">exploit</Data>

</Insert>

16

Page 23: Otrs Developer Book

Chapter 5. Database Mechanism

5.1.2.2. CREATE TABLE

Possible data types are: BIGINT, SMALLINT, INTEGER, VARCHAR (Size=1-1000000), DATE(Format: yyyy-mm-dd hh:mm:ss) and LONGBLOB.

<TableCreate Name="calendar_event"><Column Name="id" Required="true" PrimaryKey="true" AutoIncrement="true" Type="BIGINT"/><Column Name="title" Required="true" Size="250" Type="VARCHAR"/><Column Name="content" Required="false" Size="250" Type="VARCHAR"/><Column Name="start_time" Required="true" Type="DATE"/><Column Name="end_time" Required="true" Type="DATE"/><Column Name="owner_id" Required="true" Type="INTEGER"/><Column Name="event_status" Required="true" Size="50" Type="VARCHAR"/><Index Name="title">

<IndexColumn Name="title"/></Index><Unique>

<UniqueColumn Name="title"/></Unique><ForeignKey ForeignTable="system_user">

<Reference Local="owner_id" Foreign="id"/></ForeignKey>

</TableCreate>

5.1.2.3. DROP TABLE

<TableDrop Name="calendar_event"/>

5.1.2.4. ALTER TABLE

<TableAlter Name="calendar_event"><ColumnAdd Name="test_name" Type="varchar" Size="20" Required="1"/><ColumnChange NameOld="test_name" NameNew="test_title" Type="varchar" Size="30" Required="1"/><ColumnChange NameOld="test_title" NameNew="test_title" Type="varchar" Size="100" Required="0"/><ColumnDrop Name="test_title"/>

</TableAlter>

5.1.2.5. Code to process XML

my @XMLARRAY = @{$Self->ParseXML(String => $XML)};

my @SQL = $Self->{DBObject}->SQLProcessor(Database => \@XMLARRAY,

);

17

Page 24: Otrs Developer Book

Chapter 5. Database Mechanism

push(@SQL, $Self->{DBObject}->SQLProcessorPost());

foreach (@SQL) {$Self->{DBObject}->Do(SQL => $_);

}

5.2. Database Drivers

The database drivers are located under $OTRS_HOME/Kernel/System/DB/*.pm.

5.3. Supported Databases

• MySQL

• PostgreSQL

• Oracle

• MSSQL (experimental)

• DB2 (experimental)

• MaxDB/SAPDB (experimental)

18

Page 25: Otrs Developer Book

Chapter 6. Log Mechanism

OTRS comes with a log backend that can be used for application logging and debugging.

6.1. Use and Syntax

All module layers have ready-made Log Objects which can be used by

$Self->{LogObject}->Log(Priority => ’error’,Message => "Nee something!",

);

6.2. Example

The following example shows how to use the log mechanism without a module layer.

use Kernel::Config;use Kernel::System::Log;

my $ConfigObject = Kernel::Config->new();my $LogObject = Kernel::System::Log->new(

ConfigObject => $ConfigObject,);

$Self->{LogObject}->Log(Priority => ’error’,Message => "Need something!",

);

19

Page 26: Otrs Developer Book

Chapter 7. Module Format

7.1. Auth Module

There are several agent authentication modules (DB, LDAP and HTTPBasicAuth) which come with theOTRS framework. It is also possible to develop your own authentication modules. The agentauthentication modules are located under Kernel/System/Auth/*.pm. For more information about theirconfiguration see the admin manual. Following, there is an example of a simple agent auth module. Saveit under Kernel/System/Auth/Simple.pm. You just need 3 functions: new(), GetOption() and Auth().Return the uid, then the authentication is ok.

Format:

# --# Kernel/System/Auth/Simple.pm - provides the simple authentication# Copyright (C) 2001-2005 Martin Edenhofer martin+code at otrs.org# --# This software comes with ABSOLUTELY NO WARRANTY. For details, see# the enclosed file COPYING for license information (GPL). If you# did not receive this file, see http://www.gnu.org/licenses/gpl.txt.# --# Note:# available objects are: ConfigObject, LogObject and DBObject# --

package Kernel::System::Auth::Simple;

use strict;

sub new {my $Type = shift;my %Param = @_;[...]return $Self;

}sub GetOption {

my $Self = shift;my %Param = @_;# return optionreturn (PreAuth => 0);

}sub Auth {

my $Self = shift;my %Param = @_;[...]if ($Authentication) {

return $Param{User};}

20

Page 27: Otrs Developer Book

Chapter 7. Module Format

else {return;

}}

7.2. Notify Module

With agent notification modules you can inform agents about new information. A normal navigationlooks like the following screen shot.

With this examplary module you can do something like the following.

Format:

# --# Kernel/Output/HTML/NotificationMotd.pm - message of the day# Copyright (C) 2005 Hans Mueller [email protected]# --# $Id: module-format.xml,v 1.21.2.1 2007/10/17 06:24:05 tr Exp $# --# This software comes with ABSOLUTELY NO WARRANTY. For details, see# the enclosed file COPYING for license information (GPL). If you# did not receive this file, see http://www.gnu.org/licenses/gpl.txt.

21

Page 28: Otrs Developer Book

Chapter 7. Module Format

# --

package Kernel::Output::HTML::NotificationMotd;

use strict;

# --sub new {

my $Type = shift;my %Param = @_;[...]return $Self;

}# --sub Run {

my $Self = shift;my %Param = @_;return $Self->{LayoutObject}->Notify(Info => Some daily news! );

}# --1;

To use this module add the following to the Kernel/Config.pm and restart your webserver (if you usemod_perl).

# Frontend::NotifyModule - module name (50-Motd)$Self->{’Frontend::NotifyModule’}->{’50-Motd’} = {

Module => ’Kernel::Output::HTML::NotificationMotd’,};

7.3. Navigation Module

In this module layer you can create dynamic navigation bar items with dynamic content (Name andDescription). Navigation Module are located under Kernel/Output/HTML/NavBar*.pm.

Format:

# --# Kernel/Output/HTML/NavBarABC.pm - shows a navbar item dynamicaly# Copyright (C) 2005 Hans Mueller [email protected]# --# $Id: module-format.xml,v 1.21.2.1 2007/10/17 06:24:05 tr Exp $# --

22

Page 29: Otrs Developer Book

Chapter 7. Module Format

# This software comes with ABSOLUTELY NO WARRANTY. For details, see# the enclosed file COPYING for license information (GPL). If you# did not receive this file, see http://www.gnu.org/licenses/gpl.txt.# --

package Kernel::Output::HTML::NavBarABC;

use strict;

# --sub new {

my $Type = shift;my %Param = @_;[...]return $Self;

}# --sub Run {

my $Self = shift;my %Param = @_;my %Return = ();$Return{’0999989’} = {

Block => ’ItemPersonal’,Description => ’Some Desctipton’,Name => ’Text’,Image => ’new-message.png’,Link => ’Action=AgentMailbox&Subaction=New’,AccessKey => ’j’,

};return %Return;

}# --1;

To use this module add the following code to the Kernel/Config.pm and restart your webserver (if youuse mod_perl).

[Kernel/Config.pm]# agent interface notification module$Self->{’Frontend::NavBarModule’}->{’99-ABC’} = {

Module => ’Kernel::Output::HTML::NavBarABC’,};

23

Page 30: Otrs Developer Book

Chapter 7. Module Format

7.4. Frontend Modules

Frontend Modules are located under "$OTRS_HOME/Kernel/Modules/*.pm". There are two publicfunctions in there - new() and run() - which are accessed from the Frontend Handle (e. g. index.pl)."new()" is used to create a frontend module object. The Frontend Handle provides the used frontendmodule with the basic framework object. These are, for example: ParamObject (to get formular params),DBObject (to use existing database connects), LayoutObject (to use templates and other html layoutfunctions), ConfigObject (to access config settings), LogObject (to use the framework log system),UserObject (to get the user functions from the current user), GroupObject (to get the group functions).

For more information on core modules see http://dev.otrs.org/

Format:

# --# Kernel/Modules/AgentTest.pm - message of the day# Copyright (C) 2005 Hans Mueller [email protected]# --# $Id: module-format.xml,v 1.21.2.1 2007/10/17 06:24:05 tr Exp $# --# This software comes with ABSOLUTELY NO WARRANTY. For details, see# the enclosed file COPYING for license information (GPL). If you# did not receive this file, see http://www.gnu.org/licenses/gpl.txt.# --

package Kernel::Modules::AgentTest;

use strict;

# --sub new {

my $Type = shift;my %Param = @_;[...]return $Self;

}# --sub Run {

my $Self = shift;my %Param = @_;[...]# ---------------------------------------------------------- ## add a new object (Note: dtl text ’New’)# ---------------------------------------------------------- #if ($Self->{Subaction} eq ’Add’) {

my $Output = ”;my %Frontend = ();[...]# add add block$Self->{LayoutObject}->Block(

24

Page 31: Otrs Developer Book

Chapter 7. Module Format

Name => ’Add’,Data => {%Param, %Frontend},

);# build output$Output .= $Self->{LayoutObject}->Header(Area => ’Agent’, Title => "Test");$Output .= $Self->{LayoutObject}->NavigationBar();$Output .= $Self->{LayoutObject}->Output(

Data => {%Param, %Frontend},TemplateFile => ’AgentTest’,

);$Output .= $Self->{LayoutObject}->Footer();return $Output;

}# ---------------------------------------------------------- ## show overview screen# ---------------------------------------------------------- #elsif ($Self->{Subaction} eq ’Overview’) {

# add overview block$Self->{LayoutObject}->Block(

Name => ’Overview’,Data => {%Param, %Frontend},

);# build output$Output .= $Self->{LayoutObject}->Header(Area => ’Agent’, Title => "Test");$Output .= $Self->{LayoutObject}->NavigationBar();$Output .= $Self->{LayoutObject}->Output(

Data => {%Param, %Frontend},TemplateFile => ’AgentTest’,

);$Output .= $Self->{LayoutObject}->Footer();return $Output;

}# ---------------------------------------------------------- ## show error screen# ---------------------------------------------------------- #return $Self->{LayoutObject}->ErrorScreen(Message => "Invalid Subaction process!");

}# --1;

You also need a module registration for frontend modules. Define read only groups with the "GroupRo"and read/write groups with the ’Group’ param (see table below for details). You can define navigationbar icons via the "NavBar’"param, too (see table below for details).

[Kernel/Config.pm]$Self->{’Frontend::Module’}->{’AgentTest’} = {

Group => [’admin’],GroupRo => [’test’, ’admin’],Description => ’A test Module’,

25

Page 32: Otrs Developer Book

Chapter 7. Module Format

NavBarName => ’Ticket’,NavBar => [

{Description => ’Test Module’,Name => ’Test’,Image => ’stats.png’,Link => ’Action=AgentTest’,NavBar => ’Ticket’,Prio => 85,

},],

};

You can access this frontend module via http (browse) with the Action param = Module or over thenavigation bar.

http://localhost/otrs/index.pl?Action=AgentTest ()

Description of Frontend::Module options:

Key DescriptionGroup An ARRAY reference of rw groups of this module.

GroupRo An ARRAY reference of ro groups of this module.

Description Module description, just for internal use - notshown in the user interface.

NavBarName NavBar context name of this module.

Description of NavBar (icon points) options:

Key DescriptionDescription The description of the icon which is shown in the

navbar after the curser is pointed on it.

Name The icon name shown in the navbar.

Image The icon image shown in the navbar.

Link The link behind the icon in the navbar.

NavBar Only shown this icon in this NavBar context.

26

Page 33: Otrs Developer Book

Chapter 7. Module Format

Key DescriptionPrio Sort prio of the icon in the navbar.

7.5. Core Modules

Core modules are located under $OTRS_HOME/Kernel/System/*. This layer is for the logical work. Themodules are used to handle system routines like "lock ticket" and "create ticket". These modules alwaysneed pod (Perl Documentation).

A few common core modules are: Log (Kernel::System::Log); Ticket (Kernel::System::Ticket), Auth(Kernel::System::Auth), User (Kernel::System::User), Email (Kernel::System::Email).

For more information on the core modules see http://dev.otrs.org (http://dev.otrs.org/)

Format:

# --# Kernel/System/Backend.pm - a core module# Copyright (C) 2005 Hans Mueller [email protected]# --# $Id: module-format.xml,v 1.21.2.1 2007/10/17 06:24:05 tr Exp $# --# This software comes with ABSOLUTELY NO WARRANTY. For details, see# the enclosed file COPYING for license information (GPL). If you# did not receive this file, see http://www.gnu.org/licenses/gpl.txt.# --

package Kernel::System::Backend;

use strict;

=head1 NAME

Kernel::System::Log - global log interface

=head1 SYNOPSIS

All log functions.

=head1 PUBLIC INTERFACE

=over 4

27

Page 34: Otrs Developer Book

Chapter 7. Module Format

=item new()

create a backend object

use Kernel::Config;use Kernel::System::Backend;

my $ConfigObject = Kernel::Config->new();my $BackendObject = Kernel::System::Backend->new(ConfigObject => $ConfigObject);

=cut

sub new {my $Type = shift;my %Param = @_;[...]return $Self;

}

=item SomeMethodeA()

some info about the methode

$BackendObject->SomeMethodeA(ParamA => ’error’, ParamB => "Need something!");

=cut

sub SomeMethodeA{my $Self = shift;my %Param = @_;[...]return 1;

}1;

=head1 TERMS AND CONDITIONS

This software is part of the OTRS project (http://otrs.org/).

This software comes with ABSOLUTELY NO WARRANTY. For details, seethe enclosed file COPYING for license information (GPL). If youdid not receive this file, see http://www.gnu.org/licenses/gpl.txt.

=head1 VERSION

$Revision: 1.21.2.1 $ $Date: 2007/10/17 06:24:05 $

=cut

28

Page 35: Otrs Developer Book

Chapter 7. Module Format

7.6. Customer Auth Module

The same as "Agent Auth Modules" but the module location isKernel/System/CustomerAuth/*.pm.

7.7. Customer User Module

This module layer can be used as a bridge between your customer source system and OTRS. Thus it ispossible to use your customer data directly for your data ware house (read only and read/write).

Format:

# --# Kernel/System/CustomerUser/ABC.pm - a customer data backend# Copyright (C) 2005 Hans Mueller [email protected]# --# $Id: module-format.xml,v 1.21.2.1 2007/10/17 06:24:05 tr Exp $# --# This software comes with ABSOLUTELY NO WARRANTY. For details, see# the enclosed file COPYING for license information (GPL). If you# did not receive this file, see http://www.gnu.org/licenses/gpl.txt.# --

package Kernel::System::CustomerUser::ABD;

use strict;

# --sub new {

my $Type = shift;my %Param = @_;[...]return $Self;

}# --sub CustomerName {

[...]return $Name;

}# --sub CustomerSearch {

[...]return %Result;

}# --sub CustomerUserList {

[...]

29

Page 36: Otrs Developer Book

Chapter 7. Module Format

return %List;}# --sub CustomerIDs {

[...]return @CustomerIDs;

}# --sub CustomerUserDataGet {

[...]return %Data;

}# --sub CustomerUserAdd {

[...]return 1

}# --sub CustomerUserUpdate {

[...]return 1;

}# --sub SetPassword {

[...]return 1;

}1;

To use this module, see the admin manual.

7.8. Customer Navigation Module

In this module layer you can create dynamic navigation bar items with dynamic content (Name andDescription).

The format is the same as in the Navigation Module.

Just the config setting key is different. To use this module, add the following to the Kernel/Config.pmand restart your webserver (if you use mod_perl).

[Kernel/Config.pm]# customer notifiacation module

30

Page 37: Otrs Developer Book

Chapter 7. Module Format

$Self->{’CustomerFrontend::NavBarModule’}->{’99-ABC’} = {Module => ’Kernel::Output::HTML::NavBarABC’,

};

7.9. Stats Module

There are two different types of internal stats modules - dynamic and static

7.9.1. Dynamic stats

If you create a dynamic stats file, you can configurate your own statistics via the web frontend.

The following functions are required to get a functional script.

• sub new

to generate a new instance

• sub GetObjectName

gives the name of this dynamic stats module to the web frontend.

• sub GetObjectAttributes

generates an array with all possible elements of this dynamic stats module.

• sub GetStatElement

provides the content of a cell.

• sub ExportWrapper

converts the internal stats xml into a commonly usable format. For example ’queue id’ into ’queuename’.

• sub ImportWrapper

31

Page 38: Otrs Developer Book

Chapter 7. Module Format

undoes the changes of the ExportWrapper during stats import.

For example, have a look at this; Kernel/System/Stats/Dynamic/Ticket.pm:

7.9.2. Static stats

A static stats module is easy to make - you just need two functions. Param() to get all usable params forthe stats and Run() to return the stats result.

Kernel/System/Stats/Static/SomeExampleStats.pm:

# --# Kernel/System/Stats/Static/SomeExampleStats.pm - stats module# Copyright (C) 2005 Hans Mueller [email protected]# --# $Id: module-format.xml,v 1.21.2.1 2007/10/17 06:24:05 tr Exp $# --# This software comes with ABSOLUTELY NO WARRANTY. For details, see# the enclosed file COPYING for license information (GPL). If you# did not receive this file, see http://www.gnu.org/licenses/gpl.txt.# --

package Kernel::System::Stats::Static::SomeExampleStats;

use strict;use warnings;

sub new {my ( $Type, %Param ) = @_;

# allocate new hash for objectmy $Self = {};bless( $Self, $Type );

# get common objectsfor ( keys %Param ) {

$Self->{$_} = $Param{$_};}

# check all needed objectsfor (qw(DBObject ConfigObject LogObject)) {

die "Got no $_" if ( !$Self->{$_} );}

return $Self;

32

Page 39: Otrs Developer Book

Chapter 7. Module Format

}

sub Param {my $Self = shift;my @Params = ();

# get current timemy ($s,$m,$h, $D,$M,$Y) = $Self->{TimeObject}->SystemTime2Date(

SystemTime => $Self->{TimeObject}->SystemTime(),);# get one month bevoreif ($M == 1) {

$M = 12;$Y = $Y - 1;

}else {

$M = $M -1;}# create possible time selectionsmy %Year = ();foreach ($Y-10..$Y+1) {

$Year{$_} = $_;}my %Month = ();foreach (1..12) {

my $Tmp = sprintf("%02d", $_);$Month{$_} = $Tmp;

}push (@Params, {

Frontend => ’Year’,Name => ’Year’,Multiple => 0,Size => 0,SelectedID => $Y,Data => {

%Year,},

},);push (@Params, {

Frontend => ’Month’,Name => ’Month’,Multiple => 0,Size => 0,SelectedID => $M,Data => {

%Month,},

},);return @Params;

}

33

Page 40: Otrs Developer Book

Chapter 7. Module Format

sub Run {my ( $Self, %Param ) = @_;

my $Title = "$Param{Year}-$Param{Month}";

my @HeadData = (’Col A’, ’Col B’, ’Col C’);

my @Data = ([1, 4, 7],[6, 1, 4],[9, 4, 6],

);

return ([$Title],[@HeadData], @Data);}

1;

7.9.3. Using old static stats

Standard OTRS versions 1.3 and 2.0 already facilitated the generation of stats. Various stats for OTRSversions 1.3 and 2.0 which have been specially developed to meet customers’ requirements can be usedin more recent versions too.

The files must merely be moved from the Kernel/System/Stats/ path toKernel/System/Stats/Static/. Additionally the package name of the respective script must beamended by "::Static".

The following example shows how the first path is amended.

package Kernel::System::Stats::AccountedTime;

package Kernel::System::Stats::Static::AccountedTime;

34

Page 41: Otrs Developer Book

Chapter 7. Module Format

7.10. Ticket Modules

7.10.1. Ticket Number Module

If you want to create your own ticket number format, just create your own ticket number module. Thesemodules are located under "Kernel/System/Ticket/Number/*.pm". For default modules see the adminmanual. You just need 2 functions: CreateTicketNr() and GetTNByString():

Format:

# --# Ticket/Number/Simple.pm - a ticket number auto increment generator# Copyright (C) 2005 Hans Mueller [email protected]# --# This software comes with ABSOLUTELY NO WARRANTY. For details, see# the enclosed file COPYING for license information (GPL). If you# did not receive this file, see http://www.gnu.org/licenses/gpl.txt.# --# Generates auto increment ticket numbers like ss.... (e. g. 1010138, 1010139, ...)# --

package Kernel::System::Ticket::Number::Simple;

use strict; use vars qw($VERSION);

$VERSION = ’$Revision: 1.21.2.1 $’;$VERSION =~ s/^\$.*:\W(.*)\W.+?$/$1/;

sub CreateTicketNr {my $Self = shift;my $JumpCounter = shift || 0;# get needed config options[...]return $Tn;

}# --sub GetTNByString {

my $Self = shift;my $String = shift || return;[...]return $Tn;

}1;

35

Page 42: Otrs Developer Book

Chapter 7. Module Format

7.10.2. Ticket PostMaster Module

PostMaster modules are used during the PostMaster process. There are two kinds of PostMastermodules. PostMasterPre (used after parsing an email) and PostMasterPost (used after an email isprocessed and in the database) modules.

If you want to create your own postmaster filter, just create your own module. These modules are locatedunder "Kernel/System/PostMaster/Filter/*.pm". For default modules see the admin manual. You justneed two functions: new() and Run():

The following is an examplary module to match emails and set X-OTRS-Headers (seedoc/X-OTRS-Headers.txt for more info).

Kernel/Config.pm:

# Job Name: 1-Match# (block/ignore all spam email with From: noreply@)$Self->{’PostMaster::PreFilterModule’}->{’1-Example’} = {

Module => ’Kernel::System::PostMaster::Filter::Example’,Match => {

From => ’noreply@’,},Set => {

’X-OTRS-Ignore’ => ’yes’,},

};

Format:

# --# Kernel/System/PostMaster/Filter/Example.pm - a postmaster filter# Copyright (C) 2005 Hans Mueller [email protected]# --# This software comes with ABSOLUTELY NO WARRANTY. For details, see# the enclosed file COPYING for license information (GPL). If you# did not receive this file, see http://www.gnu.org/licenses/gpl.txt.# --

package Kernel::System::PostMaster::Filter::Example;

use strict;use vars qw($VERSION);

36

Page 43: Otrs Developer Book

Chapter 7. Module Format

$VERSION = ’$Revision: 1.21.2.1 $’;$VERSION =~ s/^\$.*:\W(.*)\W.+?$/$1/;

sub new {my $Type = shift;my %Param = @_;

# allocate new hash for objectmy $Self = {};bless ($Self, $Type);

$Self->{Debug} = $Param{Debug} || 0;

# get needed opbjectsforeach (qw(ConfigObject LogObject DBObject)) {

$Self->{$_} = $Param{$_} || die "Got no $_!";}

return $Self;}

sub Run {my $Self = shift;my %Param = @_;# get config optionsmy %Config = ();my %Match = ();my %Set = ();if ($Param{JobConfig} && ref($Param{JobConfig}) eq ’HASH’) {

%Config = %{$Param{JobConfig}};if ($Config{Match}) {

%Match = %{$Config{Match}};}if ($Config{Set}) {

%Set = %{$Config{Set}};}

}# match ’Match => ???’ stuffmy $Matched = ”;my $MatchedNot = 0;foreach (sort keys %Match) {

if ($Param{GetParam}->{$_} && $Param{GetParam}->{$_} =~ /$Match{$_}/i) {$Matched = $1 || ’1’;if ($Self->{Debug} > 1) {

$Self->{LogObject}->Log(Priority => ’debug’,Message => "’$Param{GetParam}->{$_}’ =~ /$Match{$_}/i matched!",

);}

}else {

$MatchedNot = 1;

37

Page 44: Otrs Developer Book

Chapter 7. Module Format

if ($Self->{Debug} > 1) {$Self->{LogObject}->Log(

Priority => ’debug’,Message => "’$Param{GetParam}->{$_}’ =~ /$Match{$_}/i matched NOT!",

);}

}}# should I ignore the incoming mail?if ($Matched && !$MatchedNot) {

foreach (keys %Set) {if ($Set{$_} =~ /\[\*\*\*\]/i) {

$Set{$_} = $Matched;}$Param{GetParam}->{$_} = $Set{$_};$Self->{LogObject}->Log(

Priority => ’notice’,Message => "Set param ’$_’ to ’$Set{$_}’ (Message-ID: $Param{GetParam}->{’Message-ID’}) ",

);}

}

return 1;}

1;

7.10.3. Ticket Menu Module

To add links in the ticket menu, just use ticket menu modules.

If you want to create your own ticket menu link, just create your own module. These modules are locatedunder "Kernel/Output/HTML/TicketMenu*.pm". For default modules see the admin manual. You justneed two functions: new() and Run():

The following example shows you how to show a lock or a unlock ticket link.

Kernel/Config.pm:

# for ticket zoom menu$Self->{’Ticket::Frontend::MenuModule’}->{’100-Lock’} = {

’Action’ => ’AgentTicketLock’,’Module’ => ’Kernel::Output::HTML::TicketMenuLock’,

38

Page 45: Otrs Developer Book

Chapter 7. Module Format

’Name’ => ’Lock’};

# for ticket preview menu$Self->{’Ticket::Frontend::PreMenuModule’}->{’100-Lock’} = {

Action => ’AgentTicketLock’,Module => ’Kernel::Output::HTML::TicketMenuLock’,Name => ’Lock’

};

Format:

# --# Kernel/Output/HTML/TicketMenuLock.pm# Copyright (C) 2005 Hans Mueller [email protected]# --# $Id: module-format.xml,v 1.21.2.1 2007/10/17 06:24:05 tr Exp $# --# This software comes with ABSOLUTELY NO WARRANTY. For details, see# the enclosed file COPYING for license information (GPL). If you# did not receive this file, see http://www.gnu.org/licenses/gpl.txt.# --

package Kernel::Output::HTML::TicketMenuLock;

use strict;

use vars qw($VERSION);$VERSION = ’$Revision: 1.21.2.1 $’;$VERSION =~ s/^\$.*:\W(.*)\W.+?$/$1/;

# --sub new {

my $Type = shift;my %Param = @_;

# allocate new hash for objectmy $Self = {};bless ($Self, $Type);

# get needed objectsforeach (qw(ConfigObject LogObject DBObject LayoutObject UserID TicketObject)) {

$Self->{$_} = $Param{$_} || die "Got no $_!";}

return $Self;}# --

39

Page 46: Otrs Developer Book

Chapter 7. Module Format

sub Run {my $Self = shift;my %Param = @_;# check needed stuffif (!$Param{Ticket}) {

$Self->{LogObject}->Log(Priority => ’error’, Message => "Need Ticket!");return;

}

# check permissionif ($Self->{TicketObject}->LockIsTicketLocked(TicketID => $Param{TicketID})) {

my $AccessOk = $Self->{TicketObject}->OwnerCheck(TicketID => $Param{TicketID},OwnerID => $Self->{UserID},

);if (!$AccessOk) {

return $Param{Counter};}

}

$Self->{LayoutObject}->Block(Name => ’Menu’,Data => { },

);if ($Param{Counter}) {

$Self->{LayoutObject}->Block(Name => ’MenuItemSplit’,Data => { },

);}if ($Param{Ticket}->{Lock} eq ’lock’) {

$Self->{LayoutObject}->Block(Name => ’MenuItem’,Data => {

%{$Param{Config}},%{$Param{Ticket}},%Param,Name => ’Unlock’,Description => ’Unlock to give it back to the queue!’,Link => ’Action=AgentTicketLock&Subaction=Unlock&TicketID=$QData{"TicketID"}’,

},);

}else {

$Self->{LayoutObject}->Block(Name => ’MenuItem’,Data => {

%{$Param{Config}},%Param,Name => ’Lock’,Description => ’Lock it to work on it!’,Link => ’Action=AgentTicketLock&Subaction=Lock&TicketID=$QData{"TicketID"}’,

},

40

Page 47: Otrs Developer Book

Chapter 7. Module Format

);}$Param{Counter}++;return $Param{Counter};

}# --1;

7.10.4. Ticket Event Module

Do do some actions on ticket events, just write your own ticket event module.

These modules are located under "Kernel/System/Ticket/Event/*.pm". For default modules see theadmin manual. You just need two functions: new() and Run():

The following example shows you how to unlock a ticket after a move action.

Kernel/Config.pm:

$Self->{’Ticket::EventModulePost’}->{’99-ForceUnlockOnMove’} = {Module => ’Kernel::System::Ticket::Event::ForceUnlock’

};

Format:

# --# Kernel/System/Ticket/Event/ForceUnlook.pm - unlock ticket# Copyright (C) 2005 Hans Mueller [email protected]# --# $Id: module-format.xml,v 1.21.2.1 2007/10/17 06:24:05 tr Exp $# --# This software comes with ABSOLUTELY NO WARRANTY. For details, see# the enclosed file COPYING for license information (GPL). If you# did not receive this file, see http://www.gnu.org/licenses/gpl.txt.# --

package Kernel::System::Ticket::Event::ForceUnlock;

41

Page 48: Otrs Developer Book

Chapter 7. Module Format

use strict;

use vars qw($VERSION);$VERSION = ’$Revision: 1.21.2.1 $’;$VERSION =~ s/^\$.*:\W(.*)\W.+?$/$1/;

# --sub new {

my $Type = shift;my %Param = @_;

# allocate new hash for objectmy $Self = {};bless ($Self, $Type);

# get needed objectsforeach (qw(ConfigObject TicketObject LogObject)) {

$Self->{$_} = $Param{$_} || die "Got no $_!";}

return $Self;}# --sub Run {

my $Self = shift;my %Param = @_;# check needed stuffforeach (qw(TicketID Event Config)) {if (!$Param{$_}) {$Self->{LogObject}->Log(Priority => ’error’, Message => "Need $_!");return;

}}if ($Param{Event} eq ’MoveTicket’) {

$Self->{TicketObject}->LockSet(TicketID => $Param{TicketID},Lock => ’unlock’,SendNoNotification => 1,UserID => 1,

);}return 1;

}# --1;

Ticket Events for OTRS 2.0: TicketCreate, TicketDelete, TicketTitleUpdate,TicketUnlockTimeoutUpdate, TicketEscalationStartUpdate, MoveTicket, SetCustomerData,TicketFreeTextSet, TicketFreeTimeSet, TicketPendingTimeSet, LockSet, StateSet, OwnerSet,

42

Page 49: Otrs Developer Book

Chapter 7. Module Format

TicketResponsibleUpdate, PrioritySet, HistoryAdd, HistoryDelete, TicketAccountTime, TicketMerge,ArticleCreate, ArticleFreeTextSet, ArticleUpdate, ArticleSend, ArticleBounce, SendAgentNotification,SendCustomerNotification, SendAutoResponse, ArticleFlagSet;

Ticket Events for OTRS 2.1 and higher: TicketCreate, TicketDelete, TicketTitleUpdate,TicketUnlockTimeoutUpdate, TicketEscalationStartUpdate, TicketQueueUpdate (MoveTicket),TicketCustomerUpdate (SetCustomerData), TicketFreeTextUpdate (TicketFreeTextSet),TicketFreeTimeUpdate (TicketFreeTimeSet), TicketPendingTimeUpdate (TicketPendingTimeSet),TicketLockUpdate (LockSet), TicketStateUpdate (StateSet), TicketOwnerUpdate (OwnerSet),TicketResponsibleUpdate, TicketPriorityUpdate (PrioritySet), HistoryAdd, HistoryDelete,TicketAccountTime, TicketMerge, ArticleCreate, ArticleFreeTextUpdate (ArticleFreeTextSet),ArticleUpdate, ArticleSend, ArticleBounce, ArticleAgentNotification, (SendAgentNotification),ArticleCustomerNotification (SendCustomerNotification), ArticleAutoResponse (SendAutoResponse),ArticleFlagSet;

7.10.5. More Modules

The Agent Ticket Permission Modules (Kernel/System/Ticket/Permission/) contain functions to verify anagent’s authorisation to access a ticket.

The Customer Ticket Permission Modules (Kernel/System/Ticket/CustomerPermission/) containfunctions to verify a customer’s authorisation to access a ticket.

The Article Module (Kernel/System/Ticket/Article.pm) facilitates the readout and generating of ticketarticles.

More modules and their descriptions are listed under http://dev.otrs.org/

43

Page 50: Otrs Developer Book

Chapter 8. Templates

The .dtl files are to 70% plain html and just used from frontend modules (Kernel/Modules/*.pm). The.dtl files are located under:

$OTRS_HOME/Kernel/Output/HTML/Standard/*.dtl

The usable dtl tags and syntax are described below.

8.1. Formatting

TAB: We use two spaces for every new open tag. Examples:

<table><tr><td>Key</td><td>Value</td>

</tr><tr><td>aaa</td><td>bbb</td>

</tr></table>

<form action ="index.pl"><input type="text" value=""><input type="text" value=""><table><tr><td>Key1</td><td>Value1</td>

</tr><tr><td>Key2</td><td>Value2</td>

</tr></table><input type="submit">

</form>

44

Page 51: Otrs Developer Book

Chapter 8. Templates

8.1.1. Comment

The dtl comment starts with a # at the beginning of a line and will not be shown in the html output.

# this can be a comment in the dtl file

8.1.2. $Data{""}

If data params are given to the templates, these params can be printed to the template.

The name of the author is $Data{"Name"}.

Warning

If the value of the param Name includes html tags, these tags are also shown.

8.1.3. $QData{""}

The same as $Data{""} but the value if the param Name is html quoted (safe).

The name of the author is $QData{"Name"}.

It’s also possible to cut the value. If, for example, you just want to show 20 characters of a variable(result will be "SomeName[..]"), use the following:

The first 20 characters of the author’s name: $QData{"Name","20"}.

45

Page 52: Otrs Developer Book

Chapter 8. Templates

8.1.4. $LQData{""}

The same as $QData{""} but with link encoding. This means for example that a space will be a + (e. g.for "a href").

<a href="$Env{"Baselink"}&Location=$LQData{"File"}">$QData{"File","110"}</a>

8.1.5. $Env{""}

Env is an environment variable which is usable in more templates at a time. $Data{""} is just availabe forone template.

The current user name is: $Env{"Userfirstname"}

Some other common variables are:$Env{"SessionID"} --> the current session id$Env{"Time"} --> the current time e. g. Thu Dec 27 16:00:55 2001$Env{"CGIHandle"} --> the current CGI handle e. g. index.pl$Env{"UserCharset"} --> the current site charset e. g. iso-8859-1$Env{"Baselink"} --> the baselink --> index.pl?SessionID=...$Env{"UserFirstname"} --> e. g. Dirk $Env{"UserFirstname"}$Env{"UserLogin"} --> e. g. [email protected]$Env{"UserIsGroup[users]"} = Yes --> user groups (useful for own links)$Env{"UserIsGroup[admin]"} = Yes $Env{"Action"} --> the current action

8.1.6. $QEnv{""}

QEnv is an html quoted environment variable (like Env but quoted).

The current user name is: $QEnv{"Userfirstname"}

8.1.7. $Quote{""}

A tag to quote html strings.

Show no html tags, quote this: $Quote{"<hr><b>some text</b></hr>"}

46

Page 53: Otrs Developer Book

Chapter 8. Templates

It’s also possible to cut the value. If, for example, you just want to show 20 characters of a variable(result will be "SomeMess[..]"), use the following:

Show no html tags, quote this and show just 20 characters:$Quote{"<hr><b>some text</b></hr>","20"}

8.1.8. $Text{""}

This tag translates the string (based on the user selected language).

Translate this text: $Text{"Help"}

8.1.9. $Config{""}

With this tag you can use config variables in the template. For example the Kernel/config.pm:

[Kernel/Config.pm]# FQDN# (Full qualified domain name of your system.)$Self->{FQDN} = ’otrs.example.com’;# AdminEmail# (Email of the system admin.)$Self->{AdminEmail} = ’[email protected]’;

[...]

And the use in the dtl template:

The hostname is ’$Config{"FQDN"}’The admin email address is ’$Config{"AdminEmail"}’

47

Page 54: Otrs Developer Book

Chapter 8. Templates

8.1.10. $Include{""}

If you want to include other dtl templates into a template, use the include tag:

# include Copyright.dtl$Include{"Copyright"}

Yet another examlpe:

<html><head>

<tilte>Some Title</tilte># include css.dtl file$Include{"css"}</head>

8.1.11. Block

The block tag can be used to define blocks. These blocks can be used several times by the frontendmodule with different data params.

<table><!-- dtl:block:Row -->

<tr><td valign="top" width="15%"><b>$Text{"$Data{"Key"}"}:</b></td><td width="85%"><div title="$QData{"Value"}">$QData{"Value","160"}</div></td>

</tr><!-- dtl:block:Row --></table>

The html code can be displayed in template blocks in the frontend:

48

Page 55: Otrs Developer Book

Chapter 8. Templates

# get articlemy %Article = $Self->{TicketObject}->ArticleGet(

ArticleID => $ArticleID,);

# file blocksforeach (qw(From To Cc Subject)) {

if ($Article{$_}) {$Self->{LayoutObject}->Block(

Name => ’Row’,Data => {

Key => $_,Value => $Article{$_},

},);

}}

# process templatemy $HTMLOutput = $Self->{LayoutObject}->Output(

TemplateFile => ’AgentZoomBody’,Data => {

%Article},

);

8.1.12. set

With this tag you can set a variable in the dtl template.

<dtl set $Data{"Test"} = "Some Text">

8.1.13. if

It’s also possible to use a really "simple" (ne|eq|=~|!~) if condition.

<dtl if ($Text{"Lock"} eq "Lock") { $Data{"Language"} = "en"; }>

Or with a regexp.

49

Page 56: Otrs Developer Book

Chapter 8. Templates

<dtl if ($Text{"Lock"} =~ "/text/i") { $Data{"Lala"} = "Matched"; }>

This template function can still be found in several OTRS templates but will be removed in futureversions of OTRS. The removal is necessary as a sequence control in the templates is not desired. Thefunction should thus not be used any more.

8.1.14. system-call

If you want the output of a system call back to a dtl variable.

# execute system call<dtl system-call $Data{"uptime"} = "uptime"># printThe output of ’uptime’ is: $Data{"uptime"}

Yet another example:

# execute system call<dtl system-call $Data{"procinfo"} = "procinfo | head -n1 "># printThe output of ’procinfo’ is: $Data{"procinfo"}

Usable to set: $Data{""}, $Env{""} and $Config{""}.

8.2. Example

# set variable<dtl set $Data{"Test1"} = "English">

# print variableEcho: $Data{"Test1"}

# condition<dtl if ($Text{"Lock"} ne "Lock") { $Data{"Test2"} = "Not English!"; }>

50

Page 57: Otrs Developer Book

Chapter 8. Templates

# print resultResult: $Data{"Test1"}

51

Page 58: Otrs Developer Book

Chapter 9. Layout

9.1. CSS Style

9.1.1. View

52

Page 59: Otrs Developer Book

Chapter 9. Layout

9.1.2. Edit/New/Search

The default width for the content tables is 700px and should be maintained on all pages.

53

Page 60: Otrs Developer Book

Chapter 9. Layout

9.1.3. Overview/Search Result

54

Page 61: Otrs Developer Book

Chapter 9. Layout

9.1.4. Delete

9.2. Images

The image format is png. The image size for the navigation icons is 22x22 pixels. All other icons are16x16 pixels.

Images are named after their function. For example new.png or search.png.

Default images are:

• new.png (for creating)

• search.png (for searching)

55

Page 62: Otrs Developer Book

Chapter 9. Layout

• overview.png (for an overview)

• logout.png (logout)

9.3. Special CSS Definitions

All html pages in OTRS use a readymade CSS declaration that is part of every header. Should the stylesheets not contain the needed declaration, additional sheets must be defined as an extra css block in thehtml source code instead of in an html element.

Examples from the Calendar Module:

[..]<!-- dtl:block:Overview --><style type="text/css"><!--

.sunday {font-family:Geneva,Helvetica,Arial,sans-serif;font-size:10pt;vertical-align:top;background-color:#ffe0e0;color:#000000;

}.saturday {

font-family:Geneva,Helvetica,Arial,sans-serif;font-size:10pt;vertical-align:top;background-color:#ffe0e0;color:#000000;

}[..]//--></style>

<table border="0" width="100%" cellspacing="0" cellpadding="3" cols="1"><tr><td class="mainhead">$Env{"Box0"}$Text{"Calendar"}$Env{"Box1"}

</td></tr>[..]

56

Page 63: Otrs Developer Book

Chapter 10. Language Translations

The OTRS framework allows for different languages to be used in the frontend.

10.1. How it works

There are three different translation file types which are used in the following order. If a word/sentence isredefined in a translation file, the latest definition will be used.

1. Default Framework Translation File

Kernel/Language/$Language.pm

2. Frontend Module Translation File

Kernel/Language/$Language_$FrontendModule.pm

3. Custom Translation File

Kernel/Language/$Language_Custom.pm

10.1.1. Default Framework Translation File

The Default Framework Translation File includes the basic translations. The following is an example of aDefault Framework Translation File.

Format:

# --# Kernel/Language/de.pm - provides de language translation# Copyright (C) 2001-2006 Martin Edenhofer <[email protected]># --# $Id: language-translations.xml,v 1.10 2006/04/02 23:25:09 martin Exp $# --# This software comes with ABSOLUTELY NO WARRANTY. For details, see# the enclosed file COPYING for license information (GPL). If you# did not receive this file, see http://www.gnu.org/licenses/gpl.txt.# --package Kernel::Language::de;

57

Page 64: Otrs Developer Book

Chapter 10. Language Translations

use strict;

use vars qw($VERSION);$VERSION = ’$Revision: 1.10 $’;$VERSION =~ s/^\$.*:\W(.*)\W.+?$/$1/;

# --sub Data {

my $Self = shift;my %Param = @_;

# $$START$$

# possible charsets$Self->{Charset} = [’iso-8859-1’, ’iso-8859-15’, ];# date formats (%A=WeekDay;%B=LongMonth;%T=Time;%D=Day;%M=Month;%Y=Jear;)$Self->{DateFormat} = ’%D.%M.%Y %T’;$Self->{DateFormatLong} = ’%A %D %B %T %Y’;$Self->{DateFormatShort} = ’%D.%M.%Y’;$Self->{DateInputFormat} = ’%D.%M.%Y’;$Self->{DateInputFormatLong} = ’%D.%M.%Y - %T’;

$Self->{Translation} = {# Template: AAABase’Yes’ => ’Ja’,’No’ => ’Nein’,’yes’ => ’ja’,’no’ => ’kein’,’Off’ => ’Aus’,’off’ => ’aus’,Kernel/Language/$Language_Custome.pm};# $$STOP$$

}# --1;

10.1.2. Frontend Translation File

The Frontend Translation File is used for a specific frontend module. If, for example, the frontendmodule "Kernel/Modules/AgentCalendar.pm", alsohttp://otrs.example.com/otrs/index.pl?Action=AgentCalendar, is used, the Frontend Translation File"Kernel/Language/de_Agentcalendar.pm" is used, too.

Format:

# --# Kernel/Language/de_AgentCalendar.pm - provides de language translation

58

Page 65: Otrs Developer Book

Chapter 10. Language Translations

# Copyright (C) 2001-2006 Martin Edenhofer <[email protected]># --# $Id: language-translations.xml,v 1.10 2006/04/02 23:25:09 martin Exp $# --# This software comes with ABSOLUTELY NO WARRANTY. For details, see# the enclosed file COPYING for license information (GPL). If you# did not receive this file, see http://www.gnu.org/licenses/gpl.txt.# --

package Kernel::Language::de_AgentCalendar;

use strict;

sub Data {my $Self = shift;

$Self->{Translation}->{’CW’} = ’KW’;$Self->{Translation}->{’Today’} = ’heute’;$Self->{Translation}->{’Tomorrow’} = ’Morgen’;$Self->{Translation}->{’1 St. May’} = ’Erster Mai’;$Self->{Translation}->{’Christmas’} = ’Weihnachten’;$Self->{Translation}->{’Silvester’} = ’Silvester’;$Self->{Translation}->{’New Year\’s Eve!’} = ’Neu Jahr!’;$Self->{Translation}->{’January’} = ’Januar’;$Self->{Translation}->{’February’} = ’Februar’;

}1;

10.1.3. Custom Translation File

The Custom Translation File is read out last and so its translation which will be used. If you want to addyour own wording to your installation, create this file for your language.

Format:

# --# Kernel/Language/xx_Custom.pm - provides xx custom language translation# Copyright (C) 2001-2006 Martin Edenhofer <[email protected]># --# $Id: language-translations.xml,v 1.10 2006/04/02 23:25:09 martin Exp $# --# This software comes with ABSOLUTELY NO WARRANTY. For details, see# the enclosed file COPYING for license information (GPL). If you# did not receive this file, see http://www.gnu.org/licenses/gpl.txt.# --package Kernel::Language::xx_Custom;

59

Page 66: Otrs Developer Book

Chapter 10. Language Translations

use strict;

use vars qw($VERSION);$VERSION = ’$Revision: 1.10 $’;$VERSION =~ s/^\$.*:\W(.*)\W.+?$/$1/;

# --sub Data {

my $Self = shift;my %Param = @_;

# $$START$$

# own translations$Self->{Translation}->{’Lock’} = ’Lala’;$Self->{Translation}->{’Unlock’} = ’Lulu’;

# $$STOP$$}# --1;

10.2. Add a new default framework translation

If you want to translate the OTRS framework into a new language, you have to follow these five steps:

1. Take the current German translation (Kernel/Language/de.pm) from CVS (http://cvs.otrs.org(http://cvs.otrs.org/)). Use the German version because this is always up to date.

2. Change the package name (e.g. "package Kernel::Language::de;" to "packageKernel::Language::fr;") and translate each word/sentence.

3. Add the new language translation to the framework by adding it to your Kernel/Config.pm.

$Self->{DefaultUsedLanguages}->{fr} = ’French’;

4. If you use mod_perl, restart your webserver and the new language will be shown in your preferencesselection.

5. Send the new translation file to mailing list "i18n at otrs.org" - Thanks!

60

Page 67: Otrs Developer Book

Chapter 11. Object Basics

This chapter describes the basics of a new object (e. g. a ticket, faq, calendar, ...) and how theenvironment should look like.

11.1. Object Options

An object (e.g. a ticket, faq, calendar, ...) should at least have the following options (named after theirfunction) in the application and in the database.

Application database namingObjectID object_id

Number number

Title title

... ...

StateID state_id

WordAndWord word_and_word

... ...

Created created

CreatedBy created_by

Changed changed

ChangedBy changed_by

11.2. Search Options

A search over free text fields should support:

• a normal search "thomas" (always)

• an and condition like "thomas+raith" (if possible)

• an or condition like "thomas||raith" (if possible)

61

Page 68: Otrs Developer Book

Chapter 11. Object Basics

11.3. Config Naming

Config naming should be with a leading prefix, the object name like this:

$Self->{"Object::Option"} = 1234;

Config-Hashes should be named with the same name as in the .dtl. For example:

$Self->{"Object::CategoryList"} -> $Data{"CategoryList"}

The config order should be global setting followed by detail settings.

11.4. Config File

An object should have a unique config file which should be located under$OTRS_HOME/Kernel/Config/Files/*.pm. For example:

# module reg and nav bar$Self->{’Frontend::Module’}->{’AgentFileManager’} = {

Description => ’Web File Manager’,NavBarName => ’FileManager’,NavBar => [{

Description => ’A web file manager’,Name => ’File-Manager’,Image => ’filemanager.png’,Link => ’Action=AgentFileManager’,NavBar => ’FileManager’,Prio => 5000,AccessKey => ’f’,

},],

};

# browse/download root directory$Self->{"FileManager::Root"} = ’/home/’;

62

Page 69: Otrs Developer Book

Chapter 11. Object Basics

# trash directory$Self->{"FileManager::Trash"} = "/home/Trash/";

Description of the Config Preferences:

Element descriptionNavBarName module name

Group/GroupRo group access authorization

Name name of the link button

Image image for the link button

Link URI

NavBar module name (correlation)

Prio prio in the button list

AccessKey short key (key + ALT) for quick access over thekeyboard.

11.5. NavBar Settings

A NavBar item should look like the following example:

NavBarPoint Prio AccessKey ImageOverview 100 o overview.png

New 200 n new.png

Search 300 s search.png

Delete 400 d delete.png

Import 500 - import.png

Setting 900 - module_setting.png

Menu functions - generic, used by any application module

NavBarPoint Prio AccessKey Image

63

Page 70: Otrs Developer Book

Chapter 11. Object Basics

NavBarPoint Prio AccessKey ImageLogout 10 l logout.png

Preferences 0 p preferences.png

New Messages 999989 m new-messages.png

Locked Tickets 9999999 k personal.png

Menu functions - global, always used

NavBarPoint Prio AccessKey ImageTicket 200 t ticket.png

Incident(SIRIOS-Project)

2000 i incident.png

Advisory(SIRIOS-Project)

2100 d advisory.png

ShortAdvisory(SIRIOS-BSI-specific)

2150 z advisory_short.png

VirusWarning(SIRIOS-BSI-specific)

2300 x viruswarning.png

FreeTextMessage(SIRIOS-BSI-specific)

2400 y freetextmessage.png

Vulnerability(SIRIOS-Project)

2500 v vulnerability.png

Artefact(SIRIOS-Project)

2600 r artefactdb.png

WebWatcher(SIRIOS-Project)

2700 z webwatcher.png

IDMEFConsole(SIRIOS-Project)

2800 - idmef_console.png

WID-Authoring(WID-Project)

2900 - wid_authoring.png

WID-Portal-Admin-User (WID-Project)

2910 - wid_portal_admin_user.png

WID-Portal-Admin-Group (WID-Project)

2920 - wid_portal_admin_group.png

ITSMService(OTRS::ITSM)

3100 - itsm_service.png

ITSMConfigItem(OTRS::ITSM)

3200 - itsm_configitem.png

64

Page 71: Otrs Developer Book

Chapter 11. Object Basics

NavBarPoint Prio AccessKey ImageITSMLocation(OTRS::ITSM)

3300 - itsm_location.png

ContentManager 7050 - contentmanager.png

Calendar 8000 c calendar.png

FileManager 8100 f filemanager.png

WebMail 8200 w webmail.png

FAQ 8300 q help.png

Call 8400 - call.png

Stats 8500 - stats.png

CustomerDB 9000 - folder_yellow.png

CustomerCompanyDB 9100 - folder_yellow.png

Admin 10000 a admin.png

Table 3: Menu Applications -default application modules

Note: AccessKey "g" is also reserved for the submission of forms.

11.6. Screen flow

An object module should have the following process flow:

65

Page 72: Otrs Developer Book

Chapter 11. Object Basics

66

Page 73: Otrs Developer Book

Chapter 12. Development Environment

To facilitate the writing of OTRS expansion modules, the creation of a development environment inLinux is necessary.

12.1. Framework checkout (CVS)

First of all a directory must be created in which the modules can be stored. Then switch to the newdirectory using the command line and check them out of OTRS 2.2 or the CVS head by using thefollowing command (loginpassword: cvs):

shell> cvs -d :pserver:[email protected]:/home/cvs login

shell> cvs -z3 -d :pserver:[email protected]:/home/cvs co -r otrs

shell> cvs -z3 -d :pserver:[email protected]:/home/cvs co -r rel-2_2 otrs

OTRS expansion modules can be checked out following the same routine. Check out the "module-tools"module, too for your development environment. It contains a number of useful tools.

To enable the CVS-OTRS it is necessary to configure it on the Apache web server and to create theConfig.pm. Then the Installer.pl can be executed. The basic system is ready to run now.

12.2. Linking Expansion Modules

A clear separation between OTRS and the modules is necessary for proper developing. Particularly whenusing a CVS, a clear separation is crucial. In order to facilitate the OTRS access to the files, links must becreated. This is done by a script in the directory module tools (to get this tools, check out the CVSmodule "module-tools"). Example: Linking the Calendar Module:

67

Page 74: Otrs Developer Book

Chapter 12. Development Environment

shell> ~/src/module-tools/link.pl ~/src/Calendar/ ~/src/otrs/

Whenever new files are added, they must be linked as described above.

To remove links from OTRS enter the following command:

shell> ~/src/module-tools/remove_links.pl ~/src/otrs/

12.3. Necessary Actions after Linking

As soon as the linking is completed, the Sysconfig must be run to register the module in OTRS. Requiredusers, groups and roles must be created manually and access authorizations must be defined. If anadditional databank table is required, this must be created manually, too. If an OPM package exists, theSQL commands can be read out to create the tables. Example:

shell> cat Calendar.sopm | bin/xml2sql.pl -t mysql

68

Page 75: Otrs Developer Book

Chapter 13. Writing an OTRS module for a newobject

In this chapter, the writing of a new OTRS module is illustrated on the basis of a simple smallprogramme. Necessary prerequisite is an OTRS development environment as specified in the chapter ofthe same name.

13.1. What we want to write

We want to write a little OTRS module that displays the text ’Hello World’ when called up. First of allwe must build the directory /Hello World for the module in the developer directory. In this directory, alldirectories existent in OTRS can be created. Each module should at least contain the followingdirectories:

Kernel/

Kernel/System/

Kernel/Modules/

Kernel/Output/HTML/Standard/

Kernel/Config/

Kernel/Config/Files/

Kernel/Language/

13.2. Default Config File

The creation of a module registration facilitates the display of the new module in OTRS. Therefore wecreate a file ’/Kernel/System/Config/Files/HelloWorld.xml’. In this file, we create a new config element.The impact of the various settings is described in the chapter ’Config Mechanism’.

<?xml version="1.0" encoding="iso-8859-1" ?><otrs_config version="1.0" init="Application">

69

Page 76: Otrs Developer Book

Chapter 13. Writing an OTRS module for a new object

<ConfigItem Name="Frontend::Module###AgentHelloWorld" Required="1" Valid="1"><Description Lang="en">FrontendModuleRegistration for HelloWorld modul.</Description><Description Lang="de">FrontendModulRegistration für das HelloWorld Modul.</Description><Group>HelloWorld</Group><SubGroup>AgentFrontendModuleRegistration</SubGroup><Setting>

<FrontendModuleReg><Title>HelloWorld</Title><Group>users</Group><Description>HelloWorld</Description><NavBarName>HelloWorld</NavBarName><NavBar>

<Description>HelloWorld</Description><Name>HelloWorld</Name><Image>overview.png</Image><Link>Action=AgentHelloWorld</Link><NavBar>HelloWorld</NavBar><Type>Menu</Type><Prio>8400</Prio><Block>ItemArea</Block>

</NavBar></FrontendModuleReg>

</Setting></ConfigItem>

</otrs_config>

13.3. Frontend Module

After creating the links and executing the Sysconfig, a new module with the name ’HelloWorld’ isdisplayed. When calling it up, an error message is displayed as OTRS cannot find the matching frontendmodule yet. This is the next thing to be created. To do so, we create the following file:

# --# Kernel/Modules/AgentHelloWorld.pm - frontend modul# Copyright (C) 2001-2005 Martin Edenhofer <[email protected]># --# $Id: writing-otrs-application.xml,v 1.11 2006/06/07 14:10:34 tr Exp $# --# This software comes with ABSOLUTELY NO WARRANTY. For details, see# the enclosed file COPYING for license information (GPL). If you# did not receive this file, see http://www.gnu.org/licenses/gpl.txt.# --

package Kernel::Modules::AgentHelloWorld;

70

Page 77: Otrs Developer Book

Chapter 13. Writing an OTRS module for a new object

use strict;use Kernel::System::HelloWorld;

sub new {my $Type = shift;my %Param = @_;

# allocate new hash for objectmy $Self = {};bless ($Self, $Type);# get common objectsforeach (keys %Param) {

$Self->{$_} = $Param{$_};}# check needed Opjectsforeach (qw(ParamObject DBObject ModuleReg LogObject ConfigObject)) {

$Self->{LayoutObject}->FatalError(Message => "Got no $_!") if (!$Self->{$_});}# create needed objects$Self->{HelloWorldObject} = Kernel::System::HelloWorld->new(%Param);

return $Self;}# --sub Run {

my $Self = shift;my %Param = @_;my $Output = ”;my %Data = ();

$Data{HelloWorldText} = $Self->{HelloWorldObject}->GetHelloWorldText();# build output$Output .= $Self->{LayoutObject}->Header(Title => "HelloWorld");$Output .= $Self->{LayoutObject}->NavigationBar();$Output .= $Self->{LayoutObject}->Output(

Data => \%Data,TemplateFile => ’AgentHelloWorld’,

);$Output .= $Self->{LayoutObject}->Footer();return $Output;

}1;

13.4. Core Module

Next, we create the file for the core module "/HelloWorld/Kernel/System/HelloWorld.pm" with thefollowing content:

71

Page 78: Otrs Developer Book

Chapter 13. Writing an OTRS module for a new object

# --# Kernel/System/HelloWorld.pm - core modul# Copyright (C) 2001-2005 Martin Edenhofer <[email protected]># --# $Id: writing-otrs-application.xml,v 1.11 2006/06/07 14:10:34 tr Exp $# --# This software comes with ABSOLUTELY NO WARRANTY. For details, see# the enclosed file COPYING for license information (GPL). If you# did not receive this file, see http://www.gnu.org/licenses/gpl.txt.# --

package Kernel::System::HelloWorld;

use strict;

sub new {my $Type = shift;my %Param = @_;

# allocate new hash for objectmy $Self = {};bless ($Self, $Type);

return $Self;}

sub GetHelloWorldText {my $Self = shift;my %Param = @_;

return ’Hello World’;}

1;

13.5. dtl Template File

The last thing missing before the new module can run is the relevant template. Thus, we create thefollowing file:

# --# Kernel/Output/HTML/Standard/AgentHelloWorld.dtl - overview# Copyright (C) 2001-2005 Martin Edenhofer <[email protected]># --# $Id: writing-otrs-application.xml,v 1.11 2006/06/07 14:10:34 tr Exp $# --

72

Page 79: Otrs Developer Book

Chapter 13. Writing an OTRS module for a new object

# This software comes with ABSOLUTELY NO WARRANTY. For details, see# the enclosed file COPYING for license information (GPL). If you# did not receive this file, see http://www.gnu.org/licenses/gpl.txt.# --<!-- start form --><table border="0" width="100%" cellspacing="0" cellpadding="3"><tr><td class="mainhead">

$Env{"Box0"}$Text{"Overview"}: $Text{"HelloWorld"}$Env{"Box1"}</td>

</tr><tr><td class="mainbody">

<br>$Text{"$QData{"HelloWorldText"}"}!<br><br><br>

</td></tr>

</table><!-- end form -->

The module is working now and displays the text ’Hello World’ when called up.

13.6. Language File

If the text ’Hello World’ is to be translated into German, a language file for this language must becreated: ’/HelloWorld/Kernel/Language/de_AgentHelloWorld.pm’. Example:

package Kernel::Language::de_AgentHelloWorld;

use strict;

sub Data {my $Self = shift;

$Self->{Translation} = { %{$Self->{Translation}},’Hello World’ => ’Hallo Welt’,

};}1;

73

Page 80: Otrs Developer Book

Chapter 13. Writing an OTRS module for a new object

13.7. Summary

The example given above shows that it is not too difficult to write a new module for OTRS. It isimportant, though, to make sure that the module and file name are unique and thus do not interfere withthe framework or other expansion modules. When a module is finished, an OPM package must begenerated from it (see chapter ’Package Building’).

74

Page 81: Otrs Developer Book

Chapter 14. Package Management

The OPM (OTRS Package Manager) is a mechanism to distribute software packages for the OTRSframework via http, ftp or file upload.

For example, the OTRS project offers OTRS modules like a calendar, a file manager or web mail inOTRS packages via online repositories on our ftp servers. The packages can be managed(install/upgrade/uninstall) via the admin interface.

14.1. Package Distribution

If you want to create an OPM online repositiory, just tell the OTRS framework where the location is.Then you will have a new select option in the admin interface.

[Kernel/Config.pm]

# Package::RepositoryList# (repository list)$Self->{’Package::RepositoryList’} = {

’ftp://ftp.example.com/packages/’ => ’[Example-Repository]’,};

[...]

14.1.1. Package Repository Index

In your repository, create an index file for your OPM packages. OTRS just reads this index file andknows what packages are available.

shell> bin/opm.pl -a index -d /path/to/repository/ > /path/to/repository/otrs.xmlshell>

75

Page 82: Otrs Developer Book

Chapter 14. Package Management

14.2. Package Commands

You can use the following OPM commands over the admin interface or over bin/opm.pl to manageadmin jobs for OPM packages.

14.2.1. Install

Install OPM packages.

• Web: http://localhost/otrs/index.pl?Action=AdminPackage

• CMD:

shell> bin/opm.pl -a install -p /path/to/package.opm

14.2.2. Uninstall

Uninstall OPM packages.

• Web: http://localhost/otrs/index.pl?Action=AdminPackage

• CMD:

shell> bin/opm.pl -a uninstall -p /path/to/package.opm

14.2.3. Upgrade

Upgrade OPM packages.

• Web: http://localhost/otrs/index.pl?Action=AdminPackage

• CMD:

shell> bin/opm.pl -a upgrade -p /path/to/package.opm

76

Page 83: Otrs Developer Book

Chapter 14. Package Management

14.2.4. List

List all OPM packages.

• Web: http://localhost/otrs/index.pl?Action=AdminPackage

• CMD:

shell> bin/opm.pl -a list

77

Page 84: Otrs Developer Book

Chapter 15. Package Building

If you want to create an OPM package (.opm) you need to create a spec file (.sopm) which includes theproperties of the package.

15.1. Package Spec File

The OPM package is XML based. You can create/edit the .sopm via a text or xml editor. It contains metadata, a file list and database options.

15.1.1. Name

The package name (required).

<Name>Calendar</Name>

15.1.2. Version

The package version (required).

<Version>1.2.3</Version>

15.1.3. Framework

The required framework version (2.0.x means e.g. 2.0.1 or 2.0.9) (required).

<Framework>2.0.x</Framework>

78

Page 85: Otrs Developer Book

Chapter 15. Package Building

15.1.4. Vendor

The package vendor (required).

<Vendor>OTRS AG</Vendor>

15.1.5. URL

The vendor URL (required).

<URL>http://otrs.org/</URL>

15.1.6. License

The license of the package (required).

<License>GNU GENERAL PUBLIC LICENSE Version 2, June 1991</License>

15.1.7. ChangeLog

The package change log (optional).

<ChangeLog Version="1.1.2" Date="2007-02-15 18:45:21">Added some feature.</ChangeLog><ChangeLog Version="1.1.1" Date="2007-02-15 16:17:51">New package.</ChangeLog>

15.1.8. Description

The package description in different languages (required).

<Description Lang="en">A web calendar.</Description><Description Lang="de">Ein Web Kalender.</Description>

79

Page 86: Otrs Developer Book

Chapter 15. Package Building

15.1.9. BuildHost

This will be filled in automatically by OPM (auto).

<BuildHost>?</BuildHost>

15.1.10. BuildDate

This will be filled in automatically by OPM (auto).

<BuildDate>?</BuildDate>

15.1.11. PackageRequired

Packages that must be installed beforehand (optional). If PackageRequired is used, a version of therequired package must be specified.

<PackageRequired Version="1.0.3">SomeOtherPackage</PackageRequired><PackageRequired Version="5.3.2">SomeotherPackage2</PackageRequired>

15.1.12. OS (^M)

Required OS (optional).

<OS>Linux</OS><OS>MacOS</OS>

80

Page 87: Otrs Developer Book

Chapter 15. Package Building

15.1.13. Filelist

This is a list of files included in the package (optional).

<Filelist><File Permission="644" Location="Kernel/Config/Files/Calendar.pm"/><File Permission="644" Location="Kernel/System/CalendarEvent.pm"/><File Permission="644" Location="Kernel/Modules/AgentCalendar.pm"/><File Permission="644" Location="Kernel/Language/de_AgentCalendar.pm"/>

</Filelist>

15.1.14. DatabaseInstall

Database entries that have to be created when a package is installed (optional).

<DatabaseInstall><TableCreate Name="calendar_event"><Column Name="id" Required="true" PrimaryKey="true" AutoIncrement="true" Type="BIGINT"/><Column Name="title" Required="true" Size="250" Type="VARCHAR"/><Column Name="content" Required="false" Size="250" Type="VARCHAR"/><Column Name="start_time" Required="true" Type="DATE"/><Column Name="end_time" Required="true" Type="DATE"/><Column Name="owner_id" Required="true" Type="INTEGER"/><Column Name="event_status" Required="true" Size="50" Type="VARCHAR"/></TableCreate>

</DatabaseInstall>

15.1.15. DatabaseUpgrade

Information on which actions have to be performed in case of an upgrade (subject to version tag),(optional). Example (if installed package version is below 1.3.4, defined action will be performed):

<DatabaseUpgrade><TableCreate Name="calendar_event_involved" Version="1.3.4">

<Column Name="event_id" Required="true" Type="BIGINT"/><Column Name="user_id" Required="true" Type="INTEGER"/>

</TableCreate></DatabaseUpgrade>

81

Page 88: Otrs Developer Book

Chapter 15. Package Building

15.1.16. DatabaseReinstall

Information on what actions have to be performed if the package is reinstalled, (optional).

<DatabaseReinstall></DatabaseReinstall>

15.1.17. DatabaseUninstall

Uninstall (if a package gets uninstalled), (optional).

<DatabaseUninstall><TableDrop Name="calendar_event" />

</DatabaseUninstall>

15.1.18. CodeInstall

To execute perl code if the package is installed (optional).

<CodeInstall># exampleif (1) {

print STDERR "Some info to STDERR\n";}# log example$Self->{LogObject}->Log(

Priority => ’notice’,Message => "Some Message!",

)# database example$Self->{DBObject}->Do(SQL => "SOME SQL");

</CodeInstall>

15.1.19. CodeUninstall

To execute perl code if the package is uninstalled (optional).

<CodeUninstall>

82

Page 89: Otrs Developer Book

Chapter 15. Package Building

# exampleif (1) {

print STDERR "Some info to STDERR\n";}

</CodeUninstall>

15.1.20. CodeReinstall

To execute perl code if the package is reinstalled (optional).

<CodeReinstall># exampleif (1) {

print STDERR "Some info to STDERR\n";}

</CodeReinstall>

15.1.21. CodeUpgrade

To execute perl code if the package is upgraded (optional).

<CodeUpgrade># exampleif (1) {

print STDERR "Some info to STDERR\n";}

</CodeUpgrade>

15.1.22. IntroInstall(Pre|Post)

To show a pre or post install introdution in installation dialog.

<IntroInstallPre Title="Some Title" Lang="en">Some Info formated in dtl/html....</IntroInstallPre>

83

Page 90: Otrs Developer Book

Chapter 15. Package Building

15.1.23. IntroUninstall(Pre|Post)

To show a pre or post uninstall introdution in uninstallation dialog.

<IntroUninstallPre Title="Some Title" Lang="en">Some Info formated in dtl/html....</IntroUninstallPre>

15.1.24. IntroReinstall(Pre|Post)

To show a pre or post reinstall introdution in reinstallation dialog.

<IntroReinstallPre Title="Some Title" Lang="en">Some Info formated in dtl/html....</IntroReinstallPre>

15.1.25. IntroUpgrade(Pre|Post)

To show a pre or post upgrade introdution in upgrading dialog.

<IntroUpgradePre Title="Some Title" Lang="en">Some Info formated in dtl/html....</IntroUpgradePre>

15.2. Example .sopm

This is a whole example spec file.

<?xml version="1.0" encoding="utf-8" ?><otrs_package version="1.0">

<Name>Calendar</Name><Version>0.0.1</Version><Framework>2.0.x</Framework><Vendor>OTRS AG</Vendor><URL>http://otrs.org/</URL><License>GNU GENERAL PUBLIC LICENSE Version 2, June 1991</License>

84

Page 91: Otrs Developer Book

Chapter 15. Package Building

<ChangeLog Version="1.1.2" Date="2007-02-15 18:45:21">Added some feature.</ChangeLog><ChangeLog Version="1.1.1" Date="2007-02-15 16:17:51">New package.</ChangeLog><Description Lang="en">A web calendar.</Description><Description Lang="de">Ein Web Kalender.</Description><IntroInstallPre Title="Thank you!" Lang="en">Thank you for choosing the Calendar module.</IntroInstallPre><IntroInstallPre Title="Vielen Dank!" Lang="de">Vielen Dank fuer die Auswahl des Kalender Modules.</IntroInstallPre><BuildDate>?</BuildDate><BuildHost>?</BuildHost><Filelist>

<File Permission="644" Location="Kernel/Config/Files/Calendar.pm"></File><File Permission="644" Location="Kernel/System/CalendarEvent.pm"></File><File Permission="644" Location="Kernel/Modules/AgentCalendar.pm"></File><File Permission="644" Location="Kernel/Language/de_AgentCalendar.pm"></File><File Permission="644" Location="Kernel/Output/HTML/Standard/AgentCalendar.dtl"></File><File Permission="644" Location="Kernel/Output/HTML/NotificationCalendar.pm"></File><File Permission="644" Location="var/httpd/htdocs/images/Standard/calendar.png"></File>

</Filelist><DatabaseInstall>

<TableCreate Name="calendar_event"><Column Name="id" Required="true" PrimaryKey="true" AutoIncrement="true" Type="BIGINT"/><Column Name="title" Required="true" Size="250" Type="VARCHAR"/><Column Name="content" Required="false" Size="250" Type="VARCHAR"/><Column Name="start_time" Required="true" Type="DATE"/><Column Name="end_time" Required="true" Type="DATE"/><Column Name="owner_id" Required="true" Type="INTEGER"/><Column Name="event_status" Required="true" Size="50" Type="VARCHAR"/>

</TableCreate></DatabaseInstall><DatabaseReinstall></DatabaseReinstall><DatabaseUninstall>

<TableDrop Name="calendar_event"/></DatabaseUninstall>

</otrs_package>

15.3. Package Build

To build an .opm package from the spec opm.

shell> bin/opm.pl -a build -p /path/to/example.sopmwriting /tmp/example-0.0.1.opmshell>

85

Page 92: Otrs Developer Book

Chapter 16. Unit Tests

OTRS provides unit tests for core modules.

16.1. Creating a test file

The test files are stored in .t files under /scripts/test/*.t. For example the file /scripts/test/Calendar.t forthe Calendar Module.

A test file consists of the function call of the function to be tested and the analysis of the return value.Example (/scripts/test/Calendar.t):

# --# Calendar.t - Calendar# Copyright (C) 2001-2005 Martin Edenhofer <[email protected]># --# $Id: test-mechanism.xml,v 1.4 2006/04/02 23:25:09 martin Exp $# --# This software comes with ABSOLUTELY NO WARRANTY. For details, see# the enclosed file COPYING for license information (GPL). If you# did not receive this file, see http://www.gnu.org/licenses/gpl.txt.# --

use Kernel::System::User;use Kernel::System::CalendarEvent;

$Self->{UserObject} = Kernel::System::User->new(%{$Self});$Self->{EventObject} = Kernel::System::CalendarEvent->new(%{$Self}, UserID => 1);

my $EventID = $Self->{EventObject}->EventAdd(Title => ’Some Test’,StartTime => ’1977-10-27 20:15’,EndTime => ’1977-10-27 21:00’,State => ’public’,UserIDs => [1],

);

$Self->True($EventID,’EventAdd()’,

);

[..]

86

Page 93: Otrs Developer Book

Chapter 16. Unit Tests

16.2. Testing

To check your tests, just use "bin/UnitTest.pl -n Calendar" to use /scripts/test/Calendar.t.

shell:/opt/otrs> bin/UnitTest.pl -n Calendar+-------------------------------------------------------------------+/opt/otrs/scripts/test/Calendar.t:+-------------------------------------------------------------------+ok 1 - EventAdd()=====================================================================Product: OTRS 2.0.x CVSTest Time: 0 sTime: 2006-04-02 12:58:37Host: yourhost.example.comPerl: 5.8.7OS: linuxTestOk: 1TestNotOk: 0=====================================================================shell:/opt/otrs>

16.3. True()

This function tests whether the return value of the function ’EventAdd()’ in the variable $EventID isvalid.

$Self->True($EventID,’EventAdd()’,

);

16.4. False()

This function tests whether the return value of the function ’EventAdd()’ in the variable $EventID isinvalid.

$Self->False($EventID,’EventAdd()’,

);

87

Page 94: Otrs Developer Book

Chapter 16. Unit Tests

16.5. Is()

This function tests whether the variables $A and $B are equal.

$Self->Is($A,$B,’Test Name’,

);

88

Page 95: Otrs Developer Book

Appendix A. Additional Ressources

A.1. OTRS.org

The OTRS project website with source code, documentation and news is available at:

http://otrs.org/

A.2. Online API Library

The OTRS developer API documentation is available at:

http://dev.otrs.org/

A.3. Developer Mailing List

The OTRS developer mailing list is available at:

http://lists.otrs.org/

A.4. Commercial Support

For business assistance (support, consulting and training) please contact the commercial part of OTRS,the OTRS AG.

OTRS AGEuroparing 494315 Straubing (Germany)Phone: +49 (0)9421 1862 760Fax: +49 (0)9421 1862 769Web: http://otrs.com/

89